Files
yetone 589e4ba6da agent: OpenCode finds magpie's models itself; opencode.json no longer lists them
chawyehsu on X asked for dynamic model discovery, as
yuhp/opencode-models-discovery does. magpie wrote its whole catalog into
opencode.json's magpie provider. For an OpenCode that loads plugins of
today's shape (1.4.0 and later, 2.0.5 and later; openCodeDiscovers),
the provider now has no "models". magpie writes plugins/magpie-models.js
beside the file (opencode_models.js, marked by its first line). It fills
the provider's models as OpenCode starts, from the gateway's new
/v1/models?format=opencode (opencode2 for OpenCode 2;
gateway/opencode_models.go). That endpoint gives the same entries a sync
would have listed, in magpie's order, never cached, and only the
models of OpenCode's catalog the key asking may use (keyListed).

- OpenCode 1: through its config hook, which runs before it reads
  providers. The user's entries under magpie's provider are laid over
  magpie's, and an id magpie doesn't list stays.
- OpenCode 2: through ctx.model.transform. The config's own entries are
  laid on afterwards by OpenCode. Every entry says variants ([] for
  none), so OpenCode makes up none.
- Gateway not answering (3s timeout): the plugin lists the models magpie
  had when it last wrote it.

Existing users: the first sync on such an OpenCode takes magpie's list
out of the file (modelsLeft). Of each model, only what the user said
differently stays: their own variant, or a limit.output they typed. A
limit or cost they changed stays whole, since OpenCode 1.19.6 refuses
one without its context ("Missing key ...limit.context"). An id magpie
no longer lists goes that once (stash opencode-discover:<path>), as it
did on every sync before; one added after that is the user's and stays.
The user's other keys and providers are untouched. These keep the list
in the file as before: an OpenCode older than those versions, of no
known version, and the forks (mimocode, DevEco, Air). Going back to
such an OpenCode writes the list again and removes the plugin, and so
does taking magpie out. A file at the plugin's path without magpie's
first line is the user's and is never touched.

Run:
- mote-run go vet ./internal/agent ./internal/gateway, also with
  GOOS=linux and GOOS=windows: clean. gofmt -l: clean.
- mote-run go test ./internal/agent -run
  'OpenCode|OpenChamber|Air|DevEco|Mimo': ok (TestOpenCodePluginRuns runs
  the plugin in node against a stubbed gateway, up and down, v1 and v2).
- mote-run go test ./internal/gateway -run 'TestOpenCodeModelsList|Models': ok.
- Broken by hand, each red: no key filter (TestOpenCodeModelsList),
  openCodeDiscovers always false (Finds/ListMoves/DiscoversFrom), the
  delta keeping whole models (ListMoves), and the plugin letting magpie's
  fields win over the user's (PluginRuns).
- Three opencode_v2 tests that check the listed words now pin 2.0.4 and
  1.3.9, which still list.
- Real OpenCode on mote in a sandbox HOME, opencode-ai 1.19.6 and
  @opencode/cli 2.3.2. Config and plugin written by magpie's own code, a
  fake /v1/models serving one extra model:
  - `opencode models` lists the served model with the gateway up, and
    the cached list with it down. Both versions, Bearer key sent.
  - A file moved from 1.3.9/2.0.4 with a user limit.output and a user
    model: `opencode models magpie --verbose` (1.19.6) and
    `opencode api --standalone GET /api/model` (2.3.2) resolve magpie's
    models the same as the old full-list file did. Names, limits,
    variants and the user's edits are identical; 2.3.2 orders a model
    the file names first.
- Full suite: mote-run go test ./... -timeout 45m -count=1 on this change over base 1bfa8d5a1: 103 packages ok, no FAIL.
- Rebased on 7300be4d0 (main touched agents.go and gateway.go): go vet
  darwin/linux/windows of internal/agent and internal/gateway clean;
  go test ./internal/agent ok; ./internal/gateway red only in
  TestSearchQueueKeepsCodexAlive/comments and /cancel at load ~37, the
  idle-bar class of #7090 (commented), 5/5 ok alone at this head.
