From 9e665491ece07dc986dc6bdf7f6569a622157697 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 10 Oct 2026 14:45:34 +0800 Subject: [PATCH] =?UTF-8?q?context:=20Tuned=20for=20you=20=E2=80=94=20each?= =?UTF-8?q?=20agent's=20settings=20worked=20out=20from=20the=20user's=20ow?= =?UTF-8?q?n=20calls,=20for=20the=20fewest=20tokens,=20put=20in=20on=20a?= =?UTF-8?q?=20click=20and=20undone=20on=20another?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Context tab now replays the period's calls of each agent against the settings that decide what they cost, and shows, per agent and per model, the value that would have used the fewest tokens for how this user works: Claude Code's auto-compact window per model (modelSettings.. autoCompactWindow), its main and subagent prompt cache lifetimes (promptCacheTtl, subagentPromptCacheTtl: 5m or 1h), and Codex's model_auto_compact_token_limit. Each row says where the value comes from now (the agent's default, the user's own setting, one magpie set, or a variable that comes first and locks it), why (how fast conversations grow, what a compaction leaves, how long the user pauses), the cost curve, and the saving. Nothing is written until "Use …" is clicked; what was there is stashed and Undo puts it back, unless the user changed it since. A window the user set past the model's own is shown capped, as Claude Code caps it (min(setting, model window)), so no saving is claimed that wouldn't happen. Advice under a 3% saving is "already the leanest". On the owner's 7 days (88K Claude Code calls, 956 Codex): opus keeps 200K (their 500K is capped to it), fable 5.1 200K → 160K saves 5% (2.56M tokens), both cache lifetimes and Codex's 272K are already the leanest. Run: go vet ./... and go test ./... pass (internal/tune, internal/agent TestTune*: user-set values kept, env locks, undo after a user edit, TOML key order). context-tune.test.cjs passes in Chromium and WebKit, en/zh/ zh-TW/ja/de, at 360 and 1100px (22); context-window, context-scroll-end pass. Full GUI suite: library-servers-bulk and market-have failed once under load and pass alone; market-have fails on origin/main 494dedcf too (1 of 8 runs). Claude Code 2.1.296 in a sandbox config dir shows "Auto-compact window for Fable 5.1: 160k tokens (from settings)" for the written modelSettings key. The real-data advice was read from the owner's own ~/.claude and ~/.codex, nothing written. --- docs/subsystems/agent-wiring.md | 4 + docs/subsystems/gui-shell.md | 2 +- internal/agent/tune.go | 261 +++++++++++++ internal/agent/tune_test.go | 153 ++++++++ internal/gui/assets/context.css | 33 +- internal/gui/assets/context.js | 176 +++++++++ internal/gui/assets/i18n.js | 108 ++++++ internal/gui/providers.go | 1 + internal/gui/tests/context-tune.test.cjs | 140 +++++++ internal/gui/tune.go | 159 ++++++++ internal/tune/tune.go | 469 +++++++++++++++++++++++ internal/tune/tune_test.go | 126 ++++++ 12 files changed, 1630 insertions(+), 2 deletions(-) create mode 100644 internal/agent/tune.go create mode 100644 internal/agent/tune_test.go create mode 100644 internal/gui/tests/context-tune.test.cjs create mode 100644 internal/gui/tune.go create mode 100644 internal/tune/tune.go create mode 100644 internal/tune/tune_test.go diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 121b6d90f..8daac6770 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -22,6 +22,7 @@ something else shows up as drift. | Keeping configs current | `Reseat` moves agents off a model magpie no longer serves (#200). `OnGateway` and `Rewire` write the new gateway address into every connected agent when the port changes. `Source` and `Stale` say what an unconnected agent runs on, and whether running copies still use the old list. | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) | | Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#` on Windows, `omp#@wsl:` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) | | WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `@wsl:`, edited through `\\wsl.localhost\`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) | +| Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings..autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`; Codex's top-level `model_auto_compact_token_limit`. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) | | Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`cursorLocalEfforts`, #1003). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) | ## Runtime path @@ -55,6 +56,7 @@ something else shows up as drift. - Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the Codex app holds the ChatGPT account Codex is signed in to (`codexUsedUp`, `provider.CodexUsedUp`: OpenAI no longer allows the account and it has no credits left, a workspace still within its overage excepted), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it holds, a magpie model's turn included (#540), and as a provider of its own magpie is past that. A window at 100% with credits left doesn't count, and Codex stays signed in. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them. - Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. - An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says. +- Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune..[.]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise. - Tests never touch the real machine. `TestMain` uses `testenv`, which points HOME, USERPROFILE, the XDG folders and APPDATA into a temporary folder, clears `agentenv.Vars` and puts failing stand-ins for keychain tools and agent CLIs on PATH. Agent-specific side effects (Aside, the Zed keychain, Codex's usage check) are also stubbed in `TestMain`. ## Verification @@ -65,5 +67,7 @@ go test -tags nogui ./internal/agent go test -tags nogui ./internal/agent -run '^TestAir' go test -tags nogui ./internal/agent -run '^TestAnte' go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexOwnModelThroughMagpieWhileAccountsOn|TestCodexHandWrittenBaseURLStays' +go test -tags nogui ./internal/tune ./internal/agent -run 'TestCompact|TestCacheTTL|TestTune' +node --test internal/gui/tests/context-tune.test.cjs node --test internal/gui/tests/agent-connect.test.cjs internal/gui/tests/agent-disconnect-preview.test.cjs internal/gui/tests/claude-signin.test.cjs internal/gui/tests/agent-failover.test.cjs ``` diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 00ba84e88..9f2b9208d 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -15,7 +15,7 @@ three. | Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil). `stopServing` drains requests in flight. | [`backend.go`](../../internal/gui/backend.go) | | API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set` and `/api/agents/{action}/{id}`. `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page. | [`api.go`](../../internal/gui/api.go) | | Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go) | -| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `routing.js`, `library.js`, `plugins.js`, `sessions.js` and `context.js` (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent). Strings go through `t()` with translations in `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) | +| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `routing.js`, `library.js`, `plugins.js`, `sessions.js` and `context.js` (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) | | No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../gui_off.go) | ## Runtime path diff --git a/internal/agent/tune.go b/internal/agent/tune.go new file mode 100644 index 000000000..eb952ac55 --- /dev/null +++ b/internal/agent/tune.go @@ -0,0 +1,261 @@ +package agent + +// The settings tune advises (internal/tune), as each agent's config has +// them, and putting one in on the user's say: Claude Code's auto-compact +// window for a model and its cache lifetimes, Codex's auto-compact limit. +// What was there before is stashed, so Undo puts it back; a variable that +// takes precedence over the setting is told of, never written over. + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/yetone/magpie/internal/edit" +) + +// The settings tune knows. +const ( + TuneCompact = "compact" // when the agent compacts its conversation, in tokens + TuneCache = "cache_ttl" // Claude Code: the main conversation's cache, 5m or 1h + TuneSubCache = "subagent_cache_ttl" // Claude Code: its subagents', workflows' and helpers' +) + +// TuneSetting is one of those settings as an agent has it now. +type TuneSetting struct { + Value string `json:"value,omitempty"` // "" when nothing sets it + // Where Value comes from: settings (the agent's own config file), + // model (Claude Code's modelSettings for the model), env + Source string `json:"source,omitempty"` + // Locked names the variable that takes precedence over the setting, + // which tune leaves as it is: putting the advice in would change nothing + Locked string `json:"locked,omitempty"` + // Ours: tune put Value in, and Undo puts back what was there + Ours bool `json:"ours,omitempty"` +} + +// tuneStash is what a setting was before tune put one in. +type tuneStash struct { + Had bool `json:"had"` + Raw string `json:"raw,omitempty"` // as the file had it, JSON or TOML + Set string `json:"set"` // the value tune put in +} + +func tuneKey(agent, knob, model string) string { + k := "tune." + agent + "." + knob + if model != "" { + k += "." + model + } + return k +} + +func tuneHome(home string) string { + if home != "" { + return home + } + h, _ := os.UserHomeDir() + return h +} + +// tunePlace is where a setting lives: the file, its key path, and the +// variables that take precedence over it, first first. +type tunePlace struct { + path string + key string + toml bool + env []string + number bool +} + +func tuneWhere(home, agent, knob, model string) (tunePlace, error) { + home = tuneHome(home) + switch agent { + case "claude": + path := filepath.Join(home, ".claude", "settings.json") + switch knob { + case TuneCompact: + n := claudeName(model) + if n == "" { + return tunePlace{}, fmt.Errorf("%q is no Claude model: Claude Code's window for it is magpie's own, under Settings", model) + } + return tunePlace{path: path, key: "modelSettings." + n + ".autoCompactWindow", env: []string{claudeCompactEnv}, number: true}, nil + case TuneCache: + return tunePlace{path: path, key: "promptCacheTtl", env: []string{"FORCE_PROMPT_CACHING_5M", "CLAUDE_CODE_PROMPT_CACHE_TTL"}}, nil + case TuneSubCache: + return tunePlace{path: path, key: "subagentPromptCacheTtl", env: []string{"FORCE_PROMPT_CACHING_5M", "CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL"}}, nil + } + case "codex": + if knob == TuneCompact { + return tunePlace{path: filepath.Join(home, ".codex", "config.toml"), key: "model_auto_compact_token_limit", toml: true, number: true}, nil + } + } + return tunePlace{}, fmt.Errorf("%s has no setting %q tune can put in", agent, knob) +} + +func (p tunePlace) get() (string, bool) { + if p.toml { + return edit.GetTOMLTop(p.path, p.key) + } + return edit.GetJSON(p.path, p.key) +} + +// envOf is a variable Claude Code starts with: in settings.json's env, or +// magpie's own, which a terminal it is run from most likely has too. +func (p tunePlace) envOf(k string) string { + if v, _ := edit.GetJSON(p.path, "env."+k); v != "" { + return v + } + return os.Getenv(k) +} + +// TuneRead is how an agent has a setting tune advises now. +func TuneRead(home, agent, knob, model string) (TuneSetting, error) { + p, err := tuneWhere(home, agent, knob, model) + if err != nil { + return TuneSetting{}, err + } + var s TuneSetting + for _, k := range p.env { + if v := p.envOf(k); v != "" && v != "0" && v != "false" { + s.Locked = k + s.Value, s.Source = v, "env" + if k == "FORCE_PROMPT_CACHING_5M" { + s.Value = "5m" + } + break + } + } + if s.Locked == "" { + if v, ok := p.get(); ok && v != "auto" { + s.Value, s.Source = strings.Trim(v, `"'`), "settings" + if knob == TuneCompact && agent == "claude" { + s.Source = "model" + } + } else if agent == "claude" && knob == TuneCompact { + // the top-level window serves every model with none of its own + if v, ok := edit.GetJSON(p.path, "autoCompactWindow"); ok && v != "auto" { + s.Value, s.Source = v, "settings" + } + } + } + if st, ok := tuneStashed(agent, knob, model); ok && s.Locked == "" { + v, _ := p.get() + s.Ours = strings.Trim(v, `"'`) == st.Set + } + return s, nil +} + +func tuneStashed(agent, knob, model string) (tuneStash, bool) { + raw := stashLoad()[tuneKey(agent, knob, model)] + if raw == "" { + return tuneStash{}, false + } + var st tuneStash + if json.Unmarshal([]byte(raw), &st) != nil { + return tuneStash{}, false + } + return st, true +} + +// TuneApply puts value in as an agent's setting, on the user's say. What +// was there before is kept, the first time only, for TuneUndo. A variable +// that takes precedence is an error: the setting would change nothing. +func TuneApply(home, agent, knob, model, value string) error { + p, err := tuneWhere(home, agent, knob, model) + if err != nil { + return err + } + cur, _ := TuneRead(home, agent, knob, model) + if cur.Locked != "" { + return fmt.Errorf("%s=%s is set and comes before the setting: take it out first", cur.Locked, cur.Value) + } + var v any = value + if p.number { + n, err := strconv.Atoi(value) + if err != nil || n <= 0 { + return fmt.Errorf("%q is no token count", value) + } + if agent == "claude" && (n < 100000 || n > 1000000) { + return fmt.Errorf("Claude Code takes a window of 100000 to 1000000 tokens, not %d", n) + } + v = n + } else if value != "5m" && value != "1h" { + return fmt.Errorf("the cache is kept 5m or 1h, not %q", value) + } + key := tuneKey(agent, knob, model) + if _, ok := tuneStashed(agent, knob, model); !ok { + raw, had := p.get() + b, _ := json.Marshal(tuneStash{Had: had, Raw: raw, Set: value}) + stash(map[string]string{key: string(b)}) + } else { + st, _ := tuneStashed(agent, knob, model) + st.Set = value + b, _ := json.Marshal(st) + stash(map[string]string{key: string(b)}) + } + if p.toml { + return edit.SetTOMLTop(p.path, edit.KV{Path: p.key, Value: v}) + } + return edit.SetJSON(p.path, edit.KV{Path: p.key, Value: v}) +} + +// TuneUndo puts back what a setting was before tune put one in, unless +// the user has changed it since: then it is theirs, and only forgotten. +func TuneUndo(home, agent, knob, model string) error { + p, err := tuneWhere(home, agent, knob, model) + if err != nil { + return err + } + st, ok := tuneStashed(agent, knob, model) + if !ok { + return fmt.Errorf("magpie didn't set %s", p.key) + } + defer forget(tuneKey(agent, knob, model)) + if v, _ := p.get(); strings.Trim(v, `"'`) != st.Set { + return nil + } + if st.Had { + var v any + if p.toml { + v = tomlRaw(st.Raw) + } else if json.Unmarshal([]byte(st.Raw), &v) != nil { + v = st.Raw + } + if p.toml { + return edit.SetTOMLTop(p.path, edit.KV{Path: p.key, Value: v}) + } + return edit.SetJSON(p.path, edit.KV{Path: p.key, Value: v}) + } + if p.toml { + return edit.DelTOMLTop(p.path, p.key) + } + if err := edit.DelJSON(p.path, p.key); err != nil { + return err + } + // an entry under modelSettings left with nothing in it goes too + if agent == "claude" && knob == TuneCompact { + n := claudeName(model) + empty := func(k string) bool { + v, ok := edit.GetJSON(p.path, k) + return ok && strings.Join(strings.Fields(v), "") == "{}" + } + if empty("modelSettings." + n) { + edit.DelJSON(p.path, "modelSettings."+n) + } + if empty("modelSettings") { + edit.DelJSON(p.path, "modelSettings") + } + } + return nil +} + +// tomlRaw is a TOML value as GetTOMLTop read it, as a value to write. +func tomlRaw(raw string) any { + if n, err := strconv.Atoi(raw); err == nil { + return n + } + return strings.Trim(raw, `"'`) +} diff --git a/internal/agent/tune_test.go b/internal/agent/tune_test.go new file mode 100644 index 000000000..4bc0e5cdf --- /dev/null +++ b/internal/agent/tune_test.go @@ -0,0 +1,153 @@ +package agent + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func tuneSandbox(t *testing.T) string { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming")) + t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local")) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + for _, k := range []string{"CLAUDE_CODE_AUTO_COMPACT_WINDOW", "FORCE_PROMPT_CACHING_5M", "CLAUDE_CODE_PROMPT_CACHE_TTL", "CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL"} { + t.Setenv(k, "") + } + return home +} + +func tuneWrite(t *testing.T, path, s string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(s), 0o644); err != nil { + t.Fatal(err) + } +} + +func tuneFile(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// TestTuneClaudeCompact: the advised window goes where /autocompact keeps +// it, under modelSettings for the model, the user's other settings kept; +// Undo takes it out again, empty entries with it. +func TestTuneClaudeCompact(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".claude", "settings.json") + tuneWrite(t, path, `{"theme": "dark", "autoCompactWindow": 300000}`) + s, err := TuneRead(home, "claude", TuneCompact, "claude-opus-5-5") + if err != nil || s.Value != "300000" || s.Source != "settings" || s.Ours { + t.Fatalf("read %+v %v: want the top-level 300000", s, err) + } + if err := TuneApply(home, "claude", TuneCompact, "claude-opus-5-5", "160000"); err != nil { + t.Fatal(err) + } + got := strings.Join(strings.Fields(tuneFile(t, path)), "") + if !strings.Contains(got, `"claude-opus-5-5":{"autoCompactWindow":160000}`) || !strings.Contains(got, `"theme":"dark"`) || !strings.Contains(got, `"autoCompactWindow":300000`) { + t.Fatalf("settings.json after apply:\n%s", got) + } + s, _ = TuneRead(home, "claude", TuneCompact, "claude-opus-5-5") + if s.Value != "160000" || s.Source != "model" || !s.Ours { + t.Fatalf("read after apply %+v", s) + } + if err := TuneUndo(home, "claude", TuneCompact, "claude-opus-5-5"); err != nil { + t.Fatal(err) + } + got = tuneFile(t, path) + if strings.Contains(got, "modelSettings") || !strings.Contains(got, "300000") { + t.Fatalf("settings.json after undo:\n%s", got) + } + if err := TuneApply(home, "claude", TuneCompact, "claude-opus-5-5", "50000"); err == nil { + t.Fatal("took a window under Claude Code's 100000") + } + if err := TuneApply(home, "claude", TuneCompact, "gpt-5.5", "160000"); err == nil { + t.Fatal("took a window for a model that is no Claude model") + } +} + +// TestTuneUserValueKept: a TTL the user had is put back by Undo, and one +// they changed after Apply is theirs: Undo leaves it. +func TestTuneUserValueKept(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".claude", "settings.json") + tuneWrite(t, path, `{"promptCacheTtl": "5m"}`) + if err := TuneApply(home, "claude", TuneCache, "", "1h"); err != nil { + t.Fatal(err) + } + if err := TuneUndo(home, "claude", TuneCache, ""); err != nil { + t.Fatal(err) + } + if v, _ := TuneRead(home, "claude", TuneCache, ""); v.Value != "5m" || v.Ours { + t.Fatalf("after undo %+v, want the user's 5m", v) + } + if err := TuneApply(home, "claude", TuneCache, "", "1h"); err != nil { + t.Fatal(err) + } + tuneWrite(t, path, `{"promptCacheTtl": "5m", "other": 1}`) + if err := TuneUndo(home, "claude", TuneCache, ""); err != nil { + t.Fatal(err) + } + if got := tuneFile(t, path); !strings.Contains(got, `"5m"`) { + t.Fatalf("undo wrote over the user's change:\n%s", got) + } + if err := TuneUndo(home, "claude", TuneCache, ""); err == nil { + t.Fatal("undo with nothing of magpie's to put back") + } + if err := TuneApply(home, "claude", TuneCache, "", "2h"); err == nil { + t.Fatal("took a lifetime Claude Code has no use for") + } +} + +// TestTuneLockedByEnv: a variable that comes before the setting is told +// of, and Apply changes nothing. +func TestTuneLockedByEnv(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".claude", "settings.json") + tuneWrite(t, path, `{"env": {"CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL": "1h"}}`) + s, _ := TuneRead(home, "claude", TuneSubCache, "") + if s.Locked != "CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL" || s.Value != "1h" { + t.Fatalf("read %+v", s) + } + if err := TuneApply(home, "claude", TuneSubCache, "", "5m"); err == nil { + t.Fatal("applied under a variable that takes precedence") + } + if got := tuneFile(t, path); strings.Contains(got, "subagentPromptCacheTtl") { + t.Fatalf("wrote anyway:\n%s", got) + } + t.Setenv("FORCE_PROMPT_CACHING_5M", "1") + if s, _ := TuneRead(home, "claude", TuneCache, ""); s.Locked != "FORCE_PROMPT_CACHING_5M" || s.Value != "5m" { + t.Fatalf("read %+v", s) + } +} + +// TestTuneCodexCompact: Codex's limit goes at the top of config.toml, the +// tables after it kept, and Undo puts the user's back. +func TestTuneCodexCompact(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".codex", "config.toml") + tuneWrite(t, path, "model = \"gpt-5.5\"\nmodel_auto_compact_token_limit = 200000\n\n[features]\nx = true\n") + if err := TuneApply(home, "codex", TuneCompact, "", "150000"); err != nil { + t.Fatal(err) + } + got := tuneFile(t, path) + if !strings.Contains(got, "model_auto_compact_token_limit = 150000") || strings.Index(got, "150000") > strings.Index(got, "[features]") || !strings.Contains(got, "x = true") { + t.Fatalf("config.toml after apply:\n%s", got) + } + if err := TuneUndo(home, "codex", TuneCompact, ""); err != nil { + t.Fatal(err) + } + if got := tuneFile(t, path); !strings.Contains(got, "model_auto_compact_token_limit = 200000") { + t.Fatalf("config.toml after undo:\n%s", got) + } +} diff --git a/internal/gui/assets/context.css b/internal/gui/assets/context.css index 147af7c5b..3e8a562e2 100644 --- a/internal/gui/assets/context.css +++ b/internal/gui/assets/context.css @@ -148,7 +148,7 @@ i.dot.free { background: var(--k-free); box-shadow: inset 0 0 0 1px color-mix(in /* the Usage page's Context tab */ .ctx-agents { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr)); gap: 12px; margin: 4px 0 18px; } -.ctx-agent { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px 12px; display: flex; flex-direction: column; gap: 12px; min-width: 0; font-variant-numeric: tabular-nums; } +.ctx-agent, .ctx-tune { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px 12px; display: flex; flex-direction: column; gap: 12px; min-width: 0; font-variant-numeric: tabular-nums; } .ctx-agent-head { display: flex; align-items: center; gap: 10px; min-width: 0; } .ctx-who-box { min-width: 0; display: flex; flex-direction: column; gap: 3px; } .ctx-who { display: flex; align-items: center; gap: 8px; min-width: 0; } @@ -244,3 +244,34 @@ i.dot.free { background: var(--k-free); box-shadow: inset 0 0 0 1px color-mix(in .ctx-spark .area { fill: var(--k-chat); fill-opacity: .14; } .ctx-spark .hit:hover { fill: var(--line); } } + +/* tuned for you */ +.ctx-tune { gap: 10px; } +.ctx-tune-total { font-size: 12px; font-weight: 600; color: var(--green); background: var(--green-soft); border-radius: 11px; padding: 3px 10px; white-space: nowrap; } +.ctx-tune-row { display: flex; flex-direction: column; gap: 8px; padding: 12px 0 2px; border-top: 1px solid var(--line); min-width: 0; } +.ctx-tune-title { display: flex; align-items: baseline; gap: 8px; min-width: 0; } +.ctx-tune-title b { font-size: 13px; font-weight: 600; flex: none; } +.ctx-tunes { align-items: start; } +.ctx-tunes > :only-child { grid-column: 1 / -1; } +.ctx-tune-title code { font-size: 11px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.ctx-tune-vals { display: flex; align-items: flex-end; gap: 12px; min-width: 0; } +.ctx-tune-val { display: flex; flex-direction: column; gap: 2px; flex: none; } +.ctx-tune-val .ctx-k { font-size: 9.5px; } +.ctx-tune-val b { font-size: 18px; font-weight: 600; letter-spacing: -.01em; } +.ctx-tune-val.now b { color: var(--fg-2); } +.ctx-tune-row:not(.done) .ctx-tune-val.now b { text-decoration: line-through; text-decoration-color: var(--muted); text-decoration-thickness: 1px; color: var(--muted); } +.ctx-tune-val.best b { color: var(--green); } +.ctx-tune-arrow { color: var(--muted); font-size: 14px; padding-bottom: 3px; } +.ctx-tune-curve { flex: 0 1 200px; min-width: 90px; display: flex; flex-direction: column; gap: 1px; cursor: default; } +.ctx-tune-curve svg { width: 100%; height: 40px; display: block; overflow: visible; } +.ctx-tune-curve .line { fill: none; stroke: var(--accent); stroke-width: 1.5; vector-effect: non-scaling-stroke; stroke-linejoin: round; } +.ctx-tune-curve .now { fill: var(--card); stroke: var(--muted); stroke-width: 1.5; vector-effect: non-scaling-stroke; } +.ctx-tune-curve .best { fill: var(--green); stroke: var(--card); stroke-width: 1.5; vector-effect: non-scaling-stroke; } +.ctx-tune-ends { display: flex; justify-content: space-between; font-size: 9.5px; color: var(--muted); } +.ctx-tune-why { margin: 0; font-size: 12px; line-height: 1.5; color: var(--fg-2); } +.ctx-tune-foot { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; } +.ctx-tune-src { font-size: 11px; color: var(--muted); margin-top: -5px; overflow-wrap: anywhere; } +.ctx-tune-foot .grow { flex: 1; } +@media (max-width: 520px) { + .ctx-tune-curve { display: none; } +} diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js index 8e0e444a1..03c7491b7 100644 --- a/internal/gui/assets/context.js +++ b/internal/gui/assets/context.js @@ -720,6 +720,177 @@ return box; } + + // ---------- tuned for you: the settings that would have spent the fewest tokens ---------- + + let tuneData = null, tuneJSON = "", tuneRead = 0, tuneBusy = ""; + + const KNOBS = { + compact: "Auto-compact", + cache_ttl: "Prompt cache · main conversation", + subagent_cache_ttl: "Prompt cache · subagents", + }; + const ttlName = (v) => v === "1h" ? t("1 hour") : v === "5m" ? t("5 min") : v || "—"; + + // curve draws what the range would have cost at each window, the one + // set and the best marked on it + function curve(c) { + const pts = c.curve || []; + if (pts.length < 2) return null; + const W = 220, H = 44, pad = 4; + const xs = pts.map((p) => p.value), ys = pts.map((p) => p.cost); + const x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys); + const x = (v) => pad + ((v - x0) / (x1 - x0 || 1)) * (W - 2 * pad); + const y = (v) => H - pad - ((v - y0) / (y1 - y0 || 1)) * (H - 2 * pad); + const d = pts.map((p, i) => (i ? "L" : "M") + x(p.value).toFixed(1) + " " + y(p.cost).toFixed(1)).join(" "); + const box = el("div", "ctx-tune-curve"); + const s = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + s.setAttribute("viewBox", `0 0 ${W} ${H}`); + s.setAttribute("preserveAspectRatio", "none"); + const at = (v) => pts.reduce((a, p) => Math.abs(p.value - v) < Math.abs(a.value - v) ? p : a, pts[0]); + const now = at(c.current), best = at(c.best); + s.innerHTML = `` + + (now.value !== best.value ? `` : "") + + ``; + box.append(s); + const ends = el("div", "ctx-tune-ends"); + ends.append(el("span", "", fmtK(x0)), el("span", "", fmtK(x1))); + box.append(ends); + box.dataset.tt = t("What the range would have cost at each window: lower is fewer tokens"); + return box; + } + + function adviceRow(agent, a) { + const r = a.compact || a.ttl; + const ttl = !!a.ttl; + const show = (v) => ttl ? ttlName(v) : fmtK(+v); + const cur = ttl ? r.current : r.current, best = r.best; + const same = String(cur) === String(best); + const saves = r.cost > 0 ? (r.cost - r.low) / r.cost : 0; + const set = a.setting || {}; + const applied = set.ours && String(set.value) === String(best); + const row = el("div", "ctx-tune-row" + (same || applied ? " done" : "")); + + const title = el("div", "ctx-tune-title"); + title.append(el("b", "", t(KNOBS[a.knob] || a.knob))); + if (a.model) title.append(el("code", "", a.model)); + row.append(title); + + const vals = el("div", "ctx-tune-vals"); + const val = (label, v, cls) => { + const f = el("div", "ctx-tune-val " + cls); + f.append(el("span", "ctx-k", t(label)), el("b", "", show(v))); + return f; + }; + vals.append(val("Now", cur, "now")); + if (!same) vals.append(el("span", "ctx-tune-arrow", "→"), val("Best for you", best, "best")); + if (a.compact) { const c = curve(a.compact); if (c) vals.append(el("span", "grow"), c); } + row.append(vals); + + const why = el("p", "ctx-tune-why"); + const f = r.facts || {}; + if (a.compact) { + why.textContent = f.compacts + ? t("Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.", { growth: fmtK(f.growth), after: fmtK(f.after), rework: fmtK(f.rework), n: f.compacts }) + : t("Your conversations grow {growth} a call, and none was compacted in the range.", { growth: fmtK(f.growth) }); + } else { + why.textContent = t("{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.", { quick: pct(f.quick || 0), pause: pct(f.pause || 0) }); + } + row.append(why); + + const foot = el("div", "ctx-tune-foot"); + const verdict = same || applied + ? el("span", "ctx-chip good", "") + : el("span", "ctx-chip info", ""); + verdict.append(el("i"), same ? t("Already the leanest for how you work") : applied ? t("In use") : t("{pct} fewer tokens · {tokens} over the range", { pct: pct(saves), tokens: fmtK(Math.round(r.cost - r.low)) })); + foot.append(verdict, el("span", "grow")); + const note = el("div", "ctx-tune-src"); + title.after(note); + if (set.locked) note.textContent = t("{name} is set and comes first", { name: set.locked }); + else if (set.ours) note.textContent = t("Set by magpie"); + else if (set.value && a.compact && +set.value > a.compact.window && a.compact.window) note.textContent = t("You set {value}; the model's {window} comes first", { value: show(set.value), window: fmtK(a.compact.window) }); + else if (set.value) note.textContent = t("You set {value}", { value: show(set.value) }); + else note.textContent = t("The agent's default"); + const key = [agent, a.knob, a.model || ""].join("\x00"); + const send = async (path, value) => { + tuneBusy = key; + renderContext(); + try { + await api("tune/" + path, { agent, knob: a.knob, model: a.model || "", value: String(value ?? "") }); + status(path === "apply" ? t("Saved: {agent} reads it from its next session", { agent: agentLabel(agent) }) : t("Put back"), "ok"); + } catch (e) { + status(e.message, "err"); + } + tuneBusy = ""; + await loadTune(true); + }; + if (set.ours) { + const undo = el("button", "text", t("Undo")); + undo.type = "button"; + undo.disabled = tuneBusy === key; + undo.onclick = () => send("undo"); + foot.append(undo); + } + if (!same && !applied && !set.locked) { + const go = el("button", "text primary", t("Use {value}", { value: show(best) })); + go.type = "button"; + go.disabled = tuneBusy === key; + if (set.value && !set.ours) go.dataset.tt = t("Replaces your {value}; Undo puts it back", { value: show(set.value) }); + go.onclick = () => send("apply", best); + foot.append(go); + } + row.append(foot); + return row; + } + + function tuneCard(ag) { + const card = el("div", "ctx-tune"); + const head = el("div", "ctx-agent-head"); + const who = el("div", "ctx-who"); + who.append(agentIcon(ag.agent), el("b", "", agentLabel(ag.agent))); + const name = el("div", "ctx-who-box"); + name.append(who, el("div", "ctx-who-sub", count(ag.calls, "1 call", "{n} calls"))); + head.append(name, el("span", "grow")); + const total = ag.advice.reduce((s, a) => { const r = a.compact || a.ttl; return s + Math.max(0, r.cost - r.low); }, 0); + const all = ag.advice.reduce((s, a) => s + (a.compact || a.ttl).cost, 0); + // a share that rounds to nothing is no promise + if (all > 0 && total / all >= 0.01) head.append(el("span", "ctx-tune-total", t("Up to {pct} fewer", { pct: pct(total / all) }))); + card.append(head); + for (const a of ag.advice) card.append(adviceRow(ag.agent, a)); + if (!ag.advice.length) card.append(el("p", "usage-note", t("Not enough calls in this range to tune on"))); + return card; + } + + function renderTune(pane) { + const head = el("div", "row-head ctx-sess-head"); + head.append(el("span", "label", t("Tuned for you")), el("span", "grow")); + pane.append(head); + pane.append(el("p", "usage-note", t("Your own calls of the range, replayed setting by setting from your agents' session files: the settings that would have spent the fewest tokens, for how you work. Tokens are weighed as the vendor charges them: a cache read is a tenth of one."))); + if (!tuneData) { + pane.append(el("p", "usage-note", t("Working it out from your sessions…"))); + return; + } + const shown = tuneData.agents.filter((a) => a.advice.length); + if (!shown.length) { + pane.append(el("p", "usage-note", t("Not enough calls in this range to tune on"))); + return; + } + const grid = el("div", "ctx-agents ctx-tunes"); + for (const a of shown) grid.append(tuneCard(a)); + pane.append(grid); + } + + async function loadTune(force) { + const read = ++tuneRead, days = ctxDays; + if (tuneData && tuneData.days !== +days) tuneData = null; + const data = await api("tune?days=" + days); + if (read !== tuneRead) return; + const json = JSON.stringify(data); + if (!force && tuneData && json === tuneJSON) return; + tuneData = { days: +data.days || +days, agents: (data.agents || []).map((a) => ({ ...a, advice: a.advice || [] })) }, tuneJSON = json; + renderContext(); + } + function renderContext() { const pane = $("#contextPane"); if (!pane) return; @@ -731,10 +902,14 @@ })); tools.append(el("span", "grow")); pane.replaceChildren(tools); + renderTune(pane); if (!ctxData) { pane.append(el("p", "usage-note", t("Reading the routing history…"))); return; } + const seen = el("div", "row-head ctx-sess-head"); + seen.append(el("span", "label", t("Through magpie")), el("span", "grow")); + pane.append(seen); pane.append(el("p", "usage-note", t("What each agent's prompts hold, as magpie's gateway read them: the score and tags are worked out from the requests of the range."))); if (!ctxData.agents.length) { const empty = el("div", "ctx-none"); @@ -764,6 +939,7 @@ async function loadContext() { const read = ++ctxRead, days = ctxDays; if (!ctxData || ctxData.days !== +days) { ctxData = null; renderContext(); } + loadTune().catch((e) => status(e.message, "err")); const data = await api("context?days=" + days); if (read !== ctxRead) return; // the auto refresh redraws only what changed: the same answer keeps the diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index d84aa26c8..9dbe5677c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4,6 +4,33 @@ // works. {name} slots are filled by t(str, vars). const I18N = { zh: { + "You set {value}; the model's {window} comes first": "你设置的是 {value},但模型的 {window} 优先", + "Auto-compact": "自动压缩", + "Prompt cache · main conversation": "提示缓存 · 主对话", + "Prompt cache · subagents": "提示缓存 · 子代理", + "5 min": "5 分钟", + "What the range would have cost at each window: lower is fewer tokens": "这段时间在每个窗口下的花费:越低 Token 越少", + "Best for you": "最适合你", + "Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.": "你的对话每次调用增长 {growth};压缩后剩 {after},把丢掉的内容再读回来要花 {rework}。这段时间共压缩 {n} 次。", + "Your conversations grow {growth} a call, and none was compacted in the range.": "你的对话每次调用增长 {growth},这段时间没有一次压缩。", + "{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.": "你 {quick} 的调用距上一次不到 5 分钟,{pause} 在停顿 5 到 60 分钟之后。", + "Already the leanest for how you work": "已是最适合你用法的最省配置", + "{pct} fewer tokens · {tokens} over the range": "少 {pct} Token · 这段时间省 {tokens}", + "{name} is set and comes first": "已设置 {name},它优先", + "Set by magpie": "由 magpie 设置", + "You set {value}": "你设置的是 {value}", + "The agent's default": "Agent 的默认值", + "Saved: {agent} reads it from its next session": "已保存:{agent} 从下一个会话开始使用", + "Put back": "已恢复", + "Use {value}": "使用 {value}", + "Replaces your {value}; Undo puts it back": "会替换你的 {value};撤销可恢复", + "1 call": "1 次调用", + "Up to {pct} fewer": "最多少 {pct}", + "Not enough calls in this range to tune on": "这段时间的调用太少,还算不出建议", + "Tuned for you": "为你调优", + "Your own calls of the range, replayed setting by setting from your agents' session files: the settings that would have spent the fewest tokens, for how you work. Tokens are weighed as the vendor charges them: a cache read is a tenth of one.": "用你这段时间自己的调用(来自 agent 的会话文件)逐个设置重放:按你的用法,哪组设置花的 Token 最少。Token 按厂商计费的方式加权:一次缓存读取算十分之一。", + "Working it out from your sessions…": "正在从你的会话里计算…", + "Through magpie": "经过 magpie 的", "Enable": "启用", "Record gateway conversations": "记录网关对话", "Prompts, replies and tool results may contain private code and files. Store them on this server for up to 7 days (256 MiB total)? Recognized secrets are masked, but this is not a privacy guarantee.": "提示词、回复和工具结果可能包含私有代码与文件。是否在此服务器保存最多 7 天(总计 256 MiB)?已识别的密钥会被遮蔽,但不能保证所有敏感信息都被移除。", @@ -3948,6 +3975,33 @@ const I18N = { "Video · 7 days": "视频 · 7 天", }, "zh-TW": { + "You set {value}; the model's {window} comes first": "你設定的是 {value},但模型的 {window} 優先", + "Auto-compact": "自動壓縮", + "Prompt cache · main conversation": "提示快取 · 主對話", + "Prompt cache · subagents": "提示快取 · 子代理", + "5 min": "5 分鐘", + "What the range would have cost at each window: lower is fewer tokens": "這段時間在每個視窗下的花費:越低 Token 越少", + "Best for you": "最適合你", + "Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.": "你的對話每次呼叫增長 {growth};壓縮後剩 {after},把丟掉的內容再讀回來要花 {rework}。這段時間共壓縮 {n} 次。", + "Your conversations grow {growth} a call, and none was compacted in the range.": "你的對話每次呼叫增長 {growth},這段時間沒有一次壓縮。", + "{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.": "你 {quick} 的呼叫距上一次不到 5 分鐘,{pause} 在停頓 5 到 60 分鐘之後。", + "Already the leanest for how you work": "已是最適合你用法的最省配置", + "{pct} fewer tokens · {tokens} over the range": "少 {pct} Token · 這段時間省 {tokens}", + "{name} is set and comes first": "已設定 {name},它優先", + "Set by magpie": "由 magpie 設定", + "You set {value}": "你設定的是 {value}", + "The agent's default": "Agent 的預設值", + "Saved: {agent} reads it from its next session": "已儲存:{agent} 從下一個工作階段開始使用", + "Put back": "已復原", + "Use {value}": "使用 {value}", + "Replaces your {value}; Undo puts it back": "會取代你的 {value};復原可還原", + "1 call": "1 次呼叫", + "Up to {pct} fewer": "最多少 {pct}", + "Not enough calls in this range to tune on": "這段時間的呼叫太少,還算不出建議", + "Tuned for you": "為你調校", + "Your own calls of the range, replayed setting by setting from your agents' session files: the settings that would have spent the fewest tokens, for how you work. Tokens are weighed as the vendor charges them: a cache read is a tenth of one.": "用你這段時間自己的呼叫(來自 agent 的工作階段檔案)逐個設定重播:按你的用法,哪組設定花的 Token 最少。Token 按廠商計費的方式加權:一次快取讀取算十分之一。", + "Working it out from your sessions…": "正在從你的工作階段裡計算…", + "Through magpie": "經過 magpie 的", "magpie's key": "magpie 的金鑰", "Claude Code sends magpie its key and is signed out of claude.ai while it runs through magpie: claude.ai's plan limits in /usage, its connectors, voice and /teleport are off": "Claude Code 向 magpie 傳送 magpie 的金鑰,經 magpie 執行期間處於 claude.ai 未登入狀態:/usage 裡的方案限額、claude.ai 連接器、語音和 /teleport 都無法使用", "Claude Code keeps its claude.ai sign-in (/login), so those work; it sends that sign-in to magpie, which never passes it on. Remote Control and ultrareview stay off: Claude Code has them only on Anthropic's own address": "Claude Code 保留 claude.ai 登入(/login),上述功能可用;它把這份登入憑證傳給 magpie,magpie 不會轉交到任何地方。Remote Control 和 ultrareview 仍無法使用:Claude Code 只在 Anthropic 官方位址上提供它們", @@ -7875,6 +7929,33 @@ const I18N = { "Video · 7 days": "影片 · 7 天", }, ja: { + "You set {value}; the model's {window} comes first": "設定は {value} ですが、モデルの {window} が優先されます", + "Auto-compact": "自動コンパクト", + "Prompt cache · main conversation": "プロンプトキャッシュ · メイン会話", + "Prompt cache · subagents": "プロンプトキャッシュ · サブエージェント", + "5 min": "5 分", + "What the range would have cost at each window: lower is fewer tokens": "各ウィンドウでこの期間にかかったコスト:低いほどトークンが少ない", + "Best for you": "あなたに最適", + "Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.": "会話は 1 回の呼び出しごとに {growth} 増えます。コンパクト後は {after} が残り、落とした内容を読み直すのに {rework} かかります。この期間のコンパクトは {n} 回。", + "Your conversations grow {growth} a call, and none was compacted in the range.": "会話は 1 回の呼び出しごとに {growth} 増え、この期間にコンパクトはありませんでした。", + "{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.": "呼び出しの {quick} は前回から 5 分以内、{pause} は 5〜60 分の間を置いた後でした。", + "Already the leanest for how you work": "すでにあなたの使い方で最も省トークン", + "{pct} fewer tokens · {tokens} over the range": "トークン {pct} 減 · この期間で {tokens}", + "{name} is set and comes first": "{name} が設定されていて優先されます", + "Set by magpie": "magpie が設定", + "You set {value}": "あなたの設定は {value}", + "The agent's default": "エージェントの既定値", + "Saved: {agent} reads it from its next session": "保存しました:{agent} は次のセッションから使います", + "Put back": "元に戻しました", + "Use {value}": "{value} にする", + "Replaces your {value}; Undo puts it back": "あなたの {value} を置き換えます。取り消すと戻ります", + "1 call": "1 回の呼び出し", + "Up to {pct} fewer": "最大 {pct} 減", + "Not enough calls in this range to tune on": "この期間は呼び出しが少なく、まだ調整できません", + "Tuned for you": "あなた向けの調整", + "Your own calls of the range, replayed setting by setting from your agents' session files: the settings that would have spent the fewest tokens, for how you work. Tokens are weighed as the vendor charges them: a cache read is a tenth of one.": "この期間のあなた自身の呼び出し(エージェントのセッションファイルから)を設定ごとに再生し、あなたの使い方で最もトークンが少なくなる設定を求めます。トークンはベンダーの課金どおりに重み付けし、キャッシュ読み取りは 10 分の 1 です。", + "Working it out from your sessions…": "セッションから計算中…", + "Through magpie": "magpie 経由", "Enable": "有効にする", "Record gateway conversations": "ゲートウェイの会話を記録", "Prompts, replies and tool results may contain private code and files. Store them on this server for up to 7 days (256 MiB total)? Recognized secrets are masked, but this is not a privacy guarantee.": "プロンプト、応答、ツールの結果には非公開のコードやファイルが含まれる場合があります。このサーバーに最大7日間(合計256 MiB)保存しますか?検出された秘密情報は隠されますが、すべての機密情報の除去は保証されません。", @@ -11804,6 +11885,33 @@ const I18N = { "Main navigation": "メインナビゲーション", }, de: { + "You set {value}; the model's {window} comes first": "Du hast {value} gesetzt; das Fenster des Modells ({window}) hat Vorrang", + "Auto-compact": "Auto-Kompaktierung", + "Prompt cache · main conversation": "Prompt-Cache · Hauptunterhaltung", + "Prompt cache · subagents": "Prompt-Cache · Subagenten", + "5 min": "5 Min.", + "What the range would have cost at each window: lower is fewer tokens": "Was der Zeitraum bei jedem Fenster gekostet hätte: niedriger heißt weniger Tokens", + "Best for you": "Am besten für dich", + "Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.": "Deine Unterhaltungen wachsen um {growth} pro Aufruf; eine Kompaktierung lässt {after} übrig, und das Zurücklesen des Entfernten kostet {rework}. {n} Kompaktierungen im Zeitraum.", + "Your conversations grow {growth} a call, and none was compacted in the range.": "Deine Unterhaltungen wachsen um {growth} pro Aufruf, und im Zeitraum wurde keine kompaktiert.", + "{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.": "{quick} deiner Aufrufe kamen innerhalb von 5 Minuten nach dem vorigen, {pause} nach einer Pause von 5 bis 60 Minuten.", + "Already the leanest for how you work": "Schon am sparsamsten für deine Arbeitsweise", + "{pct} fewer tokens · {tokens} over the range": "{pct} weniger Tokens · {tokens} im Zeitraum", + "{name} is set and comes first": "{name} ist gesetzt und hat Vorrang", + "Set by magpie": "Von magpie gesetzt", + "You set {value}": "Du hast {value} gesetzt", + "The agent's default": "Standard des Agenten", + "Saved: {agent} reads it from its next session": "Gespeichert: {agent} liest es ab der nächsten Sitzung", + "Put back": "Zurückgesetzt", + "Use {value}": "{value} verwenden", + "Replaces your {value}; Undo puts it back": "Ersetzt dein {value}; Rückgängig stellt es wieder her", + "1 call": "1 Aufruf", + "Up to {pct} fewer": "Bis zu {pct} weniger", + "Not enough calls in this range to tune on": "Zu wenige Aufrufe in diesem Zeitraum zum Abstimmen", + "Tuned for you": "Für dich abgestimmt", + "Your own calls of the range, replayed setting by setting from your agents' session files: the settings that would have spent the fewest tokens, for how you work. Tokens are weighed as the vendor charges them: a cache read is a tenth of one.": "Deine eigenen Aufrufe des Zeitraums, aus den Sitzungsdateien deiner Agenten Einstellung für Einstellung nachgespielt: die Einstellungen, die für deine Arbeitsweise am wenigsten Tokens gekostet hätten. Tokens sind gewichtet wie der Anbieter abrechnet: ein Cache-Lesezugriff zählt ein Zehntel.", + "Working it out from your sessions…": "Wird aus deinen Sitzungen berechnet …", + "Through magpie": "Über magpie", "Enable": "Aktivieren", "Record gateway conversations": "Gateway-Gespräche aufzeichnen", "Prompts, replies and tool results may contain private code and files. Store them on this server for up to 7 days (256 MiB total)? Recognized secrets are masked, but this is not a privacy guarantee.": "Prompts, Antworten und Werkzeugergebnisse können privaten Code und Dateien enthalten. Bis zu 7 Tage auf diesem Server speichern (insgesamt 256 MiB)? Erkannte Geheimnisse werden maskiert, aber vollständiger Datenschutz ist nicht garantiert.", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index b3d21d84c..b6c609d3e 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -762,6 +762,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { pluginRoutes(mux, w) traceRoutes(mux) contextRoutesAPI(mux) + tuneRoutes(mux) groupRoutes(mux) // how each key's or account's requests stand under its limit on // requests at once (#892), read every two seconds while a provider's diff --git a/internal/gui/tests/context-tune.test.cjs b/internal/gui/tests/context-tune.test.cjs new file mode 100644 index 000000000..118307610 --- /dev/null +++ b/internal/gui/tests/context-tune.test.cjs @@ -0,0 +1,140 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Usage's Context tab tells each user, for each agent, the settings that +// would have spent the fewest tokens on their own calls (/api/tune), and +// puts one in on a click: Claude Code's auto-compact window for a model and +// its two cache lifetimes, Codex's compact limit. A setting already the +// leanest says so and has no button; one a variable comes before is told +// of and has none either; one magpie put in has Undo. Drawn before the +// gateway has read anything, in Chromium and WebKit, at a phone's width and +// a desk's, in every language, none of it wider than the page. +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 curve = (lo, hi, best) => { + const pts = []; + for (let v = lo; v <= hi; v += 10000) pts.push({ value: v, cost: 1e9 + Math.abs(v - best) * 3000 }); + return pts; +}; +const facts = { calls: 4100, streams: 60, compacts: 813, peak: 166000, after: 57000, growth: 1000, rework: 4700, quick: 0.95, pause: 0.045, away: 0.005, hour: 0.9 }; +function tune(set) { + const opus = set["claude/compact/claude-opus-5-5"]; + return { + days: 7, + agents: [ + { agent: "claude", calls: 4300, advice: [ + { knob: "compact", model: "claude-opus-5-5", setting: opus || { value: "300000", source: "settings" }, + compact: { model: "claude-opus-5-5", current: opus ? +opus.value : 300000, best: 160000, cost: 1.9e9, low: 1.46e9, curve: curve(110000, 300000, 160000), facts } }, + { knob: "compact", model: "claude-haiku-4-5-20251001-with-a-very-long-name", setting: {}, + compact: { model: "claude-haiku-4-5", current: 200000, best: 200000, cost: 2e8, low: 2e8, curve: curve(100000, 200000, 200000), facts: { ...facts, compacts: 0 } } }, + { knob: "cache_ttl", setting: { value: "1h", source: "env", locked: "CLAUDE_CODE_PROMPT_CACHE_TTL" }, + ttl: { current: "5m", best: "1h", cost: 5.5e8, low: 4.6e8, short: 5.5e8, hour: 4.6e8, facts } }, + { knob: "subagent_cache_ttl", setting: {}, + ttl: { current: "5m", best: "5m", cost: 9e7, low: 9e7, short: 9e7, hour: 1.2e8, facts } }, + ] }, + { agent: "codex", calls: 900, advice: [] }, + ], + }; +} + +function serve(lang, posts) { + const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }, { id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + const set = {}; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/tune") return json(tune(set)); + if (url.pathname === "/api/tune/apply" || url.pathname === "/api/tune/undo") { + const b = JSON.parse(r.request().postData()); + posts.push({ path: url.pathname, ...b }); + const key = [b.agent, b.knob, b.model].join("/"); + if (url.pathname.endsWith("apply")) set[key] = { value: b.value, source: "model", ours: true }; + else delete set[key]; + return json(set[key] || {}); + } + // the gateway has read nothing yet + if (url.pathname === "/api/context") return json({ days: 7, agents: [], sessions: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); + return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return 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 r.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType, status: 200 }); + }; +} + +const heading = { en: "Tuned for you", zh: "为你调优", "zh-TW": "為你調校", ja: "あなた向けの調整", de: "Für dich abgestimmt" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: the Context tab advises each agent's settings and puts one in`, 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(); + }); + for (const lang of Object.keys(heading)) for (const [width, height] of [[360, 760], [1100, 760]]) { + await t.test(`${lang}, ${width}x${height}`, async () => { + const ctx = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.usageTab", "context"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=usage"); + const rows = page.locator(".ctx-tune-row"); + await rows.first().waitFor(); + assert.equal(await page.getByText(heading[lang], { exact: true }).count(), 1, "the heading in " + lang); + // Codex had too few calls: no card for it + assert.equal(await page.locator(".ctx-tune").count(), 1); + assert.equal(await rows.count(), 4); + // only the window a change saves on has a button; the locked one says why + const buttons = page.locator(".ctx-tune-row button"); + assert.equal(await buttons.count(), 1); + assert.match(await rows.nth(0).locator(".ctx-tune-val.best b").innerText(), /160K/); + assert.match(await rows.nth(2).locator(".ctx-tune-src").innerText(), /CLAUDE_CODE_PROMPT_CACHE_TTL/); + assert.equal(await rows.nth(1).locator(".ctx-tune-val.best").count(), 0, "a window already the leanest shows no other"); + assert.equal(await page.locator(".ctx-tune-curve svg").first().isVisible(), width > 520); + + // nothing wider than the page, nor than its card + const over = await page.evaluate(() => { + const out = []; + const view = document.querySelector("#view-usage"); + if (view.scrollWidth > view.clientWidth + 1) out.push("page " + view.scrollWidth + ">" + view.clientWidth); + for (const c of document.querySelectorAll(".ctx-tune")) { + const b = c.getBoundingClientRect(); + for (const e of c.querySelectorAll("*")) { + const r = e.getBoundingClientRect(); + if (r.width && (r.right > b.right + 1 || r.left < b.left - 1)) out.push((e.className.baseVal ?? e.className) + " " + Math.round(r.left) + "–" + Math.round(r.right) + " of " + Math.round(b.left) + "–" + Math.round(b.right)); + } + } + return out; + }); + assert.deepEqual(over, []); + + await buttons.first().evaluate((b) => b.click()); + await page.locator(".ctx-tune-row button", { hasText: { en: "Undo", zh: "撤销", "zh-TW": "復原", ja: "取り消す", de: "Rückgängig" }[lang] }).waitFor(); + assert.deepEqual(posts, [{ path: "/api/tune/apply", agent: "claude", knob: "compact", model: "claude-opus-5-5", value: "160000" }]); + assert.match(await rows.nth(0).getAttribute("class"), /done/); + await page.locator(".ctx-tune-row button").first().evaluate((b) => b.click()); + await page.locator(".ctx-tune-row button.primary").waitFor(); + assert.equal(posts[1].path, "/api/tune/undo"); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/gui/tune.go b/internal/gui/tune.go new file mode 100644 index 000000000..6ef2a5166 --- /dev/null +++ b/internal/gui/tune.go @@ -0,0 +1,159 @@ +package gui + +// The Context tab's advice: for each agent, the settings that would have +// cost this user the fewest tokens over the period, worked out by +// replaying their own calls (internal/tune) against what the agent's +// config has now, and putting one in, or back, on their say. + +import ( + "encoding/json" + "net/http" + "sort" + "strconv" + "time" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/sessions" + "github.com/yetone/magpie/internal/tune" +) + +type tuneAdvice struct { + Knob string `json:"knob"` + Model string `json:"model,omitempty"` + Setting agent.TuneSetting `json:"setting"` + Compact *tune.Compaction `json:"compact,omitempty"` + TTL *tune.TTL `json:"ttl,omitempty"` +} + +type tuneAgent struct { + Agent string `json:"agent"` + Calls int `json:"calls"` + Advice []tuneAdvice `json:"advice"` +} + +type tuneState struct { + Days int `json:"days"` + Agents []tuneAgent `json:"agents"` +} + +// tuneOf works the advice out of the calls the agents' files hold. +func tuneOf(cs []sessions.Call, days int, home string) tuneState { + by := map[string][]tune.Call{} + for _, c := range cs { + if c.Agent == "claude" || c.Agent == "codex" { + by[c.Agent] = append(by[c.Agent], tune.FromCalls([]sessions.Call{c})...) + } + } + out := tuneState{Days: days, Agents: []tuneAgent{}} + for _, name := range []string{"claude", "codex"} { + calls := by[name] + if len(calls) == 0 { + continue + } + ta := tuneAgent{Agent: name, Calls: len(calls), Advice: []tuneAdvice{}} + switch name { + case "claude": + models := map[string][]tune.Call{} + var main, side []tune.Call + for _, c := range calls { + models[c.Model] = append(models[c.Model], c) + if c.Sub { + side = append(side, c) + } else { + main = append(main, c) + } + } + for m, mc := range models { + s, err := agent.TuneRead(home, name, agent.TuneCompact, m) + if err != nil { + continue + } + // a model asked for with [1m], or seen past 200K, has the + // whole 1M; another the 200K Claude Code's own models start with + window := 200000 + for _, c := range mc { + if c.Long || c.Prompt > window { + window = 1000000 + break + } + } + cur, _ := strconv.Atoi(s.Value) + o := tune.CompactOpts{Min: 100000, Max: 1000000, Step: 10000, Reserve: 33000, Window: window, Current: cur} + if r := tune.Compact(mc, o); r != nil { + ta.Advice = append(ta.Advice, tuneAdvice{Knob: agent.TuneCompact, Model: m, Setting: s, Compact: r}) + } + } + sort.SliceStable(ta.Advice, func(i, j int) bool { + return ta.Advice[i].Compact.Facts.Calls > ta.Advice[j].Compact.Facts.Calls + }) + for _, k := range []struct { + knob string + calls []tune.Call + }{{agent.TuneCache, main}, {agent.TuneSubCache, side}} { + s, err := agent.TuneRead(home, name, k.knob, "") + if err != nil { + continue + } + if r := tune.CacheTTL(k.calls, s.Value); r != nil { + ta.Advice = append(ta.Advice, tuneAdvice{Knob: k.knob, Setting: s, TTL: r}) + } + } + case "codex": + s, err := agent.TuneRead(home, name, agent.TuneCompact, "") + if err != nil { + continue + } + window := 272000 + for _, c := range calls { + window = max(window, c.Prompt) + } + cur, _ := strconv.Atoi(s.Value) + o := tune.CompactOpts{Min: 50000, Max: 1000000, Step: 10000, Window: window, Current: cur} + if r := tune.Compact(calls, o); r != nil { + ta.Advice = append(ta.Advice, tuneAdvice{Knob: agent.TuneCompact, Setting: s, Compact: r}) + } + } + out.Agents = append(out.Agents, ta) + } + return out +} + +func tuneRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/tune", func(rw http.ResponseWriter, r *http.Request) { + days, _ := strconv.Atoi(r.URL.Query().Get("days")) + if days <= 0 || days > 30 { + days = 7 + } + since := time.Now().AddDate(0, 0, -days) + writeJSON(rw, tuneOf(sessions.Calls(since), days, "")) + }) + type change struct { + Agent, Knob, Model, Value string + } + mux.HandleFunc("POST /api/tune/apply", func(rw http.ResponseWriter, r *http.Request) { + var in change + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if err := agent.TuneApply("", in.Agent, in.Knob, in.Model, in.Value); err != nil { + fail(rw, err) + return + } + s, _ := agent.TuneRead("", in.Agent, in.Knob, in.Model) + writeJSON(rw, s) + }) + mux.HandleFunc("POST /api/tune/undo", func(rw http.ResponseWriter, r *http.Request) { + var in change + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if err := agent.TuneUndo("", in.Agent, in.Knob, in.Model); err != nil { + fail(rw, err) + return + } + s, _ := agent.TuneRead("", in.Agent, in.Knob, in.Model) + writeJSON(rw, s) + }) +} diff --git a/internal/tune/tune.go b/internal/tune/tune.go new file mode 100644 index 000000000..918610b1a --- /dev/null +++ b/internal/tune/tune.go @@ -0,0 +1,469 @@ +// Package tune works out, from what one user's agents really did, the +// settings that would have cost that user the fewest tokens: when each +// agent compacts its conversation, and how long Claude Code keeps its +// prompt cache. Every setting is tried on the user's own calls of the +// period, replayed one by one: the same prompts growing by the same +// amounts at the same times, compacted or read from the cache as the +// setting would have had them. What it says is so for this user and this +// agent only; another's habits give other answers. +// +// Tokens are weighed by what the vendor charges for them against a plain +// input token, which is what a subscription's quota and an API bill both +// count: a cache read is a tenth of one, a cache write a quarter more (two +// for an hour's), an output token several. +package tune + +import ( + "path/filepath" + "slices" + "sort" + "strings" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// Call is one model call of an agent's conversation, as tune replays it. +type Call struct { + Time time.Time + Stream string // the conversation it is in: its file, a subagent's its own + Sub bool // a subagent's, a workflow's or a helper's, not the main conversation + Model string // as the agent asked for it, without [1m] + Long bool // asked for with the long context ([1m]) + Prompt int // the prompt, all of it: input, cache read and cache write + Out int + Wrote int // of Prompt, written to the cache + Wrote1 int // of Wrote, kept an hour +} + +// FromCalls makes tune's calls of an agent's calls read from its files, +// leaving out those that failed or carried no prompt. +func FromCalls(cs []sessions.Call) []Call { + out := make([]Call, 0, len(cs)) + for _, c := range cs { + p := c.Input + c.CacheRead + c.CacheWrite + if c.Error != "" || p <= 0 { + continue + } + m, long := c.Requested, false + if m == "" { + m = c.Model + } + if strings.HasSuffix(strings.ToLower(m), "[1m]") { + m, long = m[:len(m)-4], true + } + stream := c.File + if stream == "" { + stream = c.Agent + "/" + c.Session + } + out = append(out, Call{ + Time: c.Time, Stream: stream, Model: strings.ToLower(m), Long: long, + Sub: strings.Contains(filepath.ToSlash(c.File), "/subagents/"), + Prompt: p, Out: c.Output, Wrote: c.CacheWrite, Wrote1: c.CacheWrite1h, + }) + } + return out +} + +// Weights is what a vendor charges for each kind of token against one of +// plain input. +type Weights struct { + Read, Write, Write1h, Out float64 +} + +// WeightsFor is the weights of the vendor of a model: Anthropic charges a +// quarter more to write its cache (twice for an hour's) and a tenth to +// read it; OpenAI writes it at the input's price and reads it at a tenth. +func WeightsFor(model string) Weights { + if strings.HasPrefix(model, "claude") { + return Weights{Read: 0.1, Write: 1.25, Write1h: 2, Out: 5} + } + return Weights{Read: 0.1, Write: 1, Write1h: 1, Out: 8} +} + +// Point is one setting tried and what the period would have cost with it. +type Point struct { + Value int `json:"value"` + Cost float64 `json:"cost"` +} + +// Facts are what a replay found of the user's habits, said beside the +// advice so it reads as theirs. +type Facts struct { + Calls int `json:"calls"` + Streams int `json:"streams"` + Compacts int `json:"compacts,omitempty"` // seen in the period + Peak int `json:"peak,omitempty"` // the median prompt a compaction was made at + After int `json:"after,omitempty"` // the median prompt right after one + Growth int `json:"growth,omitempty"` // the median a prompt grows by from one call to the next + Rework int `json:"rework,omitempty"` // what a compaction costs to read back, in the calls after it + Long float64 `json:"long,omitempty"` // of the calls, the share that reached past the window advised + Quick float64 `json:"quick,omitempty"` // of the gaps between calls, the share under 5 minutes + Pause float64 `json:"pause,omitempty"` // between 5 minutes and an hour + Away float64 `json:"away,omitempty"` // over an hour + Hour float64 `json:"hour,omitempty"` // of the cache writes, the share kept an hour + Sessions int `json:"sessions,omitempty"` // streams that reached a compaction +} + +// Compaction is the window advised for one model of an agent. +type Compaction struct { + Model string `json:"model"` + Current int `json:"current"` // the window it runs with + Window int `json:"window"` // the model's, which caps a setting + Best int `json:"best"` + Cost float64 `json:"cost"` // with Current, the period's weighted tokens + Low float64 `json:"low"` // with Best + Curve []Point `json:"curve"` + Facts Facts `json:"facts"` +} + +// CompactOpts says how an agent compacts: the windows it takes, and how +// far below the window it sets it really compacts. +type CompactOpts struct { + Min, Max int + Step int + // Reserve is what the agent keeps free under the window: Claude Code + // compacts at the window less its output's room (167K of a 200K one, + // 967K of 1M); Codex at the limit itself + Reserve int + // Current is the window it runs with now; 0 when nothing sets one, + // and tune takes it from where its compactions were made + Current int + // Window is the model's whole window, the most a setting can give + Window int +} + +const ( + // a drop to under this share of the prompt before is a compaction + dropShare = 0.6 + // and only from a prompt at least this long + dropFrom = 20000 + // the calls after a compaction its rework is counted over + reworkCalls = 10 +) + +// streams groups calls by the conversation they are in, each oldest first. +func streams(cs []Call) [][]Call { + by := map[string][]Call{} + for _, c := range cs { + by[c.Stream] = append(by[c.Stream], c) + } + keys := make([]string, 0, len(by)) + for k := range by { + keys = append(keys, k) + } + sort.Strings(keys) + out := make([][]Call, 0, len(keys)) + for _, k := range keys { + s := by[k] + sort.SliceStable(s, func(i, j int) bool { return s[i].Time.Before(s[j].Time) }) + out = append(out, s) + } + return out +} + +func compacted(prev, cur int) bool { return prev >= dropFrom && float64(cur) < dropShare*float64(prev) } + +func median(xs []int) int { + if len(xs) == 0 { + return 0 + } + s := slices.Clone(xs) + slices.Sort(s) + return s[len(s)/2] +} + +// observe reads, from an agent's own calls, how its conversations grow +// and what its compactions came to. +func observe(ss [][]Call) Facts { + var f Facts + var peaks, afters, growths, reworks []int + for _, s := range ss { + f.Streams++ + f.Calls += len(s) + var ds []int + cuts := []int{} + for i := 1; i < len(s); i++ { + if compacted(s[i-1].Prompt, s[i].Prompt) { + peaks = append(peaks, s[i-1].Prompt) + afters = append(afters, s[i].Prompt) + cuts = append(cuts, i) + continue + } + if d := s[i].Prompt - s[i-1].Prompt; d >= 0 { + ds = append(ds, d) + } + } + if len(cuts) > 0 { + f.Sessions++ + } + g := median(ds) + growths = append(growths, ds...) + // what the calls after a compaction read back beyond the stream's + // usual growth: the files and results the summary left out + for _, at := range cuts { + end := at + reworkCalls + if end >= len(s) { + continue + } + extra := s[end].Prompt - s[at].Prompt - reworkCalls*g + ok := true + for j := at + 1; j <= end; j++ { + if compacted(s[j-1].Prompt, s[j].Prompt) { + ok = false + } + } + if ok { + reworks = append(reworks, max(0, extra)) + } + } + } + f.Compacts = len(peaks) + f.Peak, f.After, f.Growth, f.Rework = median(peaks), median(afters), median(growths), median(reworks) + return f +} + +// base is a stream's first prompt: what every call of it starts from +// (the system prompt, the tools), which a compaction keeps. +func base(ss [][]Call) int { + var firsts []int + for _, s := range ss { + firsts = append(firsts, s[0].Prompt) + } + return median(firsts) +} + +// replayCompact is what the streams would have cost compacting at +// threshold: each call's prompt grows by what it grew by, a compaction +// is made when it would pass the threshold, and the agent's own +// compactions in the files are left out, the prompt after them going on +// from where it was. A compaction reads the whole prompt, writes a summary +// (after less base, as output), the next call writes the summary to the +// cache, and the calls after it read back rework. +func replayCompact(ss [][]Call, threshold, after, b, rework int, w Weights, write float64) (float64, int, int) { + cost, n, over := 0.0, 0, 0 + summary := max(0, after-b) + for _, s := range ss { + ctx := s[0].Prompt + cost += float64(ctx)*write + float64(s[0].Out)*w.Out + for i := 1; i < len(s); i++ { + d := s[i].Prompt - s[i-1].Prompt + if d < 0 || compacted(s[i-1].Prompt, s[i].Prompt) { + d = 0 + } + if ctx+d > threshold && ctx > after { + cost += float64(ctx)*w.Read + float64(summary)*w.Out + float64(summary+rework)*write + ctx = after + rework + n++ + } + if ctx+d > threshold { + over++ + } + cost += float64(ctx)*w.Read + float64(d)*write + float64(s[i].Out)*w.Out + ctx += d + } + } + return cost, n, over +} + +// Compact advises the window to compact at for one model's calls of an +// agent, or nil when there is too little to go on: a few calls, or none +// that ever came near a window. +func Compact(cs []Call, o CompactOpts) *Compaction { + ss := streams(cs) + f := observe(ss) + if f.Calls < 50 || f.Streams == 0 { + return nil + } + model := cs[0].Model + w := WeightsFor(model) + write := w.Write + var wrote, wrote1 int + for _, c := range cs { + wrote += c.Wrote + wrote1 += c.Wrote1 + } + if wrote > 0 { + f.Hour = float64(wrote1) / float64(wrote) + if f.Hour > 0.5 { + write = w.Write1h + } + } + b := base(ss) + after := f.After + if after == 0 { + // no compaction seen: the summary Claude Code and Codex write is + // some 10K over what the conversation started from + after = b + 10000 + } + rework := f.Rework + if f.Compacts < 5 { + rework = max(rework, 10000) + } + cur := o.Current + if cur == 0 { + if f.Compacts >= 3 { + cur = roundTo(f.Peak+o.Reserve, o.Step) + } else { + cur = o.Window + } + } + // the agent compacts at the smaller of the setting and the model's + // window: a 500K setting on a 200K model runs at 200K + if o.Window > 0 { + cur = min(cur, o.Window) + } + top := min(o.Max, max(o.Window, cur)) + // a window that leaves little room over the summary compacts over and + // over: it keeps at least half the summary's size, or twenty calls' + // growth, free over it + floor := max(o.Min, roundUp(after+max(after/2, 20*f.Growth)+o.Reserve, o.Step)) + r := &Compaction{Model: model, Current: cur, Window: o.Window, Facts: f} + run := func(v int) float64 { + c, _, _ := replayCompact(ss, max(after+1, v-o.Reserve), after, b, rework, w, write) + return c + } + r.Cost = run(cur) + for v := floor; v <= top; v += o.Step { + r.Curve = append(r.Curve, Point{Value: v, Cost: run(v)}) + } + if len(r.Curve) == 0 { + return nil + } + low := slices.MinFunc(r.Curve, func(a, b Point) int { return cmpF(a.Cost, b.Cost) }) + // of the windows within 1% of the cheapest, the largest: fewer + // compactions lose less of what the conversation knew + best := low + for _, p := range r.Curve { + if p.Cost <= low.Cost*1.01 && p.Value > best.Value { + best = p + } + } + r.Best, r.Low = best.Value, best.Cost + // it only says to change what would save 3% or more + if r.Cost <= 0 || (r.Cost-r.Low)/r.Cost < 0.03 { + r.Best, r.Low = cur, r.Cost + } + _, _, over := replayCompact(ss, max(after+1, r.Best-o.Reserve), after, b, rework, w, write) + f.Long = float64(over) / float64(max(1, f.Calls)) + r.Facts = f + return r +} + +func roundTo(v, step int) int { + if step <= 0 { + return v + } + return (v + step/2) / step * step +} + +func roundUp(v, step int) int { + if step <= 0 { + return v + } + return (v + step - 1) / step * step +} + +func cmpF(a, b float64) int { + switch { + case a < b: + return -1 + case a > b: + return 1 + } + return 0 +} + +// TTL is the cache lifetime advised for one part of Claude Code's calls: +// its main conversation, or what runs beside it (subagents, workflows). +type TTL struct { + Current string `json:"current"` // 5m or 1h + Best string `json:"best"` + Cost float64 `json:"cost"` + Low float64 `json:"low"` + Short float64 `json:"short"` // with 5m + Hour float64 `json:"hour"` // with 1h + Facts Facts `json:"facts"` +} + +// replayTTL is what the streams would have cost with the cache kept for +// ttl at write per token: a call within it of the one before reads what +// that one sent and writes what it adds; one after it, or after a +// compaction, writes its whole prompt again. +func replayTTL(ss [][]Call, ttl time.Duration, write float64) float64 { + cost := 0.0 + for _, s := range ss { + w := WeightsFor(s[0].Model) + cost += float64(s[0].Prompt) * write + for i := 1; i < len(s); i++ { + p, c := s[i-1].Prompt, s[i].Prompt + switch { + case s[i].Time.Sub(s[i-1].Time) > ttl, compacted(p, c): + cost += float64(c) * write + case c >= p: + cost += float64(p)*w.Read + float64(c-p)*write + default: + cost += float64(c) * w.Read + } + } + } + return cost +} + +// CacheTTL advises Claude Code's cache lifetime for calls, all of the +// main conversation or all beside it; nil when there is too little to go +// on. current is the one set, "" when nothing sets one, and tune takes +// it from what the calls' cache writes were kept for. +func CacheTTL(cs []Call, current string) *TTL { + ss := streams(cs) + f := observe(ss) + if f.Calls < 50 { + return nil + } + var wrote, wrote1, gaps, quick, pause int + for _, s := range ss { + for i, c := range s { + wrote += c.Wrote + wrote1 += c.Wrote1 + if i == 0 { + continue + } + gaps++ + switch g := c.Time.Sub(s[i-1].Time); { + case g <= 5*time.Minute: + quick++ + case g <= time.Hour: + pause++ + } + } + } + if gaps > 0 { + f.Quick = float64(quick) / float64(gaps) + f.Pause = float64(pause) / float64(gaps) + f.Away = 1 - f.Quick - f.Pause + } + if wrote > 0 { + f.Hour = float64(wrote1) / float64(wrote) + } + if current == "" { + current = "5m" + if f.Hour > 0.5 { + current = "1h" + } + } + w := WeightsFor(cs[0].Model) + r := &TTL{Current: current, Facts: f} + r.Short = replayTTL(ss, 5*time.Minute, w.Write) + r.Hour = replayTTL(ss, time.Hour, w.Write1h) + r.Cost, r.Best, r.Low = r.Short, "5m", r.Short + if current == "1h" { + r.Cost = r.Hour + } + if r.Hour < r.Short { + r.Best, r.Low = "1h", r.Hour + } + if r.Cost <= 0 || (r.Cost-r.Low)/r.Cost < 0.03 { + r.Best, r.Low = current, r.Cost + } + return r +} diff --git a/internal/tune/tune_test.go b/internal/tune/tune_test.go new file mode 100644 index 000000000..1e28c1831 --- /dev/null +++ b/internal/tune/tune_test.go @@ -0,0 +1,126 @@ +package tune + +import ( + "fmt" + "testing" + "time" +) + +// session makes one conversation: it starts at start tokens, grows by grow +// a call, and compacts down to after when it reaches at, gap apart. +func session(id string, t0 time.Time, n, start, grow, at, after int, gap time.Duration, wrote1 bool) []Call { + var out []Call + p := start + for i := 0; i < n; i++ { + c := Call{Time: t0.Add(time.Duration(i) * gap), Stream: id, Model: "claude-opus-5-5", Prompt: p, Out: 800, Wrote: grow} + if wrote1 { + c.Wrote1 = c.Wrote + } + out = append(out, c) + p += grow + if at > 0 && p >= at { + p = after + } + } + return out +} + +func many(k int, f func(id string, t0 time.Time) []Call) []Call { + var out []Call + t0 := time.Date(2026, 10, 1, 9, 0, 0, 0, time.UTC) + for i := 0; i < k; i++ { + out = append(out, f(fmt.Sprint("s", i), t0.Add(time.Duration(i)*24*time.Hour))...) + } + return out +} + +var claudeOpts = CompactOpts{Min: 100000, Max: 1000000, Step: 10000, Reserve: 33000} + +// Long conversations on the whole 1M window carry a huge prompt for every +// call: a smaller window reads far less. +func TestCompactLongSessionsGoSmaller(t *testing.T) { + cs := many(3, func(id string, t0 time.Time) []Call { + return session(id, t0, 600, 30000, 5000, 967000, 60000, 30*time.Second, false) + }) + o := claudeOpts + o.Window, o.Current = 1000000, 1000000 + r := Compact(cs, o) + if r == nil { + t.Fatal("no advice") + } + if r.Best >= 1000000 || (r.Cost-r.Low)/r.Cost < 0.2 { + t.Fatalf("best %d saves %.0f of %.0f: want a smaller window saving a fifth or more", r.Best, r.Cost-r.Low, r.Cost) + } + if r.Facts.Compacts == 0 || r.Facts.Growth != 5000 { + t.Fatalf("facts %+v", r.Facts) + } +} + +// Conversations that never come near the window: no window changes what +// they cost, so it stays as the user has it. +func TestCompactShortSessionsKeepCurrent(t *testing.T) { + cs := many(5, func(id string, t0 time.Time) []Call { + return session(id, t0, 30, 20000, 2000, 0, 0, time.Minute, false) + }) + o := claudeOpts + o.Window = 200000 + r := Compact(cs, o) + if r == nil { + t.Fatal("no advice") + } + if r.Best != r.Current || r.Current != 200000 || r.Low != r.Cost { + t.Fatalf("got %d → %d (%.0f → %.0f), want 200000 kept", r.Current, r.Best, r.Cost, r.Low) + } +} + +// Too few calls to go on: no advice at all. +func TestCompactNeedsCalls(t *testing.T) { + cs := session("s", time.Now(), 20, 20000, 2000, 0, 0, time.Minute, false) + if r := Compact(cs, claudeOpts); r != nil { + t.Fatalf("advice from 20 calls: %+v", r) + } +} + +// A user who comes back after 20 minutes each time: a 5-minute cache is +// written again on every call, an hour's is read. +func TestCacheTTLPausesWantAnHour(t *testing.T) { + cs := many(4, func(id string, t0 time.Time) []Call { + return session(id, t0, 40, 30000, 3000, 0, 0, 20*time.Minute, false) + }) + r := CacheTTL(cs, "") + if r == nil || r.Current != "5m" || r.Best != "1h" || r.Low >= r.Cost { + t.Fatalf("got %+v, want 5m → 1h", r) + } + if r.Facts.Pause < 0.99 { + t.Fatalf("pause share %.2f", r.Facts.Pause) + } +} + +// A user whose calls all come within seconds pays the hour's dearer writes +// for nothing. +func TestCacheTTLQuickWantsFiveMinutes(t *testing.T) { + cs := many(4, func(id string, t0 time.Time) []Call { + return session(id, t0, 40, 30000, 3000, 0, 0, 20*time.Second, true) + }) + r := CacheTTL(cs, "") + if r == nil || r.Current != "1h" || r.Best != "5m" { + t.Fatalf("got %+v, want 1h (read from the writes) → 5m", r) + } +} + +// A setting over the model's window runs at the window: Claude Code takes +// the smaller of the two, so that is what the advice starts from. +func TestCompactSettingCappedByWindow(t *testing.T) { + cs := many(3, func(id string, t0 time.Time) []Call { + return session(id, t0, 400, 30000, 1000, 167000, 57000, 30*time.Second, false) + }) + o := claudeOpts + o.Window, o.Current = 200000, 500000 + r := Compact(cs, o) + if r == nil || r.Current != 200000 || r.Window != 200000 { + t.Fatalf("got %+v, want current 200000", r) + } + if last := r.Curve[len(r.Curve)-1].Value; last > 200000 { + t.Fatalf("curve reaches %d, past the model's window", last) + } +}