From 2ac423f4f2bca7ef06b9a2870acf395debcb7f5f Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 03:12:21 +0800 Subject: [PATCH] kimi: a Kimi Code plan model is told always_thinking, dynamically_loaded_tools and its default effort, as Kimi's list says (jiabubu) jiabubu on Discord (Kimi Code 2.2.0, Windows): Kimi Code's own provider gives K2.8 Preview and K3.1 Pro the capabilities thinking, always_thinking, image_in, video_in, tool_use and dynamically_loaded_tools; through magpie they had thinking, image_in and tool_use, so Kimi Code offered a thinking switch the models refuse to turn off, and started K2.8 on high where Kimi's own starts it on max. Kimi Code 2.4.1's managed provider (packages/oauth managed-kimi-code.ts, capabilitiesForModel) derives them from /coding/v1/models: supports_thinking_type "only" -> thinking + always_thinking, supports_dynamic_tools -> dynamically_loaded_tools, supports_video_in -> video_in, think_efforts.default_effort -> the default. magpie now reads the same fields (flat, or nested reasoning.type, tools.dynamic_load, reasoning.effort.default) into catalog.Model (AlwaysThinks, DynamicTools, DefaultEffort; kimiFacts), carries them through provider.Entry and the agent's model list, and the new Kimi Code's table gets always_thinking, dynamically_loaded_tools and default_effort at the vendor's default (else high, as before). Only Kimi's list sends these fields, so another vendor's model is written as before; kimi-cli, which refuses unknown words, gets none. A routing group has none of them. default_effort is now recorded in the stash as magpie's (kimiOwn), so a level the user picked stays while the model has it. A table with high and no record is read as the high magpie wrote before it kept one, and becomes the vendor's default (max on K2.8, high on K3/K3.1). Left out: - video_in: with type="kimi" Kimi Code uploads a video to {base_url}/files (purpose=video) and sends the ms:// id. The gateway has no /files route, and the id belongs to the account that stored it. Filed as #4485. - dynamically_loaded_tools works (Kimi Code's tool select is behind KIMI_CODE_EXPERIMENTAL_TOOL_SELECT): the loaded tools' system message is lifted into the request's tools (liftMessageTools, #2322), so they stay callable (TestKimiCodeLoadedToolsReachKimi), but each load restarts Kimi's prompt cache. Filed as #4486. - max_output_size: Kimi's own provider writes none; magpie keeps writing the model's known reply cap (32768 on K2.8 per models.dev), unchanged. This also covers #3399 (K3.1 offered thinking off): Kimi's list says "only" for both K3.1 models. Real list: tests read Kimi's /coding/v1/models reply of 2026-10-31 (internal/catalog/testdata/kimi-code-cn-models-2026-10-31.json, read with the owner's kimi-code-cn key, no key in the file). Run (mote, at this commit on origin/main b62fa332f; the agent-wiring.md line was added after the run, docs only): - go test -tags nogui -count=1 -timeout 45m ./... : 79 packages ok; internal/proc (TestNoCommandBypassesProc) and internal/sqlitedb (TestOnlyThisPackageReachesSQLite) red on a Go module cache my e2e sandbox had left inside the run folder (vendor files under e2e-kimi/sb/home/go/pkg/mod); with it removed both ok. - go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... ok; gofmt -l clean. - Real Kimi Code 2.4.1 (npm) in a sandbox HOME/KIMI_CODE_HOME on mote, with a sandbox magpie serve (MAGPIE_ADDR 127.0.0.1:34652), the kimi-code-cn preset pointed at a fake upstream that serves the real list: magpie wrote the six tables (K2.8: thinking, always_thinking, image_in, tool_use, dynamically_loaded_tools, support_efforts low/high/ max, default_effort max; K2.7 Highspeed without dynamically_loaded_tools), Kimi Code took the config, and `kimi -p` reached the upstream with thinking enabled and reasoning_effort max (K2.8) and high (K3.1 Pro). - Rebased onto 43966a53f..f2eb56c6b (claude, GUI budget, usage; none of them touch these files) as f5a82f215, then again at this head: internal/agent, internal/catalog, internal/provider ok, internal/gateway -run 'Kimi|MessageTools|Lift' ok. The full suite was not rerun there. Broken by hand, each red then green: - kimiFacts not called: TestFetchKimiCodeFacts and TestKimiCodePlanCapabilities red. - fields not carried in route.go / entryFor: TestKimiCodePlanCapabilities red. - the unrecorded-high rule off: TestKimiCodeOldHighBecomesTheVendorsDefault red. - always_thinking without the !legacy guard: the kimi-cli case red. Not tried: the TUI picker by eye (that the thinking switch is gone); tool select with a real MCP server and the experimental flag; Windows (the reporter's system; nothing here is OS-specific); a real Kimi upstream through magpie (the list was real, the chat was a fake). --- docs/subsystems/agent-wiring.md | 1 + internal/agent/kimi.go | 70 ++++++-- internal/agent/kimi_caps_test.go | 154 ++++++++++++++++++ internal/agent/route.go | 3 +- internal/catalog/catalog.go | 12 ++ internal/catalog/kimi_facts_test.go | 67 ++++++++ internal/catalog/live.go | 43 +++++ .../kimi-code-cn-models-2026-10-31.json | 1 + internal/gateway/kimi_select_tools_test.go | 80 +++++++++ internal/provider/models.go | 14 +- 10 files changed, 425 insertions(+), 20 deletions(-) create mode 100644 internal/agent/kimi_caps_test.go create mode 100644 internal/catalog/kimi_facts_test.go create mode 100644 internal/catalog/testdata/kimi-code-cn-models-2026-10-31.json create mode 100644 internal/gateway/kimi_select_tools_test.go diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index fd270557d..6e3de6cb3 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -62,6 +62,7 @@ something else shows up as drift. - Hermes's `api_key` may be a reference, `${VAR}` or `${env:VAR}`, which Hermes expands from the `.env` beside the config (its own or a profile's) and then the environment. `Check` and a sync read the key it names (`hermesKey`): one that holds (`keyHolds`) stays and isn't drift, and so does one naming a variable magpie can't see (only a shell profile sets it), which is unknown. One naming a key the gateway doesn't take is drift, and a sync keeps the reference and writes magpie's key into that `.env` under the variable, made `0600` when there is none (`hermesKeptKey`; PaulT on Discord, `TestHermesWithAKeyInItsEnvFile`). A value with more than the one reference in it is replaced by magpie's key, as before. - omp's `models.yml` keeps `modelOverrides`, `discovery`, `disableStrictTools`, headers and compat flags (`ompKept`). Its `auth` and `apiKey` are magpie's, or gone. - Kimi Code's `[providers.magpie]` has magpie's three keys set in place, so `custom_headers`, `env` and `default_model` stay (`kimiProvider`). + - A Kimi Code model table says what Kimi's own list (`/coding/v1/models`) says of the model, as Kimi Code's own provider does (`capabilitiesForModel` in its `managed-kimi-code.ts`): `always_thinking` for `supports_thinking_type` "only", `dynamically_loaded_tools` for `supports_dynamic_tools`, and `default_effort` at its `think_efforts.default_effort` (max on K2.8 Preview), else high (`kimiModelTables`, `kimiFacts`; `TestKimiCodePlanCapabilities`). kimi-cli gets neither word. `video_in` is never written: Kimi Code uploads a video to its provider's `/files`, which the gateway has no route for (#4485). A `default_effort` the user set stays while the model has it; one magpie wrote is recorded in the stash (`kimiWroteKey`), and an unrecorded high is read as the one magpie wrote before it kept a record. - Cline's `models.json` keeps the provider's other keys, and on each model magpie lists what magpie doesn't write, such as a VS Code override (`clineKept`). - VS Code's, Insiders' and VSCodium's group in `chatLanguageModels.json` (each profile's too) keeps every key magpie doesn't write, such as `settings[""].reasoningEffort`, which VS Code writes there when the user picks an effort in Copilot Chat's model picker (`setModelConfiguration`); a whole rewrite on each Sync and pick sent the model at its first level (chim3744 on Discord). A model's settings stay after it leaves the catalog; the model list is magpie's (`vscodeGroupKept`, `TestVSCodeKeepsThePickedEffort`). - Goose's custom provider file keeps a name, `timeout_seconds`, `toolshim`, headers and the like (`gooseProviderKept`). diff --git a/internal/agent/kimi.go b/internal/agent/kimi.go index 822b7c472..3a0028888 100644 --- a/internal/agent/kimi.go +++ b/internal/agent/kimi.go @@ -94,15 +94,28 @@ func kimiModelTables(path string, legacy bool, wrote map[string]map[string]strin } } var caps []string - if len(m.Efforts) > 0 { + if len(m.Efforts) > 0 || !legacy && m.AlwaysThinks { caps = append(caps, strconv.Quote("thinking")) } + // what Kimi Code's own provider says of a Kimi Code plan model + // from the same list (packages/oauth managed-kimi-code.ts, + // capabilitiesForModel): one that always thinks has no thinking + // switch, and one that loads tools mid-conversation does with + // Kimi Code's tool select on. video_in is left out: Kimi Code + // uploads a video to its provider's /files and sends the ms:// + // id, which magpie's gateway has no route for (#4485) + if !legacy && m.AlwaysThinks { + caps = append(caps, strconv.Quote("always_thinking")) + } if m.Images { caps = append(caps, strconv.Quote("image_in")) } if !legacy { caps = append(caps, strconv.Quote("tool_use")) } + if !legacy && m.DynamicTools { + caps = append(caps, strconv.Quote("dynamically_loaded_tools")) + } if len(caps) > 0 { kvs = append(kvs, edit.KV{Path: "capabilities", Value: edit.Raw("[" + strings.Join(caps, ", ") + "]")}) } @@ -123,7 +136,11 @@ func kimiModelTables(path string, legacy bool, wrote map[string]map[string]strin } } // a default effort set by hand stays while the model has it - kvs = append(kvs, kimiEfforts(m.Efforts, was["default_effort"])...) + effs, def := kimiEfforts(m.Efforts, m.DefaultEffort, was["default_effort"], wrote[name]) + kvs = append(kvs, effs...) + if def != "" { + setWrote(now, name, "default_effort", def) + } } out = append(out, edit.Table{Name: name, KVs: kvs}) } @@ -167,12 +184,17 @@ func kimiWrote(path string) map[string]map[string]string { } // kimiEfforts are a thinking model's levels for the new Kimi Code's -// thinking picker (#333): support_efforts, and default_effort high where -// the model has it, as Kimi Code takes for its own models (else it starts -// on the middle one). Without them it offers thinking on or off only and -// asks for no level at all. none is left out: Kimi Code's own off turns -// thinking off. kimi-cli has neither key. -func kimiEfforts(efforts []string, was string) []edit.KV { +// thinking picker (#333): support_efforts, and default_effort, as Kimi +// Code takes for its own models (else it starts on the middle one): the +// one the model's list says it thinks at (vendor, Kimi Code's +// think_efforts default_effort, max on K2.8), else high where the model +// has it. Without them it offers thinking on or off only and asks for no +// level at all. none is left out: Kimi Code's own off turns thinking off. +// kimi-cli has neither key. was is the table's default_effort now and +// wrote what magpie wrote in the table last (kimiOwn): one set by hand +// stays while the model has it. def is magpie's own default, "" when the +// table keeps the user's. +func kimiEfforts(efforts []string, vendor, was string, wrote map[string]string) (kvs []edit.KV, def string) { var levels, quoted []string for _, e := range efforts { if e != "none" { @@ -181,18 +203,32 @@ func kimiEfforts(efforts []string, was string) []edit.KV { } } if len(levels) == 0 { - return nil + return nil, "" } - kvs := []edit.KV{{Path: "support_efforts", Value: edit.Raw("[" + strings.Join(quoted, ", ") + "]")}} - def := "" - if slices.Contains(levels, "high") { - def = "high" + kvs = []edit.KV{{Path: "support_efforts", Value: edit.Raw("[" + strings.Join(quoted, ", ") + "]")}} + mine := "" + if slices.Contains(levels, vendor) { + mine = vendor + } else if slices.Contains(levels, "high") { + mine = "high" } - // one set by hand (was) stays while the model has it - if def = keptEffort(was, levels, def); def != "" { - kvs = append(kvs, edit.KV{Path: "default_effort", Value: def}) + // high in a table magpie kept no record of is the one it wrote before + // it kept one (it wrote high on every model that had it) + if _, ok := wrote["default_effort"]; !ok && was == "high" { + was = "" } - return kvs + v, by := kimiOwn(map[string]string{"default_effort": was}, wrote, "default_effort", mine) + if !by && !slices.Contains(levels, v) { + v, by = mine, mine != "" + } + if v == "" { + return kvs, "" + } + kvs = append(kvs, edit.KV{Path: "default_effort", Value: v}) + if by { + def = v + } + return kvs, def } func kimi(home string) *Agent { return kimiIn(here(home)) } diff --git a/internal/agent/kimi_caps_test.go b/internal/agent/kimi_caps_test.go new file mode 100644 index 000000000..364cae93f --- /dev/null +++ b/internal/agent/kimi_caps_test.go @@ -0,0 +1,154 @@ +package agent + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// jiabubu on Discord: Kimi Code's own provider gives K2.8 Preview and +// K3.1 Pro thinking, always_thinking, image_in, video_in, tool_use and +// dynamically_loaded_tools, and starts K2.8 on max; through magpie they +// had thinking, image_in and tool_use, a thinking switch Kimi refuses to +// turn off, and high. A Kimi Code plan model is now told what Kimi's list +// says of it (Kimi Code 2.4.1's managed-kimi-code.ts capabilitiesForModel) +// but video_in, which magpie's gateway can't carry. Another vendor's model +// is told what it was, and kimi-cli, which knows none of the new words, +// gets none of them. +func TestKimiCodePlanCapabilities(t *testing.T) { + 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("KIMI_SHARE_DIR", "") + t.Setenv("KIMI_CODE_HOME", "") + + // Kimi's /coding/v1/models as it answered on 2026-10-31, read the + // way magpie reads it, with the levels models.dev's catalog gives + // (Decorate) + list, err := os.ReadFile("../catalog/testdata/kimi-code-cn-models-2026-10-31.json") + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.Write(list) })) + defer srv.Close() + ms, _, err := catalog.FetchAt(context.Background(), srv.URL+"/coding/v1", "k", false, nil) + if err != nil { + t.Fatal(err) + } + ms = catalog.Decorate(ms, []catalog.Model{ + {ID: "kimi-for-coding", Efforts: []string{"none", "low", "high", "max"}, Images: true}, + {ID: "k3.1-pro", Efforts: []string{"low", "high", "max"}, Images: true}, + }) + base := "https://api.kimi.com/coding/v1" + if err := provider.Save(provider.Provider{ID: "kimi-code-cn", Name: "Kimi Code", Preset: "kimi-code-cn", Chat: base, Key: "k", + Models: []string{"kimi-for-coding", "kimi-for-coding-highspeed", "k3.1-pro"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("kimi-code-cn", base, ms); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "https://example.test/v1", Key: "k", Models: []string{"gemini-3-pro"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("relay", "https://example.test/v1", []catalog.Model{ + {ID: "gemini-3-pro", Efforts: []string{"low", "high"}, Images: true, InputModalities: []string{"text", "image", "video"}}, + }); err != nil { + t.Fatal(err) + } + + type model struct { + Capabilities []string `toml:"capabilities"` + SupportEfforts []string `toml:"support_efforts"` + DefaultEffort string `toml:"default_effort"` + } + read := func(path string) map[string]model { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var c struct{ Models map[string]model } + if err := toml.Unmarshal(b, &c); err != nil { + t.Fatalf("%v\n%s", err, b) + } + return c.Models + } + path := filepath.Join(home, ".kimi-code", "config.toml") + writeFile(t, path, "") + if err := kimi(home).Field("model").Set("magpie/kimi-code-cn/kimi-for-coding"); err != nil { + t.Fatal(err) + } + want := map[string]model{ + "magpie/kimi-code-cn/kimi-for-coding": {[]string{"thinking", "always_thinking", "image_in", "tool_use", "dynamically_loaded_tools"}, + []string{"low", "high", "max"}, "max"}, + // its list says it always thinks and loads no tools, with no levels + "magpie/kimi-code-cn/kimi-for-coding-highspeed": {[]string{"thinking", "always_thinking", "image_in", "tool_use"}, nil, ""}, + "magpie/kimi-code-cn/k3.1-pro": {[]string{"thinking", "always_thinking", "image_in", "tool_use", "dynamically_loaded_tools"}, + []string{"low", "high", "max"}, "high"}, + // another vendor's model, video and all, as it was + "magpie/relay/gemini-3-pro": {[]string{"thinking", "image_in", "tool_use"}, []string{"low", "high"}, "high"}, + } + got := read(path) + for k, w := range want { + if g := got[k]; !reflect.DeepEqual(g, w) { + t.Errorf("%s: %+v, want %+v", k, g, w) + } + } + if b, _ := os.ReadFile(path); strings.Contains(string(b), "video_in") { + t.Errorf("video_in written, which the gateway can't carry:\n%s", b) + } + + // the user's own pick on K2.8 stays; K3.1 Pro's high, written by a + // magpie that kept no record of it, is the vendor's default too + b, _ := os.ReadFile(path) + at := strings.Index(string(b), `[models."magpie/kimi-code-cn/kimi-for-coding"]`) + s := string(b[:at]) + strings.Replace(string(b[at:]), `default_effort = "max"`, `default_effort = "low"`, 1) + writeFile(t, path, s) + if err := kimi(home).Field("model").Set("magpie/kimi-code-cn/kimi-for-coding"); err != nil { + t.Fatal(err) + } + if g := read(path)["magpie/kimi-code-cn/kimi-for-coding"].DefaultEffort; g != "low" { + t.Errorf("the user's default effort on K2.8: %q, want low", g) + } + + // kimi-cli has none of the new words + os.RemoveAll(filepath.Join(home, ".kimi-code")) + legacy := filepath.Join(home, ".kimi", "config.toml") + writeFile(t, legacy, "") + if err := kimi(home).Field("model").Set("magpie/kimi-code-cn/kimi-for-coding"); err != nil { + t.Fatal(err) + } + if g := read(legacy)["magpie/kimi-code-cn/kimi-for-coding"]; !reflect.DeepEqual(g.Capabilities, []string{"thinking", "image_in"}) || g.DefaultEffort != "" { + t.Errorf("kimi-cli: %+v", g) + } +} + +// A Kimi Code config written by a magpie before this one has high on K2.8 +// with no record that magpie wrote it: it becomes the vendor's max. One +// the user picked after a record was kept stays (TestKimiCodePlanCapabilities). +func TestKimiCodeOldHighBecomesTheVendorsDefault(t *testing.T) { + kvs, def := kimiEfforts([]string{"none", "low", "high", "max"}, "max", "high", map[string]string{"display_name": "K2.8 Preview"}) + if def != "max" || kvs[len(kvs)-1].Value != "max" { + t.Errorf("unrecorded high: %v, %q", kvs, def) + } + kvs, def = kimiEfforts([]string{"none", "low", "high", "max"}, "max", "high", map[string]string{"default_effort": "max"}) + if def != "" || kvs[len(kvs)-1].Value != "high" { + t.Errorf("the user's high: %v, %q", kvs, def) + } + kvs, def = kimiEfforts([]string{"low", "high"}, "max", "", nil) + if def != "high" || kvs[len(kvs)-1].Value != "high" { + t.Errorf("a default the model hasn't: %v, %q", kvs, def) + } +} diff --git a/internal/agent/route.go b/internal/agent/route.go index 264b2e8ba..c3541bc15 100644 --- a/internal/agent/route.go +++ b/internal/agent/route.go @@ -205,7 +205,8 @@ func magpieModels(agent string) []catalog.Model { // word on included (provider.CodexEfforts) efforts = provider.CodexEfforts(e) } - m := catalog.Model{ID: e.ID, Name: labels[i], Provider: firstOf(e.Provider.Catalogs()), Efforts: efforts, Images: e.Images || seen, ImageInput: e.ImageInput, Context: e.Context, Output: e.Output, OutputSet: e.OutputSet, AgentsV2: e.AgentsV2, Reasoning: e.Thinks()} + m := catalog.Model{ID: e.ID, Name: labels[i], Provider: firstOf(e.Provider.Catalogs()), Efforts: efforts, Images: e.Images || seen, ImageInput: e.ImageInput, Context: e.Context, Output: e.Output, OutputSet: e.OutputSet, AgentsV2: e.AgentsV2, Reasoning: e.Thinks(), + AlwaysThinks: e.AlwaysThinks, DynamicTools: e.DynamicTools, DefaultEffort: e.DefaultEffort} // where Codex and Claude Code compact it (#876): a threshold the // user set on the model or on its provider, else a window they // typed whole (#1809), else the one for every model, which codexcat diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index c741b5671..fd40e7dd8 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -133,6 +133,18 @@ type Model struct { // Reasoning is set on a model that thinks, whether or not it takes // levels: mimo-v2.6-flash thinks with a switch alone (#402). Reasoning bool `json:",omitempty"` + // AlwaysThinks is set on a model its vendor's list says always thinks, + // with no way to turn it off: Kimi Code's supports_thinking_type + // "only" (reasoning.type). Kimi Code is told always_thinking for it. + AlwaysThinks bool `json:",omitempty"` + // DynamicTools is set on a model its vendor's list says loads tools + // mid-conversation: Kimi Code's supports_dynamic_tools + // (tools.dynamic_load). Kimi Code is told dynamically_loaded_tools. + DynamicTools bool `json:",omitempty"` + // DefaultEffort is the effort the vendor's list says the model thinks + // at when none is asked: Kimi Code's think_efforts.default_effort + // (reasoning.effort.default). "" is not said. + DefaultEffort string `json:",omitempty"` // WebSearch is how another magpie (a Remote magpie) searches the web // for the model when a web search tool is offered: "native", its own // provider by itself, or "magpie", with that magpie's searcher; "" it diff --git a/internal/catalog/kimi_facts_test.go b/internal/catalog/kimi_facts_test.go new file mode 100644 index 000000000..8f1d8c0b8 --- /dev/null +++ b/internal/catalog/kimi_facts_test.go @@ -0,0 +1,67 @@ +package catalog + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "testing" +) + +// jiabubu on Discord: Kimi Code's own provider has its plan's models +// always think and load tools mid-conversation, from what +// api.kimi.com/coding/v1/models says of each (supports_thinking_type +// "only", supports_dynamic_tools, think_efforts' default_effort). The list +// is read as Kimi's own reply of 2026-10-31 sends it, and its nested forms +// (reasoning.type, tools.dynamic_load, reasoning.effort.default) alone say +// the same. +func TestFetchKimiCodeFacts(t *testing.T) { + list, err := os.ReadFile("testdata/kimi-code-cn-models-2026-10-31.json") + if err != nil { + t.Fatal(err) + } + nested := `{"data":[{"id":"nested","reasoning":{"type":"only","effort":{"valid":["low","high"],"default":"low"}},"tools":{"dynamic_load":true}}, + {"id":"both","supports_thinking_type":"both","supports_dynamic_tools":false,"reasoning":{"type":"both"},"tools":{"dynamic_load":false}}, + {"id":"odd","supports_thinking_type":7,"supports_dynamic_tools":"yes","think_efforts":"max","reasoning":"only","tools":[1]}, + {"id":"glm-5","context_length":200000}]}` + for _, c := range []struct { + body string + want map[string]Model + }{ + {string(list), map[string]Model{ + "kimi-for-coding": {AlwaysThinks: true, DynamicTools: true, DefaultEffort: "max"}, + "kimi-for-coding-highspeed": {AlwaysThinks: true}, + "k3": {AlwaysThinks: true, DynamicTools: true, DefaultEffort: "high"}, + "k3-256k": {AlwaysThinks: true, DynamicTools: true, DefaultEffort: "high"}, + "k3.1-pro": {AlwaysThinks: true, DynamicTools: true, DefaultEffort: "high"}, + "k3.1-pro-highspeed": {AlwaysThinks: true, DynamicTools: true, DefaultEffort: "high"}, + }}, + {nested, map[string]Model{ + "nested": {AlwaysThinks: true, DynamicTools: true, DefaultEffort: "low"}, + "both": {}, + "odd": {}, + "glm-5": {}, + }}, + } { + srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + rw.Write([]byte(c.body)) + })) + ms, _, err := FetchAt(context.Background(), srv.URL+"/coding/v1", "k", false, nil) + srv.Close() + if err != nil { + t.Fatal(err) + } + if len(ms) != len(c.want) { + t.Fatalf("%d models: %+v", len(ms), ms) + } + for _, m := range ms { + w, ok := c.want[m.ID] + if !ok { + t.Fatalf("%s not listed", m.ID) + } + if m.AlwaysThinks != w.AlwaysThinks || m.DynamicTools != w.DynamicTools || m.DefaultEffort != w.DefaultEffort { + t.Errorf("%s: always %v, dynamic tools %v, default %q; want %v %v %q", m.ID, m.AlwaysThinks, m.DynamicTools, m.DefaultEffort, w.AlwaysThinks, w.DynamicTools, w.DefaultEffort) + } + } + } +} diff --git a/internal/catalog/live.go b/internal/catalog/live.go index 34ec9fe59..d05ec4d0d 100644 --- a/internal/catalog/live.go +++ b/internal/catalog/live.go @@ -647,6 +647,7 @@ func fetchPage(ctx context.Context, url, key string, anthropic bool, headers map if codex != nil { codexFacts(&m, r, codex) } + kimiFacts(&m, r) out = append(out, m) } return out, v.HasMore, v.LastID, nil @@ -728,6 +729,48 @@ type liveModel struct { Window any `json:"context_window"` MaxWindow any `json:"max_context_window"` Inputs any `json:"input_modalities"` + // what Kimi Code's list (/coding/v1/models) says of a model's + // thinking and tools, flat and nested: supports_thinking_type + // "only" is a model that always thinks, supports_dynamic_tools one + // that loads tools mid-conversation, think_efforts' default_effort + // the effort it thinks at unasked (Model.AlwaysThinks, DynamicTools, + // DefaultEffort). any, as an odd value mustn't lose the whole list + ThinkingType any `json:"supports_thinking_type"` + DynTools any `json:"supports_dynamic_tools"` + ThinkEfforts any `json:"think_efforts"` + Reasoning any `json:"reasoning"` + Tools any `json:"tools"` +} + +// kimiFacts reads what Kimi Code's model list says of a model's thinking +// and tools into m, from its flat fields or their nested forms +// (reasoning.type, reasoning.effort.default, tools.dynamic_load). +func kimiFacts(m *Model, r liveModel) { + field := func(v any, keys ...string) any { + for _, k := range keys { + o, ok := v.(map[string]any) + if !ok { + return nil + } + v = o[k] + } + return v + } + if t, _ := r.ThinkingType.(string); t == "only" { + m.AlwaysThinks = true + } else if t, _ := field(r.Reasoning, "type").(string); t == "only" && r.ThinkingType == nil { + m.AlwaysThinks = true + } + if b, ok := r.DynTools.(bool); ok { + m.DynamicTools = b + } else if b, ok := field(r.Tools, "dynamic_load").(bool); ok { + m.DynamicTools = b + } + if d, _ := field(r.ThinkEfforts, "default_effort").(string); d != "" { + m.DefaultEffort = d + } else if d, _ := field(r.Reasoning, "effort", "default").(string); d != "" { + m.DefaultEffort = d + } } // codexFacts reads what a Codex catalog entry says of its model into m: diff --git a/internal/catalog/testdata/kimi-code-cn-models-2026-10-31.json b/internal/catalog/testdata/kimi-code-cn-models-2026-10-31.json new file mode 100644 index 000000000..3b69c3c07 --- /dev/null +++ b/internal/catalog/testdata/kimi-code-cn-models-2026-10-31.json @@ -0,0 +1 @@ +{"data":[{"id":"kimi-for-coding","created":1761264000,"created_at":"2025-10-24T00:00:00Z","object":"model","display_name":"K2.8 Preview","type":"model","context_length":1048576,"supports_reasoning":true,"supports_image_in":true,"supports_video_in":true,"supports_dynamic_tools":true,"supports_thinking_type":"only","think_efforts":{"support":true,"valid_efforts":["low","high","max"],"default_effort":"max"},"modalities":{"input":["text","image","video"],"output":["text"]},"reasoning":{"type":"only","effort":{"valid":["low","high","max"],"default":"max"}},"tools":{"dynamic_load":true},"limit":{"context":1048576}},{"id":"kimi-for-coding-highspeed","created":1761264000,"created_at":"2025-10-24T00:00:00Z","object":"model","display_name":"K2.7 Code Highspeed","type":"model","context_length":262144,"supports_reasoning":true,"supports_image_in":true,"supports_video_in":true,"supports_dynamic_tools":false,"supports_thinking_type":"only","modalities":{"input":["text","image","video"],"output":["text"]},"reasoning":{"type":"only"},"tools":{"dynamic_load":false},"limit":{"context":262144}},{"id":"k3","created":1761264000,"created_at":"2025-10-24T00:00:00Z","object":"model","display_name":"K3","type":"model","context_length":1048576,"supports_reasoning":true,"supports_image_in":true,"supports_video_in":true,"supports_dynamic_tools":true,"supports_thinking_type":"only","think_efforts":{"support":true,"valid_efforts":["low","high","max"],"default_effort":"high"},"modalities":{"input":["text","image","video"],"output":["text"]},"reasoning":{"type":"only","effort":{"valid":["low","high","max"],"default":"high"}},"tools":{"dynamic_load":true},"limit":{"context":1048576}},{"id":"k3-256k","created":1761264000,"created_at":"2025-10-24T00:00:00Z","object":"model","display_name":"K3-256k","type":"model","context_length":262144,"supports_reasoning":true,"supports_image_in":true,"supports_video_in":false,"supports_dynamic_tools":true,"supports_thinking_type":"only","think_efforts":{"support":true,"valid_efforts":["low","high","max"],"default_effort":"high"},"modalities":{"input":["text","image"],"output":["text"]},"reasoning":{"type":"only","effort":{"valid":["low","high","max"],"default":"high"}},"tools":{"dynamic_load":true},"limit":{"context":262144}},{"id":"k3.1-pro","created":1761264000,"created_at":"2025-10-24T00:00:00Z","object":"model","display_name":"K3.1 Pro","type":"model","context_length":1048576,"supports_reasoning":true,"supports_image_in":true,"supports_video_in":true,"supports_dynamic_tools":true,"supports_thinking_type":"only","think_efforts":{"support":true,"valid_efforts":["low","high","max"],"default_effort":"high"},"modalities":{"input":["text","image","video"],"output":["text"]},"reasoning":{"type":"only","effort":{"valid":["low","high","max"],"default":"high"}},"tools":{"dynamic_load":true},"limit":{"context":1048576}},{"id":"k3.1-pro-highspeed","created":1761264000,"created_at":"2025-10-24T00:00:00Z","object":"model","display_name":"K3.1 Pro Highspeed 2x Usage Cost","type":"model","context_length":1048576,"supports_reasoning":true,"supports_image_in":true,"supports_video_in":true,"supports_dynamic_tools":true,"supports_thinking_type":"only","think_efforts":{"support":true,"valid_efforts":["low","high","max"],"default_effort":"high"},"modalities":{"input":["text","image","video"],"output":["text"]},"reasoning":{"type":"only","effort":{"valid":["low","high","max"],"default":"high"}},"tools":{"dynamic_load":true},"limit":{"context":1048576}}],"object":"list","first_id":"kimi-for-coding","last_id":"k3.1-pro-highspeed","has_more":false} \ No newline at end of file diff --git a/internal/gateway/kimi_select_tools_test.go b/internal/gateway/kimi_select_tools_test.go new file mode 100644 index 000000000..a95dd9a10 --- /dev/null +++ b/internal/gateway/kimi_select_tools_test.go @@ -0,0 +1,80 @@ +package gateway + +import ( + "encoding/json" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// Kimi Code's tool select (dynamically_loaded_tools, behind its +// KIMI_CODE_EXPERIMENTAL_TOOL_SELECT flag) keeps an MCP tool out of the +// request's tools until the model asks for it with select_tools; the tools +// it then loads go as a system message of their own in the history, +// {"role":"system","content":"","tools":[…]} (Kimi Code 2.4.1, +// llm-kimi/trait.ts convertMessage). magpie writes the capability on a Kimi +// Code plan model, so the tools that message loads reach Kimi callable: +// the gateway lifts them into the request's tools, as for Pi (#2322), +// each once, as Kimi Code wrote them, and the empty message goes. That +// restarts Kimi's prompt cache at each load (#4486). +func TestKimiCodeLoadedToolsReachKimi(t *testing.T) { + f := &fake{t: t, reply: sse( + `data: {"id":"c1","model":"kimi-for-coding","choices":[{"delta":{"role":"assistant","content":"hi"}}]}`, + `data: {"id":"c1","choices":[{"delta":{},"finish_reason":"stop"}]}`, + `data: [DONE]`)} + up := setup(t, provider.Chat, f) + if err := provider.Save(provider.Provider{ID: "kimi-code-cn", Name: "Kimi Code (China)", Preset: "kimi-code-cn", Key: "k", + Chat: up.URL + "/coding/v1", Models: []string{"kimi-for-coding"}}); err != nil { + t.Fatal(err) + } + loaded := `{"type":"function","function":{"name":"mcp__docs__search","description":"Search the docs.","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}}` + body := `{"model":"kimi-code-cn/kimi-for-coding","stream":true, + "tools":[{"type":"function","function":{"name":"select_tools","description":"Load tools.","parameters":{"type":"object","properties":{"names":{"type":"array","items":{"type":"string"}}},"required":["names"]}}}], + "messages":[ + {"role":"system","content":"You are Kimi Code."}, + {"role":"user","content":"search the docs for x"}, + {"role":"assistant","content":"","tool_calls":[{"id":"select_tools:0","type":"function","function":{"name":"select_tools","arguments":"{\"names\":[\"mcp__docs__search\"]}"}}]}, + {"role":"tool","tool_call_id":"select_tools:0","content":"Loaded mcp__docs__search."}, + {"role":"system","content":"","tools":[` + loaded + `]}, + {"role":"user","content":"go on"}]}` + code, out := post(t, "/v1/chat/completions", body) + if code != 200 { + t.Fatalf("status %d: %s", code, out) + } + var got struct { + Tools []json.RawMessage `json:"tools"` + Messages []map[string]json.RawMessage `json:"messages"` + } + if err := json.Unmarshal(f.got, &got); err != nil { + t.Fatalf("%v: %s", err, f.got) + } + var want any + json.Unmarshal([]byte(loaded), &want) + names := map[string]int{} + found := false + for _, raw := range got.Tools { + var tool struct { + Function struct { + Name string `json:"name"` + } `json:"function"` + } + json.Unmarshal(raw, &tool) + names[tool.Function.Name]++ + var v any + json.Unmarshal(raw, &v) + if tool.Function.Name == "mcp__docs__search" && jsonEqual(v, want) { + found = true + } + } + if len(got.Tools) != 2 || names["select_tools"] != 1 || !found { + t.Fatalf("tools sent: %s", f.got) + } + if len(got.Messages) != 5 { + t.Fatalf("messages sent: %s", f.got) + } + for _, m := range got.Messages { + if _, ok := m["tools"]; ok { + t.Fatalf("a message still carries tools: %s", f.got) + } + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index 5aa30472a..3ca520748 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -2641,6 +2641,14 @@ type Entry struct { // Codex is the entry the provider's own list gives the model in // Codex's shape (catalog.Model's), handed to Codex as it is Codex json.RawMessage `json:"-"` + // AlwaysThinks, DynamicTools and DefaultEffort are what the provider's + // own list says of the model (catalog.Model's): it always thinks, it + // loads tools mid-conversation, it thinks at this effort unasked. + // Kimi Code's list says them, and Kimi Code is told them (a group + // has none of them) + AlwaysThinks bool `json:"-"` + DynamicTools bool `json:"-"` + DefaultEffort string `json:"-"` } // Catalog lists the routing groups, then every exposed model of every ready @@ -2814,7 +2822,8 @@ func entryFor(p Provider, m catalog.Model, s settings.Settings) Entry { name := cmp.Or(m.Name, m.ID) e := Entry{ID: p.ID + "/" + m.ID, Model: m.ID, Family: p.Family, Name: name, Efforts: effortsOf(m), Provider: p, Images: images, ImageInput: imageInput, Context: ctx, WindowSet: p.ContextOf(m.ID) > 0, Output: output, OutputSet: outputOf(s, p.ID, m.ID) > 0, Free: m.Free, Rate: m.Rate, RateWas: m.RateWas, Tiers: m.Tiers, Released: m.Released, - Inputs: m.InputModalities, Outputs: m.OutputModalities, Codex: m.Codex} + Inputs: m.InputModalities, Outputs: m.OutputModalities, Codex: m.Codex, + AlwaysThinks: m.AlwaysThinks, DynamicTools: m.DynamicTools, DefaultEffort: m.DefaultEffort} if lv, ok := catalog.CodexLevels(m.Codex); ok { // the levels the vendor lists the model at in Codex's shape are // its word, over models.dev's for the same id (Decorate) @@ -2828,7 +2837,7 @@ func entryFor(p Provider, m catalog.Model, s settings.Settings) Entry { // a model that thinks still does with the levels the user kept or // none at all; one its source says nothing of thinks as most of the // providers serving it say (#402) - e.Reasoning = m.Reasoning || len(e.Efforts) > 0 || catalog.Thinks(m.ID) + e.Reasoning = m.Reasoning || m.AlwaysThinks || len(e.Efforts) > 0 || catalog.Thinks(m.ID) e.Efforts = effortsKept(e.Efforts, s.ModelEfforts[e.ID]) // levels the user gave a model with none known say it thinks too, so // an agent told its levels isn't told it doesn't reason @@ -2846,6 +2855,7 @@ func entryFor(p Provider, m catalog.Model, s settings.Settings) Entry { // none (SetModelReasonless), whatever its list says if s.ModelReasonless[e.ID] { e.Efforts, e.Reasoning, e.AgentsV2, e.Reasonless = nil, false, false, true + e.AlwaysThinks, e.DefaultEffort = false, "" } return e }