diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index ac82e92da..41fd0811a 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -80,7 +80,7 @@ something else shows up as drift. - DevEco Code (Huawei's OpenCode fork, #1885) is wired as OpenCode is (`deveco` in [`agents.go`](../../internal/agent/agents.go)): magpie's provider goes into the first of `deveco.jsonc`, `deveco.json` and `config.json` in `~/.config/deveco` (the one DevEco merges last, so the one that wins), or in `$DEVECO_CONFIG_DIR` when that is absolute, read after them. 0.2.3 sends `deveco/0.2.3 ai-sdk/…` to a provider of its config, but much of the OpenCode code it keeps still sends OpenCode's own User-Agent (`opencode/`), so its provider's key is `magpie-deveco` (`openCodeKeyAt`), not the plain `magpie` OpenCode and MiMo Code send, and Check asks for that key. Its npm package has no Linux binary, so no install command is offered there (`cliSpec.only`). - Grok Build keeps magpie's models as one `[model."magpie//"]` table each in `config.toml` under `$GROK_HOME`, else `~/.grok` (`grok` in [`grok.go`](../../internal/agent/grok.go)), each on the gateway's `/v1` with magpie's key. Grok Build takes `api_backend` per model table, `"chat_completions"` (its default), `"responses"` or `"messages"` (Anthropic Messages), and sends each to `base_url` joined with `/chat/completions`, `/responses` or `/messages` (the "Supported API Backends" page bundled in its binary; grok 1.0.67). magpie writes each model's native API (`grokBackend`, from `catalog.Model.APIs` as Pi, droid and dsh pick theirs; uk.jent on Discord), so the gateway relays the request as it is: Responses for a model served best there, Messages for a Claude on an Anthropic endpoint, Chat for the rest, a group whose members differ, or one not known. Each table's `context_window` "drives auto-compact timing" (Grok Build's config reference), so it is where Long conversations has Codex compact (`grokWindow`, codexcat's rule): a threshold set on the model or its provider, else `settings.Working` of the model's window, the whole window under Full window; Long conversations is in Grok Build's sheet on the Agents page (`AGENT_PREFS`). A `context_window` the user set in one of magpie's tables by hand stays through a sync and a new pick (uk.jent on Discord: dozens of 1M models set to 300K one by one): what magpie last gave each model is stashed (`grok::windows`), and a value other than it is the user's (`grokOwnWindow`). With no record yet (a config an older magpie wrote, which gave every model its whole window), a value other than the model's whole window and other than magpie's now is taken for the user's. Disconnect drops the record with the tables. `TestGrokKeepsAWindowSetByHand`, `TestGrokKeepsAWindowSetBeforeTheRecord`, `TestGrokWindowFollowsLongConversations`. - Grok App (RongleCat/grok-app, a desktop front end that starts Grok Build over ACP) keeps its provider channels in `agent-home/config.toml` under its data folder: `$GROK_APP_HOME`, else where its `directories` crate puts it, or its `~/.grok-app` fallback when that is the one there (`grokApp` in [`grokapp.go`](../../internal/agent/grokapp.go)). Its composer lists only Grok Build's official catalog, never the `[model."magpie/…"]` tables of Grok Build's row, so magpie adds itself as a channel, `[model.magpie]`, with the keys the App's Providers page writes: the gateway's `/v1`, a key naming Grok App, `api_backend = "chat_completions"`, `app_provider_mode = "generic"`, and `app_models`, a JSON list of magpie's models with `contextWindow`, `supportsVision` and their effort levels (no `none`; a default the user marks in the App stays, else medium). The picked model's `context_window` (a bare integer) and `supports_reasoning_effort` (a bare bool, Grok Build's gate for `--reasoning-effort`) are on the channel, as the App puts them there when a model is picked in its composer. `[models] default` is the route, and magpie does not set it: setting it to `"magpie"` makes the App drop its own sign-in (`ensure_independent_for_custom_route`). The route stays whatever the App had. Pressing Use on magpie under Accounts is what switches it. A magpie that already set the route puts the old one back once, on the next sync or connect (`grokAppReleased`); a Use after that stays. Disconnect drops only the channel, and puts the route back only when it is still `"magpie"`: the one stashed at connect, else the one `connect.was` holds. One of the App's own routes picked in magpie's model field is written as the route and takes magpie's channel out, as picking another provider does elsewhere. A sync with no channel and a route other than `"magpie"` writes nothing, magpie's stash included, and Check says so when the route is `"magpie"` with the channel gone. A model picked in the App's composer since is the user's and stays through a sync, and a sync with nothing to change doesn't write. Shared mode keeps `GROK_HOME` at `~/.grok` (Grok Build's library row). Independent mode, which Use turns on, reads agent-home: the Library writes `AGENTS.md`, `[mcp_servers]` in the same `config.toml`, and `skills/` there, and Grok App also reads `~/.agents/skills`. RTK has no Grok hook, so the Library lists Grok App with the switch off. The notice, while the App runs, says magpie is a custom provider in Settings › Account, a chat can pick its models in the model picker, and the App stays on its current route until Use. -- JSON/JSONC config edits and their previews reject malformed input rather than editing a partially parsed document. Object edits and VS Code's model-group array edits leave the original file untouched on a parse error; valid comments and trailing commas remain supported (`internal/edit`). +- JSON/JSONC config edits and their previews reject malformed input rather than editing a partially parsed document. Object edits and VS Code's model-group array edits leave the original file untouched on a parse error; valid comments and trailing commas remain supported (`internal/edit`). An edit's result is checked as the apps read JSONC (`edit.ValidJSONC`: jsonc-parser with `allowTrailingComma`, as OpenCode, VS Code and Zed parse; a trailing comma after a value is fine, one with nothing before it, `{,}` or `},,`, is not), and an edit that would turn a file the app reads into one it can't is refused, nothing written (`checkJSONC`). A delete takes the last member's own trailing comma with it, an insert into an object of comments only adds no comma, and a lone comma an older magpie left (`"mcp": {,}` after the hub was toggled for OpenCode, chenxiang0010 on Discord) is dropped by the next edit of that file (`dropLoneCommas`). - A config that starts with a UTF-8 byte order mark (a Windows `settings.json` or `config.toml` saved by PowerShell, Notepad or a channel switcher, #1534) is read without it (`edit.Read`), and a write keeps it (`keepBOM` in `WriteAtomic`): the user's file keeps the encoding it was saved in. That covers every format `internal/edit` writes (JSON/JSONC and its arrays, TOML, YAML, env); Codex reads a TOML file through a BOM too, so magpie no longer refuses one. A file read some other way trims it with `edit.TrimBOM` (the Claude Code and CC Switch imports). A line an edit takes out of a CRLF file goes with its `\r\n`. - Codex's model picker tags each of its own models by where a pick on the Agents page sends it: via magpie while routed, joined, or failing over, and direct while it is only beside its sign-in on one of magpie's models (`beside`, not joined, failover off), where such a pick takes magpie out (#940) and the GUI asks first (`TestCodexBesideOwnModelsSayDirect`). - Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes (`model_provider`, `openai_base_url`, `model_catalog_json`, the magpie table's `base_url`, and a hash of what the catalog file holds, `codexCatalogTag` in [`codex_app_route.go`](../../internal/agent/codex_app_route.go), read again only when its size or time changes; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out, a provider or group renamed or a model added. Without the catalog in it the app kept the names and models it started with until it was restarted (lucis0116 on X). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexAppRouteFollowsTheCatalog`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. @@ -148,7 +148,8 @@ go test -tags nogui ./internal/agent go test -tags nogui ./internal/agent -run '^TestAir' go test -tags nogui ./internal/agent -run 'TestReverseProxy|TestClaudeManagedProxyIsStillMagpie|TestMagpieProbe|TestCodexBehindReverseProxy|TestCodexSignedInBehindReverseProxy|TestAwayPath|TestClaudeBehindLocalProxyKeepsIt' go test -tags nogui ./internal/agent ./internal/edit -run 'TestSyncKeepsAnAddressOnAnotherMachine|TestKeptAwayOnlyWhatIsSure|TestKeyValuesFormats|TestFilteredWrites|TestOwnWritesDuringASyncWithALinkedConfig' -go test -tags nogui ./internal/edit -run 'BOM|CRLF' +go test -tags nogui ./internal/edit -run 'BOM|CRLF|JSONC|TrailingComma|LoneComma' +go test -tags nogui ./internal/library -run TestHubToggleKeepsOpenCodeJSONCValid go test -tags nogui ./internal/agent ./internal/proc -run 'ClaudeCloud|TestT3CodeSaysAClaudeCloudSwitch|TestLoginEnvClaudeProvidersNotSet' go test -tags nogui ./internal/agent -run '^TestAnte' go test -tags nogui ./internal/agent -run 'AionUi|Cindy' diff --git a/internal/edit/json.go b/internal/edit/json.go index 3cefc1cb1..e507c9cfc 100644 --- a/internal/edit/json.go +++ b/internal/edit/json.go @@ -55,13 +55,18 @@ func SetJSON(path string, kvs ...KV) error { raw = []byte("{}\n") } orig := raw + raw = dropLoneCommas(raw) for _, kv := range kvs { raw, err = setJSONBytes(raw, kv.Path, kv.Value) if err != nil { return fmt.Errorf("%s: %w", path, err) } } - return WriteAtomic(path, keepCRLF(raw, orig)) + out, err := checkJSONC(keepCRLF(raw, orig), dropLoneCommas(orig)) + if err != nil { + return fmt.Errorf("%s: %w", path, err) + } + return WriteAtomic(path, out) } // keepCRLF is out, an edit of orig, with \r\n at every line break when orig @@ -84,6 +89,7 @@ func PatchJSON(raw []byte, set []KV, del []string) ([]byte, error) { raw = []byte("{}\n") } orig := raw + raw = dropLoneCommas(raw) var err error for _, kv := range set { raw, err = setJSONBytes(raw, kv.Path, kv.Value) @@ -97,10 +103,14 @@ func PatchJSON(raw []byte, set []KV, del []string) ([]byte, error) { return nil, err } } - if marked { - return append(append([]byte(nil), bom...), keepCRLF(raw, orig)...), nil + out, err := checkJSONC(keepCRLF(raw, orig), dropLoneCommas(orig)) + if err != nil { + return nil, err } - return keepCRLF(raw, orig), nil + if marked { + return append(append([]byte(nil), bom...), out...), nil + } + return out, nil } func setJSONBytes(raw []byte, keyPath string, value any) ([]byte, error) { @@ -180,11 +190,15 @@ func insertKey(raw, stripped []byte, from int, key string, value any) ([]byte, e k, _ := json.Marshal(key) pretty := bytes.IndexByte(raw, '\n') >= 0 empty := len(bytes.TrimSpace(raw[open+1:close])) == 0 + // an object of comments only has no member for the new one to come + // before: a comma after it would be the object's trailing comma, which + // only some apps read + members := len(bytes.TrimSpace(stripped[open+1:close])) > 0 if !pretty { v, _ := json.Marshal(value) ins := string(k) + ":" + string(v) - if !empty { + if members { ins += "," } return splice(raw, open+1, 0, []byte(ins)) @@ -198,6 +212,9 @@ func insertKey(raw, stripped []byte, from int, key string, value any) ([]byte, e if empty { return splice(raw, open, close-open+1, []byte("{\n"+kv+"\n"+base+"}")) } + if !members { + return splice(raw, open+1, 0, []byte("\n"+kv)) + } return splice(raw, open+1, 0, []byte("\n"+kv+",")) } @@ -271,6 +288,8 @@ func DelJSON(path string, keyPaths ...string) error { if err != nil || len(bytes.TrimSpace(raw)) == 0 { return err } + orig := raw + raw = dropLoneCommas(raw) changed := false for _, kp := range keyPaths { out, ok, err := delJSONBytes(raw, kp) @@ -284,7 +303,11 @@ func DelJSON(path string, keyPaths ...string) error { if !changed { return nil } - return WriteAtomic(path, raw) + out, err := checkJSONC(raw, dropLoneCommas(orig)) + if err != nil { + return fmt.Errorf("%s: %w", path, err) + } + return WriteAtomic(path, out) } // pastLineEnd is i past the line end raw has at i, \n or \r\n, else i: a @@ -343,10 +366,23 @@ func delJSONBytes(raw []byte, keyPath string) ([]byte, bool, error) { } out, _ = splice(raw, from, to-from, nil) } else { - // last member: drop the line, then the comma that preceded it + // last member: its own trailing comma goes (jsonc blanks it in + // stripped, so it isn't seen above), or the only member's would be + // left with nothing before it, "{ , }", which OpenCode calls invalid + if t := nextToken(raw, b); t < len(raw) && raw[t] == ',' { + raw = append(raw[:t:t], raw[t+1:]...) + stripped = append(stripped[:t:t], stripped[t+1:]...) + } + // then drop the line, and the comma that preceded it if alone { from = ls - to = pastLineEnd(raw, to) + e := to + for e < len(raw) && (raw[e] == ' ' || raw[e] == '\t') { + e++ + } + if p := pastLineEnd(raw, e); p > e { + to = p + } } out, _ = splice(raw, from, to-from, nil) k := a diff --git a/internal/edit/jsonarray.go b/internal/edit/jsonarray.go index 48f9ca533..d788398c3 100644 --- a/internal/edit/jsonarray.go +++ b/internal/edit/jsonarray.go @@ -41,6 +41,13 @@ func SetJSONItem(path string, where map[string]string, value any) error { v, _ := json.MarshalIndent(value, "\t", "\t") return WriteAtomic(path, []byte("[\n\t"+string(v)+"\n]\n")) } + write := func(out []byte) error { + out, err := checkJSONC(out, raw) + if err != nil { + return fmt.Errorf("%s: %w", path, err) + } + return WriteAtomic(path, out) + } stripped := jsonc.ToJSONInPlace(append([]byte(nil), raw...)) if !json.Valid(stripped) { return fmt.Errorf("%s: invalid JSON/JSONC", path) @@ -51,13 +58,13 @@ func SetJSONItem(path string, where map[string]string, value any) error { } if r, ok := findItem(stripped, where); ok { out, _ := splice(raw, r.Index, len(r.Raw), marshalAt(raw, r.Index, value)) - return WriteAtomic(path, keepCRLF(out, raw)) + return write(keepCRLF(out, raw)) } items := root.Array() if len(items) == 0 { v, _ := json.MarshalIndent(value, "\t", "\t") out, _ := splice(raw, open, close-open+1, []byte("[\n\t"+string(v)+"\n]")) - return WriteAtomic(path, keepCRLF(out, raw)) + return write(keepCRLF(out, raw)) } last := items[len(items)-1] at := last.Index + len(last.Raw) @@ -70,12 +77,12 @@ func SetJSONItem(path string, where map[string]string, value any) error { if bytes.IndexByte(raw, '\n') < 0 { v, _ := json.Marshal(value) out, _ := splice(raw, at, 0, []byte(sep+string(v))) - return WriteAtomic(path, out) + return write(out) } indent := lineIndent(raw, last.Index) v := marshalAt(raw, last.Index, value) out, _ := splice(raw, at, 0, []byte(sep+"\n"+indent+string(v))) - return WriteAtomic(path, keepCRLF(out, raw)) + return write(keepCRLF(out, raw)) } // DelJSONItem removes every element of the file's top-level array that has @@ -85,6 +92,7 @@ func DelJSONItem(path string, where map[string]string) error { if err != nil || len(bytes.TrimSpace(raw)) == 0 { return err } + orig := raw changed := false for { stripped := jsonc.ToJSONInPlace(append([]byte(nil), raw...)) @@ -100,7 +108,11 @@ func DelJSONItem(path string, where map[string]string) error { if !changed { return nil } - return WriteAtomic(path, raw) + out, err := checkJSONC(raw, orig) + if err != nil { + return fmt.Errorf("%s: %w", path, err) + } + return WriteAtomic(path, out) } // topArray is stripped's top-level array, with the offsets of its brackets diff --git a/internal/edit/jsonc_trailing_comma_test.go b/internal/edit/jsonc_trailing_comma_test.go new file mode 100644 index 000000000..afed4b197 --- /dev/null +++ b/internal/edit/jsonc_trailing_comma_test.go @@ -0,0 +1,171 @@ +package edit + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// Turning the Library's MCP hub on for OpenCode and off again (chenxiang0010 +// on Discord, Windows) left opencode.jsonc's "mcp" as {,}: the member taken +// out was the only one and had a trailing comma, which jsonc blanks before +// the delete looked for it, so the comma stayed with nothing before it, and +// OpenCode's jsonc-parser (allowTrailingComma) called the file invalid. Each +// order the sync can add and take out entries in, from each shape of file, +// leaves a file OpenCode reads. +func TestHubToggleLeavesValidJSONC(t *testing.T) { + hub := map[string]any{"type": "remote", "url": "http://127.0.0.1:3425/mcp/magpie/hub/opencode", "enabled": true} + srv := map[string]any{"type": "local", "command": []string{"npx", "x"}, "enabled": true} + fixtures := map[string]string{ + "empty_mcp": "{\n \"mcp\": {}\n}\n", + "no_mcp": "{\n \"$schema\": \"https://opencode.ai/config.json\"\n}\n", + "one": "{\n \"mcp\": {\n \"x\": {\"type\": \"local\"}\n }\n}\n", + "one_trailing": "{\n \"mcp\": {\n \"x\": {\"type\": \"local\"},\n },\n}\n", + "one_trailing_crlf": "{\r\n \"mcp\": {\r\n \"x\": {\"type\": \"local\"},\r\n },\r\n}\r\n", + "one_crlf": "{\r\n \"mcp\": {\r\n \"x\": {\"type\": \"local\"}\r\n }\r\n}\r\n", + "two_trailing": "{\n \"mcp\": {\n \"x\": {\"type\": \"local\"},\n \"y\": {\"type\": \"local\"},\n }\n}\n", + "comment_only": "{\n \"mcp\": {\n // none yet\n }\n}\n", + "comment_after": "{\n \"mcp\": {\n \"x\": {\"type\": \"local\"} // mine\n }\n}\n", + "comma_after_note": "{\n \"mcp\": {\n \"x\": {\"type\": \"local\"} // mine\n ,\n }\n}\n", + "tabs_trailing": "{\n\t\"mcp\": {\n\t\t\"x\": {\"type\": \"local\"},\n\t},\n}\n", + "compact_trailing": `{"mcp":{"x":{"type":"local"},}}`, + } + seqs := map[string][]string{ + "hub_on_off": {"+magpie", "-magpie"}, + "add_first_del_first": {"+magpie", "-x", "-magpie", "+x"}, + "add_first_add_first": {"+magpie", "-x", "+x", "-magpie"}, + "del_first_del_first": {"-x", "+magpie", "-magpie", "+x"}, + "del_first_add_first": {"-x", "+magpie", "+x", "-magpie"}, + "two_servers": {"+magpie", "-x", "-y", "-magpie", "+x", "+y"}, + "two_servers_add_back": {"-x", "-y", "+magpie", "+x", "+y", "-magpie"}, + } + for fn, fx := range fixtures { + for sn, seq := range seqs { + t.Run(fn+"/"+sn, func(t *testing.T) { + p := filepath.Join(t.TempDir(), "opencode.jsonc") + if err := os.WriteFile(p, []byte(fx), 0o644); err != nil { + t.Fatal(err) + } + for i, st := range seq { + name := st[1:] + var err error + if st[0] == '+' { + v := srv + if name == "magpie" { + v = hub + } + err = SetJSON(p, KV{Path: "mcp." + name, Value: v}) + } else { + err = DelJSON(p, "mcp."+name) + } + b, _ := os.ReadFile(p) + if err != nil || !ValidJSONC(b) { + t.Fatalf("step %d %s: err=%v, file OpenCode can't read:\n%s", i, st, err, strings.ReplaceAll(string(b), "\r", `\r`)) + } + if _, ok := GetJSON(p, "mcp."+name); ok != (st[0] == '+') { + t.Fatalf("step %d %s: mcp.%s there=%v", i, st, name, ok) + } + if strings.Contains(fx, "\r\n") && strings.Count(string(b), "\n") != strings.Count(string(b), "\r\n") { + t.Fatalf("step %d %s: CRLF file got a bare \\n:\n%q", i, st, b) + } + if strings.Contains(fx, "// ") && !strings.Contains(string(b), "// ") { + t.Fatalf("step %d %s: the comment went:\n%s", i, st, b) + } + } + }) + } + } +} + +// The reporter's file, as the delete leaves it. +func TestDelOnlyMemberTakesItsTrailingComma(t *testing.T) { + for _, c := range []struct{ in, want string }{ + {"{\n \"mcp\": {\n \"magpie\": {\n \"type\": \"remote\"\n },\n },\n}\n", "{\n \"mcp\": {},\n}\n"}, + {"{\r\n \"mcp\": {\r\n \"magpie\": {\"type\": \"remote\"},\r\n }\r\n}\r\n", "{\r\n \"mcp\": {}\r\n}\r\n"}, + {"{\n \"mcp\": {\n \"a\": 1,\n \"magpie\": 2,\n }\n}\n", "{\n \"mcp\": {\n \"a\": 1\n }\n}\n"}, + {`{"mcp":{"magpie":2,}}`, `{"mcp":{}}`}, + } { + p := filepath.Join(t.TempDir(), "opencode.jsonc") + os.WriteFile(p, []byte(c.in), 0o644) + if err := DelJSON(p, "mcp.magpie"); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(p); string(b) != c.want { + t.Errorf("DelJSON(%q):\n got %q\nwant %q", c.in, b, c.want) + } + } +} + +// An object of comments only gets its first member with no comma after it. +func TestInsertIntoCommentOnlyObjectNoTrailingComma(t *testing.T) { + p := filepath.Join(t.TempDir(), "opencode.jsonc") + os.WriteFile(p, []byte("{\n \"mcp\": {\n // none yet\n }\n}\n"), 0o644) + if err := SetJSON(p, KV{Path: "mcp.magpie", Value: 1}); err != nil { + t.Fatal(err) + } + want := "{\n \"mcp\": {\n \"magpie\": 1\n // none yet\n }\n}\n" + if b, _ := os.ReadFile(p); string(b) != want { + t.Errorf("got %q\nwant %q", b, want) + } +} + +// A file an older magpie left with {,} is mended by the next edit of it. +func TestLoneCommaMendedOnNextEdit(t *testing.T) { + p := filepath.Join(t.TempDir(), "opencode.jsonc") + os.WriteFile(p, []byte("{\n \"mcp\": {\n,\n },\n \"x\": [\n ,]\n}\n"), 0o644) + if err := SetJSON(p, KV{Path: "mcp.magpie", Value: 1}); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(p); !ValidJSONC(b) { + t.Errorf("still invalid:\n%s", b) + } + os.WriteFile(p, []byte("{\n \"mcp\": {\n,\n },\n \"magpie\": 1\n}\n"), 0o644) + if err := DelJSON(p, "magpie"); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(p); !ValidJSONC(b) { + t.Errorf("still invalid:\n%s", b) + } + out, err := PatchJSON([]byte("{\"a\": {,}}"), []KV{{Path: "b", Value: 1}}, nil) + if err != nil || !ValidJSONC(out) { + t.Errorf("PatchJSON: %v %s", err, out) + } +} + +// What jsonc-parser with allowTrailingComma reads, and what it calls invalid. +func TestValidJSONC(t *testing.T) { + for in, want := range map[string]bool{ + `{}`: true, + `{"a":1,}`: true, + "{\"a\":1 // c\n,}": true, + `[1,2,]`: true, + `{"a":"x,}","b":[",]"]}`: true, + "// ,}\n{\"a\":1}": true, + "/* {,} */{\"a\":[1,]}": true, + "\xef\xbb\xbf{\"a\":1,}": true, + `{,}`: false, + "{\n,\n}": false, + `[,]`: false, + `{"a":1,,}`: false, + `{"a":,}`: false, + "{\"a\":1 /* never ends ": false, + `{"a":1`: false, + } { + if got := ValidJSONC([]byte(in)); got != want { + t.Errorf("ValidJSONC(%q) = %v, want %v", in, got, want) + } + } +} + +// An edit that would turn a file the app reads into one it can't is +// refused, and nothing is written. +func TestInvalidEditNotWritten(t *testing.T) { + if _, err := checkJSONC([]byte("{,}"), []byte("{}")); !errors.Is(err, errEditInvalid) { + t.Errorf("checkJSONC on {,} from {}: %v", err) + } + if out, err := checkJSONC([]byte(`{"a":1,}`), []byte("{}")); err != nil || string(out) != `{"a":1,}` { + t.Errorf("a trailing comma after a value is not refused: %v", err) + } +} diff --git a/internal/edit/jsonc_valid.go b/internal/edit/jsonc_valid.go new file mode 100644 index 000000000..2693d2138 --- /dev/null +++ b/internal/edit/jsonc_valid.go @@ -0,0 +1,144 @@ +package edit + +import ( + "bytes" + "encoding/json" + "errors" +) + +// errEditInvalid is an edit refused because the file it would leave is one +// the app reading it calls invalid. +var errEditInvalid = errors.New("the edit would leave invalid JSON/JSONC; not written") + +// ValidJSONC reports whether raw is JSON with comments and trailing commas +// as the apps that write JSONC read it (OpenCode, VS Code and Zed parse +// with jsonc-parser's allowTrailingComma): a comma may end a list of +// members or elements, but a comma with nothing before it ("{ , }", "[,]", +// ",,") is an error there. tidwall/jsonc, which the editors here read +// through, blanks every comma before a closing bracket, so a file that +// passes json.Valid after it can still be one the app calls invalid; an +// edit is checked with this before it is written. +func ValidJSONC(raw []byte) bool { + b, ok := blankComments(bytes.TrimPrefix(raw, bom)) + if !ok { + return false + } + for _, i := range trailingCommas(b) { + if lone(b, i) { + return false + } + b[i] = ' ' + } + return json.Valid(b) +} + +// blankComments is a copy of raw with each comment turned to spaces, line +// breaks kept, so offsets in it are offsets in raw; false when a block +// comment is never closed. +func blankComments(raw []byte) ([]byte, bool) { + b := append([]byte(nil), raw...) + inStr := false + for i := 0; i < len(b); i++ { + c := b[i] + switch { + case inStr: + if c == '\\' { + i++ + } else if c == '"' { + inStr = false + } + case c == '"': + inStr = true + case c == '/' && i+1 < len(b) && b[i+1] == '/': + for ; i < len(b) && b[i] != '\n'; i++ { + b[i] = ' ' + } + case c == '/' && i+1 < len(b) && b[i+1] == '*': + end := bytes.Index(b[i+2:], []byte("*/")) + if end < 0 { + return nil, false + } + for j := i; j < i+2+end+2; j++ { + if b[j] != '\n' && b[j] != '\r' { + b[j] = ' ' + } + } + i += 2 + end + 1 + } + } + return b, true +} + +// trailingCommas are the offsets of the commas in comment-free b, outside +// strings, that a closing bracket follows. +func trailingCommas(b []byte) []int { + var at []int + inStr := false + for i := 0; i < len(b); i++ { + c := b[i] + switch { + case inStr: + if c == '\\' { + i++ + } else if c == '"' { + inStr = false + } + case c == '"': + inStr = true + case c == ',': + j := i + 1 + for j < len(b) && isSpace(b[j]) { + j++ + } + if j < len(b) && (b[j] == '}' || b[j] == ']') { + at = append(at, i) + } + } + } + return at +} + +// lone is whether the comma at i in comment-free b has no value before it: +// an opening bracket, another comma or a colon. +func lone(b []byte, i int) bool { + k := i - 1 + for k >= 0 && isSpace(b[k]) { + k-- + } + return k < 0 || b[k] == ',' || b[k] == '{' || b[k] == '[' || b[k] == ':' +} + +// dropLoneCommas is raw without the commas before a closing bracket that +// have no value before them: what magpie's own delete left in a JSONC file +// when the member it took out was the only one and had a trailing comma +// ("mcp": {,}), which the app then calls invalid. Anything else is left as +// it is. +func dropLoneCommas(raw []byte) []byte { + b, ok := blankComments(raw) + if !ok { + return raw + } + at := trailingCommas(b) + var out []byte + for n := len(at) - 1; n >= 0; n-- { + if i := at[n]; lone(b, i) { + if out == nil { + out = append([]byte(nil), raw...) + } + out = append(out[:i], out[i+1:]...) + } + } + if out == nil { + return raw + } + return out +} + +// checkJSONC is out, an edit of orig, or an error when the edit would +// leave a file the app reads as invalid that it read before. +func checkJSONC(out, orig []byte) ([]byte, error) { + if !ValidJSONC(out) && ValidJSONC(orig) { + return nil, errEditInvalid + } + return out, nil +} diff --git a/internal/library/mcp_hub_jsonc_test.go b/internal/library/mcp_hub_jsonc_test.go new file mode 100644 index 000000000..72c3ac1ac --- /dev/null +++ b/internal/library/mcp_hub_jsonc_test.go @@ -0,0 +1,60 @@ +package library + +import ( + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/edit" +) + +// The hub turned on for OpenCode and off again (chenxiang0010 on Discord, +// Windows) left opencode.jsonc's "mcp" ending in a comma with nothing +// before it, which OpenCode calls invalid. The file had the Library's +// server as the only one, with a trailing comma, as OpenCode and editors +// allow. Each toggle leaves a file OpenCode reads, LF and CRLF. +func TestHubToggleKeepsOpenCodeJSONCValid(t *testing.T) { + for _, eol := range []string{"\n", "\r\n"} { + t.Run(map[string]string{"\n": "lf", "\r\n": "crlf"}[eol], func(t *testing.T) { + hubSandbox(t) + p := targetByID("opencode").MCP.Path + ok(t)(SaveServer("", Server{Name: "fs", Transport: "stdio", Command: "npx", Args: []string{"-y", "fs"}, Agents: []string{"opencode"}})) + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + // as the user keeps it: the server's member ends in a comma, + // and so does mcp's, with a comment of theirs and their line + // ends + s := strings.Replace(string(b), "\"mcp\": {", "// mine\n \"mcp\": {", 1) + i := strings.Index(s, "\"fs\": {") + j := i + strings.Index(s[i:], "\n }") + len("\n }") + s = s[:j] + "," + s[j:] + s = strings.ReplaceAll(strings.ReplaceAll(s, "\r\n", "\n"), "\n", eol) + if err := os.WriteFile(p, []byte(s), 0o644); err != nil { + t.Fatal(err) + } + if !edit.ValidJSONC([]byte(s)) || !strings.Contains(s, "},"+eol+" }") { + t.Fatalf("fixture:\n%s", s) + } + check := func(when string, want ...string) { + t.Helper() + b, _ := os.ReadFile(p) + if !edit.ValidJSONC(b) { + t.Fatalf("%s: OpenCode can't read it:\n%s", when, b) + } + for _, w := range want { + if !strings.Contains(string(b), w) { + t.Fatalf("%s: no %q in:\n%s", when, w, b) + } + } + } + for range 2 { + ok(t)(SetMCPHub(true)) + check("hub on", `"magpie"`, "// mine") + ok(t)(SetMCPHub(false)) + check("hub off", `"fs"`, "// mine") + } + }) + } +}