Files
magpie/internal/agent/pi_extension.go
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

113 lines
3.6 KiB
Go

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))
}