- Not changed: the forks mimocode, DevEco and Air keep the list; filed as #7055.
Not tried: a WSL distro's OpenCode, and OpenChamber's own UI over the
plugin-filled provider.
2026-11-18 19:47:19 +08:00

334 lines
11 KiB
Go

package agent
import (
"encoding/json"
"errors"
"maps"
"github.com/yetone/magpie/internal/edit"
)
// OpenCode 2 reads OpenCode 1's config and turns it into its own words as
// it loads it (packages/core/src/config/normalize.ts at v2.2.6): provider
// into providers, small_model into agents.title.model. A model's reasoning,
// which OpenCode 2 doesn't read, it drops with a WARN on every load, one per
// model ("omitted unsupported legacy setting", kaising00 on X). Where the
// OpenCode the config is for is 2.x, magpie writes the file in OpenCode 2's
// words: magpie's provider under providers only (openCodeNative), its small
// model under agents.title.model. For OpenCode 1, or a version not known,
// it writes OpenCode 1's, which every OpenCode reads.
// openCodeVersion is the version of the opencode on PATH, "" when not
// known; a var so tests can fake it.
var openCodeVersion = func() string { return (&Agent{ID: "opencode", Bin: "opencode"}).InstalledVersion() }
// openCodeTwo is whether the OpenCode at a place is 2.x: the one on this
// machine's PATH, or the distro's, as its probe found it.
func openCodeTwo(at place) bool {
n, ok := openCodeVersionParts(openCodeVersionAt(at))
return ok && n[0] >= 2
}
// openCodeTitleKey is where OpenCode 2 keeps the model it titles sessions
// with, which OpenCode 1's small_model became.
const openCodeTitleKey = "agents.title.model"
// ocFile is an OpenCode config magpie writes its provider into: two when
// the OpenCode reading it is 2.x, block magpie's provider in OpenCode 1's
// words (magpieProviderJSONAt).
type ocFile struct {
path string
two bool
discover bool // the OpenCode loads magpie's plugin (opencode_discover.go)
block func() any
}
// sync brings magpie's provider in the file up to date, and writes it
// where it is missing when put (a model of magpie's is chosen there). For
// OpenCode 2 a provider of magpie's under provider, and a small_model of
// magpie's, move to OpenCode 2's words first.
//
// Where the OpenCode finds magpie's models itself (discover), the file has
// magpie's provider without them, and magpie's plugin beside it.
func (f ocFile) sync(put bool) error {
var err error
if f.discover {
err = f.syncFound(put)
} else {
err = f.syncListed(put)
if unstashPeek(openCodeDiscoverKey(f.path)) != "" {
stash(map[string]string{openCodeDiscoverKey(f.path): ""})
}
}
return errors.Join(err, f.pluginSynced())
}
// syncFound is sync for an OpenCode that finds magpie's models itself:
// magpie's models in the file go first, leaving what the user said of
// them (modelsLeft), and the provider is written without them.
func (f ocFile) syncFound(put bool) error {
moved := unstashPeek(openCodeDiscoverKey(f.path)) != ""
listed := f
listed.block = withoutModels(f.block)
var err error
if !f.two {
err = f.modelsLeft("provider."+magpieID, openCodeKept(f.path, f.block)(), f.block(), moved)
if _, ok := edit.GetJSON(f.path, openCodeNativeKey); ok && err == nil {
err = f.modelsLeft(openCodeNativeKey, openCodeNativeKept(f.path, f.block)(), openCodeNative(f.block()), moved)
}
} else {
if err := f.moveProvider(); err != nil {
return err
}
if err := f.moveSmall(); err != nil {
return err
}
err = f.modelsLeft(openCodeNativeKey, openCodeNativeKept(f.path, f.outputsKept)(), openCodeNative(f.block()), moved)
}
if err != nil {
return err
}
if !moved {
stash(map[string]string{openCodeDiscoverKey(f.path): "1"})
}
return listed.syncListed(put)
}
// syncListed is sync with magpie's models as block has them.
func (f ocFile) syncListed(put bool) error {
if !f.two {
v1 := openCodeKept(f.path, f.block)
var err error
if _, ok := edit.GetJSON(f.path, "provider."+magpieID); !ok && put {
err = edit.SetJSON(f.path, edit.KV{Path: "provider." + magpieID, Value: v1()})
} else {
err = syncJSONInOrder(f.path, "provider."+magpieID, v1)
}
// and where the file keeps it under providers too, which OpenCode
// 2 reads instead, there as well (#3883)
return errors.Join(err, syncOpenCodeNative(f.path, f.block))
}
if err := f.moveProvider(); err != nil {
return err
}
if err := f.moveSmall(); err != nil {
return err
}
native := openCodeNativeKept(f.path, f.outputsKept)
if _, ok := edit.GetJSON(f.path, openCodeNativeKey); !ok && put {
return edit.SetJSON(f.path, edit.KV{Path: openCodeNativeKey, Value: native()})
}
return syncJSONInOrder(f.path, openCodeNativeKey, native)
}
// outputsKept is block with a limit.output the user typed into one of
// magpie's models kept (openCodeOutputsKept).
func (f ocFile) outputsKept() any {
v := f.block()
if b, ok := v.(map[string]any); ok {
if ms, ok := b["models"].(orderedJSON); ok {
openCodeOutputsKept(f.path, ms)
}
}
return v
}
// moveProvider moves magpie's provider under provider to providers, in
// OpenCode 2's words, as OpenCode 2 itself reads it (openCodeFromV1): what
// the user added to it goes along. Where providers has magpie's already,
// OpenCode 2 reads that one whole and not the other (mergeMaps), so the
// other goes.
func (f ocFile) moveProvider() error {
raw, ok := edit.GetJSONRaw(f.path, "provider."+magpieID)
if !ok {
return nil
}
if _, has := edit.GetJSON(f.path, openCodeNativeKey); !has {
v, ok := openCodeFromV1([]byte(raw))
if !ok {
// not a provider OpenCode reads: left as it is
return nil
}
if err := edit.SetJSON(f.path, edit.KV{Path: openCodeNativeKey, Value: v}); err != nil {
return err
}
}
if err := edit.DelJSON(f.path, "provider."+magpieID); err != nil {
return err
}
// and a provider left with nothing in it
return f.dropEmpty("provider")
}
// moveSmall moves a small_model of magpie's to agents.title.model, where
// OpenCode 2 reads it, unless the title agent has a model of its own
// already, which OpenCode 2 reads instead.
func (f ocFile) moveSmall() error {
sm, ok := edit.GetJSON(f.path, "small_model")
if !ok || !usesMagpie(sm) {
return nil
}
if _, has := edit.GetJSON(f.path, openCodeTitleKey); has {
return nil
}
if err := edit.SetJSON(f.path, edit.KV{Path: openCodeTitleKey, Value: sm}); err != nil {
return err
}
return edit.DelJSON(f.path, "small_model")
}
// small is the file's small model as the OpenCode reading it takes it:
// for OpenCode 2 its title agent's, else small_model.
func (f ocFile) small() string {
if f.two {
if v, ok := edit.GetJSONRaw(f.path, openCodeTitleKey); ok {
return openCodeSelection(v)
}
}
v, _ := edit.GetJSON(f.path, "small_model")
return v
}
// setSmall sets the file's small model: for OpenCode 2 its title agent's,
// with a small_model, which it would read only without one, gone.
func (f ocFile) setSmall(v string) error {
if !f.two {
if v == "" {
return edit.DelJSON(f.path, "small_model")
}
return edit.SetJSON(f.path, edit.KV{Path: "small_model", Value: v})
}
if v == "" {
if err := edit.DelJSON(f.path, "small_model", openCodeTitleKey); err != nil {
return err
}
return f.dropEmpty("agents.title", "agents")
}
if err := edit.SetJSON(f.path, edit.KV{Path: openCodeTitleKey, Value: v}); err != nil {
return err
}
return edit.DelJSON(f.path, "small_model")
}
// dropEmpty takes out each of keys, in order, that is an empty object.
func (f ocFile) dropEmpty(keys ...string) error {
for _, k := range keys {
if raw, ok := edit.GetJSONRaw(f.path, k); ok {
var m map[string]json.RawMessage
if json.Unmarshal([]byte(raw), &m) == nil && m != nil && len(m) == 0 {
if err := edit.DelJSON(f.path, k); err != nil {
return err
}
}
}
}
return nil
}
// openCodeSelection is a model as OpenCode 2 has one, raw: "provider/model"
// (#variant), or {providerID, model, variant}, as "provider/model".
func openCodeSelection(raw string) string {
var s string
if json.Unmarshal([]byte(raw), &s) == nil {
return s
}
var o struct {
ProviderID string `json:"providerID"`
Model string `json:"model"`
}
if json.Unmarshal([]byte(raw), &o) != nil || o.ProviderID == "" || o.Model == "" {
return ""
}
return o.ProviderID + "/" + o.Model
}
// openCodeFromV1 is a provider in OpenCode 1's words, raw, in OpenCode 2's,
// as OpenCode 2.2.6 reads it (packages/core/src/v1/config/migrate.ts,
// migrateStandardProvider): npm is package "aisdk:<npm>", api a baseURL in
// settings, options settings but for headers and body, which are the
// provider's own, and setCacheKey, which is compatibility's
// supportsPromptCacheKey. Of a model it keeps the parts magpie's models
// leave to the user, as openCodeNativeKept reads them: its name, limit and
// variants (openCodeNativeVariant); magpie writes the rest of its models
// whole. What OpenCode 2 doesn't read of OpenCode 1's (id, whitelist,
// blacklist) goes, as it goes there.
func openCodeFromV1(raw []byte) (orderedJSON, bool) {
var p struct {
API string `json:"api"`
Name json.RawMessage `json:"name"`
Env json.RawMessage `json:"env"`
NPM string `json:"npm"`
Options map[string]json.RawMessage `json:"options"`
Models json.RawMessage `json:"models"`
}
if json.Unmarshal(raw, &p) != nil {
return nil, false
}
out := orderedJSON{}
if p.Name != nil {
out = append(out, jsonPair{"name", p.Name})
}
if p.Env != nil {
out = append(out, jsonPair{"env", p.Env})
}
if p.NPM != "" {
out = append(out, jsonPair{"package", "aisdk:" + p.NPM})
}
if ck, ok := p.Options["setCacheKey"]; ok {
out = append(out, jsonPair{"compatibility", map[string]any{"supportsPromptCacheKey": ck}})
}
if p.Options != nil || p.API != "" {
settings := maps.Clone(p.Options)
if settings == nil {
settings = map[string]json.RawMessage{}
}
for _, k := range []string{"setCacheKey", "headers", "body"} {
delete(settings, k)
}
if p.API != "" {
b, _ := json.Marshal(p.API)
settings["baseURL"] = b
}
out = append(out, jsonPair{"settings", settings})
}
for _, k := range []string{"headers", "body"} {
if v, ok := p.Options[k]; ok {
out = append(out, jsonPair{k, v})
}
}
if p.Models != nil {
ms := orderedJSON{}
for _, mp := range objectPairs(p.Models) {
var m struct {
Name json.RawMessage `json:"name"`
Limit json.RawMessage `json:"limit"`
Variants json.RawMessage `json:"variants"`
}
if json.Unmarshal(mp.v.(json.RawMessage), &m) != nil {
continue
}
e := orderedJSON{}
if m.Name != nil {
e = append(e, jsonPair{"name", m.Name})
}
if m.Limit != nil {
e = append(e, jsonPair{"limit", m.Limit})
}
if m.Variants != nil {
list := []any{}
for _, vp := range objectPairs(m.Variants) {
var opts map[string]any
if json.Unmarshal(vp.v.(json.RawMessage), &opts) != nil {
continue
}
list = append(list, openCodeNativeVariant(vp.k, opts))
}
e = append(e, jsonPair{"variants", list})
}
ms = append(ms, jsonPair{mp.k, e})
}
out = append(out, jsonPair{"models", ms})
}
return out, true
}