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.
This commit is contained in:
yetone
2026-11-02 15:43:43 +08:00
parent 1aca55909f
commit a8d6a861a4
6 changed files with 429 additions and 1 deletions
+1
View File
@@ -132,6 +132,7 @@ something else shows up as drift.
- omp's `enabledModels` in `config.yml` is the list it holds its default role to: a model left out of it isn't used, whatever `modelRoles.default` says (#1769). So a model picked for the default role is added to a list that is there and doesn't take it in already, by name or by one of omp's globs (`*` not crossing `/`, as `Bun.Glob`), and once nothing in `config.yml` is on magpie its plain `magpie/…` entries are taken out (a list left empty goes, never `[]`); a renamed provider's entries are renamed once, and folder-scoped entries are left alone (`ompScope*` in [`omp_scope.go`](../../internal/agent/omp_scope.go)). No list, no change: omp then takes every model. A list that leaves the default role's model out is drift, which Reapply mends.
- Pi's `enabledModels` in `settings.json` (and OmO's and Prime Agent's, `piLike`) is the Ctrl+P list a new session starts from. A picked model the list doesn't take in is added (`piScopeWith` in [`pi.go`](../../internal/agent/pi.go)), and a renamed provider's `magpie/<old>/` entries are renamed with it, a glob or a thinking level included, the copy the pick just added dropped (`renameRefList` in [`rename.go`](../../internal/agent/rename.go), #1919, `TestPiEnabledModelsFollowRename`). The user's other entries stay; a list naming none of the provider's models isn't rewritten.
- After the catalog sync, an entry in Pi's (and its forks'), StepCode's or omp's `enabledModels` that names one of magpie's models outright (no glob; a thinking level read off) whose model magpie no longer gives the agent is taken out: Pi warned "No models match pattern" for each one at every start (#2055). It may be the user's own, so it is remembered in `stash.json` (`<agent>.scope.gone`) and goes back on the list's end when the model is offered again; a rename moves the remembered entries too, and a disconnect forgets them. Globs, other providers' entries and omp's folder-scoped entries stay. A list left empty is removed and made again when its entries come back, with the model picked meanwhile; one the user removed isn't. When magpie's model list in the agent's file can't be read, nothing is taken out ([`scope_gone.go`](../../internal/agent/scope_gone.go), `TestPiEnabledModelsLoseDeselected`). For StepCode, the wiring state's last-written scope follows, so a disconnect still puts the user's own list back.
- Pi's codemode calls classifier and image models (`models.classify`, `models.generateImages`; Pi's docs/models.md "Use classifier models" and "Use image models"), which Pi's `models.json` can't define: its model entries have no `type`, so every one is a chat model, and 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 writes `extensions/magpie.ts` in Pi's agent folder, which Pi loads by itself (`piExtensionSynced` in [`pi_extension.go`](../../internal/agent/pi_extension.go), its source [`pi_extension.ts`](../../internal/agent/pi_extension.ts); wangbinyq on Discord). It registers magpie's decision models (`provider.OfferedDeciders`, labelled as `/v1/models` labels them) as provider `magpie-systemone` on Pi's own `typesafe-system-one` client, which posts TypeSafe's System One body to the gateway's `/v1/systemone`, and its image models (`gateway.ImageModels`: what generate_image may use, the Settings › Images default first, none while it is off) as `magpie-images`, drawn by `/v1/images/generations` with the input's images as data URLs. Separate provider ids, because an extension's `models` replace those `models.json` gives a provider of the same id: registered as `magpie`, Pi 1.4.0 lost magpie's chat models. Classifier input is text only, as the gateway hands a TypeSafe body's `assets` on as they are. The extension does nothing on a Pi older than its classifier models (no `@earendil-works/pi-ai/providers/all`, or a TypeSafe provider without `classify`; Pi 0.87.1 and 1.0.0 start and chat with it). It is rewritten at each Sync and on a pick, and removed with `providers.magpie` (a 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, never written over or removed. Pi only, not OmO or Prime Agent. Codemode itself stays off unless the user turns it on (`"defaultTools": ["+codemode"]`). Tried with real Pi 1.4.0 in a sandbox home against a fake gateway: both lists, a classify and a drawing reached `/v1/systemone` and `/v1/images/generations` with magpie's key (`TestPiExtensionListsDecisionAndImageModels`, `TestPiExtensionFollowsSync`, `TestPiExtensionLeavesTheUsersOwn`, `TestPiExtensionPiOnly`).
- A model's price goes into every agent file that takes one, in USD per million tokens: Pi's and its forks' `cost`, omp's `cost` (omp 18.9.1 prices a custom provider's call by it alone; without it a `group/*` id matched no bundled model and cost 0, taotao7 on Discord), OpenCode's `cost` (`cache_read`, `cache_write`) and Crush's `cost_per_1m_*` (`in_cached` is a write, `out_cached` a read). A group whose members cost the same is priced at that; one whose members differ at the member it sends to first, a manual group's pick, else its first not switched off (`provider.AgentPricer`), and none when that member is in a fast mode or has no price. The gateway's `/v1/models` keeps `EntryPricer`, which prices only a group of one price. The price is read at each Sync, so it follows the group's members ([`route.go`](../../internal/agent/route.go), `TestGroupModelsCarryTheirFirstMembersPrice`).
- A value an agent spells as its own provider's model is never taken for one of magpie's, even when magpie has a provider of the same name (`Spelled`, #835).
- The other way round, a value that names one of magpie's models the agent isn't shown (kept from it by `magpie visible` or a model not ticked for it), a model of one of magpie's providers that isn't on its list (a remote magpie's group added there since the list was fetched), or a `group/…` magpie has no group for, is refused by `Spell` (`notOffered`), and nothing changes. It used to be written as the agent's own: Pi read `remote/group/smart` as its own provider `remote` and model `group/smart`, and was taken out of magpie (#2376). A model shown the agent that a field offers fewer of (Claude Desktop's tiers) is still taken, and so is a value whose provider part one of the agent's own models goes by (`openai/…` in Pi) ([`agent.go`](../../internal/agent/agent.go), `TestSpellRefusesMagpieModelNotOffered`).
+16 -1
View File
@@ -1347,8 +1347,17 @@ func piLikeKeyed(at place, id, name, dir string, key func() string) *Agent {
b["apiKey"] = key()
return b
})
// Pi's own: magpie's decision and image models, for codemode
// (pi_extension.go); a fork's extensions may not be Pi's
extension := func() error { return nil }
if id == "pi" {
extension = func() error { return piExtensionSynced(dir, modelsPath, at.v1(), key()) }
}
writeMagpie := func() error {
return edit.SetJSON(modelsPath, edit.KV{Path: "providers." + magpieID, Value: block()})
if err := edit.SetJSON(modelsPath, edit.KV{Path: "providers." + magpieID, Value: block()}); err != nil {
return err
}
return extension()
}
// the user's two files as they were before magpie's first write, put
// back byte for byte by Disconnect where it leaves them saying the same
@@ -1370,6 +1379,9 @@ func piLikeKeyed(at place, id, name, dir string, key func() string) *Agent {
if err := syncJSON(modelsPath, "providers."+magpieID, block); err != nil {
return err
}
if err := extension(); err != nil {
return err
}
// an entry on a model magpie no longer gives Pi names nothing
// (#2055, scope_gone.go)
return piScopeSynced(path, modelsPath, gone)
@@ -1398,6 +1410,9 @@ func piLikeKeyed(at place, id, name, dir string, key func() string) *Agent {
if err := edit.DelJSON(modelsPath, "providers."+magpieID); err != nil {
return err
}
if err := extension(); err != nil {
return err
}
forget(gone)
return piScopeWithout(path)
}
+112
View File
@@ -0,0 +1,112 @@
package agent
import (
"bytes"
"cmp"
_ "embed"
"encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
// Pi's codemode calls classifier and image models (models.classify,
// models.generateImages; Pi's docs/models.md "Use classifier models" and
// "Use image models"), wangbinyq on Discord. Pi's models.json defines chat
// models only: its model definitions have no type, and a custom provider's
// classifier or image models come from an extension alone
// (docs/custom-provider.md, "Register mixed-operation models"). So magpie
// writes one, extensions/magpie.ts in Pi's agent folder, which Pi loads by
// itself. It lists magpie's decision models as provider magpie-systemone,
// on Pi's own System One client against magpie's /v1/systemone, and its
// image models as magpie-images, drawn by /v1/images/generations. It is
// there while models.json has providers.magpie, and gone with it.
//go:embed pi_extension.ts
var piExtensionSource string
// piExtensionMark opens the file magpie writes. A file at that path
// without it is the user's own, and is never written over or removed.
const piExtensionMark = "// magpie: written by magpie"
// piExtensionPath is magpie's extension in Pi's agent folder dir.
func piExtensionPath(dir string) string {
return filepath.Join(dir, "extensions", "magpie.ts")
}
// piExtensionModel is a model as the extension registers it.
type piExtensionModel struct {
ID string `json:"id"`
Name string `json:"name"`
Input []string `json:"input,omitempty"`
}
// piExtensionFor is the extension's source for a gateway at baseURL (its
// /v1) and key; "" when magpie has no decision or image model to list.
func piExtensionFor(baseURL, key string) string {
ds := provider.OfferedDeciders(nil)
for i := range ds {
ds[i].Name = cmp.Or(ds[i].Name, ds[i].Model)
}
labels := provider.Labels(ds)
classifiers := make([]piExtensionModel, 0, len(ds))
for i, e := range ds {
classifiers = append(classifiers, piExtensionModel{ID: e.ID, Name: labels[i]})
}
images := []piExtensionModel{}
for _, m := range gateway.ImageModels() {
in := []string{"text"}
if m.Images {
in = append(in, "image")
}
images = append(images, piExtensionModel{ID: m.ID, Name: m.Name, Input: in})
}
if len(classifiers) == 0 && len(images) == 0 {
return ""
}
data, _ := json.Marshal(map[string]any{
"baseUrl": baseURL, "apiKey": key,
"classifiers": classifiers, "images": images,
})
return strings.Replace(piExtensionSource, "__MAGPIE__", string(data), 1)
}
// piExtensionSynced brings magpie's extension in Pi's agent folder dir
// to what models.json says: written while it has providers.magpie and
// magpie has models to list, else gone. A file there magpie didn't write
// is left as it is.
func piExtensionSynced(dir, modelsPath, baseURL, key string) error {
path := piExtensionPath(dir)
cur, err := os.ReadFile(path)
switch {
case errors.Is(err, fs.ErrNotExist):
cur = nil
case err != nil:
return err // unknown: neither written over nor removed
case !bytes.HasPrefix(edit.TrimBOM(cur), []byte(piExtensionMark)):
return nil // the user's own
}
want := ""
if _, on := edit.GetJSON(modelsPath, "providers."+magpieID); on {
want = piExtensionFor(baseURL, key)
}
if want == "" {
if cur == nil {
return nil
}
return os.Remove(path)
}
if string(cur) == want {
return nil
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
return edit.WriteAtomic(path, []byte(want))
}
+85
View File
@@ -0,0 +1,85 @@
// 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 };
+176
View File
@@ -0,0 +1,176 @@
package agent
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
// piExtensionHome is a sandbox home with a provider that decides
// (typesafe/jev) and one that draws (gpt-image-2, which takes images too).
func piExtensionHome(t *testing.T) string {
t.Helper()
home := syncHome(t)
// no request reaches these: the extension only names them
if err := provider.Save(provider.Provider{ID: "mixed", Name: "Mixed", Key: "k", Chat: "http://127.0.0.1:9/v1", Decide: "http://127.0.0.1:9/v1", Models: []string{"deepseek-v4.1-flash", "typesafe/jev"}}); err != nil {
t.Fatal(err)
}
art := provider.Provider{ID: "art", Name: "Art", Responses: "http://127.0.0.1:9/v1", Key: "k"}
if err := provider.Save(art); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("art", art.Responses, []catalog.Model{{ID: "text"}, {ID: "gpt-image-2", Name: "GPT Image 2", Draws: true, Images: true}}); err != nil {
t.Fatal(err)
}
return home
}
type piExtensionData struct {
BaseURL string `json:"baseUrl"`
APIKey string `json:"apiKey"`
Classifiers []piExtensionModel `json:"classifiers"`
Images []piExtensionModel `json:"images"`
}
// readPiExtension is the data in the extension magpie wrote at path.
func readPiExtension(t *testing.T, path string) piExtensionData {
t.Helper()
src := readFile(path)
if !strings.HasPrefix(src, piExtensionMark) {
t.Fatalf("%s is not magpie's: %.200s", path, src)
}
_, rest, ok := strings.Cut(src, "const MAGPIE = ")
line, _, _ := strings.Cut(rest, ";\n")
var d piExtensionData
if !ok || json.Unmarshal([]byte(line), &d) != nil {
t.Fatalf("no MAGPIE data in %s: %.400s", path, rest)
}
return d
}
func hasModel(ms []piExtensionModel, id string) (piExtensionModel, bool) {
for _, m := range ms {
if m.ID == id {
return m, true
}
}
return piExtensionModel{}, false
}
// Pi's codemode reaches classifier and image models, which models.json
// can't define (wangbinyq on Discord): picking a model of magpie's writes
// extensions/magpie.ts with magpie's decision and image models, and
// taking Pi off magpie removes it.
func TestPiExtensionListsDecisionAndImageModels(t *testing.T) {
home := piExtensionHome(t)
a := pi(home)
path := piExtensionPath(a.Dir)
if err := a.Field("model").Set(magpieID + "/mixed/deepseek-v4.1-flash"); err != nil {
t.Fatal(err)
}
d := readPiExtension(t, path)
if d.BaseURL != here(home).v1() {
t.Errorf("baseUrl = %q, want %q", d.BaseURL, here(home).v1())
}
if want := mustGet(t, filepath.Join(a.Dir, "models.json"), "providers.magpie.apiKey"); d.APIKey != strings.Trim(want, `"`) {
t.Errorf("apiKey = %q, models.json's is %s", d.APIKey, want)
}
if _, ok := hasModel(d.Classifiers, "mixed/typesafe/jev"); !ok {
t.Errorf("classifiers = %+v, want mixed/typesafe/jev", d.Classifiers)
}
if _, ok := hasModel(d.Classifiers, "mixed/deepseek-v4.1-flash"); ok {
t.Errorf("a chat model listed as a classifier: %+v", d.Classifiers)
}
img, ok := hasModel(d.Images, "art/gpt-image-2")
if !ok {
t.Fatalf("images = %+v, want art/gpt-image-2", d.Images)
}
if strings.Join(img.Input, ",") != "text,image" || img.Name != "GPT Image 2 · Art" {
t.Errorf("image model = %+v", img)
}
if !strings.Contains(readFile(path), `pi.registerProvider("magpie-systemone"`) || !strings.Contains(readFile(path), `"typesafe-system-one"`) {
t.Errorf("extension source: %.300s", readFile(path))
}
if err := a.Field("model").Set(""); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Errorf("extension left after Pi went off magpie: %v", err)
}
}
// The catalog sync rewrites the extension as magpie's models change, and
// removes it once models.json has no provider magpie.
func TestPiExtensionFollowsSync(t *testing.T) {
home := piExtensionHome(t)
a := pi(home)
path := piExtensionPath(a.Dir)
if err := a.Field("model").Set(magpieID + "/mixed/deepseek-v4.1-flash"); err != nil {
t.Fatal(err)
}
// the one provider that draws removed: no image model is listed
if err := provider.Delete("art"); err != nil {
t.Fatal(err)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if d := readPiExtension(t, path); len(d.Images) != 0 || len(d.Classifiers) == 0 {
t.Errorf("after the drawing provider went: %+v", d)
}
models := filepath.Join(a.Dir, "models.json")
if err := edit.DelJSON(models, "providers.magpie"); err != nil {
t.Fatal(err)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Errorf("extension left with no provider magpie: %v", err)
}
}
// A magpie.ts the user wrote themselves is theirs: never written over,
// never removed.
func TestPiExtensionLeavesTheUsersOwn(t *testing.T) {
home := piExtensionHome(t)
a := pi(home)
path := piExtensionPath(a.Dir)
os.MkdirAll(filepath.Dir(path), 0o755)
own := "// my own magpie helpers\nexport default function (pi) {}\n"
os.WriteFile(path, []byte(own), 0o644)
if err := a.Field("model").Set(magpieID + "/mixed/deepseek-v4.1-flash"); err != nil {
t.Fatal(err)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if got := readFile(path); got != own {
t.Errorf("the user's file written over: %.200s", got)
}
if err := a.Field("model").Set(""); err != nil {
t.Fatal(err)
}
if got := readFile(path); got != own {
t.Errorf("the user's file removed or changed: %q", got)
}
}
// OmO keeps Pi's files but may not load Pi's extensions: it gets none.
func TestPiExtensionPiOnly(t *testing.T) {
home := piExtensionHome(t)
a := omo(home)
if err := a.Field("model").Set(magpieID + "/mixed/deepseek-v4.1-flash"); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(piExtensionPath(a.Dir)); !os.IsNotExist(err) {
t.Errorf("OmO got Pi's extension: %v", err)
}
}
+39
View File
@@ -1,6 +1,7 @@
package gateway
import (
"cmp"
"fmt"
"net/http"
"slices"
@@ -64,6 +65,44 @@ func mediaModels(video bool) (all []string, def string) {
return all, def
}
// ImageModel is a model magpie draws with, as an agent's own list of
// image models names it (Pi's, internal/agent/pi_extension.go).
type ImageModel struct {
ID string // provider/model, what /v1/images takes as model
Name string // the model's name · its provider's, as /v1/models labels it
Images bool // it takes images as input too
}
// ImageModels are the models generate_image may be asked for
// (mediaModels), the Settings › Images default first, each with its label;
// none when image generation is off.
func ImageModels() []ImageModel {
all, _ := mediaModels(false)
if len(all) == 0 {
return nil
}
known := map[string]ImageModel{}
for _, p := range provider.All() {
if !p.On() || p.DecideOnly() {
continue
}
// every drawer, so a default the user unticked is labelled too
for _, m := range Drawers(p) {
ref := p.ID + "/" + m.ID
known[ref] = ImageModel{ID: ref, Name: cmp.Or(m.Name, m.ID) + " · " + p.Name, Images: m.Images}
}
}
out := make([]ImageModel, 0, len(all))
for _, ref := range all {
m, ok := known[ref]
if !ok {
m = ImageModel{ID: ref, Name: ref}
}
out = append(out, m)
}
return out
}
// mediaModelsFor is mediaModels less those r's gateway key may not use.
func mediaModelsFor(r *http.Request, video bool) (all, shown []string, def string) {
all, def = mediaModels(video)