diff --git a/README.md b/README.md index 5fb955679..2763fc6d4 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ magpie tui # the whole thing, in a terminal
-Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy +Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy
diff --git a/README.zh-CN.md b/README.zh-CN.md index 1aa9b032e..594d8344f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -70,7 +70,7 @@ magpie tui # 全部功能,在终端里
-Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy +Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy
diff --git a/docs/reference.md b/docs/reference.md index aeade3153..432793eaa 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -120,6 +120,7 @@ line; agents connected to magpie lose it when it quits. | Empryo | `~/.empryo/config.json` | defaultModel (a `magpie` provider at the gateway in `providers`) | | Ante | `~/.ante/catalog.json` and `settings.json` (`$ANTE_HOME`) | provider, model (a `magpie` provider on OpenAiCompatible, with no auth of magpie's: the gateway lets this machine in with any token and Ante counts a provider with none as authenticated; magpie's models in Ante's model picker, and Ante started on magpie, which is what its settings' `provider` decides) | | AstrBot | `data/cmd_config.json` under `$ASTRBOT_ROOT`, else `~/.astrbot` (the desktop app's) | model (a `magpie` entry in `provider_sources` and magpie's models in `provider`, the user's own entries kept; the default chat model in `agent_runner.config.model.provider_id`, or `provider_settings.default_provider_id` on AstrBot before 4.28's agent runner; restart AstrBot after connecting; Docker installs aren't reached) | +| jcode | `config.toml` in `$JCODE_HOME`, else `~/.jcode` | model (a `[providers.magpie]` profile, `openai-compatible`, with magpie's models in it; `[provider] default_provider`/`default_model` set to it, what was there put back on Disconnect; the user's own keys in the profile, such as `headers` and a model's `reasoning_effort`, kept; restart open jcode sessions after connecting) | | MiniMax Code (mcode) | `~/.minimax/config.yaml` (`$MINIMAX_DATA_DIR`) | model (a `magpie` custom provider; magpie's models in its /model) | | Droid (Factory) | `~/.factory/settings.json` (`$FACTORY_HOME_OVERRIDE`) | model (magpie's models as BYOK `customModels`, in Droid's /model) | | Cline (CLI) | `~/.cline/data/settings/providers.json` (`$CLINE_DIR`) | model, effort (magpie takes its openai-compatible provider) | diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index e8b7298dd..6b16fb568 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -42,6 +42,7 @@ something else shows up as drift. - Copilot in JetBrains IDEs keeps its Bring Your Own Key providers in the Copilot language server's `byok.json`, shared with Xcode's and Eclipse's Copilot (`copilotJetBrains` in [`copilotjetbrains.go`](../../internal/agent/copilotjetbrains.go)). magpie writes its own three keys there, `magpie-provider-config`, `magpie-api-key` and `magpie-models-config`, in the bytes the server itself writes, and only when they differ; the user's providers and keys stay. A magpie model the user hid in Manage Models (`isRegistered: false`) stays hidden through a sync. A new file is made 0600 in a 0700 folder, as the server makes it. - Ante's `catalog.json` keeps user-added fields in `providers.magpie` the same way (`ante` in [`ante.go`](../../internal/agent/ante.go)); its `auth`, `http_headers`, `extra_body` and `stream_idle_timeout_secs` are what a gateway shared on the local network or reached from WSL needs to send a key. Ante starts a session on the `provider` and `model` of `settings.json`, not on what its catalog holds (#1210), so magpie sets that pair and puts back what it found there; a pick the user makes in Ante while magpie is wired is theirs and stands. - AstrBot keeps its providers in `data/cmd_config.json` under its root (`$ASTRBOT_ROOT`, else `~/.astrbot`, the desktop app's, else `~/astrbot`), written with a UTF-8 BOM, which magpie keeps (`astrbot` in [`astrbot.go`](../../internal/agent/astrbot.go)). magpie adds a `magpie` entry to `provider_sources` and one `magpie/` entry per model to `provider`, keeps the user's own entries byte for byte and keeps what the user changes in magpie's (timeout, proxy, enable), and sets the default chat model (`agent_runner.config.model.provider_id`, or `provider_settings.default_provider_id` before the agent runner), putting back what it found there. A pick the user makes while magpie is wired is theirs and stands. The first connect copies the file to `cmd_config.json.before-magpie`. AstrBot reads the file only at start-up and its WebUI writes it back whole on save, so the agent's notice says to restart AstrBot before saving in the WebUI. A Docker install's root is inside its container, which magpie doesn't reach. +- jcode keeps its settings in `config.toml` in `$JCODE_HOME`, else `~/.jcode` (`jcode` in [`jcode.go`](../../internal/agent/jcode.go)). magpie adds a named profile, `[providers.magpie]`, as `jcode provider add` writes one: `type = "openai-compatible"`, the gateway's `/v1`, an inline `api_key` naming jcode (jcode sends nothing else that tells it apart) and `requires_api_key = true`, since jcode sends no key to a loopback URL without it. Its `models` list has one entry per model, with `context_window`, `input` and `reasoning` for a model with effort levels. A `reasoning_effort` the user set on one stays while the model has that level. The model jcode starts on is `[provider] default_provider = "magpie"` and `default_model`. What was there is stashed and put back on Disconnect. A model of jcode's own picked while it is on magpie takes magpie out. Each key is set alone, so the user's other keys and tables stay, and the `[[providers.magpie.models]]` tables jcode writes when it saves the file itself are replaced by the one list. A sync with nothing to change doesn't write. Disconnect drops the profile whole, its sub-tables included. jcode reads the file when it starts, so the notice says to restart open sessions. - 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`). - 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). - Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is. @@ -76,6 +77,7 @@ go test -tags nogui ./internal/agent -run '^TestAir' go test -tags nogui ./internal/agent ./internal/edit -run 'TestSyncKeepsAnAddressOnAnotherMachine|TestKeptAwayOnlyWhatIsSure|TestKeyValuesFormats|TestFilteredWrites' go test -tags nogui ./internal/agent -run '^TestAnte' go test -tags nogui ./internal/agent -run '^TestAstrBot' +go test -tags nogui ./internal/agent -run '^TestJcode' go test -tags nogui ./internal/agent -run '^TestPlugged' go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexOwnModelThroughMagpieWhileAccountsOn|TestCodexHandWrittenBaseURLStays' go test -tags nogui ./internal/agent -run 'TestDisconnectStaysThroughSync|TestCodexDisconnectStaysWithAccountsOn|TestCodexAPIDisconnectStays' diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 0ea6790d1..2c21b6087 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -120,6 +120,7 @@ func builtins(home, cfg string) []*Agent { empryo(home), ante(home), astrbot(home), + jcode(home), miniMax(home), droid(home), cline(home), diff --git a/internal/agent/jcode.go b/internal/agent/jcode.go new file mode 100644 index 000000000..acbfdee9b --- /dev/null +++ b/internal/agent/jcode.go @@ -0,0 +1,375 @@ +package agent + +// jcode (1jehuang/jcode, a coding agent in Rust) keeps its settings in +// config.toml in $JCODE_HOME, else ~/.jcode. A provider of the user's own +// making is a named profile, [providers.], which `jcode provider add` +// writes: type "openai-compatible" (jcode's chat completions client), a +// base_url, a key (api_key inline, or api_key_env) and its models as +// [[providers..models]] entries (id, context_window, input, +// reasoning). jcode starts on [provider] default_provider and default_model, +// a profile's name and one of its models. +// +// magpie adds itself as the profile "magpie": the gateway, with one model +// entry per catalog model, so the catalog is in jcode's /model picker, and +// jcode is started on the model picked. What [provider] named before is +// stashed and put back when magpie steps out. Every other key of the file is +// the user's and stays as written, the user's own keys in magpie's profile +// too (headers, extra_body, a model's reasoning_effort). + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + + toml "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/edit" +) + +// jcodeProfile is magpie's profile's table in jcode's config.toml, and +// jcodeModels its models' array. +const ( + jcodeProfile = "providers." + magpieID + jcodeModels = jcodeProfile + ".models" +) + +// what jcode says after a change (notice.go) +var noticeJcode = newNotice("jcode reads its settings at start-up — restart open jcode sessions to use this.") + +// jcodeContext is what jcode is told of a model whose context magpie +// doesn't know; without one it takes 200k. +const jcodeContext = 128000 + +// jcodeDir is jcode's folder: $JCODE_HOME, else ~/.jcode (jcode-storage's +// jcode_dir). +func jcodeDir(at place) string { + if d := strings.TrimSpace(at.getenv("JCODE_HOME")); d != "" { + return d + } + return filepath.Join(at.home, ".jcode") +} + +// jcodeModel is one [[providers..models]] entry, as jcode's +// NamedProviderModelConfig reads it. +type jcodeModel struct { + ID string `toml:"id"` + Reasoning *bool `toml:"reasoning,omitempty"` + ReasoningEffort string `toml:"reasoning_effort,omitempty"` + ContextWindow int `toml:"context_window,omitempty"` + Input []string `toml:"input,omitempty"` +} + +// jcodeConf is what magpie reads of jcode's config.toml. +type jcodeConf struct { + Provider struct { + DefaultProvider string `toml:"default_provider"` + DefaultModel string `toml:"default_model"` + } `toml:"provider"` + Providers map[string]struct { + BaseURL string `toml:"base_url"` + APIKey string `toml:"api_key"` + Models []jcodeModel `toml:"models"` + } `toml:"providers"` +} + +// jcodeRead reads jcode's config.toml; a missing file is an empty one, and +// one that doesn't parse is an error, never taken as empty. +func jcodeRead(path string) (jcodeConf, error) { + var c jcodeConf + b, err := os.ReadFile(path) + if os.IsNotExist(err) { + return c, nil + } + if err != nil { + return c, err + } + if err := toml.Unmarshal(b, &c); err != nil { + return c, fmt.Errorf("jcode's %s isn't TOML magpie can read; it was left as it is: %w", path, err) + } + return c, nil +} + +// jcodeWant is magpie's models as jcode is told them: the context window +// (one magpie doesn't know is jcodeContext), whether it takes images, and +// reasoning on for a model with effort levels, so jcode's /effort offers +// them. A reasoning_effort the user set on one of magpie's models stays +// while the model has that level. +func jcodeWant(was []jcodeModel) []jcodeModel { + kept := map[string]string{} + for _, m := range was { + kept[m.ID] = m.ReasoningEffort + } + var out []jcodeModel + for _, m := range magpieModels("jcode") { + ctx := m.Context + if ctx <= 0 { + ctx = jcodeContext + } + e := jcodeModel{ID: m.ID, ContextWindow: ctx, Input: []string{"text"}} + if m.Images { + e.Input = append(e.Input, "image") + } + var levels []string + for _, l := range m.Efforts { + if l != "none" { + levels = append(levels, l) + } + } + if len(levels) > 0 { + yes := true + e.Reasoning = &yes + e.ReasoningEffort = keptEffort(kept[m.ID], levels, "") + } + out = append(out, e) + } + return out +} + +// jcodeArray is models as one TOML array of inline tables, one per line. +func jcodeArray(models []jcodeModel) edit.Raw { + if len(models) == 0 { + return "[]" + } + var b strings.Builder + b.WriteString("[\n") + for _, m := range models { + parts := []string{"id = " + strconv.Quote(m.ID)} + if m.ContextWindow > 0 { + parts = append(parts, "context_window = "+strconv.Itoa(m.ContextWindow)) + } + if len(m.Input) > 0 { + var q []string + for _, in := range m.Input { + q = append(q, strconv.Quote(in)) + } + parts = append(parts, "input = ["+strings.Join(q, ", ")+"]") + } + if m.Reasoning != nil { + parts = append(parts, "reasoning = "+strconv.FormatBool(*m.Reasoning)) + } + if m.ReasoningEffort != "" { + parts = append(parts, "reasoning_effort = "+strconv.Quote(m.ReasoningEffort)) + } + b.WriteString(" { " + strings.Join(parts, ", ") + " },\n") + } + b.WriteString("]") + return edit.Raw(b.String()) +} + +// jcodeSame reports whether two model lists say the same to jcode. +func jcodeSame(a, b []jcodeModel) bool { + return slices.EqualFunc(a, b, func(x, y jcodeModel) bool { + return x.ID == y.ID && x.ContextWindow == y.ContextWindow && slices.Equal(x.Input, y.Input) && + (x.Reasoning == nil) == (y.Reasoning == nil) && (x.Reasoning == nil || *x.Reasoning == *y.Reasoning) && + x.ReasoningEffort == y.ReasoningEffort + }) +} + +// jcodePick is what [provider] named before magpie: a profile (or one of +// jcode's providers) and a model, "" each for none. +type jcodePick struct { + Provider string `json:"provider,omitempty"` + Model string `json:"model,omitempty"` +} + +func jcode(home string) *Agent { return jcodeAt(here(home)) } + +func jcodeAt(at place) *Agent { + dir := jcodeDir(at) + path := filepath.Join(dir, "config.toml") + keyPick := at.key("jcode:" + path + ":default") + key := func() string { return agentKeyAt("jcode", at.gw()) } + read := func() jcodeConf { c, _ := jcodeRead(path); return c } + ours := func(c jcodeConf) bool { return c.Provider.DefaultProvider == magpieID } + get := func() string { + c := read() + if ours(c) && c.Provider.DefaultModel != "" { + return magpieID + "/" + c.Provider.DefaultModel + } + return c.Provider.DefaultModel + } + // setPick names the profile and model jcode starts on, a key taken out + // for "" + setPick := func(p jcodePick) error { + for _, kv := range [][2]string{{"default_provider", p.Provider}, {"default_model", p.Model}} { + var err error + if kv[1] == "" { + err = edit.DelTOMLKey(path, "provider", kv[0]) + } else { + err = edit.SetTOMLKey(path, "provider", kv[0], kv[1]) + } + if err != nil { + return err + } + } + return nil + } + // wire writes magpie's profile, its own keys set and the user's others + // left as they are, with model, if given, the profile's default; it + // writes nothing when the file has it all already + wire := func(model string) error { + c, err := jcodeRead(path) + if err != nil { + return err + } + have, on := c.Providers[magpieID] + want := jcodeWant(have.Models) + t, err := edit.GetTOMLTable(path, jcodeProfile) + if err != nil { + return err + } + kvs := [][2]any{ + {"type", "openai-compatible"}, + {"base_url", at.v1()}, + {"api_key", key()}, + // a gateway on loopback is taken by jcode as needing no key, + // and then it sends none: the key names jcode to the gateway + {"requires_api_key", edit.Raw("true")}, + } + if model != "" { + kvs = append(kvs, [2]any{"default_model", model}) + } + same := on && t != nil && jcodeSame(have.Models, want) + for _, kv := range kvs { + v := fmt.Sprint(kv[1]) + if t[kv[0].(string)] != v { + same = false + } + } + if same { + return nil + } + // jcode writes the models as [[providers.magpie.models]] when it + // saves its settings itself: those go, for the one array below + if err := edit.SetTOMLTablesMatching(path, []string{jcodeModels}, nil, nil); err != nil { + return err + } + for _, kv := range kvs { + if err := edit.SetTOMLKey(path, jcodeProfile, kv[0].(string), kv[1]); err != nil { + return err + } + } + return edit.SetTOMLKey(path, jcodeProfile, "models", jcodeArray(want)) + } + // unwire takes magpie's profile out, and jcode back to what it started + // on before — when it still starts on magpie: a pick the user made in + // jcode since is theirs and stands + unwire := func(own string) error { + c, err := jcodeRead(path) + if err != nil { + return err + } + if ours(c) { + var was jcodePick + json.Unmarshal([]byte(unstash(keyPick)), &was) + if own != "" && own != was.Model { + was.Model = own + } + if err := setPick(was); err != nil { + return err + } + } else { + forget(keyPick) + if own != "" { + if err := edit.SetTOMLKey(path, "provider", "default_model", own); err != nil { + return err + } + } + } + // the profile whole: its models' tables and the user's own in it + // (headers, extra_body) are magpie's profile's, and go with it + return edit.SetTOMLTablesMatching(path, []string{jcodeProfile}, []string{jcodeProfile + "."}, nil) + } + return atomic(&Agent{ + ID: "jcode", Name: "jcode", Icon: "jcode", Spelled: prefixed, + Bin: "jcode", Dir: dir, Path: path, + Notice: func() string { + if Running(`(^|/)jcode( |$)`) { + return noticeJcode.String() + } + return "" + }, + Sync: func() error { + c, err := jcodeRead(path) + if err != nil { + return err + } + if _, on := c.Providers[magpieID]; !on { + return nil + } + return wire("") + }, + Check: func() string { + c, err := jcodeRead(path) + if err != nil { + return err.Error() + } + if !ours(c) { + return "" + } + p, on := c.Providers[magpieID] + if !on { + return "jcode's [" + jcodeProfile + "] (config.toml) is gone, so it no longer reaches magpie" + } + return wiringOff("jcode", path, func(k string) (string, bool) { + switch k { + case "base_url": + return p.BaseURL, p.BaseURL != "" + case "api_key": + return p.APIKey, p.APIKey != "" + } + return "", false + }, "base_url", at.v1(), "api_key", key()) + }, + Fields: []Field{{ + // the model jcode starts on: one of magpie's is + // magpie//, magpie's profile with the model's + // id in it + Key: "model", Label: "model", + Get: get, + Set: func(v string) error { + c, err := jcodeRead(path) + if err != nil { + return err + } + if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { + if !ours(c) { + b, _ := json.Marshal(jcodePick{c.Provider.DefaultProvider, c.Provider.DefaultModel}) + stash(map[string]string{keyPick: string(b)}) + } + if err := wire(ref); err != nil { + return err + } + return setPick(jcodePick{magpieID, ref}) + } + if _, on := c.Providers[magpieID]; on || ours(c) { + return unwire(v) + } + return setPick(jcodePick{c.Provider.DefaultProvider, v}) + }, + Options: func(cur map[string]string) []Option { + return append(jcodeOwn(path, keyPick, cur["model"]), viaMagpie("jcode", magpieID+"/")...) + }, + }}, + }, path) +} + +// jcodeOwn is the model jcode started on before magpie, or starts on now, +// for the picker: jcode's own providers are its sign-ins, which magpie +// can't list. +func jcodeOwn(path, keyPick, cur string) []Option { + var was jcodePick + json.Unmarshal([]byte(stashLoad()[keyPick]), &was) + var out []Option + for _, m := range []string{was.Model, cur} { + if m == "" || prefixed(m) || slices.ContainsFunc(out, func(o Option) bool { return o.Value == m }) { + continue + } + out = append(out, Option{Value: m, Icon: modelIcon("", m), Note: "jcode's own"}) + } + return group("jcode", out) +} diff --git a/internal/agent/jcode_test.go b/internal/agent/jcode_test.go new file mode 100644 index 000000000..86fe8bb08 --- /dev/null +++ b/internal/agent/jcode_test.go @@ -0,0 +1,303 @@ +package agent + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + toml "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// jcodeConfig is a config.toml as jcode 0.94.0 writes it after `jcode +// provider add deepseek --base-url … --model deepseek-chat --api-key-stdin +// --set-default` (toml-rs, to_string_pretty), with a comment the user added +// by hand. +const jcodeConfig = `[provider] +# my own pick +default_provider = "deepseek" +default_model = "deepseek-chat" + +[providers.deepseek] +type = "openai-compatible" +base_url = "https://api.deepseek.com/v1" +auth = "bearer" +api_key_env = "JCODE_PROVIDER_DEEPSEEK_API_KEY" +env_file = "provider-deepseek.env" +default_model = "deepseek-chat" +requires_api_key = true + +[[providers.deepseek.models]] +id = "deepseek-chat" +` + +// jcodeHome is a HOME with jcode's ~/.jcode holding body as its +// config.toml, and magpie with a provider of two models, one of them with +// effort levels. +func jcodeHome(t *testing.T, body string) (home, path string) { + t.Helper() + home = t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("JCODE_HOME", "") + if err := provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Key: "k", + Chat: "https://api.moonshot.cn/v1", Models: []string{"k2", "k2-vision"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("kimi", "https://api.moonshot.cn/v1", []catalog.Model{ + {ID: "k2", Context: 262144, Efforts: []string{"low", "medium", "high"}}, + {ID: "k2-vision", Images: true}, + }); err != nil { + t.Fatal(err) + } + path = filepath.Join(home, ".jcode", "config.toml") + if body != "" { + writeFile(t, path, body) + } + return home, path +} + +func jcodeParse(t *testing.T, path string) map[string]any { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var m map[string]any + if err := toml.Unmarshal(b, &m); err != nil { + t.Fatalf("%s is not TOML: %v\n%s", path, err, b) + } + return m +} + +func jcodeTable(m map[string]any, keys ...string) map[string]any { + for _, k := range keys { + m, _ = m[k].(map[string]any) + } + return m +} + +// jcodeModelsOf is magpie's profile's models, by id. +func jcodeModelsOf(t *testing.T, m map[string]any) map[string]map[string]any { + t.Helper() + out := map[string]map[string]any{} + list, _ := jcodeTable(m, "providers", "magpie")["models"].([]any) + for _, x := range list { + e := x.(map[string]any) + out[e["id"].(string)] = e + } + return out +} + +// Connecting jcode adds magpie's profile — the gateway, with a key naming +// jcode, and every one of magpie's models — and starts jcode on the model +// picked. The user's own profile and pick stay in the file, and Disconnect +// gives the file back byte for byte. +func TestJcode(t *testing.T) { + home, path := jcodeHome(t, jcodeConfig) + a := jcode(home) + if a.Path != path || !a.Detected() { + t.Fatalf("path %q, detected %v", a.Path, a.Detected()) + } + f := a.Field("model") + if got := f.Get(); got != "deepseek-chat" || a.Wired() || a.Check() != "" { + t.Fatalf("before: %q wired %v check %q", got, a.Wired(), a.Check()) + } + var own, ours bool + for _, o := range f.Options(a.Values()) { + own = own || o.Value == "deepseek-chat" + ours = ours || o.Value == "magpie/kimi/k2" + } + if !own || !ours { + t.Fatalf("options: own %v magpie %v", own, ours) + } + + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + m := jcodeParse(t, path) + if p := jcodeTable(m, "provider"); p["default_provider"] != "magpie" || p["default_model"] != "kimi/k2" { + t.Fatalf("[provider]: %v", p) + } + if !a.Wired() || f.Get() != "magpie/kimi/k2" { + t.Fatalf("wired %v, model %q", a.Wired(), f.Get()) + } + if c := a.Check(); c != "" { + t.Fatalf("check: %s", c) + } + p := jcodeTable(m, "providers", "magpie") + if p["type"] != "openai-compatible" || p["base_url"] != here(home).v1() || p["requires_api_key"] != true || + p["api_key"] != agentKeyAt("jcode", here(home).gw()) || p["default_model"] != "kimi/k2" { + t.Fatalf("magpie's profile: %v", p) + } + models := jcodeModelsOf(t, m) + k2, vision := models["kimi/k2"], models["kimi/k2-vision"] + if len(models) != 2 || k2 == nil || vision == nil { + t.Fatalf("models: %v", models) + } + if k2["context_window"] != int64(262144) || k2["reasoning"] != true || k2["reasoning_effort"] != nil { + t.Fatalf("k2: %v", k2) + } + if vision["context_window"] != int64(jcodeContext) || !reflect.DeepEqual(vision["input"], []any{"text", "image"}) || + vision["reasoning"] != nil { + t.Fatalf("k2-vision: %v", vision) + } + b, _ := os.ReadFile(path) + own0 := jcodeConfig[strings.Index(jcodeConfig, "[providers.deepseek]"):] + if !strings.Contains(string(b), own0) || !strings.Contains(string(b), "# my own pick\n") { + t.Fatalf("the user's own profile or comment changed:\n%s", b) + } + + // switching between magpie's models keeps what jcode was on before + if err := a.Pick("model", "magpie/kimi/k2-vision"); err != nil { + t.Fatal(err) + } + if got := f.Get(); got != "magpie/kimi/k2-vision" { + t.Fatalf("model %q", got) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != jcodeConfig { + t.Fatalf("Disconnect left:\n%s", got) + } + if a.Wired() { + t.Fatal("still wired") + } +} + +// A model of jcode's own picked while it is on magpie takes magpie out: the +// profile goes, and jcode is on the user's own provider with that model. +func TestJcodeOwnModelTakesMagpieOut(t *testing.T) { + home, path := jcodeHome(t, jcodeConfig) + a := jcode(home) + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + if err := a.Pick("model", "deepseek-reasoner"); err != nil { + t.Fatal(err) + } + want := strings.Replace(jcodeConfig, `default_model = "deepseek-chat"`+"\n\n", `default_model = "deepseek-reasoner"`+"\n\n", 1) + if got, _ := os.ReadFile(path); string(got) != want { + t.Fatalf("got:\n%s\nwant:\n%s", got, want) + } + if a.Wired() { + t.Fatal("still wired") + } +} + +// What the user sets in magpie's profile — a header, an effort on one of +// its models — is theirs, also after jcode saved the file itself (its +// models then are [[providers.magpie.models]] tables): a catalog sync +// rewrites the models and the endpoint, not those. A sync with nothing to +// change doesn't write. +func TestJcodeSyncKeepsTheirs(t *testing.T) { + home, path := jcodeHome(t, "") + a := jcode(home) + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + gw := here(home) + // as jcode's Config::save writes it, with what the user changed in it + saved := `[provider] +default_provider = "magpie" +default_model = "kimi/k2" + +[providers.magpie] +type = "openai-compatible" +base_url = "` + gw.v1() + `" +api_key = "` + agentKeyAt("jcode", gw.gw()) + `" +default_model = "kimi/k2" +requires_api_key = true + +[[providers.magpie.models]] +id = "kimi/k2" +reasoning = true +reasoning_effort = "high" +context_window = 262144 +input = ["text"] + +[[providers.magpie.models]] +id = "kimi/k2-vision" +context_window = 128000 +input = ["text", "image"] + +[providers.magpie.headers] +X-Team = "mine" +` + writeFile(t, path, saved) + // a model magpie lists no more leaves jcode's list + if err := catalog.SaveLive("kimi", "https://api.moonshot.cn/v1", []catalog.Model{ + {ID: "k2", Context: 262144, Efforts: []string{"low", "medium", "high"}}, + }); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Key: "k", + Chat: "https://api.moonshot.cn/v1", Models: []string{"k2"}}); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + m := jcodeParse(t, path) + models := jcodeModelsOf(t, m) + if len(models) != 1 || models["kimi/k2"]["reasoning_effort"] != "high" { + t.Fatalf("models: %v", models) + } + if h := jcodeTable(m, "providers", "magpie", "headers"); h["X-Team"] != "mine" { + t.Fatalf("the user's header: %v", h) + } + if c := a.Check(); c != "" { + t.Fatalf("check: %s", c) + } + + // nothing to change: the file isn't written + old := time.Now().Add(-time.Hour).Truncate(time.Second) + if err := os.Chtimes(path, old, old); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if st, _ := os.Stat(path); !st.ModTime().Equal(old) { + t.Fatalf("a sync with nothing to change wrote the file (%v)", st.ModTime()) + } + + // Disconnect takes magpie's profile out whole, its array tables and + // the user's header in it too, and leaves jcode with no pick, as before + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); strings.TrimSpace(string(got)) != "" { + t.Fatalf("Disconnect left:\n%s", got) + } +} + +// jcode's folder is $JCODE_HOME when it is set; magpie's profile gone from +// the file while jcode still starts on it is said. +func TestJcodeHome(t *testing.T) { + home, _ := jcodeHome(t, "") + dir := filepath.Join(home, "elsewhere") + t.Setenv("JCODE_HOME", dir) + a := jcode(home) + if a.Path != filepath.Join(dir, "config.toml") || a.Detected() { + t.Fatalf("path %q detected %v", a.Path, a.Detected()) + } + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + if !a.Wired() || !a.Detected() { + t.Fatalf("wired %v detected %v", a.Wired(), a.Detected()) + } + writeFile(t, a.Path, "[provider]\ndefault_provider = \"magpie\"\ndefault_model = \"kimi/k2\"\n") + if c := a.Check(); !strings.Contains(c, "is gone") { + t.Fatalf("check: %q", c) + } +} diff --git a/internal/agentenv/agentenv.go b/internal/agentenv/agentenv.go index c20a2288a..fe6208bc9 100644 --- a/internal/agentenv/agentenv.go +++ b/internal/agentenv/agentenv.go @@ -60,6 +60,8 @@ var Vars = []string{ "ANTE_HOME", // AstrBot's root, the folder holding its data/ (else ~/.astrbot, the desktop app's) "ASTRBOT_ROOT", + // jcode's folder, ~/.jcode without it + "JCODE_HOME", // MiMo Code, MiniMax Code, OpenHanako, Hermes, dsh, WorkBuddy, CodeBuddy Code "MIMOCODE_HOME", "MINIMAX_DATA_DIR", "HANA_HOME", "HERMES_HOME", "DSH_HOME", "WORKBUDDY_CONFIG_DIR", "CODEBUDDY_CONFIG_DIR", diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index eeb03791f..cd3608e28 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4146,6 +4146,7 @@ const I18N = { "Install GitHub Copilot Chat in {agent} to see magpie's models in its Chat.": "在 {agent} 中安装 GitHub Copilot Chat,才能在它的 Chat 里看到 magpie 的模型。", "It reads its settings at start-up — restart open Command Code sessions to use this.": "它启动时读取设置,需重启已打开的 Command Code 会话才会生效。", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.": "Kimi Code 启动时读取设置,需重启已打开的 kimi 会话才会生效。", + "jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode 启动时读取设置,需重启已打开的 jcode 会话才会生效。", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.": "MiniMax Code 启动时读取设置,需重启已打开的 mcode 会话才会生效。", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.": "Mister Morph 的 Console 会在新任务中使用这项设置;已打开的 morph 对话需重启才会生效。", "Muse Code reads its settings at start-up — restart open muse sessions to use this.": "Muse Code 启动时读取设置,需重启已打开的 muse 会话才会生效。", @@ -8329,6 +8330,7 @@ const I18N = { "Install GitHub Copilot Chat in {agent} to see magpie's models in its Chat.": "在 {agent} 中安裝 GitHub Copilot Chat,才能在它的 Chat 裡看到 magpie 的模型。", "It reads its settings at start-up — restart open Command Code sessions to use this.": "它啟動時讀取設定,需重啟已打開的 Command Code 會話才會生效。", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.": "Kimi Code 啟動時讀取設定,需重啟已打開的 kimi 會話才會生效。", + "jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode 啟動時讀取設定,需重啟已打開的 jcode 會話才會生效。", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.": "MiniMax Code 啟動時讀取設定,需重啟已打開的 mcode 會話才會生效。", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.": "Mister Morph 的 Console 會在新任務中使用這項設定;已打開的 morph 對話需重啟才會生效。", "Muse Code reads its settings at start-up — restart open muse sessions to use this.": "Muse Code 啟動時讀取設定,需重啟已打開的 muse 會話才會生效。", @@ -12514,6 +12516,7 @@ const I18N = { "Install GitHub Copilot Chat in {agent} to see magpie's models in its Chat.": "{agent} の Chat に magpie のモデルを表示するには、GitHub Copilot Chat をインストールしてください。", "It reads its settings at start-up — restart open Command Code sessions to use this.": "起動時に設定を読み込むため、反映するには開いている Command Code セッションを再起動してください。", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.": "Kimi Code は起動時に設定を読み込みます。反映するには開いている kimi セッションを再起動してください。", + "jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode は起動時に設定を読み込みます。反映するには開いている jcode セッションを再起動してください。", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.": "MiniMax Code は起動時に設定を読み込みます。反映するには開いている mcode セッションを再起動してください。", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.": "Mister Morph の Console は新しいタスクでこれを使います。開いている morph チャットに反映するには再起動してください。", "Muse Code reads its settings at start-up — restart open muse sessions to use this.": "Muse Code は起動時に設定を読み込みます。反映するには開いている muse セッションを再起動してください。", @@ -16699,6 +16702,7 @@ const I18N = { "Install GitHub Copilot Chat in {agent} to see magpie's models in its Chat.": "GitHub Copilot Chat in {agent} installieren, um magpies Modelle in seinem Chat zu sehen.", "It reads its settings at start-up — restart open Command Code sessions to use this.": "Es liest seine Einstellungen beim Start – offene Command-Code-Sitzungen neu starten, damit es gilt.", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.": "Kimi Code liest seine Einstellungen beim Start – offene kimi-Sitzungen neu starten, damit es gilt.", + "jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode liest seine Einstellungen beim Start – offene jcode-Sitzungen neu starten, damit es gilt.", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.": "MiniMax Code liest seine Einstellungen beim Start – offene mcode-Sitzungen neu starten, damit es gilt.", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.": "Die Console von Mister Morph nutzt dies für neue Aufgaben; offene morph-Chats neu starten, damit es dort gilt.", "Muse Code reads its settings at start-up — restart open muse sessions to use this.": "Muse Code liest seine Einstellungen beim Start – offene muse-Sitzungen neu starten, damit es gilt.", @@ -16786,6 +16790,7 @@ const NOTICES = [ "Install GitHub Copilot Chat in {agent} to see magpie's models in its Chat.", "It reads its settings at start-up — restart open Command Code sessions to use this.", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.", + "jcode reads its settings at start-up — restart open jcode sessions to use this.", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.", "Muse Code reads its settings at start-up — restart open muse sessions to use this.", diff --git a/internal/gui/assets/icons/jcode.svg b/internal/gui/assets/icons/jcode.svg new file mode 100644 index 000000000..5dea0611d --- /dev/null +++ b/internal/gui/assets/icons/jcode.svg @@ -0,0 +1 @@ +jcode