diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index d767e02b7..cd0605a57 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -86,6 +86,7 @@ something else shows up as drift. - 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`). A routing group says each of the three when every member's entry says the same, and none of it when one member doesn't (`groupSharedKimi`; `TestGroupSharesKimiFacts`). 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. + - Kimi Code's thinking field (`kimiThinkingField`) is the level its sessions start at, in `[thinking]` as Kimi Code's own `/model` saves it: `enabled = false` for off, else `enabled = true` and `effort`; Default takes both out, so each model starts at its `default_effort`, and off keeps `effort` for the next on, as Kimi Code does. Its levels are the current model table's `support_efforts` (an `[overrides]` table's first), with off unless the model is `always_thinking`, and the common levels for a model the config doesn't describe (`kimiThinkingOptions`). kimi-cli has only its top-level `default_thinking` (on, off). The `[thinking]` table keeps every other key (`keep`), and an empty one goes (`TestKimiThinkingField`). - 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 55d35d838..6c9dec2a6 100644 --- a/internal/agent/kimi.go +++ b/internal/agent/kimi.go @@ -21,6 +21,8 @@ import ( "strconv" "strings" + "github.com/pelletier/go-toml/v2" + "github.com/yetone/magpie/internal/edit" ) @@ -364,10 +366,130 @@ func kimiIn(at place) *Agent { Options: func(cur map[string]string) []Option { return withVia(kimiOwnOptions(path, cur["model"]), "kimi", magpieID+"/") }, - }}, + }, kimiThinkingField(path, legacy, at.cold)}, }, path) } +// kimiThinkingField is the thinking level Kimi Code starts its sessions +// at (@apple_test_src on X: every other agent had one). The new Kimi Code +// keeps it in [thinking] (packages/agent-core-v2's ThinkingConfigSchema): +// enabled = false for off, else effort, the level its own /model saves +// beside default_model (persistModelSelection, thinkingEffortToConfig); +// with neither it starts each model at the model's default_effort. A level +// the model doesn't have starts it at its default too. kimi-cli has only +// thinking on or off, its top-level default_thinking. A stopped WSL +// distro's (cold) levels are the common ones: reading its config would +// start it again (#3896). +func kimiThinkingField(path string, legacy, cold bool) Field { + if legacy { + return Field{ + Key: "effort", Label: "thinking", + Get: func() string { + switch v, _ := edit.GetTOMLTop(path, "default_thinking"); v { + case "true": + return "on" + case "false": + return "off" + } + return "" + }, + Set: func(v string) error { + if v == "" { + return edit.DelTOMLTop(path, "default_thinking") + } + return edit.SetTOMLTop(path, edit.KV{Path: "default_thinking", Value: v != "off"}) + }, + Options: func(map[string]string) []Option { return static("off", "on") }, + } + } + return Field{ + Key: "effort", Label: "thinking", + Get: func() string { + t, _ := edit.GetTOMLTable(path, "thinking") + if t["enabled"] == "false" { + return "off" + } + return t["effort"] + }, + Set: func(v string) error { + switch v { + case "": + if err := edit.DelTOMLKey(path, "thinking", "effort"); err != nil { + return err + } + return edit.DelTOMLKey(path, "thinking", "enabled") + case "off": + // as Kimi Code's own off: the level stays for the next on + return edit.SetTOMLKey(path, "thinking", "enabled", false) + } + if err := edit.SetTOMLKey(path, "thinking", "enabled", true); err != nil { + return err + } + return edit.SetTOMLKey(path, "thinking", "effort", v) + }, + Options: func(cur map[string]string) []Option { + if cold { + return static(kimiCommonLevels...) + } + return kimiThinkingOptions(path, cur["model"]) + }, + } +} + +// kimiCommonLevels are the levels offered for a model whose own aren't known. +var kimiCommonLevels = []string{"off", "low", "medium", "high"} + +// kimiThinkingOptions are the levels Kimi Code offers for model, the key +// of a model table in its config at path: off, then its support_efforts +// (its [overrides]' when they say), Default being the model's +// default_effort; off alone for a model that thinks with no levels, and +// none for one that doesn't think. A model the config doesn't describe +// (Kimi Code's own sign-in's, from its catalog) gets the common levels. +func kimiThinkingOptions(path, model string) []Option { + type levels struct { + Capabilities []string `toml:"capabilities"` + SupportEfforts []string `toml:"support_efforts"` + DefaultEffort string `toml:"default_effort"` + } + var doc struct { + Models map[string]struct { + levels + Overrides *levels `toml:"overrides"` + } `toml:"models"` + } + b, err := edit.Read(path) + if err != nil || toml.Unmarshal(edit.TrimBOM(b), &doc) != nil { + return static(kimiCommonLevels...) + } + m, ok := doc.Models[model] + if !ok { + return static(kimiCommonLevels...) + } + efforts, def, caps := m.SupportEfforts, m.DefaultEffort, m.Capabilities + if o := m.Overrides; o != nil { + if o.SupportEfforts != nil { + efforts = o.SupportEfforts + } + if o.DefaultEffort != "" { + def = o.DefaultEffort + } + if o.Capabilities != nil { + caps = o.Capabilities + } + } + if len(efforts) == 0 && !slices.Contains(caps, "thinking") && !slices.Contains(caps, "always_thinking") { + return nil + } + var out []Option + if slices.Contains(efforts, def) { + out = append(out, Option{Value: "", Note: "Kimi Code's default for the model: " + def, Takes: def}) + } + if !slices.Contains(caps, "always_thinking") { + out = append(out, Option{Value: "off"}) + } + return append(out, static(efforts...)...) +} + // kimiOwnOptions are the models of the user's own in Kimi's config: its // Kimi Code sign-in's and any provider they added, and the current one. func kimiOwnOptions(path, cur string) []Option { diff --git a/internal/agent/kimi_efforts_test.go b/internal/agent/kimi_efforts_test.go index 09aaacaaa..9114aa941 100644 --- a/internal/agent/kimi_efforts_test.go +++ b/internal/agent/kimi_efforts_test.go @@ -4,6 +4,7 @@ import ( "os" "path/filepath" "reflect" + "strings" "testing" "github.com/pelletier/go-toml/v2" @@ -81,3 +82,160 @@ func TestKimiEfforts(t *testing.T) { t.Errorf("kimi-cli's: %+v", got) } } + +// @apple_test_src on X: Kimi Code had no thinking level to pick where +// every other agent had one. It is Kimi Code's [thinking] (enabled, +// effort), as its own /model saves it, the rest of the table kept; the +// levels are the current model's; kimi-cli has default_thinking only. +func TestKimiThinkingField(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("KIMI_SHARE_DIR", "") + t.Setenv("KIMI_CODE_HOME", "") + path := filepath.Join(home, ".kimi-code", "config.toml") + writeFile(t, path, `default_model = "deep" + +[models.deep] +provider = "p" +model = "deep" +capabilities = ["thinking"] +support_efforts = ["low", "high", "max"] +default_effort = "high" + +[models.plain] +provider = "p" +model = "plain" + +[models.bare] +provider = "p" +model = "bare" +capabilities = ["thinking"] + +[models.always] +provider = "p" +model = "always" +support_efforts = ["low"] + +[models.always.overrides] +capabilities = ["thinking", "always_thinking"] +support_efforts = ["medium", "max"] + +[thinking] +keep = "all" +`) + f := kimi(home).Field("effort") + if f == nil { + t.Fatal("Kimi Code has no thinking field") + } + type th struct { + Enabled *bool `toml:"enabled"` + Effort string `toml:"effort"` + Keep string `toml:"keep"` + } + read := func() *th { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var c struct{ Thinking *th } + if err := toml.Unmarshal(b, &c); err != nil { + t.Fatalf("%v\n%s", err, b) + } + return c.Thinking + } + yes, no := true, false + for _, step := range []struct { + set string + want th + }{ + {"max", th{&yes, "max", "all"}}, + {"off", th{&no, "max", "all"}}, + {"low", th{&yes, "low", "all"}}, + {"", th{nil, "", "all"}}, + } { + if err := f.Set(step.set); err != nil { + t.Fatal(err) + } + if got := read(); got == nil || !reflect.DeepEqual(*got, step.want) { + t.Fatalf("set %q: [thinking] %+v, want %+v", step.set, got, step.want) + } + if got := f.Get(); got != step.set { + t.Errorf("set %q, read back %q", step.set, got) + } + } + // with nothing of the user's beside it, Default takes the table out + writeFile(t, path, "[models.deep]\nprovider = \"p\"\n\n[thinking]\nenabled = false\n") + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if got := read(); got != nil { + t.Errorf("Default left [thinking] %+v", *got) + } + if got := f.Get(); got != "" { + t.Errorf("no [thinking] reads %q", got) + } + + writeFile(t, path, `[models.deep] +capabilities = ["thinking"] +support_efforts = ["low", "high", "max"] +default_effort = "high" + +[models.plain] +model = "plain" + +[models.bare] +capabilities = ["thinking"] + +[models.always] +support_efforts = ["low"] + +[models.always.overrides] +capabilities = ["thinking", "always_thinking"] +support_efforts = ["medium", "max"] +`) + vals := func(opts []Option) []string { + out := []string{} + for _, o := range opts { + out = append(out, o.Value+"/"+o.Takes) + } + return out + } + for model, want := range map[string][]string{ + "deep": {"/high", "off/", "low/", "high/", "max/"}, + "plain": {}, + "bare": {"off/"}, + "always": {"medium/", "max/"}, + "unknown": {"off/", "low/", "medium/", "high/"}, + } { + if got := vals(f.Options(map[string]string{"model": model})); !reflect.DeepEqual(got, want) { + t.Errorf("%s: levels %v, want %v", model, got, want) + } + } + + // kimi-cli: default_thinking, on or off + os.RemoveAll(filepath.Join(home, ".kimi-code")) + legacy := filepath.Join(home, ".kimi", "config.toml") + writeFile(t, legacy, "default_model = \"x\"\n") + f = kimi(home).Field("effort") + if got := vals(f.Options(nil)); !reflect.DeepEqual(got, []string{"off/", "on/"}) { + t.Errorf("kimi-cli levels %v", got) + } + for _, step := range []struct{ set, line string }{ + {"on", "default_thinking = true"}, + {"off", "default_thinking = false"}, + {"", ""}, + } { + if err := f.Set(step.set); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(legacy) + if step.line != "" && !strings.Contains(string(b), step.line) || step.line == "" && strings.Contains(string(b), "default_thinking") { + t.Errorf("set %q: %s", step.set, b) + } + if got := f.Get(); got != step.set { + t.Errorf("kimi-cli: set %q, read back %q", step.set, got) + } + } +} diff --git a/internal/gui/tests/kimi-thinking.test.cjs b/internal/gui/tests/kimi-thinking.test.cjs new file mode 100644 index 000000000..717490bc8 --- /dev/null +++ b/internal/gui/tests/kimi-thinking.test.cjs @@ -0,0 +1,132 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Kimi Code's thinking level (@apple_test_src on X: every other agent had +// one, Kimi Code none). It is Kimi Code's own [thinking] in config.toml; +// Default is the model's default_effort, which the row names, then off and +// the model's support_efforts. In the window it is in the row opened from +// its link; in the tray panel the row opens to its slider. A pick posts +// the field; nothing runs off the side of a narrow window. +// English, Simplified and Traditional Chinese, Japanese and German, +// Chromium and WebKit. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const levels = ["off", "low", "medium", "high", "max"]; +const model = "magpie/moonshot/kimi-k2.8"; +const kimi = (effort) => ({ + id: "kimi", name: "Kimi Code", icon: "kimi", path: "/home/u/.kimi-code/config.toml", wired: true, + fields: [ + { key: "model", label: "model", value: model, options: [{ value: model, icon: "kimi", ref: "moonshot/kimi-k2.8" }] }, + { key: "effort", label: "thinking", value: effort, options: [{ value: "", note: "Kimi Code's default for the model: medium", takes: "medium" }, ...levels.map((value) => ({ value }))] }, + ], +}); +const filler = Array.from({ length: 6 }, (_, i) => ({ id: "pi" + i, name: "Pi " + i, path: "/p", fields: [{ key: "model", label: "model", value: "", options: [] }] })); + +function serve(lang, sets) { + let effort = ""; + const st = () => ({ agents: [kimi(effort), ...filler], profiles: [], settings: { lang, theme: "light", guideHidden: true } }); + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: st() }); + if (url.pathname === "/api/set") { + const b = req.postDataJSON(); + sets.push(b); + if (b.field === "effort") effort = b.value; + return route.fulfill({ json: st() }); + } + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { thinking: "thinking", def: "default (medium)", low: "low", off: "off" }, + zh: { thinking: "思考", def: "默认(中)", low: "低", off: "关闭" }, + "zh-TW": { thinking: "思考", def: "預設(中)", low: "低", off: "關閉" }, + ja: { thinking: "思考", def: "デフォルト(中)", low: "低", off: "オフ" }, + de: { thinking: "Thinking", def: "Standard (mittel)", low: "niedrig", off: "aus" }, +}; +const row = `.row.agent[data-id="kimi"]`; +const noSideScroll = (page) => page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: Kimi Code has a thinking level`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + const open = async (mode, sets) => { + const page = await (await browser.newContext({ viewport: { width: mode ? 440 : 560, height: 640 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, sets)); + await page.goto("http://magpie.test/" + (mode ? "?mode=" + mode : "")); + await page.locator(row).waitFor(); + return page; + }; + + await t.test("the window", async () => { + const sets = []; + const page = await open("", sets); + await page.locator(`${row} .ag-link`).click(); + await page.locator(`${row} .ag-exp`).waitFor(); + const field = page.locator(`${row} .field[data-key="effort"]`); + assert.equal(await field.count(), 1); + assert.equal(await field.locator(".v").textContent(), w.def); + const box = await field.boundingBox(); + assert(box.x >= 0 && box.x + box.width <= 560, `the effort runs off the window: ${JSON.stringify(box)}`); + assert(await noSideScroll(page), "the window scrolls sideways"); + + const y = await page.evaluate(() => scrollY); + await field.click(); + await page.locator("#effortControl:not([hidden])").waitFor(); + assert.equal(await page.evaluate(() => scrollY), y, "the click scrolled the page"); + assert.equal(await page.locator("#effortTitle").textContent(), w.thinking); + assert.equal(await page.locator("#effortValue").textContent(), w.def); + // the default, off, then the model's four levels + assert.equal(await page.locator("#effortTicks i").count(), 6); + await page.locator("#effortRange").evaluate((r) => { + r.value = "2"; + r.dispatchEvent(new Event("input", { bubbles: true })); + r.dispatchEvent(new Event("change", { bubbles: true })); + }); + assert.equal(await page.locator("#effortValue").textContent(), w.low); + await page.waitForFunction(() => document.querySelector('.row.agent[data-id="kimi"] .field[data-key="effort"] .v')?.textContent !== document.querySelector("#effortMin")?.textContent); + assert.deepEqual(sets, [{ agent: "kimi", field: "effort", value: "low" }]); + assert.equal(await page.locator(`${row} .field[data-key="effort"] .v`).textContent(), w.low); + assert(await noSideScroll(page), "the window scrolls sideways"); + }); + + await t.test("the panel", async () => { + const sets = []; + const page = await open("panel", sets); + await page.locator(`${row} .ag-sum`).click(); + await page.waitForTimeout(700); + const box = page.locator(`${row} .ag-open .effort-control`); + assert.equal(await box.locator(".effort-ticks i").count(), 6); + await box.locator(".eslide").press("ArrowRight"); + await page.waitForTimeout(300); + assert.deepEqual(sets, [{ agent: "kimi", field: "effort", value: "off" }]); + assert(await noSideScroll(page), "the panel scrolls sideways"); + }); + + assert.deepEqual(errors, []); + }); + } +}