Files
magpie/internal/agent/pi_extension.ts
T
yetone a8d6a861a4 agent: Pi's codemode gets magpie's decision and image models (extensions/magpie.ts)
wangbinyq on Discord (#feedback) asked for magpie's System One and image
models in Pi's config, since Pi's codemode can call classifier and image
models (models.classify, models.generateImages; Pi docs/models.md "Use
classifier models").

Pi's models.json can't hold them: its model entries have no type, so
every one is a chat model (ModelDefinitionSchema, modelFromJson in
provider-composer.ts, Pi 1.4.0 / c9f4c7b9f). A custom provider's
classifier and image models come from an extension alone
(docs/custom-provider.md, "Register mixed-operation models"). So while
models.json has providers.magpie, magpie now writes
extensions/magpie.ts in Pi's agent folder, which Pi loads by itself:

- provider magpie-systemone: provider.OfferedDeciders, labelled as
  /v1/models labels them, on Pi's own typesafe-system-one client
  (builtinProviders' typesafe .classify), which posts the TypeSafe
  System One body to the gateway's /v1/systemone. Text input only.
- provider magpie-images: gateway.ImageModels (new; mediaModels with
  labels, the Settings > Images default first, none while it is off),
  drawn by POST /v1/images/generations with the input's images as data
  URLs, b64_json back as image blocks.

Separate ids because an extension's models replace those models.json
gives the same provider id: registered as "magpie", Pi 1.4.0 listed no
chat models at all ("No models available").

The file is rewritten at each Sync and on a pick, and removed with
providers.magpie (pick of none, Disconnect, a Sync that finds it gone).
A magpie.ts whose first line isn't magpie's mark is the user's and is
never written over or removed. Pi only, not OmO or Prime Agent. On a Pi
older than its classifier models the extension returns without
registering anything. Codemode itself is not turned on: that is the
user's defaultTools.

Run at the pushed head (on mote):
- At e7185daeb plus this change: go build ./..., go vet (darwin, GOOS=linux,
  GOOS=windows) of agent and gateway, gofmt -l clean; go test -timeout 45m
  of agent, backup, cli, davsync, gateway, gui, library, profile, stats,
  tui, uninstall. All ok but three reds that are the same on origin/main
  1747559d0 and filed: cli TestEveryRouteHasACommandOrIsNamed (#4826), gui
  TestMainWindowCorners/macOS_26_SDK (#3949), gateway
  TestCodexPoolSaysTheClientsVersion (full-run only, passes alone, #4807).
- Rebased on 1aca55909: go build ./..., go vet linux/windows of agent and
  gateway, go test ./internal/agent/ ok (181s), gateway -run
  'Image|Media|Draw|Decide|SystemOne' ok.

Real Pi in a sandbox HOME on mote (npm @earendil-works/pi-coding-agent),
against a fake gateway, with the extension magpie generated
(piExtensionFor from the test fixture):
- 1.4.0: `pi -p --tools +codemode`, the script listed
  magpie-systemone/mixed/typesafe/jev and magpie-images/art/gpt-image-2
  (in=text,image); classify answered {approved: bool 0.93}; a drawing
  with an image input came back as image/png. The fake logged
  /v1/systemone {model: mixed/typesafe/jev, noul question} and
  /v1/images/generations {model: art/gpt-image-2, images: [data URL]},
  both with Bearer magpie; the chat model from models.json still ran.
- 0.87.1 and 1.0.0: start and chat with the file in place, no error.

Broken by hand: the user's-own check removed -> LeavesTheUsersOwn red
(file written over, then removed); the Pi-only gate removed ->
PiOnly red; the extension write made a no-op -> ListsDecisionAndImage
Models and FollowsSync red.

Not tried: a real magpie gateway with real decision or image vendors
behind it (the fake answers in TypeSafe's wire shape, as magpie's
/v1/systemone does); classifier image input (left off); a WSL Pi. A
change of decision or image models reaches the file at the agent's next
Sync (a catalog change) or pick; whether a Settings > Images change
alone starts a Sync was not checked.
2026-11-02 15:43:43 +08:00

86 lines
3.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// magpie: written by magpie, and written again as its models change.
// magpie's decision models (System One) and image models (Settings ›
// Images), for codemode's models.classify() and models.generateImages().
// Pi's models.json holds chat models only, so they are registered here,
// as providers magpie-systemone and magpie-images. Take Pi off magpie in
// magpie to have this file gone; with this first line changed, magpie
// leaves the file to you.
const MAGPIE = __MAGPIE__;
export default async function (pi) {
// a Pi older than its classifier models (1.x) has no such module, or a
// System One provider without classify: it gets nothing from here
let typesafe;
try {
const { builtinProviders } = await import("@earendil-works/pi-ai/providers/all");
typesafe = builtinProviders().find((p) => p.id === "typesafe");
} catch {
return;
}
if (typeof typesafe?.classify !== "function") return;
const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
if (MAGPIE.classifiers.length)
pi.registerProvider("magpie-systemone", {
name: "magpie System One",
baseUrl: MAGPIE.baseUrl,
apiKey: MAGPIE.apiKey,
// magpie's /v1/systemone takes TypeSafe's System One protocol for
// every decision model, Cloudflare's and OpenRouter's too
models: MAGPIE.classifiers.map((m) => ({ type: "classifier", api: "typesafe-system-one", id: m.id, name: m.name, input: ["text"], cost, contextWindow: 64000 })),
classifiers: {
"typesafe-system-one": { classify: (model, context, options) => typesafe.classify(model, context, options) },
},
});
if (MAGPIE.images.length)
pi.registerProvider("magpie-images", {
name: "magpie Images",
baseUrl: MAGPIE.baseUrl,
apiKey: MAGPIE.apiKey,
models: MAGPIE.images.map((m) => ({ type: "image", api: "magpie-images", id: m.id, name: m.name, input: m.input, output: ["image"], cost })),
images: { "magpie-images": { generateImages: draw } },
});
}
// draw asks magpie's images API (POST …/v1/images/generations) for the
// input's text, with its images as references.
async function draw(model, context, options) {
const out = { api: model.api, provider: model.provider, model: model.id, output: [], stopReason: "stop", timestamp: Date.now() };
try {
const prompt = context.input.filter((b) => b.type === "text").map((b) => b.text).join("\n");
const images = context.input.filter((b) => b.type === "image").map((b) => `data:${b.mimeType};base64,${b.data}`);
const body = { model: model.id, prompt, response_format: "b64_json" };
if (images.length) body.images = images;
const res = await (options?.fetch ?? fetch)(new URL("images/generations", `${model.baseUrl.replace(/\/+$/u, "")}/`), {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${options?.apiKey ?? ""}`, ...options?.headers },
body: JSON.stringify(body),
signal: options?.signal,
});
const text = await res.text();
let got;
try {
got = JSON.parse(text);
} catch {
got = undefined;
}
if (!res.ok) throw new Error(`magpie answered ${res.status}: ${got?.error?.message ?? text.slice(0, 500)}`);
if (got?.text) out.output.push({ type: "text", text: got.text });
for (const d of got?.data ?? []) {
if (d.b64_json) out.output.push({ type: "image", data: d.b64_json, mimeType: d.mime_type ?? "image/png" });
else if (d.url) out.output.push({ type: "text", text: d.url });
}
const u = got?.usage;
if (u) {
const input = u.input_tokens ?? 0;
const output = u.output_tokens ?? 0;
out.usage = { input, output, cacheRead: 0, cacheWrite: 0, totalTokens: u.total_tokens ?? input + output, cost: { ...cost0, total: 0 } };
}
} catch (error) {
out.stopReason = options?.signal?.aborted ? "aborted" : "error";
out.errorMessage = error instanceof Error ? error.message : String(error);
}
return out;
}
const cost0 = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };