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.
This commit is contained in:
@@ -71,6 +71,7 @@ something else shows up as drift.
|
||||
- An IDE opens a WSL project through the distro's own environment, and starts Air's agent there: a Windows `command` is refused as "ACP executable belongs to a different environment" (`AcpAgentLauncher` in the air plugin of IDEA 2026.3, build 263.7307.200), which the agent list shows as "Magpie does not run" (@yanghonghang on X). `env` values are passed as written, so one entry can't serve both. `air-ide` therefore also writes a `Magpie (WSL <distro>)` entry for each running distro whose probe found OpenCode on its own `PATH` (`distro.Paths`): the command is OpenCode's path as `\\wsl.localhost` opens it, which has the distro's environment, and `OPENCODE_CONFIG` is a Linux path to a `magpie-opencode.json` in the distro's `~/.jetbrains`, with magpie's provider at the address and key that distro reaches the gateway with (`distro.base`, `keyAt`). Sync follows a changed address and adds a distro found later once; a stopped distro is never opened for it; turning Magpie off removes the entries and the configs of running distros (`air_wsl.go`, `TestAirIDEAddsMagpieAgentForWSLProjects`). Not run with a real IDE: no JetBrains IDE is on the Windows test box, so the launch is read from the plugin's bytecode.
|
||||
- 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`).
|
||||
- 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 finds magpie's models itself (chawyehsu on X, after yuhp/opencode-models-discovery; [`opencode_discover.go`](../../internal/agent/opencode_discover.go)). For an OpenCode that loads plugins of today's shape (1.4.0 and later, 2.0.5 and later: `openCodeDiscovers`), magpie's provider in `opencode.json` has no `models`, and magpie writes `plugins/magpie-models.js` beside it ([`opencode_models.js`](../../internal/agent/opencode_models.js)), which OpenCode loads from its config folder. As OpenCode starts, the plugin asks the gateway's `/v1/models?format=opencode` (`opencode2` for OpenCode 2; [`opencode_models.go`](../../internal/gateway/opencode_models.go)), the same entries a sync would have listed, in magpie's order, only those the key may use. OpenCode 1 gets them through its `config` hook, which runs before it reads its providers; OpenCode 2 through `ctx.model.transform`, under the config's own entries, with `variants: []` so it makes up none. A model under magpie's provider in the file is the user's: its fields are laid over magpie's, and an id magpie doesn't list stays. With the gateway not answering (3s), the plugin lists what magpie had when it last wrote it. Moving a file that has the list: the first sync takes out what magpie wrote and keeps of each model only what says other than magpie's (a variant, a `limit.output` of the user's; `modelsLeft`), and ids magpie doesn't list go that once (the stash's `opencode-discover:<path>`); after that they are the user's. An OpenCode older than those versions, or of no known version, a WSL distro's with no version, and the forks (mimocode, DevEco, Air) keep the list in the file; going back to such an OpenCode writes the list again and removes the plugin, and so does taking magpie out. OpenChamber writes the same file and takes the same decision. A file at the plugin's path without magpie's first line is the user's and is never touched. `TestOpenCodeFindsMagpiesModels`, `TestOpenCodeListMovesToThePlugin`, `TestOpenCodePluginRuns`, `TestOpenCodeModelsList`.
|
||||
- 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 `<level>-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.
|
||||
|
||||
@@ -1265,7 +1265,7 @@ func openCodeLike(at place, id, name, icon, bin, dir, auth string, ua []string,
|
||||
block := func() any { return magpieProviderJSONAt("opencode", id, at.gw()) }
|
||||
// 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} }
|
||||
file := func() ocFile { return openCodeFileAt(at, path, id, 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+"/")
|
||||
@@ -1296,7 +1296,10 @@ func openCodeLike(at place, id, name, icon, bin, dir, auth string, ua []string,
|
||||
if onMagpie() {
|
||||
return nil
|
||||
}
|
||||
return edit.DelJSON(path, "provider."+magpieID, openCodeNativeKey)
|
||||
if err := edit.DelJSON(path, "provider."+magpieID, openCodeNativeKey); err != nil {
|
||||
return err
|
||||
}
|
||||
return openCodePluginGone(path)
|
||||
}
|
||||
v, err := openCodeRefAt(at, path, id, v)
|
||||
if err != nil {
|
||||
@@ -1359,7 +1362,7 @@ func openCodeRefAt(at place, path, id, v string) (string, error) {
|
||||
return own + "/" + ref, nil
|
||||
}
|
||||
block := func() any { return magpieProviderJSONAt("opencode", id, at.gw()) }
|
||||
return v, ocFile{path: path, two: id == "opencode" && openCodeTwo(at), block: block}.sync(true)
|
||||
return v, openCodeFileAt(at, path, id, block).sync(true)
|
||||
}
|
||||
|
||||
// ownGatewayProvider is the provider in an OpenCode config, other than
|
||||
|
||||
@@ -168,7 +168,7 @@ func openChamber(home, cfg string) *Agent {
|
||||
// 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} }
|
||||
file := func() ocFile { return openCodeFileAt(here(""), ocPath, "opencode", 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+"/")
|
||||
@@ -181,7 +181,10 @@ func openChamber(home, cfg string) *Agent {
|
||||
if usesMagpie(m, file().small(), s.model(), s.small()) {
|
||||
return nil
|
||||
}
|
||||
return edit.DelJSON(ocPath, "provider."+magpieID, openCodeNativeKey)
|
||||
if err := edit.DelJSON(ocPath, "provider."+magpieID, openCodeNativeKey); err != nil {
|
||||
return err
|
||||
}
|
||||
return openCodePluginGone(ocPath)
|
||||
}
|
||||
return &Agent{
|
||||
ID: "openchamber", Name: "OpenChamber", Icon: "openchamber", Aliases: []string{"chamber"}, Spelled: openCodeSpelled(ocPath, gatewayV1),
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
)
|
||||
|
||||
func TestOpenCodeDiscoversFrom(t *testing.T) {
|
||||
for v, want := range map[string]bool{
|
||||
"": false, "junk": false, "0.15.0": false, "1.2.0": false, "1.3.9": false,
|
||||
"1.4.0": true, "1.19.6": true, "v1.19.6": true, "2.0.0": false, "2.0.4": false,
|
||||
"2.0.5": true, "2.3.2": true, "2.10.0": true, "3.0.0": true,
|
||||
} {
|
||||
if got := openCodeDiscovers(v); got != want {
|
||||
t.Errorf("openCodeDiscovers(%q) = %v, want %v", v, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pluginOf is magpie's plugin beside the OpenCode config at path, "" with
|
||||
// none.
|
||||
func pluginOf(path string) string {
|
||||
b, _ := os.ReadFile(openCodePluginPath(path))
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// modelsUnder is the file's models under key, by id.
|
||||
func modelsUnder(t *testing.T, path, key string) map[string]any {
|
||||
t.Helper()
|
||||
raw, ok := edit.GetJSON(path, key+".models")
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(raw), &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// chawyehsu on X: OpenCode finds magpie's models itself, as
|
||||
// yuhp/opencode-models-discovery does, so opencode.json has no list of
|
||||
// them. For an OpenCode that loads plugins so, magpie's provider is in
|
||||
// the file without models, and magpie's plugin, with the list it falls
|
||||
// back on, beside it; both go when magpie's provider does.
|
||||
func TestOpenCodeFindsMagpiesModels(t *testing.T) {
|
||||
for _, c := range []struct{ version, key string }{{"1.19.6", "provider." + magpieID}, {"2.3.2", openCodeNativeKey}} {
|
||||
t.Run(c.version, func(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
reasonCatalog(t)
|
||||
openCodeAt(t, c.version)
|
||||
oc := opencode(home, filepath.Join(home, ".config"))
|
||||
if err := oc.Apply("model", "magpie/think/deep"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := readFile(oc.Path)
|
||||
if _, ok := edit.GetJSON(oc.Path, c.key); !ok {
|
||||
t.Fatalf("no %s:\n%s", c.key, raw)
|
||||
}
|
||||
if ms, ok := edit.GetJSON(oc.Path, c.key+".models"); ok {
|
||||
t.Fatalf("models listed in the file: %s", ms)
|
||||
}
|
||||
p := pluginOf(oc.Path)
|
||||
if !strings.HasPrefix(p, openCodePluginMark) {
|
||||
t.Fatalf("no plugin of magpie's: %q", p)
|
||||
}
|
||||
for _, w := range []string{`"think/deep"`, `"think/new"`, `"rsn/plan"`, gatewayV1(), `"v1":`, `"v2":`} {
|
||||
if !strings.Contains(p, w) {
|
||||
t.Fatalf("the plugin has no %s:\n%s", w, p)
|
||||
}
|
||||
}
|
||||
if strings.Contains(p, "__MAGPIE__") {
|
||||
t.Fatal("the plugin's list was never filled in")
|
||||
}
|
||||
if off := oc.Check(); off != "" {
|
||||
t.Fatalf("Check: %s", off)
|
||||
}
|
||||
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)
|
||||
}
|
||||
if err := oc.Apply("model", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v, ok := edit.GetJSON(oc.Path, c.key); ok {
|
||||
t.Fatalf("%s left: %s", c.key, v)
|
||||
}
|
||||
if _, err := os.Stat(openCodePluginPath(oc.Path)); !os.IsNotExist(err) {
|
||||
t.Fatalf("the plugin outlived magpie's provider: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An OpenCode that doesn't load such a plugin (before 1.4, 2.0.0 to
|
||||
// 2.0.4), or of a version magpie can't tell, has the list in the file as
|
||||
// before; and one moving back to such an OpenCode gets the list back and
|
||||
// magpie's plugin taken away.
|
||||
func TestOpenCodeBeforePluginsKeepsTheList(t *testing.T) {
|
||||
for _, v := range []string{"", "1.3.9", "2.0.4"} {
|
||||
t.Run("v"+v, func(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
reasonCatalog(t)
|
||||
openCodeAt(t, "2.3.2")
|
||||
oc := opencode(home, filepath.Join(home, ".config"))
|
||||
if err := oc.Apply("model", "magpie/think/deep"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pluginOf(oc.Path) == "" {
|
||||
t.Fatal("no plugin for 2.3.2")
|
||||
}
|
||||
openCodeAt(t, v)
|
||||
if err := oc.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := "provider." + magpieID
|
||||
if strings.HasPrefix(v, "2.") {
|
||||
key = openCodeNativeKey
|
||||
}
|
||||
ms := modelsUnder(t, oc.Path, key)
|
||||
for _, id := range []string{"think/deep", "think/new", "rsn/plan"} {
|
||||
if ms[id] == nil {
|
||||
t.Fatalf("no %s under %s:\n%s", id, key, readFile(oc.Path))
|
||||
}
|
||||
}
|
||||
if p := pluginOf(oc.Path); p != "" {
|
||||
t.Fatalf("the plugin stayed for %q", v)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A config magpie wrote the list into moves: magpie's models go, and of
|
||||
// them only what the user said stays (a variant of theirs, a reply limit
|
||||
// they typed, with the rest of that limit), with a model magpie no
|
||||
// longer lists gone, the user's other providers and options untouched. A
|
||||
// model the user adds afterwards is theirs.
|
||||
func TestOpenCodeListMovesToThePlugin(t *testing.T) {
|
||||
for _, c := range []struct{ version, key string }{{"1.19.6", "provider." + magpieID}, {"2.3.2", openCodeNativeKey}} {
|
||||
t.Run(c.version, func(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
reasonCatalog(t)
|
||||
old := "1.3.9"
|
||||
if strings.HasPrefix(c.version, "2.") {
|
||||
old = "2.0.4"
|
||||
}
|
||||
openCodeAt(t, old)
|
||||
oc := opencode(home, filepath.Join(home, ".config"))
|
||||
if err := oc.Apply("model", "magpie/think/deep"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the user's own: a provider, a timeout, a variant, a reply
|
||||
// limit; and a model of magpie's from before
|
||||
mine := map[string]any{"reasoningEffort": "low", "temperature": 0.3}
|
||||
var variant any = mine
|
||||
if strings.HasPrefix(c.version, "2.") {
|
||||
variant = map[string]any{"id": "mine", "settings": mine}
|
||||
ms := modelsUnder(t, oc.Path, c.key)
|
||||
deep := ms["think/deep"].(map[string]any)
|
||||
deep["variants"] = append(deep["variants"].([]any), variant)
|
||||
if err := edit.SetJSON(oc.Path, edit.KV{Path: c.key + ".models", Value: ms}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if err := edit.SetJSON(oc.Path, edit.KV{Path: c.key + ".models.think/deep.variants.mine", Value: variant}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings := "options"
|
||||
if strings.HasPrefix(c.version, "2.") {
|
||||
settings = "settings"
|
||||
}
|
||||
if err := edit.SetJSON(oc.Path,
|
||||
edit.KV{Path: c.key + ".models.rsn/plan.limit.output", Value: 1234},
|
||||
edit.KV{Path: c.key + ".models.gone/old", Value: map[string]any{"name": "old"}},
|
||||
edit.KV{Path: c.key + "." + settings + ".timeout", Value: 600000},
|
||||
edit.KV{Path: "provider.other", Value: map[string]any{"npm": "@ai-sdk/openai-compatible", "models": map[string]any{"x": map[string]any{}}}},
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
openCodeAt(t, c.version)
|
||||
if err := oc.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := readFile(oc.Path)
|
||||
ms := modelsUnder(t, oc.Path, c.key)
|
||||
if ms["gone/old"] != nil || ms["think/new"] != nil {
|
||||
t.Fatalf("magpie's models stayed:\n%s", raw)
|
||||
}
|
||||
deep, _ := ms["think/deep"].(map[string]any)
|
||||
if _, has := deep["name"]; has {
|
||||
t.Fatalf("magpie's fields stayed on think/deep:\n%s", raw)
|
||||
}
|
||||
if strings.HasPrefix(c.version, "2.") {
|
||||
vs, _ := deep["variants"].([]any)
|
||||
if len(vs) != 1 || !sameJSONValue(vs[0], variant) {
|
||||
t.Fatalf("think/deep's variants %v, want the user's alone:\n%s", vs, raw)
|
||||
}
|
||||
} else {
|
||||
vs, _ := deep["variants"].(map[string]any)
|
||||
if len(vs) != 1 || !sameJSONValue(vs["mine"], variant) {
|
||||
t.Fatalf("think/deep's variants %v, want the user's alone:\n%s", vs, raw)
|
||||
}
|
||||
}
|
||||
plan, _ := ms["rsn/plan"].(map[string]any)
|
||||
// the limit stays whole, which OpenCode 1 needs ("Missing key
|
||||
// …limit.context" for one without its context, 1.19.6)
|
||||
if l, _ := plan["limit"].(map[string]any); l == nil || l["output"] != float64(1234) || l["context"] != float64(200000) {
|
||||
t.Fatalf("rsn/plan's own limit.output lost, or its limit not whole:\n%s", raw)
|
||||
}
|
||||
if v, _ := edit.GetJSON(oc.Path, c.key+"."+settings+".timeout"); v != "600000" {
|
||||
t.Fatalf("the user's timeout = %q:\n%s", v, raw)
|
||||
}
|
||||
if _, ok := edit.GetJSON(oc.Path, "provider.other.models.x"); !ok {
|
||||
t.Fatalf("the user's provider changed:\n%s", raw)
|
||||
}
|
||||
if pluginOf(oc.Path) == "" {
|
||||
t.Fatal("no plugin")
|
||||
}
|
||||
// a model the user adds now is theirs
|
||||
if err := edit.SetJSON(oc.Path, edit.KV{Path: c.key + ".models.local/own", Value: map[string]any{"name": "own"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := oc.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if modelsUnder(t, oc.Path, c.key)["local/own"] == nil {
|
||||
t.Fatalf("the user's model went:\n%s", readFile(oc.Path))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A file at the plugin's path magpie didn't write is the user's: never
|
||||
// written over, and never removed.
|
||||
func TestOpenCodeUsersOwnPluginStays(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
reasonCatalog(t)
|
||||
openCodeAt(t, "1.19.6")
|
||||
oc := opencode(home, filepath.Join(home, ".config"))
|
||||
path := openCodePluginPath(oc.Path)
|
||||
os.MkdirAll(filepath.Dir(path), 0o755)
|
||||
const own = "export default {}\n"
|
||||
if err := os.WriteFile(path, []byte(own), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := oc.Apply("model", "magpie/think/deep"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := pluginOf(oc.Path); got != own {
|
||||
t.Fatalf("the user's file written over: %q", got)
|
||||
}
|
||||
if err := oc.Apply("model", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := pluginOf(oc.Path); got != own {
|
||||
t.Fatalf("the user's file removed: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The plugin as OpenCode runs it (opencode_models.js, under node): for
|
||||
// OpenCode 1 its config hook fills magpie's provider from the gateway,
|
||||
// the user's fields over magpie's and a model of theirs kept; for OpenCode
|
||||
// 2 its transform does, every model with variants; with the gateway down,
|
||||
// both fall back on the list in the file.
|
||||
func TestOpenCodePluginRuns(t *testing.T) {
|
||||
node, err := exec.LookPath("node")
|
||||
if err != nil {
|
||||
t.Skip("no node to run the plugin")
|
||||
}
|
||||
home, _ := codexHome(t, "", "")
|
||||
reasonCatalog(t)
|
||||
src := openCodePluginFor(magpieProviderJSONAt("opencode", "opencode", "http://127.0.0.1:1"))
|
||||
plugin := filepath.Join(home, "magpie-models.mjs")
|
||||
if err := os.WriteFile(plugin, []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
served, _ := json.Marshal(map[string]any{"opencode": map[string]any{"models": []any{
|
||||
map[string]any{"id": "live/one", "entry": map[string]any{"name": "One", "limit": map[string]any{"context": 1000, "output": 100}, "variants": map[string]any{"high": map[string]any{"reasoningEffort": "high"}}}},
|
||||
}}, "opencode2": map[string]any{"models": []any{
|
||||
map[string]any{"id": "live/one", "entry": map[string]any{"name": "One", "limit": map[string]any{"context": 1000, "output": 100}, "variants": []any{}}},
|
||||
}}})
|
||||
run := func(mode string) map[string]any {
|
||||
t.Helper()
|
||||
abs, _ := filepath.Abs(filepath.Join("testdata", "opencode", "drive-plugin.mjs"))
|
||||
cmd := exec.Command(node, abs, plugin, mode)
|
||||
cmd.Env = append(os.Environ(), "MAGPIE_SERVED="+string(served))
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v\n%s", mode, err, out)
|
||||
}
|
||||
var r map[string]any
|
||||
if err := json.Unmarshal(out, &r); err != nil {
|
||||
t.Fatalf("%s: %v\n%s", mode, err, out)
|
||||
}
|
||||
return r
|
||||
}
|
||||
get := func(v any, path ...string) any {
|
||||
for _, k := range path {
|
||||
m, _ := v.(map[string]any)
|
||||
v = m[k]
|
||||
}
|
||||
return v
|
||||
}
|
||||
// OpenCode 1, gateway up
|
||||
r := run("v1-up")
|
||||
if get(r, "live/one", "name") != "One" || get(r, "live/one", "limit", "output") != float64(4321) ||
|
||||
get(r, "live/one", "limit", "context") != float64(1000) || get(r, "live/one", "variants", "high", "reasoningEffort") != "high" ||
|
||||
get(r, "live/one", "variants", "mine", "temperature") != 0.5 || get(r, "local/own", "name") != "own" || r["think/deep"] != nil {
|
||||
t.Fatalf("OpenCode 1, magpie up: %v", r)
|
||||
}
|
||||
// down: the list the file has
|
||||
r = run("v1-down")
|
||||
if get(r, "think/deep", "name") == nil || get(r, "rsn/plan", "name") == nil || get(r, "local/own", "name") != "own" || get(r, "live/one", "name") != nil {
|
||||
t.Fatalf("OpenCode 1, magpie down: %v", r)
|
||||
}
|
||||
r = run("v2-up")
|
||||
if get(r, "live/one", "name") != "One" || get(r, "live/one", "limit", "context") != float64(1000) || r["think/deep"] != nil {
|
||||
t.Fatalf("OpenCode 2, magpie up: %v", r)
|
||||
}
|
||||
if vs, ok := get(r, "live/one", "variants").([]any); !ok || len(vs) != 0 {
|
||||
t.Fatalf("OpenCode 2's variants: %v", r)
|
||||
}
|
||||
r = run("v2-down")
|
||||
if get(r, "think/deep", "name") == nil || get(r, "rsn/plan", "name") == nil {
|
||||
t.Fatalf("OpenCode 2, magpie down: %v", r)
|
||||
}
|
||||
if vs, ok := get(r, "think/deep", "variants").([]any); !ok || len(vs) == 0 {
|
||||
t.Fatalf("OpenCode 2's think/deep has no variants: %v", r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// magpie: written by magpie; it is rewritten as magpie's models change and removed with magpie's provider
|
||||
//
|
||||
// Fills the models of magpie's provider from magpie itself as OpenCode
|
||||
// starts: OpenCode 1 through its config hook, OpenCode 2 through a model
|
||||
// transform. A model in opencode.json under magpie's provider is the
|
||||
// user's: its fields win over magpie's, and one magpie doesn't list stays.
|
||||
// With magpie not answering, the list magpie had when it wrote this file.
|
||||
const M = __MAGPIE__
|
||||
const ID = "magpie"
|
||||
|
||||
const plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v)
|
||||
|
||||
// over's fields over base's, objects merged alike
|
||||
const merge = (base, over) => {
|
||||
if (!plain(base) || !plain(over)) return over === undefined ? base : over
|
||||
const out = { ...base }
|
||||
for (const [k, v] of Object.entries(over)) out[k] = merge(base[k], v)
|
||||
return out
|
||||
}
|
||||
|
||||
// magpie's models as [{id, entry}] in its order, null when it can't say
|
||||
const fetchList = async (baseURL, apiKey, format) => {
|
||||
if (typeof baseURL !== "string" || !baseURL) return null
|
||||
try {
|
||||
const res = await fetch(baseURL.replace(/\/+$/, "") + "/models?format=" + format, {
|
||||
headers: apiKey ? { authorization: "Bearer " + apiKey } : {},
|
||||
signal: AbortSignal.timeout(3000),
|
||||
})
|
||||
if (!res.ok) return null
|
||||
const body = await res.json()
|
||||
return Array.isArray(body?.models) ? body.models : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
id: "magpie.models",
|
||||
|
||||
// OpenCode 1: the config hook runs before OpenCode reads its providers
|
||||
server: async () => ({
|
||||
config: async (cfg) => {
|
||||
const p = cfg?.provider?.[ID]
|
||||
if (!plain(p)) return
|
||||
const o = plain(p.options) ? p.options : {}
|
||||
const list = (await fetchList(o.baseURL ?? M.baseURL, o.apiKey ?? M.apiKey, "opencode")) ?? M.v1
|
||||
const mine = plain(p.models) ? p.models : {}
|
||||
const out = {}
|
||||
for (const { id, entry } of list) out[id] = id in mine ? merge(entry, mine[id]) : structuredClone(entry)
|
||||
for (const [id, m] of Object.entries(mine)) if (!(id in out)) out[id] = m
|
||||
p.models = out
|
||||
},
|
||||
}),
|
||||
|
||||
// OpenCode 2: the config's own models are laid over these afterwards
|
||||
setup: async (ctx) => {
|
||||
const models = ctx?.model?.transform ? ctx.model : ctx?.catalog
|
||||
if (!models?.transform) return
|
||||
let s = {}
|
||||
try {
|
||||
const got = await ctx.provider.get({ providerID: ID })
|
||||
const info = got?.data ?? got
|
||||
if (plain(info?.settings)) s = info.settings
|
||||
} catch {}
|
||||
const list = (await fetchList(s.baseURL ?? M.baseURL, s.apiKey ?? M.apiKey, "opencode2")) ?? M.v2
|
||||
await models.transform((ed) => {
|
||||
if (ed.provider?.get && !ed.provider.get(ID)) return
|
||||
for (const { id, entry } of list)
|
||||
ed.update(ID, id, (m) => {
|
||||
m.name = entry.name ?? m.name
|
||||
if (plain(entry.capabilities)) m.capabilities = { ...m.capabilities, ...entry.capabilities }
|
||||
if (plain(entry.limit)) m.limit = { ...m.limit, ...entry.limit }
|
||||
if (Array.isArray(entry.cost)) m.cost = structuredClone(entry.cost)
|
||||
m.variants = Array.isArray(entry.variants) ? structuredClone(entry.variants) : []
|
||||
})
|
||||
})
|
||||
},
|
||||
}
|
||||
@@ -54,8 +54,13 @@ func openCodeNative(block any) any {
|
||||
}
|
||||
// in the order magpie lists them (#4575): OpenCode lists a provider's
|
||||
// models in the file's key order
|
||||
// and none where the block has none (OpenCode's magpie plugin lists
|
||||
// them: opencode_discover.go)
|
||||
in, listed := b["models"].(orderedJSON)
|
||||
if !listed {
|
||||
return out
|
||||
}
|
||||
ms := orderedJSON{}
|
||||
in, _ := b["models"].(orderedJSON)
|
||||
for _, p := range in {
|
||||
m, _ := p.v.(map[string]any)
|
||||
e := map[string]any{"name": m["name"]}
|
||||
|
||||
@@ -4,8 +4,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"maps"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
)
|
||||
@@ -27,13 +25,8 @@ var openCodeVersion = func() string { return (&Agent{ID: "opencode", Bin: "openc
|
||||
// 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
|
||||
n, ok := openCodeVersionParts(openCodeVersionAt(at))
|
||||
return ok && n[0] >= 2
|
||||
}
|
||||
|
||||
// openCodeTitleKey is where OpenCode 2 keeps the model it titles sessions
|
||||
@@ -44,16 +37,65 @@ const openCodeTitleKey = "agents.title.model"
|
||||
// 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
|
||||
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
|
||||
|
||||
@@ -69,7 +69,7 @@ func nativeOnly(t *testing.T, path string, models ...string) {
|
||||
func TestOpenCode2WritesItsOwnWords(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
reasonCatalog(t)
|
||||
openCodeAt(t, "2.2.6")
|
||||
openCodeAt(t, "2.0.4") // one that has the list in its file (openCodeDiscovers); the plugin's list says the same words
|
||||
oc := opencode(home, filepath.Join(home, ".config"))
|
||||
if err := oc.Apply("model", "magpie/rsn/plan"); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -131,7 +131,7 @@ func TestOpenCode2WritesItsOwnWords(t *testing.T) {
|
||||
func TestOpenCode1KeepsItsWords(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
reasonCatalog(t)
|
||||
openCodeAt(t, "1.19.5")
|
||||
openCodeAt(t, "1.3.9") // one that has the list in its file (openCodeDiscovers); the plugin's list says the same words
|
||||
oc := opencode(home, filepath.Join(home, ".config"))
|
||||
if err := oc.Apply("model", "magpie/rsn/plan"); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -261,7 +261,7 @@ func TestOpenCode2LeavesTheirSmallModel(t *testing.T) {
|
||||
func TestOpenChamberAndOpenCode2AgreeOnWords(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
reasonCatalog(t)
|
||||
openCodeAt(t, "2.2.6")
|
||||
openCodeAt(t, "2.0.4") // one that has the list in its file (openCodeDiscovers); the plugin's list says the same words
|
||||
writeFile(t, filepath.Join(home, ".config", "openchamber", "settings.json"), `{}`)
|
||||
ch := openChamber(home, filepath.Join(home, ".config"))
|
||||
oc := opencode(home, filepath.Join(home, ".config"))
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// Runs magpie's OpenCode plugin (argv[2]) as OpenCode would, mode argv[3]:
|
||||
// v1-up, v1-down (OpenCode 1's config hook), v2-up, v2-down (OpenCode 2's
|
||||
// model transform), with the gateway answering MAGPIE_SERVED or down.
|
||||
// Prints magpie's provider's models.
|
||||
import { pathToFileURL } from "node:url"
|
||||
|
||||
const [, , plugin, mode] = process.argv
|
||||
const served = JSON.parse(process.env.MAGPIE_SERVED || "{}")
|
||||
globalThis.fetch = async (url, opts) => {
|
||||
if (mode.endsWith("-down")) throw new Error("connection refused")
|
||||
const format = new URL(url).searchParams.get("format")
|
||||
if (!opts?.headers?.authorization?.startsWith("Bearer ")) return { ok: false, status: 401 }
|
||||
return { ok: true, json: async () => served[format] }
|
||||
}
|
||||
const mod = (await import(pathToFileURL(plugin).href)).default
|
||||
|
||||
if (mode.startsWith("v1")) {
|
||||
const hooks = await mod.server({}, {})
|
||||
const cfg = {
|
||||
provider: {
|
||||
magpie: {
|
||||
npm: "@ai-sdk/openai-compatible",
|
||||
options: {},
|
||||
models: {
|
||||
"live/one": { limit: { output: 4321 }, variants: { mine: { temperature: 0.5 } } },
|
||||
"local/own": { name: "own" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
await hooks.config(cfg)
|
||||
console.log(JSON.stringify(cfg.provider.magpie.models))
|
||||
} else {
|
||||
const models = {}
|
||||
const editor = {
|
||||
provider: { get: (id) => (id === "magpie" ? { provider: { id }, models: [] } : undefined) },
|
||||
update: (p, m, fn) => {
|
||||
if (p !== "magpie") return
|
||||
const cur = models[m] ?? {
|
||||
id: m, name: m, variants: [], cost: [],
|
||||
capabilities: { tools: true, input: ["text", "image"], output: ["text"] },
|
||||
limit: { context: 200000, output: 32000 },
|
||||
}
|
||||
fn(cur)
|
||||
models[m] = cur
|
||||
},
|
||||
}
|
||||
await mod.setup({
|
||||
model: { transform: async (cb) => { cb(editor); return { dispose() {} } } },
|
||||
provider: { get: async () => ({ location: "test", data: { id: "magpie", settings: {} } }) },
|
||||
})
|
||||
console.log(JSON.stringify(models))
|
||||
}
|
||||
@@ -1781,6 +1781,11 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) {
|
||||
antigravityModels(w, r)
|
||||
return
|
||||
}
|
||||
// OpenCode's magpie plugin's (opencode_models.go)
|
||||
if f := r.URL.Query().Get("format"); f == OpenCodeFormat || f == OpenCode2Format {
|
||||
openCodeModels(w, r, f == OpenCode2Format)
|
||||
return
|
||||
}
|
||||
if waitsForList(r) {
|
||||
// another magpie waiting for the list to change (models_wait.go)
|
||||
s.modelsOnceChanged(w, r)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// The /v1/models formats OpenCode's magpie plugin reads (the agent
|
||||
// package's opencode_models.js): each of magpie's models for OpenCode as
|
||||
// opencode.json would list it under magpie's provider, in OpenCode 1's
|
||||
// words (OpenCodeFormat) or OpenCode 2's (OpenCode2Format). The plugin
|
||||
// fills magpie's provider with them as OpenCode starts, so OpenCode
|
||||
// follows magpie's models without a list of them in its config
|
||||
// (chawyehsu on X).
|
||||
const (
|
||||
OpenCodeFormat = "opencode"
|
||||
OpenCode2Format = "opencode2"
|
||||
)
|
||||
|
||||
// OpenCodeModel is one model of OpenCode's list: its id and its entry as
|
||||
// the config would have it.
|
||||
type OpenCodeModel struct {
|
||||
ID string `json:"id"`
|
||||
Entry any `json:"entry"`
|
||||
}
|
||||
|
||||
// OpenCodeModels is magpie's models for OpenCode, in OpenCode 2's words
|
||||
// when two; set by the agent package, which writes OpenCode's config.
|
||||
var OpenCodeModels func(two bool) []OpenCodeModel
|
||||
|
||||
// openCodeModels answers /v1/models?format=opencode and =opencode2:
|
||||
// {"models": [{"id", "entry"}]}, a list so the order stays magpie's (a
|
||||
// JSON object's integer-like keys come first in JavaScript). Only the
|
||||
// models of OpenCode's catalog the key asking may use (keyListed).
|
||||
func openCodeModels(w http.ResponseWriter, r *http.Request, two bool) {
|
||||
list := []OpenCodeModel{}
|
||||
if OpenCodeModels != nil {
|
||||
list = OpenCodeModels(two)
|
||||
}
|
||||
shown, _ := provider.CatalogFor("opencode")
|
||||
may := map[string]bool{}
|
||||
for _, e := range keyListed(r, shown, provider.ModelOff("opencode")) {
|
||||
may[e.ID] = true
|
||||
}
|
||||
out := make([]OpenCodeModel, 0, len(list))
|
||||
for _, m := range list {
|
||||
if may[m.ID] {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, 200, map[string]any{"models": out})
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// OpenCode's magpie plugin fills magpie's provider from
|
||||
// /v1/models?format=opencode (opencode2 for OpenCode 2): {"models": [{id,
|
||||
// entry}]}, the agent package's entries in magpie's order, never cached,
|
||||
// and only the models of OpenCode's catalog the key asking may use.
|
||||
func TestOpenCodeModelsList(t *testing.T) {
|
||||
setup(t, provider.Anthropic, &fake{})
|
||||
for _, id := range []string{"ds", "other"} {
|
||||
if err := provider.Save(provider.Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"big", "plain"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := catalog.SaveLive(id, "http://127.0.0.1:1/v1", []catalog.Model{{ID: "big", Context: 1048576}, {ID: "plain"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
was := OpenCodeModels
|
||||
t.Cleanup(func() { OpenCodeModels = was })
|
||||
var asked []bool
|
||||
OpenCodeModels = func(two bool) []OpenCodeModel {
|
||||
asked = append(asked, two)
|
||||
return []OpenCodeModel{
|
||||
{ID: "other/plain", Entry: map[string]any{"name": "Plain", "two": two}},
|
||||
{ID: "ds/big", Entry: map[string]any{"name": "Big"}},
|
||||
{ID: "nowhere/x", Entry: map[string]any{"name": "not in OpenCode's catalog"}},
|
||||
}
|
||||
}
|
||||
keys, secrets := newCaller(t, "Held")
|
||||
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"ds/*"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := New().Handler()
|
||||
get := func(format, secret string) []string {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest("GET", "/v1/models?format="+format, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+secret)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%s: %d %s", format, rec.Code, rec.Body)
|
||||
}
|
||||
if cc := rec.Header().Get("Cache-Control"); cc != "no-store" {
|
||||
t.Errorf("Cache-Control %q", cc)
|
||||
}
|
||||
var got struct {
|
||||
Models []struct {
|
||||
ID string `json:"id"`
|
||||
Entry map[string]any `json:"entry"`
|
||||
} `json:"models"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil || got.Models == nil {
|
||||
t.Fatalf("not OpenCode's list: %s", rec.Body)
|
||||
}
|
||||
var ids []string
|
||||
for _, m := range got.Models {
|
||||
if m.Entry["name"] == nil {
|
||||
t.Errorf("%s has no entry: %s", m.ID, rec.Body)
|
||||
}
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
local := TokenFor("opencode")
|
||||
if ids := get(OpenCodeFormat, local); !slices.Equal(ids, []string{"other/plain", "ds/big"}) {
|
||||
t.Fatalf("opencode lists %v", ids)
|
||||
}
|
||||
if ids := get(OpenCode2Format, local); !slices.Equal(ids, []string{"other/plain", "ds/big"}) {
|
||||
t.Fatalf("opencode2 lists %v", ids)
|
||||
}
|
||||
if !slices.Equal(asked, []bool{false, true}) {
|
||||
t.Fatalf("asked for %v", asked)
|
||||
}
|
||||
if ids := get(OpenCodeFormat, secrets[0]); !slices.Equal(ids, []string{"ds/big"}) {
|
||||
t.Fatalf("a key held to ds/* is told of %v", ids)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user