diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index c33c94bd3..40a05ec1a 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -55,8 +55,8 @@ something else shows up as drift. - JetBrains Air's `magpie-opencode.json` keeps user-added fields in `provider.magpie`, including nested options, on sync and model picks (`air` in [`air.go`](../../internal/agent/air.go), using `theirsKept` in [`sync.go`](../../internal/agent/sync.go)). The gateway fields and complete model list are still replaced, so removed models leave the list. - Air comes in two forms that read different files, both wired by `airAt` in [`air.go`](../../internal/agent/air.go). The Air app (`air`) reads `acp.json` in its own config folder. The Air plugin in JetBrains IDEs (`air-ide`; bundled from 2026.3, from Marketplace in 2026.2) reads `~/.jetbrains/acp.json` on every system, the file AI Assistant's custom agents are in too (`AcpConfigurationLoader` in the plugin's `intellij.air.backend.acp.runtime`, checked in air-plugin 262.8665.521). Each gets its own Magpie entry and `magpie-opencode.json` beside its `acp.json`. `air-ide` shows for an IDE config folder of 2026.2 or later, or with its entry already there (`TestAirIDEDetectedByIDEVersion`). Neither has a base URL for its own agents (JetBrains AI, the agent's login, or an Anthropic, OpenAI, Gemini or OpenRouter key); The plugin's Codex on its own login runs this computer's `codex` (the terminal's `PATH`, else the `@openai/codex` it installs) as `codex app-server` with the user's `CODEX_HOME` or `~/.codex`, and sets no `model_provider` (`CodexAppServerProcessKt`); its menu is Codex's `model/list` and its default `config/read`'s model. Its Claude Agent runs `claude` with only Air's hooks in `--settings`. So both go through magpie while Codex and Claude Code are connected here. The Air app's Codex runs with a `CODEX_HOME` of its own and JetBrains' gateway (`codexRuntimeEnvironment`, `[model_providers.air-gateway]`), and never does. The model on either Air row is the Magpie agent's alone, and the opened row says which of Air's own agents go through magpie (`airSaid` in `app.js`, `agent-air-own.test.cjs`; jumy_18634 on Discord). - In every OpenCode-shaped config (OpenCode, DevEco, Air, OpenChamber; `openCodeKept` in [`agents.go`](../../internal/agent/agents.go)), a variant the user put on one of magpie's models stays through a sync, and so does one they wrote over under a name of magpie's. A variant exactly as magpie writes it under its name (`openCodeVariant`) is magpie's, so one the model no longer has goes (#2379, `TestOpenCodeCodexFastVariants`). -- magpie's OpenCode provider goes under `provider` (OpenCode 1's key), not OpenCode 2's native `providers`, on purpose. OpenCode 2 reads `provider` and turns it into its own shape in memory without rewriting the file (`migrateProviders` in packages/core/src/config/normalize.ts at v2.2.0; its "Migrate from V1" page calls the V1 format supported and converting optional), while OpenCode 1 ignores `providers` (`ConfigV2Compat.lower` in packages/opencode/src/config/v2-compat.ts at v1.19.5, npm's `latest`), and both read the same opencode.json. A native entry is a different shape too (`package`, `settings.baseURL`, variants as an array). Checked on 10-29 against a fake server: 2.2.0 listed and used magpie's `provider` entry (`#high-fast` sent reasoning_effort high and service_tier priority), and 1.19.5 with the entry under `providers` had no magpie models. OpenCode 2 logs one WARN for each model marked `reasoning`, which only OpenCode 1 reads. -- OpenCode 2 reads a provider under `providers`, in words of its own, before the same name under `provider`, and logs the other as a conflict. OpenChamber's provider form saves one there and takes it out of `provider`, so once it had saved magpie's, OpenCode 2 and OpenChamber kept the models magpie had then (#3883). Where an OpenCode config keeps magpie's provider under `providers`, every sync and pick writes it there too, as OpenCode 2 reads `provider.magpie` (`openCodeNative` in [`opencode_providers.go`](../../internal/agent/opencode_providers.go); OpenCode 2.1.4's `opencode debug config` reads the two alike and logs no conflict). A config without one doesn't get one. Keys of the user's there stay, and so do their variants, in OpenCode 2's split or all in `settings` as OpenChamber writes them. Taking magpie out takes out both, and the wiring check reads both (`TestOpenCodeProvidersKeptCurrent`, `TestOpenChamberProvidersKeptCurrent`). +- Which OpenCode reads the file decides its words (`openCodeTwo`, `ocFile` in [`opencode_v2.go`](../../internal/agent/opencode_v2.go)): the `opencode` on PATH (`openCodeVersion`), or a WSL distro's as its probe found it. For OpenCode 1, or a version not known, magpie's provider goes under `provider` and the small model is `small_model`, OpenCode 1's keys, which OpenCode 2 also reads and converts in memory (`migrateProviders` in packages/core/src/config/normalize.ts) while OpenCode 1 ignores `providers` (`ConfigV2Compat.lower` in packages/opencode/src/config/v2-compat.ts at v1.19.5). For OpenCode 2 it writes OpenCode 2's own: the provider under `providers` alone (`openCodeNative`), the small model as `agents.title.model`, and no model's `reasoning`, which OpenCode 2 doesn't read and warned about once per model on every load ("omitted unsupported legacy setting", kaising00 on X). A file written for OpenCode 1 moves over on the next sync once OpenCode 2 is there (`openCodeFromV1`, a port of `migrateStandardProvider` in packages/core/src/v1/config/migrate.ts at v2.2.6): the user's keys in magpie's provider go along, and a `small_model` of their own stays. Checked on 11-10 with `opencode debug config`: OpenCode 2.2.6 reads the file magpie writes for it with no WARN, and resolves it the same as the OpenCode 1 file it replaces; OpenCode 1.19.5 reads the OpenCode 1 file with no WARN. An OpenCode 1 reading a file written for an OpenCode 2 on PATH sees no magpie provider (it logs `providers` as not representable). OpenChamber writes the same file and takes the same decision. mimocode and DevEco Code keep OpenCode 1's words. `TestOpenCode2WritesItsOwnWords`, `TestOpenCode2MovesAnOpenCode1File`. +- OpenCode 2 reads a provider under `providers`, in words of its own, before the same name under `provider`, and logs the other as a conflict. OpenChamber's provider form saves one there and takes it out of `provider`, so once it had saved magpie's, OpenCode 2 and OpenChamber kept the models magpie had then (#3883). For OpenCode 1, where the config keeps magpie's provider under `providers` too, every sync and pick writes it there as well, as OpenCode 2 reads `provider.magpie` (`openCodeNative` in [`opencode_providers.go`](../../internal/agent/opencode_providers.go); OpenCode 2.1.4's `opencode debug config` reads the two alike and logs no conflict). A config without one doesn't get one. Keys of the user's there stay, and so do their variants, in OpenCode 2's split or all in `settings` as OpenChamber writes them. Taking magpie out takes out both, and the wiring check reads both (`TestOpenCodeProvidersKeptCurrent`, `TestOpenChamberProvidersKeptCurrent`). - OpenCode has no `/fast`. A ChatGPT account's own `gpt-*` model, not a routing group (`catalog.Model.CodexFast`, set in `magpieModels`), gets each reasoning level again as `-fast` (or `fast` alone with no levels), asking `service_tier: "priority"` as Codex's `/fast` does. The tier is written twice: as an option, which OpenCode 1's `@ai-sdk/openai-compatible` sends as it is, and in `extraBody`, which OpenCode 2 sends while it drops an option it doesn't know (checked with OpenCode 2.0.25 against a fake server). The gateway drops OpenCode 1's stray `extraBody` field when it rebuilds the request as Responses for the ChatGPT backend (`TestOpenCodeFastVariantReachesCodex`). - Every sync and pick that writes magpie's own block into an agent's config lays it over what is there, so keys magpie doesn't write stay (#2030, then its siblings). Each block was checked against the app's own schema or source. magpie's parts are named; a key it no longer writes goes with them. - Qoder's `providers.magpie` keeps `routing`, the timeouts, `type`, `authType`, `anthropic` and a non-empty `displayName` (`qoderKept`). diff --git a/internal/agent/agents.go b/internal/agent/agents.go index acf278c2d..f230c3b31 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -1119,7 +1119,9 @@ func openCodeLike(at place, id, name, icon, bin, dir, auth string, ua []string, } } block := func() any { return magpieProviderJSONAt("opencode", id, at.gw()) } - provider := openCodeKept(path, block) + // the file as the agent reads it: in OpenCode 2's words for an + // OpenCode 2, asked each time, as an update may have come since + file := func() ocFile { return ocFile{path: path, two: id == "opencode" && openCodeTwo(at), block: block} } opts := func(key string) func(map[string]string) []Option { return func(cur map[string]string) []Option { return withVia(ownOptions(auth, cur[key]), id, magpieID+"/") @@ -1130,12 +1132,21 @@ func openCodeLike(at place, id, name, icon, bin, dir, auth string, ua []string, // OpenCode it runs on this config, is one of magpie's: magpie's // provider has to stay onMagpie := func() bool { - return usesMagpie(get("model"), get("small_model")) || id == "opencode" && at.spell == nil && openChamberOnMagpie() + return usesMagpie(get("model"), file().small()) || id == "opencode" && at.spell == nil && openChamberOnMagpie() } set := func(key string) func(string) error { + put := func(v string) error { + if key == "small_model" { + return file().setSmall(v) + } + if v == "" { + return edit.DelJSON(path, key) + } + return edit.SetJSON(path, edit.KV{Path: key, Value: v}) + } return func(v string) error { if v == "" { - if err := edit.DelJSON(path, key); err != nil { + if err := put(""); err != nil { return err } if onMagpie() { @@ -1147,7 +1158,7 @@ func openCodeLike(at place, id, name, icon, bin, dir, auth string, ua []string, if err != nil { return err } - return edit.SetJSON(path, edit.KV{Path: key, Value: v}) + return put(v) } } return &Agent{ @@ -1155,28 +1166,20 @@ func openCodeLike(at place, id, name, icon, bin, dir, auth string, ua []string, UA: ua, Bin: bin, Dir: dir, Path: path, Check: func() string { - if !usesMagpie(get("model"), get("small_model")) { + if !usesMagpie(get("model"), file().small()) { return "" } return openCodeWiringOff(name, path, at.v1(), openCodeKeyAt(id, at.gw())) }, ListOnly: true, Sync: func() error { - var err error // a model of magpie's chosen, but its provider gone from the // file: put it back, or the agent has nothing to send it to - if _, ok := edit.GetJSON(path, "provider."+magpieID); !ok && onMagpie() { - err = edit.SetJSON(path, edit.KV{Path: "provider." + magpieID, Value: provider()}) - } else { - err = syncJSONInOrder(path, "provider."+magpieID, provider) - } - // and where the file keeps it under providers too, which - // OpenCode 2 reads instead, there as well (#3883) - return errors.Join(err, syncOpenCodeNative(path, block)) + return file().sync(onMagpie()) }, Fields: []Field{ {Key: "model", Label: "model", Get: jsonGet(path, "model"), Set: set("model"), Options: opts("model")}, - {Key: "small", Label: "small", Get: jsonGet(path, "small_model"), Set: set("small_model"), Options: opts("small")}, + {Key: "small", Label: "small", Get: func() string { return file().small() }, Set: set("small_model"), Options: opts("small")}, }, } } @@ -1212,10 +1215,7 @@ func openCodeRefAt(at place, path, id, v string) (string, error) { return own + "/" + ref, nil } block := func() any { return magpieProviderJSONAt("opencode", id, at.gw()) } - if err := edit.SetJSON(path, edit.KV{Path: "provider." + magpieID, Value: openCodeKept(path, block)()}); err != nil { - return v, err - } - return v, syncOpenCodeNative(path, block) + return v, ocFile{path: path, two: id == "opencode" && openCodeTwo(at), block: block}.sync(true) } // ownGatewayProvider is the provider in an OpenCode config, other than diff --git a/internal/agent/main_test.go b/internal/agent/main_test.go index a39ff72ca..7d2ea734c 100644 --- a/internal/agent/main_test.go +++ b/internal/agent/main_test.go @@ -51,6 +51,10 @@ func TestMain(m *testing.M) { // refused every test that turns magpie on for each agent; the tests // about it say their own ombRunning = func() bool { return false } + // nor which OpenCode this machine has: an OpenCode 2 on PATH turned + // every OpenCode test's file into OpenCode 2's words; the tests about + // it say their own (opencode_v2_test.go) + openCodeVersion = func() string { return "" } // a desktop app's Restart never quits or opens one of this machine's // (the Codex app, Claude Desktop, WorkBuddy the developer runs); the // restart tests stand in for each step diff --git a/internal/agent/openchamber.go b/internal/agent/openchamber.go index 8e1d054cb..d69b68cdc 100644 --- a/internal/agent/openchamber.go +++ b/internal/agent/openchamber.go @@ -165,7 +165,10 @@ func openChamber(home, cfg string) *Agent { ocPath := oc.Path auth := filepath.Join(home, ".local", "share", "opencode", "auth.json") block := func() any { return magpieProviderJSONFor("opencode", "opencode") } - provider := openCodeKept(ocPath, block) + // the OpenCode config as the OpenCode on PATH reads it, which writes + // it in OpenCode 2's words for an OpenCode 2 (ocFile), as OpenCode's + // own Sync does: the two never write it in each other's + file := func() ocFile { return ocFile{path: ocPath, two: openCodeTwo(here("")), block: block} } opts := func(key string) func(map[string]string) []Option { return func(cur map[string]string) []Option { return withVia(ownOptions(auth, cur[key]), "opencode", magpieID+"/") @@ -175,8 +178,7 @@ func openChamber(home, cfg string) *Agent { // OpenCode config names one of its models tidy := func() error { m, _ := edit.GetJSON(ocPath, "model") - sm, _ := edit.GetJSON(ocPath, "small_model") - if usesMagpie(m, sm, s.model(), s.small()) { + if usesMagpie(m, file().small(), s.model(), s.small()) { return nil } return edit.DelJSON(ocPath, "provider."+magpieID, openCodeNativeKey) @@ -208,14 +210,8 @@ func openChamber(home, cfg string) *Agent { }, ListOnly: true, Sync: func() error { - var err error - if _, ok := edit.GetJSON(ocPath, "provider."+magpieID); !ok && usesMagpie(s.model(), s.small()) { - err = edit.SetJSON(ocPath, edit.KV{Path: "provider." + magpieID, Value: provider()}) - } else { - err = syncJSONInOrder(ocPath, "provider."+magpieID, provider) - } // and the copy under providers its own form writes (#3883) - return errors.Join(err, syncOpenCodeNative(ocPath, block)) + return file().sync(usesMagpie(s.model(), s.small())) }, Fields: []Field{ {Key: "model", Label: "model", Get: s.model, Options: opts("model"), Set: func(v string) error { diff --git a/internal/agent/opencode_providers.go b/internal/agent/opencode_providers.go index 1f9a5ca93..57723345e 100644 --- a/internal/agent/opencode_providers.go +++ b/internal/agent/opencode_providers.go @@ -11,8 +11,9 @@ import ( // OpenCode 2 keeps a provider under providers, in words of its own, and // still reads OpenCode 1's provider: a provider named under both is the one // under providers, whole, and the other only a line in its log -// (packages/core/src/config/normalize.ts, mergeMaps, at v2.1.4). magpie -// writes its provider under provider, which both read. OpenChamber writes a +// (packages/core/src/config/normalize.ts, mergeMaps, at v2.1.4). For +// OpenCode 1 magpie writes its provider under provider, which both read; for +// OpenCode 2 under providers alone (ocFile). OpenChamber writes a // provider its form saves under providers and takes it out of provider // (packages/web/server/lib/opencode/config-v2.js, writeSectionEntry), so // once it had saved magpie's, magpie's next sync put magpie's back under @@ -215,15 +216,20 @@ func syncOpenCodeNative(path string, block func() any) error { // openCodeWiringOff is wiringOff for magpie's provider in the OpenCode // config at path: under provider, and under providers where the file keeps -// it there, which OpenCode 2 reads instead. +// it there, which OpenCode 2 reads instead; under providers alone in a file +// written for OpenCode 2 (ocFile). With neither, it is gone. func openCodeWiringOff(name, path, v1, key string) string { under := func(prefix string) func(string) (string, bool) { return func(k string) (string, bool) { return edit.GetJSON(path, prefix+k) } } - if off := wiringOff(name, path, under("provider."+magpieID+".options."), "baseURL", v1, "apiKey", key); off != "" { - return off + _, legacy := edit.GetJSON(path, "provider."+magpieID) + _, native := edit.GetJSON(path, openCodeNativeKey) + if legacy || !native { + if off := wiringOff(name, path, under("provider."+magpieID+".options."), "baseURL", v1, "apiKey", key); off != "" { + return off + } } - if _, ok := edit.GetJSON(path, openCodeNativeKey); !ok { + if !native { return "" } return wiringOff(name, path, under(openCodeNativeKey+".settings."), "baseURL", v1, "apiKey", key) diff --git a/internal/agent/opencode_v2.go b/internal/agent/opencode_v2.go new file mode 100644 index 000000000..3d09b61f3 --- /dev/null +++ b/internal/agent/opencode_v2.go @@ -0,0 +1,291 @@ +package agent + +import ( + "encoding/json" + "errors" + "maps" + "strconv" + "strings" + + "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 { + v := at.version + if at.spell == nil { + v = openCodeVersion() + } + major, _, _ := strings.Cut(strings.TrimPrefix(strings.TrimSpace(v), "v"), ".") + n, err := strconv.Atoi(major) + return err == nil && n >= 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 + 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. +func (f ocFile) sync(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:", 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 +} diff --git a/internal/agent/opencode_v2_test.go b/internal/agent/opencode_v2_test.go new file mode 100644 index 000000000..6a0c3d25d --- /dev/null +++ b/internal/agent/opencode_v2_test.go @@ -0,0 +1,312 @@ +package agent + +import ( + "encoding/json" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/provider" +) + +// openCodeAt has the OpenCode on PATH say version v for the test. +func openCodeAt(t *testing.T, v string) { + t.Helper() + was := openCodeVersion + openCodeVersion = func() string { return v } + t.Cleanup(func() { openCodeVersion = was }) +} + +// reasonCatalog gives the sandbox think's models (thinkCatalog) and +// rsn/plan, a model that reasons with no levels to pick, which magpie +// marks reasoning for OpenCode 1 (openCodeReasons). +func reasonCatalog(t *testing.T) { + t.Helper() + thinkCatalog(t) + if err := provider.Save(provider.Provider{ID: "rsn", Name: "Rsn", Chat: "https://example.test/v1", Key: "key", + Models: []string{"plan"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("rsn", "https://example.test/v1", []catalog.Model{{ID: "plan", Reasoning: true, Context: 200000, Output: 64000}}); err != nil { + t.Fatal(err) + } +} + +// nativeOnly checks magpie's provider under providers is OpenCode 2's, +// with models among them, and none says reasoning. +func nativeOnly(t *testing.T, path string, models ...string) { + t.Helper() + raw, ok := edit.GetJSON(path, openCodeNativeKey) + if !ok { + t.Fatalf("no %s", openCodeNativeKey) + } + var got struct { + Package string `json:"package"` + Settings map[string]any `json:"settings"` + Models map[string]json.RawMessage `json:"models"` + } + if err := json.Unmarshal([]byte(raw), &got); err != nil { + t.Fatal(err) + } + if got.Package != "aisdk:@ai-sdk/openai-compatible" || got.Settings["baseURL"] != gatewayV1() || got.Settings["apiKey"] == nil { + t.Fatalf("not magpie's provider: %s", raw) + } + for _, m := range models { + if _, ok := got.Models[m]; !ok { + t.Fatalf("no %s: %s", m, raw) + } + } +} + +// kaising00 on X: for OpenCode 2 magpie wrote OpenCode 1's words, which +// OpenCode 2 turns into its own as it loads them, and a model's reasoning, +// which it doesn't read, it warned of on every load ("omitted unsupported +// legacy setting", OpenCode 2.2.6). For an OpenCode 2 magpie's provider is +// under providers alone, in OpenCode 2's words, the small model is the +// title agent's, and nothing says reasoning. +func TestOpenCode2WritesItsOwnWords(t *testing.T) { + home, _ := codexHome(t, "", "") + reasonCatalog(t) + openCodeAt(t, "2.2.6") + oc := opencode(home, filepath.Join(home, ".config")) + if err := oc.Apply("model", "magpie/rsn/plan"); err != nil { + t.Fatal(err) + } + if err := oc.Apply("small", "magpie/think/new"); err != nil { + t.Fatal(err) + } + if err := oc.Sync(); err != nil { + t.Fatal(err) + } + raw := readFile(oc.Path) + for _, k := range []string{"provider", "small_model"} { + if v, ok := edit.GetJSON(oc.Path, k); ok { + t.Fatalf("OpenCode 1's %s written for OpenCode 2: %s\n%s", k, v, raw) + } + } + if strings.Contains(raw, `"reasoning"`) { + t.Fatalf("reasoning written for OpenCode 2:\n%s", raw) + } + nativeOnly(t, oc.Path, "rsn/plan", "think/deep", "think/new") + if v, _ := edit.GetJSON(oc.Path, openCodeTitleKey); v != "magpie/think/new" { + t.Fatalf("agents.title.model = %q\n%s", v, raw) + } + if v, _ := edit.GetJSON(oc.Path, "model"); v != "magpie/rsn/plan" { + t.Fatalf("model = %q", v) + } + if got := oc.Values()["small"]; got != "magpie/think/new" { + t.Fatalf("small reads %q", got) + } + if off := oc.Check(); off != "" { + t.Fatalf("Check: %s", off) + } + // the next sync has nothing to write + var wrote []string + if err := edit.Filtered(func(p string, b []byte) []byte { wrote = append(wrote, p); return b }, oc.Sync); err != nil { + t.Fatal(err) + } + if len(wrote) > 0 { + t.Fatalf("a second sync wrote %v", wrote) + } + // the small model off: its key goes, and the agents it was in + if err := oc.Apply("small", ""); err != nil { + t.Fatal(err) + } + if v, ok := edit.GetJSON(oc.Path, "agents"); ok { + t.Fatalf("agents left: %s", v) + } + // stepped off magpie, its provider goes + if err := oc.Apply("model", ""); err != nil { + t.Fatal(err) + } + if v, ok := edit.GetJSON(oc.Path, openCodeNativeKey); ok { + t.Fatalf("providers.magpie left: %s", v) + } +} + +// OpenCode 1 is written as before: provider, small_model and reasoning, +// and nothing of OpenCode 2's. +func TestOpenCode1KeepsItsWords(t *testing.T) { + home, _ := codexHome(t, "", "") + reasonCatalog(t) + openCodeAt(t, "1.19.5") + oc := opencode(home, filepath.Join(home, ".config")) + if err := oc.Apply("model", "magpie/rsn/plan"); err != nil { + t.Fatal(err) + } + if err := oc.Apply("small", "magpie/think/new"); err != nil { + t.Fatal(err) + } + raw := readFile(oc.Path) + for _, k := range []string{"providers", "agents"} { + if v, ok := edit.GetJSON(oc.Path, k); ok { + t.Fatalf("OpenCode 2's %s written for OpenCode 1: %s", k, v) + } + } + if v, _ := edit.GetJSON(oc.Path, "provider.magpie.models.rsn/plan.reasoning"); v != "true" { + t.Fatalf("rsn/plan not marked reasoning for OpenCode 1:\n%s", raw) + } + if v, _ := edit.GetJSON(oc.Path, "small_model"); v != "magpie/think/new" { + t.Fatalf("small_model = %q", v) + } +} + +// A file magpie wrote for OpenCode 1 moves to OpenCode 2's words once +// OpenCode 2 is installed: magpie's provider, with what the user added to +// it (a header, a timeout, their setCacheKey, a variant of their own, a +// reply limit they typed), and a small model of magpie's. Their own +// provider under provider, and a key of theirs, stay as they are. +func TestOpenCode2MovesAnOpenCode1File(t *testing.T) { + home, _ := codexHome(t, "", "") + reasonCatalog(t) + openCodeAt(t, "1.19.5") + oc := opencode(home, filepath.Join(home, ".config")) + if err := oc.Apply("model", "magpie/think/deep"); err != nil { + t.Fatal(err) + } + if err := oc.Apply("small", "magpie/rsn/plan"); err != nil { + t.Fatal(err) + } + mine := `{"npm":"@ai-sdk/anthropic","options":{"apiKey":"theirs"},"models":{"m":{"reasoning":true}}}` + if err := edit.SetJSON(oc.Path, + edit.KV{Path: "provider.magpie.options.headers", Value: map[string]string{"X-Mine": "1"}}, + edit.KV{Path: "provider.magpie.options.timeout", Value: 600000}, + edit.KV{Path: "provider.magpie.options.setCacheKey", Value: false}, + edit.KV{Path: "provider.magpie.models.think/deep.variants.mine", Value: map[string]any{"reasoningEffort": "high", "temperature": 0.3}}, + edit.KV{Path: "provider.magpie.models.rsn/plan.limit.output", Value: 1234}, + edit.KV{Path: "provider.other", Value: json.RawMessage(mine)}, + edit.KV{Path: "theme", Value: "tokyonight"}, + ); err != nil { + t.Fatal(err) + } + openCodeAt(t, "2.2.6") + if err := oc.Sync(); err != nil { + t.Fatal(err) + } + raw := readFile(oc.Path) + if v, ok := edit.GetJSON(oc.Path, "provider.magpie"); ok { + t.Fatalf("provider.magpie left: %s", v) + } + if v, _ := edit.GetJSONRaw(oc.Path, "provider.other"); !sameJSON(v, json.RawMessage(mine)) { + t.Fatalf("the user's own provider changed: %s", v) + } + if v, _ := edit.GetJSON(oc.Path, "theme"); v != "tokyonight" { + t.Fatalf("theme = %q", v) + } + for k, want := range map[string]string{ + openCodeNativeKey + ".headers.X-Mine": "1", + openCodeNativeKey + ".settings.timeout": "600000", + openCodeNativeKey + ".settings.baseURL": gatewayV1(), + openCodeNativeKey + ".compatibility.supportsPromptCacheKey": "false", + openCodeNativeKey + ".models.rsn/plan.limit.output": "1234", + openCodeNativeKey + ".models.think/deep.variants.#(id==\"mine\").settings.reasoningEffort": "high", + openCodeNativeKey + ".models.think/deep.variants.#(id==\"mine\").body.temperature": "0.3", + openCodeTitleKey: "magpie/rsn/plan", + "model": "magpie/think/deep", + } { + if v, _ := edit.GetJSON(oc.Path, k); v != want { + t.Fatalf("%s = %q, want %q\n%s", k, v, want, raw) + } + } + if v, ok := edit.GetJSON(oc.Path, "small_model"); ok { + t.Fatalf("small_model left: %s", v) + } + if native, _ := edit.GetJSONRaw(oc.Path, openCodeNativeKey); strings.Contains(native, `"reasoning"`) { + t.Fatalf("reasoning left in magpie's provider:\n%s", raw) + } + if off := oc.Check(); off != "" { + t.Fatalf("Check: %s", off) + } + // with their own provider gone too, no provider is left empty + if err := edit.DelJSON(oc.Path, "provider.other"); err != nil { + t.Fatal(err) + } + openCodeAt(t, "1.19.5") + if err := oc.Sync(); err != nil { + t.Fatal(err) + } + openCodeAt(t, "2.2.6") + if err := oc.Sync(); err != nil { + t.Fatal(err) + } + if v, ok := edit.GetJSON(oc.Path, "provider"); ok { + t.Fatalf("an empty provider left: %s", v) + } +} + +// A small_model of the user's own, not magpie's, is theirs: OpenCode 2 +// reads it, and it stays where it is. +func TestOpenCode2LeavesTheirSmallModel(t *testing.T) { + home, _ := codexHome(t, "", "") + reasonCatalog(t) + openCodeAt(t, "2.2.6") + oc := opencode(home, filepath.Join(home, ".config")) + writeFile(t, oc.Path, `{"small_model":"anthropic/claude-haiku-5"}`) + if err := oc.Apply("model", "magpie/think/deep"); err != nil { + t.Fatal(err) + } + if v, _ := edit.GetJSON(oc.Path, "small_model"); v != "anthropic/claude-haiku-5" { + t.Fatalf("small_model = %q", v) + } + if v, ok := edit.GetJSON(oc.Path, "agents"); ok { + t.Fatalf("agents written: %s", v) + } +} + +// OpenChamber writes magpie's provider into the same file: for an +// OpenCode 2 in OpenCode 2's words too, so its sync and OpenCode's never +// write the file back and forth. +func TestOpenChamberAndOpenCode2AgreeOnWords(t *testing.T) { + home, _ := codexHome(t, "", "") + reasonCatalog(t) + openCodeAt(t, "2.2.6") + writeFile(t, filepath.Join(home, ".config", "openchamber", "settings.json"), `{}`) + ch := openChamber(home, filepath.Join(home, ".config")) + oc := opencode(home, filepath.Join(home, ".config")) + if err := ch.Apply("model", "magpie/think/deep"); err != nil { + t.Fatal(err) + } + if err := oc.Apply("model", "magpie/rsn/plan"); err != nil { + t.Fatal(err) + } + if v, ok := edit.GetJSON(oc.Path, "provider"); ok { + t.Fatalf("provider written for OpenCode 2: %s", v) + } + nativeOnly(t, oc.Path, "rsn/plan", "think/deep", "think/new") + var wrote []string + if err := edit.Filtered(func(p string, b []byte) []byte { wrote = append(wrote, p); return b }, func() error { + for range 2 { + if err := oc.Sync(); err != nil { + return err + } + if err := ch.Sync(); err != nil { + return err + } + } + return nil + }); err != nil { + t.Fatal(err) + } + if len(wrote) > 0 { + t.Fatalf("syncs wrote %v", wrote) + } +} + +// Which OpenCode a file is for: this machine's on PATH, or a distro's as +// its probe found it; one not known is written for OpenCode 1, which +// every OpenCode reads. +func TestOpenCodeTwo(t *testing.T) { + for v, want := range map[string]bool{"2.2.6": true, "v2.0.25": true, "10.1.0": true, "1.19.5": false, "": false, "opencode": false} { + openCodeAt(t, v) + if got := openCodeTwo(here(t.TempDir())); got != want { + t.Errorf("here %q: %v, want %v", v, got, want) + } + openCodeAt(t, "2.2.6") + wsl := place{spell: func(s string) string { return s }, version: v} + if got := openCodeTwo(wsl); got != want { + t.Errorf("wsl %q: %v, want %v", v, got, want) + } + } +} diff --git a/internal/agent/output_kept.go b/internal/agent/output_kept.go index 8682b753e..9dfd78317 100644 --- a/internal/agent/output_kept.go +++ b/internal/agent/output_kept.go @@ -156,7 +156,13 @@ func openCodeOutputsKept(path string, ms orderedJSON) { return } have := map[string]int{} - if raw, ok := edit.GetJSON(path, "provider."+magpieID+".models"); ok { + // under providers where the file keeps it there alone: OpenCode 2's, + // whose limit is OpenCode 1's + raw, ok := edit.GetJSON(path, "provider."+magpieID+".models") + if !ok { + raw, ok = edit.GetJSON(path, openCodeNativeKey+".models") + } + if ok { var cur map[string]struct { Limit struct { Output int `json:"output"` diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index 49b543ce0..b600c74f3 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -562,7 +562,9 @@ var wslKinds = []wslKind{ // this machine, at their default folders: the distro's variables that // move them (OPENCODE_CONFIG_DIR, KIMI_CODE_HOME, HERMES_HOME, …) // aren't read. Each one's restart advice is its own Notice's. - {id: "opencode", name: "OpenCode", dir: ".config/opencode", bin: "opencode", in: opencodeIn, + // its version says whether its config is written in OpenCode 2's words + // (ocFile) + {id: "opencode", name: "OpenCode", dir: ".config/opencode", bin: "opencode", in: opencodeIn, version: true, restart: newNotice("{agent} in WSL {distro} reads its config at start-up — restart open opencode sessions to use this."), asleep: wslOwnAsleep("opencode", "model", "small")}, {id: "mimocode", name: "MiMo Code", dir: ".config/mimocode", bin: "mimo", in: mimocodeIn, diff --git a/site/public/docs/ja/opencode-models.html b/site/public/docs/ja/opencode-models.html index 56d6e0cba..4a9e14f05 100644 --- a/site/public/docs/ja/opencode-models.html +++ b/site/public/docs/ja/opencode-models.html @@ -219,7 +219,7 @@ magpie opencode small deepseek/deepseek-v4-flash # small_model provider.magpie.options.apiKeyゲートウェイのキー provider.magpie.modelsmagpie が OpenCode に見せるすべてのモデル -

各モデルにはコンテキストウィンドウと出力の上限(OpenCode が圧縮のタイミングを判断するのに使います)、画像を受け付けるかどうか、推論レベル、料金が入ります。プロバイダやアカウントを追加すると、magpie がこの一覧を更新します。ファイルの providers(OpenCode 2 の書き方)にもこのプロバイダがあれば、そちらにも書き込みます。Windows の WSL ディストリビューション内の OpenCode も同じように設定され、そのディストリビューションの ~/.config/opencode に書き込みます。

+

各モデルにはコンテキストウィンドウと出力の上限(OpenCode が圧縮のタイミングを判断するのに使います)、画像を受け付けるかどうか、推論レベル、料金が入ります。プロバイダやアカウントを追加すると、magpie がこの一覧を更新します。OpenCode 2 がインストールされていれば、OpenCode 2 自身のキーで書き込みます。プロバイダは providers.magpie、small モデルは agents.title.model です。Windows の WSL ディストリビューション内の OpenCode も同じように設定され、そのディストリビューションの ~/.config/opencode に書き込みます。

推論レベルと料金