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

337 lines
10 KiB
Go

package agent
import (
"bytes"
_ "embed"
"encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
)
// OpenCode finds magpie's models itself (chawyehsu on X, after
// yuhp/opencode-models-discovery): opencode.json keeps magpie's provider
// without a list of its models, and a plugin magpie writes beside it,
// plugins/magpie-models.js in OpenCode's config folder, fills the list
// from the gateway's /v1/models?format=opencode (opencode2 for OpenCode 2)
// each time OpenCode starts. So OpenCode follows magpie's models without a
// sync, and a model the user puts under magpie's provider in the file is
// theirs: the plugin lays its fields over magpie's, and lists one magpie
// doesn't. With magpie not answering, the plugin lists the models magpie
// had when it last wrote the file, which it keeps in the file.
//
// OpenCode loads every {plugin,plugins}/*.{js,ts} in its config folders
// (OpenCode 1.19.6's config/plugin.ts, OpenCode 2's plugin loader). A file
// whose default export is {id, server} is a plugin of OpenCode 1 from
// 1.4.0 (plugin/shared.ts, readV1Plugin), whose config hook runs before
// OpenCode reads its providers (provider.ts: "load plugins first so
// config() hook runs before reading cfg.provider"); before 1.4 each export
// was called as a function, and an object was an error. OpenCode 2 reads
// {id, setup} and its setup's ctx.model.transform from 2.0.5 (ctx.catalog
// before). An OpenCode older than those, or of a version not known, gets
// the list in opencode.json, as before.
//
// Moving a config that has the list: the first sync that finds it takes
// out what magpie wrote there and leaves what the user added to a model
// of magpie's (a variant, a limit.output of theirs), as only the fields
// that say something other than magpie's (modelsLeft).
//go:embed opencode_models.js
var openCodePluginSource string
// openCodePluginMark opens the plugin magpie writes; a file at its path
// without it is the user's own, never written over or removed.
const openCodePluginMark = "// magpie: written by magpie"
// openCodePluginPath is magpie's plugin beside the OpenCode config at
// path.
func openCodePluginPath(path string) string {
return filepath.Join(filepath.Dir(path), "plugins", "magpie-models.js")
}
// openCodeVersionAt is the version of the OpenCode at a place, "" when not
// known.
func openCodeVersionAt(at place) string {
if at.spell == nil {
return openCodeVersion()
}
return at.version
}
// openCodeVersionParts is v's major, minor and patch; ok false for a v
// that doesn't start with them.
func openCodeVersionParts(v string) (n [3]int, ok bool) {
v = strings.TrimPrefix(strings.TrimSpace(v), "v")
parts := strings.SplitN(v, ".", 3)
if len(parts) < 2 {
return n, false
}
for i, p := range parts {
end := 0
for end < len(p) && p[end] >= '0' && p[end] <= '9' {
end++
}
x, err := strconv.Atoi(p[:end])
if err != nil {
return n, false
}
n[i] = x
}
return n, true
}
// openCodeDiscovers says whether the OpenCode of version v loads magpie's
// plugin: OpenCode 1 from 1.4.0, OpenCode 2 from 2.0.5.
func openCodeDiscovers(v string) bool {
n, ok := openCodeVersionParts(v)
if !ok {
return false
}
at := func(a, b, c int) bool {
return n[0] > a || n[0] == a && (n[1] > b || n[1] == b && n[2] >= c)
}
switch n[0] {
case 1:
return at(1, 4, 0)
case 0:
return false
}
return at(2, 0, 5)
}
// openCodeFileAt is the OpenCode config at path as the OpenCode at a place
// reads it, for agent id (opencode, or a fork that keeps its shape, which
// gets neither OpenCode 2's words nor the plugin).
func openCodeFileAt(at place, path, id string, block func() any) ocFile {
if id != "opencode" {
return ocFile{path: path, block: block}
}
return ocFile{path: path, two: openCodeTwo(at), discover: openCodeDiscovers(openCodeVersionAt(at)), block: block}
}
// withoutModels is block without its models, which the plugin lists.
func withoutModels(block func() any) func() any {
return func() any {
v := block()
if m, ok := v.(map[string]any); ok {
out := make(map[string]any, len(m))
for k, x := range m {
if k != "models" {
out[k] = x
}
}
return out
}
return v
}
}
// openCodeDiscoverKey is the stash's word that the OpenCode config at path
// had magpie's models taken out of it.
func openCodeDiscoverKey(path string) string { return "opencode-discover:" + path }
// openCodeModelList is the models of magpie's block (its "models", an
// orderedJSON) as the plugin reads them.
func openCodeModelList(block any) []gateway.OpenCodeModel {
b, _ := block.(map[string]any)
ms, _ := b["models"].(orderedJSON)
out := make([]gateway.OpenCodeModel, 0, len(ms))
for _, p := range ms {
out = append(out, gateway.OpenCodeModel{ID: p.k, Entry: p.v})
}
return out
}
func init() {
gateway.OpenCodeModels = func(two bool) []gateway.OpenCodeModel {
block := magpieProviderJSONAt("opencode", "opencode", gateway.URL())
if two {
block = openCodeNative(block)
}
return openCodeModelList(block)
}
}
// openCodePluginFor is the plugin's source for magpie's block: the
// gateway's address and key, and the models it lists when magpie doesn't
// answer.
func openCodePluginFor(block any) string {
b, _ := block.(map[string]any)
o, _ := b["options"].(map[string]any)
data, _ := json.Marshal(map[string]any{
"baseURL": o["baseURL"], "apiKey": o["apiKey"],
"v1": openCodeModelList(block), "v2": openCodeModelList(openCodeNative(block)),
})
return strings.Replace(openCodePluginSource, "__MAGPIE__", string(data), 1)
}
// pluginSynced brings magpie's plugin beside the file to what the file
// says: there while the file has magpie's provider and its OpenCode
// discovers, else gone. A file there magpie didn't write is left as it is.
func (f ocFile) pluginSynced() error {
path := openCodePluginPath(f.path)
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(openCodePluginMark)):
return nil // the user's own
}
_, legacy := edit.GetJSON(f.path, "provider."+magpieID)
_, native := edit.GetJSON(f.path, openCodeNativeKey)
if !f.discover || !legacy && !native {
if cur == nil {
return nil
}
return os.Remove(path)
}
want := openCodePluginFor(f.block())
if string(cur) == want {
return nil
}
return edit.WriteAtomic(path, []byte(want))
}
// openCodePluginGone takes magpie's plugin beside the OpenCode config at
// path out, once magpie's provider is out of it.
func openCodePluginGone(path string) error {
return ocFile{path: path}.pluginSynced()
}
// modelsLeft takes magpie's models out of the file, under key (provider's
// or providers'), leaving what the user said there. kept is the block as a
// sync would have written it, with what of the user's a sync keeps (a
// variant of theirs, a limit.output they typed: openCodeKept,
// openCodeNativeKept); pure is magpie's own. Of each model magpie lists,
// what stays is the fields of kept's that say other than pure's
// (jsonDelta), which the plugin lays over magpie's. A model magpie doesn't
// list was magpie's while magpie wrote the models whole, and goes the first
// time (moved false); after that it is one the user added, and stays.
func (f ocFile) modelsLeft(key string, kept, pure any, moved bool) error {
raw, ok := edit.GetJSONRaw(f.path, key+".models")
if !ok {
return nil
}
have := objectPairs([]byte(raw))
if have == nil {
return nil // not an object: left as it is
}
ours, keptBy := modelsOf(pure), modelsOf(kept)
out := orderedJSON{}
for _, p := range have {
var cur any
if json.Unmarshal(p.v.(json.RawMessage), &cur) != nil {
continue
}
base, mine := ours[p.k]
if !mine {
if moved {
out = append(out, jsonPair{p.k, cur})
}
continue
}
if k, ok := keptBy[p.k]; ok {
cur = k
}
d, keep := jsonDelta(cur, base)
if !keep {
continue
}
// a limit or cost the user changed stays whole: OpenCode 1 refuses
// one without its context and output (or input and output: "Missing
// key …limit.context", 1.19.6), and OpenCode 2 a cost item without
// its output
if m, ok := d.(map[string]any); ok {
c, _ := cur.(map[string]any)
for _, k := range []string{"limit", "cost"} {
if _, said := m[k]; said && c[k] != nil {
m[k] = c[k]
}
}
}
if key == openCodeNativeKey {
// with no variants to say, OpenCode 2 would make up its own
// for the model (Variant.resolve), where magpie's has none
if m, ok := d.(map[string]any); ok && m["variants"] == nil {
m["variants"] = []any{}
}
}
out = append(out, jsonPair{p.k, d})
}
if len(out) == 0 {
return edit.DelJSON(f.path, key+".models")
}
if sameJSON(raw, out) && sameOrder(raw, out) {
return nil
}
return edit.SetJSON(f.path, edit.KV{Path: key + ".models", Value: out})
}
// modelsOf is the models of a provider block, by id, as JSON decodes them.
func modelsOf(block any) map[string]any {
var b struct {
Models map[string]any `json:"models"`
}
raw, err := json.Marshal(block)
if err != nil || json.Unmarshal(raw, &b) != nil || b.Models == nil {
return map[string]any{}
}
return b.Models
}
// jsonDelta is what have says other than base: of objects, the keys whose
// values differ, alike; of lists, the items base doesn't have. keep false
// when nothing is left.
func jsonDelta(have, base any) (any, bool) {
switch h := have.(type) {
case map[string]any:
b, ok := base.(map[string]any)
if !ok {
break
}
out := map[string]any{}
for k, hv := range h {
bv, in := b[k]
if !in {
out[k] = hv
continue
}
if d, keep := jsonDelta(hv, bv); keep {
out[k] = d
}
}
return out, len(out) > 0
case []any:
b, ok := base.([]any)
if !ok {
break
}
var out []any
for _, x := range h {
if !slicesContainsDeep(b, x) {
out = append(out, x)
}
}
return out, len(out) > 0
}
return have, !reflect.DeepEqual(have, base)
}
func slicesContainsDeep(xs []any, x any) bool {
for _, y := range xs {
if reflect.DeepEqual(x, y) {
return true
}
}
return false
}