Murciee (#3883, OpenCode 2.1.4 as OpenChamber bundles it, Windows): a model added in magpie never reached OpenCode 2, though magpie said it was exposed. ~/.config/opencode/opencode.json held magpie's provider twice, provider.magpie with 43 models and providers.magpie with 38, and opencode models listed the 38. 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 WARN in its log, "retained native value over legacy value" (packages/core/src/config/normalize.ts, mergeMaps, at v2.1.4). OpenChamber's provider form saves a provider under providers and takes it out of provider (packages/web/server/lib/opencode/config-v2.js, writeSectionEntry). Once it had saved magpie's, magpie's next sync put provider.magpie back, as a model of magpie's was picked, and from then on brought only that one up to date. Where an OpenCode config keeps magpie's provider under providers, each sync and model pick now write it there too, and the wiring check reads it there (opencode_providers.go). It is written as OpenCode 2 reads magpie's provider.magpie (packages/core/src/v1/config/migrate.ts, migrateStandardProvider and migrateModel): npm as package "aisdk:<npm>", options as settings, a model's modalities as capabilities beside tools, its variants a list of {id, settings, body} with the options OpenCode 2 reads itself in settings and the rest in body (provider-options.ts, COMPATIBLE_KEYS: a fast variant's service_tier), and reasoning, which it doesn't read, left out. As under provider (theirsKept, openCodeKept), magpie's models are written whole, a key of the user's in the block stays, and so does a variant the user put on a model of magpie's. A variant is magpie's when it says what magpie's of its name says, split as OpenCode 2 splits it or all in settings, as OpenChamber carries one over from provider (toModelVariants). A config without providers.magpie doesn't get one: provider.magpie is still what magpie writes, and OpenCode 1 and 2 both read it. Taking magpie out of OpenCode or OpenChamber takes out both blocks, as OpenChamber's own delete does. agent-wiring.md says so beside #2379's variants. Old data: a config already in the reporter's state is brought up to date by the next sync, which SyncCatalog runs over every agent at each start and update of magpie. A providers.magpie an older magpie left behind when taking magpie out (it took out provider.magpie alone) is kept up to date from now on, and goes the next time magpie is taken out. Not changed: - Air: its magpie-opencode.json is magpie's own and holds provider.magpie alone. With OpenChamber's providers.magpie in the global config and nothing else of magpie's there, OpenCode 2.1.4 handed Air's file as OPENCODE_CONFIG still listed the model only Air's file had. - MiMo Code and DevEco Code go through the same code. Their configs hold no providers block unless something of theirs writes one; not checked against their source. - A provider of the user's own at magpie's gateway kept under providers isn't read by openCodeSpelled and ownGatewayProvider, which read provider alone: #3915, filed with this. - What else OpenChamber's form puts on a model of magpie's under providers (a modelID, a cost) goes with the rest of the model at the next sync, as a key on one under provider does today. What was run (tree 61b3fff7, on origin/maine056779a, go1.26.8, linux/amd64, Linux 5.15), outside graftcp, umask 077: - TestOpenCodeNativeIsOpenCode2s, new: openCodeNative of a block with levels, fast variants, an image model and one without levels is what OpenCode 2.1.4's opencode debug config printed under providers.magpie for that block in an opencode.json (its apiKey, shown as ***, put back). - TestOpenCodeProvidersKeptCurrent and TestOpenChamberProvidersKeptCurrent, new: a config as OpenChamber's form leaves it, provider.magpie gone and providers.magpie from before think/new (a stale baseURL and key, a header and a timeout of the user's, a modelID, magpie's variants of levels deep no longer has, one of them in OpenChamber's form, one the user wrote over, one of their own, and a model the catalog dropped). A sync, and a model picked, bring it to the models under provider with the user's keys and two variants kept; a second sync writes nothing; stepping off magpie takes out both. A config without providers gets none. TestOpenCodeCheckReadsProviders, new: a providers.magpie at another address is off until a sync. - The 21 tests named TestOpenCode*, TestOpenChamber* and TestDevEco*: ok. -race -count=5 over the four new ones: ok. - Broken by hand, one at a time, each red where it says: no sync under providers in OpenCode's Sync, in a pick, in OpenChamber's Sync; no delete there for OpenCode or for OpenChamber; the check reading provider alone; no theirsKept; the user's variants dropped; no variant taken for magpie's; only OpenCode 2's split taken for magpie's (OpenChamber's high-fast stayed); providers written into a config without it; a write on every sync; every option in settings; no capabilities. The sync, pick, delete and check breaks at once, which is whate056779adoes: three of the four new tests red. - The reporter's case with the real binaries, in a sandbox HOME: magpie ate056779awired OpenCode to think/deep; OpenChamber's own toProviderEntity (openchamber main 6b48aecb, its zod import stubbed so the module loads) turned that provider.magpie into the providers.magpie its form saves, and provider.magpie was taken out, as its form does; think/new was added, and magpie ate056779asynced. OpenCode 2.1.4's opencode models (npm @opencode/cli-linux-x64, integrity checked) listed magpie/think/deep alone, and its log had two "retained native value over legacy value" lines. The same file synced by this commit: magpie/think/deep and magpie/think/new, no such line, and a second sync left the file as it was, mtime too. - go test -tags nogui -count=1 -timeout 45m ./... (log kept), Bun 1.4.2: 69 packages ok and 7 red, none in what this changes; in internal/agent every test this adds or touches passes. The reds: agent TestFolderVarsAreListed (#3884, main's CI red), TestInstalledVersion, TestCursorFolderFromTheEditorIsNotTheCLI, TestCopilotFolderFromAnIDEPluginIsNotTheCLI, TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir and TestZedAppPath (#3141: alone at -count=40, TestZedAppPath is red 37 and 35 times ate056779a, 35 and 38 here), TestReasonixCLIRequiresSupportedNativeVersion and TestReasonixCLIRecoversAfterProbeTimeout (#3641); davsync TestSync (#3420: alone at -count=20, red 3 times ate056779aand 2 here); edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask 077, #3640); gateway TestPluginToldWhereTheAgentWorks (#3675); gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie (#3649); provider TestCodexAppServersOnHome (#3906, main's CI red), then "close of synctest channel from outside bubble" from TestUnreadLoginsWriteErrorsKeepCredentials (#3632, main's CI red). - gofmt -l clean. go vet -tags nogui and go build -tags nogui for linux, windows and darwin, and go vet and go build for windows without the tag: exit 0 each. go vet and go build without the tag on linux: exit 1 (this box has no GTK or WebKitGTK dev packages). Not tried: Windows, the reporter's system, and OpenChamber's app itself: its converter alone was run. Ported onto main by yetone. Since this was written,cdd470ce9(#4575) made the models of magpie's provider under provider an ordered list (orderedJSON) instead of a map, so the block under providers came out with no models at all (TestOpenCodeProvidersKeptCurrent and TestOpenChamberProvidersKeptCurrent red on main with the patch as it was), and #4575 added a model's cost. openCodeNative now reads that list and writes the models under providers in the same order, and a cost in OpenCode 2's words: a list of tiers, cache prices under cache (migrateModel's costs in packages/core/src/v1/config/migrate.ts). OpenCode's source read at v2.1.4 (68bc26b7) and v2.2.5: in both, normalize.ts merges provider into providers (mergeMaps), and a name under both is the one under providers, taken whole, so the fix holds on the current 2.2.x too. TestOpenCodeNativeKeepsOrderAndCost is new, and providersCurrent checks the order. Run for the port (mote-run, macOS, go1.26.8): go test -tags nogui -count=1 -run 'OpenCode|OpenChamber|MiMo|DevEco|Spelled|Wiring' ./internal/agent: ok. Batch run, at tree 104d75f0a (the twelve coffemon ports together, on origin/main7d022bdb6), mote, macOS, go1.26.8: - go test -tags nogui -count=1 -timeout 45m on the packages the batch changes (agent, autostart, daemon, gateway, library, proc, provider, sessions, testenv, tui, gui): ok each. - GUI, node --test with Playwright 1.62.0, Chromium and WebKit: library-*.test.cjs and i18n-keys.test.cjs, 1044 of 1044 pass. - gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... and go build ./...: ok at cdd7c8e46, the same batch on origin/main00098f12bone rebase before. - The whole go test ./... at cdd7c8e46: 86 packages ok, one red, internal/cli TestEveryRouteHasACommandOrIsNamed (GET /api/context/reply has no command), red on main too (#5026). - Linux (wsl-run, Ubuntu 24.04, at 339055896, the batch onf4c664a09): proc, autostart, testenv, tui ok; agent: only TestGrokInstalled red (#3548); #4033's proc.Look reds (Zed, Copilot, Qoder, Cursor, Omp) pass. - Windows (win-run, Windows 11, at 339055896): proc, autostart, testenv, tui ok; library and agent red in the same tests as on origin/mainf4c664a09(#4115, #1827, #4786; #5068, #5069, #5070 filed now). - Rebased onto origin/mainfb1f4856a(three commits, no file in common with the batch) and run again at the pushed tree: gofmt -l nothing, go build ./... and go vet ./... ok; go test -tags nogui sessions, agent, autostart, tui, proc, testenv ok; i18n-keys and library-* 1044 of 1044 pass. - Not run before the push: the whole GUI suite (a run at cdd7c8e46 was cut off at 1170 of ~1174 tests when mote rebooted; it runs again after the tag and any red is filed). Co-authored-by: yetone <9rqwv2ak@gmail.com>
262 lines
8.3 KiB
Go
262 lines
8.3 KiB
Go
package agent
|
|
|
|
// OpenChamber (a desktop, web and VS Code front end for OpenCode, #321) runs
|
|
// an OpenCode of its own — the desktop app bundles OpenCode 2 — on the
|
|
// user's OpenCode config: $OPENCODE_CONFIG_DIR, else
|
|
// $XDG_CONFIG_HOME/opencode (openCodeDir). Its own settings are under
|
|
// $OPENCHAMBER_DATA_DIR, ~/.config/openchamber by default (not moved by
|
|
// XDG_CONFIG_HOME):
|
|
//
|
|
// preferences.json {"version":1,"fields":{"<key>":{"value":…,"updatedAt":<ms>}}}: the profile
|
|
// settings.json the instance's facts, plus a copy of the profile's values for older builds
|
|
//
|
|
// Each new session is sent the model it picks, in this order: the project's
|
|
// defaultModel (settings.json projects[]), the profile's defaultModel, the
|
|
// agent's own, and only then OpenCode's model — so a defaultModel of its own
|
|
// wins over the one magpie sets for OpenCode. Its small model (titles, commit
|
|
// messages) is smallModelOverride once smallModelUseDefault is false, else
|
|
// OpenCode's small_model. A model is "provider/model" as OpenCode names it,
|
|
// so one of magpie's needs magpie's provider in the OpenCode config.
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/appdir"
|
|
"github.com/yetone/magpie/internal/edit"
|
|
)
|
|
|
|
// openChamberDir is where OpenChamber keeps its settings.
|
|
func openChamberDir(home string) string {
|
|
if d := appdir.Getenv("OPENCHAMBER_DATA_DIR"); d != "" {
|
|
if abs, err := filepath.Abs(d); err == nil {
|
|
return abs
|
|
}
|
|
}
|
|
return filepath.Join(home, ".config", "openchamber")
|
|
}
|
|
|
|
// ocStore reads and writes OpenChamber's profile as it does: a key in
|
|
// preferences.json wins over its copy in settings.json, which is all a
|
|
// build from before the split reads, and seeds preferences.json when that
|
|
// is missing.
|
|
type ocStore struct{ dir string }
|
|
|
|
func (s ocStore) prefs() string { return filepath.Join(s.dir, "preferences.json") }
|
|
func (s ocStore) settings() string { return filepath.Join(s.dir, "settings.json") }
|
|
|
|
// hasPrefs says whether preferences.json is there; an error when it is
|
|
// but isn't a version-1 document, which OpenChamber doesn't write to either.
|
|
func (s ocStore) hasPrefs() (bool, error) {
|
|
b, err := os.ReadFile(s.prefs())
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return false, nil
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
var doc struct {
|
|
Version int `json:"version"`
|
|
Fields json.RawMessage `json:"fields"`
|
|
}
|
|
if json.Unmarshal(b, &doc) != nil || doc.Version != 1 || len(doc.Fields) == 0 || doc.Fields[0] != '{' {
|
|
return false, fmt.Errorf("OpenChamber's %s isn't a preferences file it can read; fix or remove it first", s.prefs())
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
func (s ocStore) get(key string) string {
|
|
if v, ok := edit.GetJSON(s.prefs(), "fields."+key+".value"); ok {
|
|
return v
|
|
}
|
|
v, _ := edit.GetJSON(s.settings(), key)
|
|
return v
|
|
}
|
|
|
|
// set writes key = v, or takes key out for a nil v, in both files: the
|
|
// copy in settings.json only where that file is, or the profile has
|
|
// nowhere else to go.
|
|
func (s ocStore) set(kvs map[string]any) error {
|
|
has, err := s.hasPrefs()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, statErr := os.Stat(s.settings())
|
|
for key, v := range kvs {
|
|
if has {
|
|
if v == nil {
|
|
err = edit.DelJSON(s.prefs(), "fields."+key)
|
|
} else {
|
|
err = edit.SetJSON(s.prefs(), edit.KV{Path: "fields." + key + ".value", Value: v},
|
|
edit.KV{Path: "fields." + key + ".updatedAt", Value: time.Now().UnixMilli()})
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if has && statErr != nil {
|
|
continue
|
|
}
|
|
if v == nil {
|
|
err = edit.DelJSON(s.settings(), key)
|
|
} else {
|
|
err = edit.SetJSON(s.settings(), edit.KV{Path: key, Value: v})
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// model and small are the models OpenChamber sends, "" when it leaves them
|
|
// to OpenCode's config.
|
|
func (s ocStore) model() string { return s.get("defaultModel") }
|
|
func (s ocStore) small() string {
|
|
if s.get("smallModelUseDefault") != "false" {
|
|
return ""
|
|
}
|
|
return s.get("smallModelOverride")
|
|
}
|
|
|
|
// projectModels are the projects that pick a default model of their own,
|
|
// name → model.
|
|
func (s ocStore) projectModels() map[string]string {
|
|
raw, ok := edit.GetJSON(s.settings(), "projects")
|
|
if !ok {
|
|
return nil
|
|
}
|
|
var ps []struct {
|
|
Label, Path, DefaultModel string
|
|
}
|
|
json.Unmarshal([]byte(raw), &ps)
|
|
out := map[string]string{}
|
|
for _, p := range ps {
|
|
if p.DefaultModel == "" {
|
|
continue
|
|
}
|
|
name := p.Label
|
|
if name == "" {
|
|
name = filepath.Base(p.Path)
|
|
}
|
|
out[name] = p.DefaultModel
|
|
}
|
|
return out
|
|
}
|
|
|
|
// openChamberOnMagpie says whether OpenChamber sends one of magpie's
|
|
// models: OpenCode's config must keep magpie's provider for it.
|
|
func openChamberOnMagpie() bool {
|
|
home, _ := os.UserHomeDir()
|
|
s := ocStore{openChamberDir(home)}
|
|
return usesMagpie(s.model(), s.small())
|
|
}
|
|
|
|
func openChamber(home, cfg string) *Agent {
|
|
s := ocStore{openChamberDir(home)}
|
|
oc := opencode(home, cfg)
|
|
ocPath := oc.Path
|
|
auth := filepath.Join(home, ".local", "share", "opencode", "auth.json")
|
|
block := func() any { return magpieProviderJSONFor("opencode", "opencode") }
|
|
provider := openCodeKept(ocPath, 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+"/")
|
|
}
|
|
}
|
|
// stepped off magpie: its provider goes too, when nothing else in the
|
|
// 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()) {
|
|
return nil
|
|
}
|
|
return edit.DelJSON(ocPath, "provider."+magpieID, openCodeNativeKey)
|
|
}
|
|
return &Agent{
|
|
ID: "openchamber", Name: "OpenChamber", Icon: "openchamber", Aliases: []string{"chamber"}, Spelled: openCodeSpelled(ocPath, gatewayV1),
|
|
// its model requests are its OpenCode's, and counted as OpenCode's
|
|
Bin: "openchamber", Dir: s.dir, Path: s.prefs(),
|
|
Notice: func() string {
|
|
var notes []string
|
|
if usesMagpie(s.model()) {
|
|
ps := s.projectModels()
|
|
for _, name := range slices.Sorted(maps.Keys(ps)) {
|
|
if m := ps[name]; !usesMagpie(m) {
|
|
notes = append(notes, noticeOpenchamber1.say("project", name, "model", m))
|
|
}
|
|
}
|
|
}
|
|
if Running(`OpenChamber\.app/`, `(^|/)openchamber( |$)`) {
|
|
notes = append(notes, noticeOpenchamber2.String())
|
|
}
|
|
return strings.Join(notes, " ")
|
|
},
|
|
Check: func() string {
|
|
if !usesMagpie(s.model(), s.small()) {
|
|
return ""
|
|
}
|
|
return openCodeWiringOff("OpenChamber", ocPath, gatewayV1(), hereKey())
|
|
},
|
|
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))
|
|
},
|
|
Fields: []Field{
|
|
{Key: "model", Label: "model", Get: s.model, Options: opts("model"), Set: func(v string) error {
|
|
if v == "" {
|
|
if err := s.set(map[string]any{"defaultModel": nil, "defaultVariant": nil}); err != nil {
|
|
return err
|
|
}
|
|
return tidy()
|
|
}
|
|
v, err := openCodeRef(ocPath, "opencode", v)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
kv := map[string]any{"defaultModel": v}
|
|
// the variant was the old model's, as OpenChamber's own
|
|
// picker has it
|
|
if v != s.model() {
|
|
kv["defaultVariant"] = nil
|
|
}
|
|
return s.set(kv)
|
|
}},
|
|
{Key: "small", Label: "small", Get: s.small, Options: opts("small"), Set: func(v string) error {
|
|
if v == "" {
|
|
if err := s.set(map[string]any{"smallModelUseDefault": nil, "smallModelOverride": nil}); err != nil {
|
|
return err
|
|
}
|
|
return tidy()
|
|
}
|
|
v, err := openCodeRef(ocPath, "opencode", v)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return s.set(map[string]any{"smallModelUseDefault": false, "smallModelOverride": v})
|
|
}},
|
|
},
|
|
}
|
|
}
|
|
|
|
// what openchamber says after a change (notice.go)
|
|
var (
|
|
noticeOpenchamber1 = newNotice("OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.")
|
|
noticeOpenchamber2 = newNotice("OpenChamber takes the new model for new sessions; sessions already open keep theirs.")
|
|
)
|