diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index e004c3050..98772485f 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -25,7 +25,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. For Codex that is where its config sends it and which models its lists hold (`listedModels`, slug and visibility), not every byte of each entry: the Codex app's list carries the ChatGPT backend's entries as sent, asked for each hour, and a rewrite with the same models told the user to reopen the app several times a day (Qyburn3 on X). A digest an older magpie stashed over the same files is kept (`readsBefore`). | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) | | Restarting a desktop app | Claude Desktop, WorkBuddy (WorkBuddy AI on macOS), OpenMausBot and ZCode (`ZCode.app`, `ZCode.exe`; `zcodePart`: magpie's provider without its key and magpie's rules in `provider_config.json`, Flandern1211 on X, #5662) read magpie's settings only as they start (微雨南山 and stones on Discord). `AppBehind` names one running here that started more than a second before magpie last changed what it reads (`changedAt`, which puts a change no file's time shows, such as Claude Desktop's gateway model list, at when it is first seen); only for an agent connected in magpie or disconnected in it. The row's Restart asks first in magpie's own dialog (`confirmRestart`), then `POST /api/agents/restart/{id}` runs `RestartApp`. On macOS (`restartApps`, the bundle found by id under `appFolders`, its `CFBundleExecutable` matched in `pgrep`) it quits as ⌘Q does and waits for every process of the bundle (`reopenBundle`), but a script run on the app's own executable (`runsScript`: a `.js` argument or an absolute path as its first argument), which the running check skips too. WorkBuddy starts its sidecar (`sidecar-entry.js`) and its `codebuddy` CLIs that way, detached; the sidecar outlives a quit, so counting it kept the row behind after every restart and made Restart wait it out and never open the app (Northes on Discord, 11-04, #3700). On Windows the same check reads each process's command line (`proc.CommandLine`); one still open after `appQuitWait` (a "Save?" question) is left as it is and not opened again (`noticeRestartStillOpen`). On Windows (`claude.exe` under `AnthropicClaude` or its Store package, `WorkBuddy.exe` outside the WorkBuddy AI folder) its processes are asked to close (`taskkill` without `/F`); one that has hidden every window and still runs after `appTrayGrace` (1s) is in the tray and has its tree ended at once (`waitClosed`, `winShown`: Claude Desktop hides its window in ~0.6s and keeps all its processes, so waiting the whole `appCloseWait` made a Restart ~12s where quitting by hand takes ~2s, CyberCaius on Discord, 10-29); one still showing a window (a question) gets `appCloseWait` before it is ended, and it is opened again through its Store id or Squirrel's stub. The Codex app's own Restart (`ReopenCodexApp`) asks first too, then ends only the app-server that app runs for itself (`provider.RestartCodexApp`: under its bundle, never a `--listen` one), as a switch does; the app starts another and keeps its window. Quitting and opening it, as before, opened a new window (yoshi037070 on Discord, 10-27). Codex on Windows, WorkBuddy AI on Windows and Linux aren't restarted: their process names aren't known. | [`apprestart.go`](../../internal/agent/apprestart.go), [`apprestart_windows.go`](../../internal/agent/apprestart_windows.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) | | Codex background compaction | Long conversations' Codex background compaction, in Codex's opened row on the Agents page (`CodexAsyncCompact`, `CodexAsyncCompactPercent`, #2490) writes `[features.async_compaction]` `enabled = true` and `model_async_compact_threshold_percent` (Codex 0.163 reads it only in that table) into each Codex config magpie routes, on every `Sync`. The table is written only when every Codex that reads the config is 0.163.0-alpha.8 or later (`codexReaders`: the CLI on PATH, the Mac app's bundled `codex-cli/codex-package.json`, the Windows Store app and an editor's `openai.chatgpt` extension, whose versions aren't known, a WSL distro's CLI): an older Codex takes every unknown `[features]` entry for a bool and won't load a config with the table ("invalid type: map, expected a boolean"). Otherwise, or with no Codex found, magpie writes the bare `[features]` `async_compaction = true`, which every Codex loads, and no threshold; a table magpie wrote before is taken out on the next `Sync`, and Settings' row names the Codex that held it (`CodexAsyncHeld`). Codex starts a background compaction only on a provider whose `capabilities.remote_compaction` is `"v2"`, which it gives OpenAI and Azure alone, so `[model_providers.magpie]` gets `capabilities = { remote_compaction = "v2" }` too, also when the user turned the feature on by hand (#2493); `putProvider` carries the table's capabilities over when it writes it again. What magpie wrote is in the stash under `codex.async`: a value the user set, or changed since, is never written over and stays when the switch goes off; a bare `async_compaction = true` the stash doesn't name as magpie's (`bool`), an inline or dotted table is the user's as written. | [`codex_async.go`](../../internal/agent/codex_async.go) | -| Codex windows | Each magpie model's entry in Codex's catalog (`codexcat.entriesAt`, and `listedEntry` for a relay's own entry) says the model's whole window as `context_window`, which Codex shows (95% of it) as the conversation's context. Where Codex compacts goes in the entry's `auto_compact_token_limit`: the threshold set on the model or its provider, else Long conversations' (`settings.Working`, 272K by default), only when that is below the window; Full window writes none. A model whose window magpie doesn't know (a relay listing none, one models.dev lacks) gets no `context_window` and still the threshold as `auto_compact_token_limit` (Long conversations' Compact at, 272K by default; a relay's own entry only a user-set one, under its own window and limit): Codex compacts at no point on an entry with neither, and after the vendor's "too long" every turn errors again until a manual /compact (jiangguochao666 on X, 11-01; reproduced with real Codex 0.165 and a relay refusing past 100K, compacted at 80K after the fix). `TestCodexCompactsWithNoKnownWindow`. A vendor that lists a larger window than it takes is not caught: Codex compacts on that window's 90%, or the threshold. Codex 0.165 compacts at the lesser of it and 90% of the window, and a `model_auto_compact_token_limit` the user put in config.toml comes before it, as a `model_context_window` there replaces every model's window (Codex then compacts at 90% of it). Long conversations' row in Codex's opened card names either one, top-level or in the profile config.toml picks (`agent.CodexCompactHeld`, sent to the page as one line by `codexKeysText`), and Take it out deletes them (`DropCodexCompactHolds`); magpie never deletes them on its own, as the value is the user's (zgjfjfl on Discord, 10-31: 128000 there, 544K in Long conversations). No threshold above a model's window moves Codex either, which then compacts at 90% of it: the row names the model Codex's config runs (`agent.CodexModel`, the picked profile's first) and the window magpie tells Codex for it, when Long conversations doesn't come below it and no threshold is set on the model or its provider (`codexWindowUnder` in internal/gui/api.go; the reporter's model was a relay's gpt-6-A). `TestCodexCompactHeldNamedAndTakenOut`, `TestCodexWindowUnderLongConversations`, codex-compact-held.test.cjs. Until 10-30 the threshold went in `context_window` with the window as `max_context_window`, so a 1M model showed 258K in Codex (01huadalang on Discord); `max_context_window` stays a field magpie owns so `Keep` doesn't carry an old catalog's over. Codex's own models (`codex/`) keep their entry's window. `Tag` carries `catalogFormat`, so a Codex holding a list in the old shape asks again. `TestCodexCatalogCompactAt`, `TestCodexWindowShownCompactApart`. | [`codexcat.go`](../../internal/codexcat/codexcat.go) | +| Codex windows | Each magpie model's entry in Codex's catalog (`codexcat.entriesAt`, and `listedEntry` for a relay's own entry) says the model's whole window as `context_window`, which Codex shows (95% of it) as the conversation's context. Where Codex compacts goes in the entry's `auto_compact_token_limit`: the threshold set on the model or its provider, else Long conversations' (`codexcat.Working`: `settings.Working`, 272K by default, except that at that default an OpenAI model is held to the window official Codex holds it to, `codexcat.OwnWindow` from the account's models_cache.json list, else Codex's bundled catalog (`bundledWindows`), matched by longest prefix; GPT-6.1 Terra's 500K, @flower__daisy on X; `TestCodexCatalogHoldsOpenAIModelToCodexWindow`, `TestBundledWindowsAreCodexOwn`), only when that is below the window; Full window writes none. A model whose window magpie doesn't know (a relay listing none, one models.dev lacks) gets no `context_window` and still the threshold as `auto_compact_token_limit` (Long conversations' Compact at, 272K by default; a relay's own entry only a user-set one, under its own window and limit): Codex compacts at no point on an entry with neither, and after the vendor's "too long" every turn errors again until a manual /compact (jiangguochao666 on X, 11-01; reproduced with real Codex 0.165 and a relay refusing past 100K, compacted at 80K after the fix). `TestCodexCompactsWithNoKnownWindow`. A vendor that lists a larger window than it takes is not caught: Codex compacts on that window's 90%, or the threshold. Codex 0.165 compacts at the lesser of it and 90% of the window, and a `model_auto_compact_token_limit` the user put in config.toml comes before it, as a `model_context_window` there replaces every model's window (Codex then compacts at 90% of it). Long conversations' row in Codex's opened card names either one, top-level or in the profile config.toml picks (`agent.CodexCompactHeld`, sent to the page as one line by `codexKeysText`), and Take it out deletes them (`DropCodexCompactHolds`); magpie never deletes them on its own, as the value is the user's (zgjfjfl on Discord, 10-31: 128000 there, 544K in Long conversations). No threshold above a model's window moves Codex either, which then compacts at 90% of it: the row names the model Codex's config runs (`agent.CodexModel`, the picked profile's first) and the window magpie tells Codex for it, when Long conversations doesn't come below it and no threshold is set on the model or its provider (`codexWindowUnder` in internal/gui/api.go; the reporter's model was a relay's gpt-6-A). `TestCodexCompactHeldNamedAndTakenOut`, `TestCodexWindowUnderLongConversations`, codex-compact-held.test.cjs. Until 10-30 the threshold went in `context_window` with the window as `max_context_window`, so a 1M model showed 258K in Codex (01huadalang on Discord); `max_context_window` stays a field magpie owns so `Keep` doesn't carry an old catalog's over. Codex's own models (`codex/`) keep their entry's window. `Tag` carries `catalogFormat`, so a Codex holding a list in the old shape asks again. `TestCodexCatalogCompactAt`, `TestCodexWindowShownCompactApart`. | [`codexcat.go`](../../internal/codexcat/codexcat.go) | | An agent's own Long conversations | Codex, Claude Code and Grok Build (`settings.CompactAgents`) can each have a Long conversations of their own over the one for every agent (molianyin4227 on Discord: models differ, so one size fits none): `settings.AgentCompacts[agent]` holds Compact at (`At`, 0 for the working window) or Full window (`Full`), and `Settings.ForAgent(agent)` lays it over `CompactAt`/`FullContext` for that agent's readers alone (`codexcat.entriesAt`, `codexListed`, `claudeIn`'s `writeCompact` and `desktopPlan`, `grokModelTables`, the route list's `buildModels`, Codex's window line and Tuned for you). A threshold set on a model or its provider still comes first. An agent with none follows the value for every agent, so an agent without the key (any agent outside the three) gets nothing new written. Set by `provider.SetAgentCompact` (`POST /api/settings/agent-compact` `{agent, own, full, at}`; `own` false takes it away), shown as a row under Long conversations in the agent's opened row and its sheet ("Long conversations in ": Every agent, Compact at, Full window), drawn by `agentcompact.js`, which app.js imports when the agent's settings hold Long conversations. Tuned for you's Use on an agent with its own value changes that one and stashes it under `tune.long.compact.`. In a terminal, `magpie model compact [every|off|]` (`agentCompact`, `TestModelCompactAgentCmd`). Not covered: t3code's route list reads the value for every agent. `TestSetAgentCompact`, `TestCodexCatalogCompactAt`, `TestGrokWindowFollowsLongConversations`, `TestClaudeCompactAt`, `TestTuneAgentOwnLong`, agent-compact.test.cjs. | [`settings.go`](../../internal/settings/settings.go), [`compact.go`](../../internal/provider/compact.go), [`agentcompact.js`](../../internal/gui/assets/agentcompact.js) | | An agent's own context window | Any agent with a model list can be told a window of its own for a model (ul3140773077392 on X: dsh compacts earlier than Codex at the same window, so one window fits some and has others compact too early). `settings.AgentContexts[agent]` (the agent's `ListsFor` id) maps `provider/model`, `group/`, `provider/*`, a bare model id or `*` to a window; the most specific wins, and `*` only shortens a known window. `provider.CatalogFor` lays it over the entries last (`withAgentWindows`, `agentwindow.go`) and marks them `WindowSet`, so every writer of that agent's list (dsh's `contextWindow`, Pi, OpenCode, the gateway's /models) and `CompactFor` (Codex, Claude Code compact at the whole window unless a size was typed) follow it; other agents keep the model's own. Set by `provider.SetAgentContexts` (`POST /api/settings/agent-contexts` `{agent, contexts}`; none takes them away), shown as "Context window in " in the agent's sheet (`agentwindow.js`, any agent with fields), and `magpie model window [=…\|off]`. `TestAgentOwnContextWindow`, `TestDshOwnContextWindow`, `TestModelAgentWindowCmd`, `TestSettingsSaveKeepsWhatItDoesNotSend`, agent-window.test.cjs. Not tried against a live dsh. | [`agentwindow.go`](../../internal/provider/agentwindow.go), [`agentwindow.js`](../../internal/gui/assets/agentwindow.js) | | A group's own Compact at | A routing group can carry where agents compact on it (`Group.Compact`, NovaStudiosss on X: no need to set a context size and a compaction size on each provider model). `compactSet` returns it before the smallest of its members' sizes, so Codex and Claude Code are told it; 0 is none. Set in the group's editor, Advanced, "Compact at" (beside "Context", which is the window agents are told), by `magpie group set compact=\|off`, and carried by every other save of the group. `TestGroupOwnCompactAt`, group-compact.test.cjs. | [`compact.go`](../../internal/provider/compact.go), [`group.go`](../../internal/provider/group.go) | @@ -221,7 +221,7 @@ something else shows up as drift. - Codex on a magpie model the user has since unchecked in its provider's model list (`provider.Unpicked`: the provider has picks, its served models lack it, and it is not a decision model) moves to that provider's first model magpie lists for Codex (`pickedInstead`, [`model_unpicked.go`](../../internal/agent/model_unpicked.go)), in each wiring: Codex's Sync puts it through `set`, as picking it does, and the profile's Sync through `put` (JNDliuliuM on X: Codex CLI, restarted, still started on the old model; `Resolve` still serves it). A provider with no picks, whose list is the vendor's, keeps a model it lacks (#2642), and one with none of its models listed leaves Codex where it is. Other agents' model fields, and Codex's subagent and compaction models, are not moved yet (#6504). - A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887). Codex 0.166 refuses to resume a thread whose provider isn't the one configured ("This chat uses openai, but your current provider is magpie", openai/codex#58865; 毅 on Discord), and for a legacy thread the rollout's `session_meta` wins over the state DB row. So when magpie becomes the provider, bringOver relabels plain rollouts in place and also moves legacy threads Codex packed to `.jsonl.zst` that were updated in the last 30 days, up to 128 MB a sync, newest first, each with a copy kept in the trash (`sessions.MovePackedCodexThreads`, `TestCodexThreadsFollowMagpieIn`, `TestMovePackedCodexThreads`); bringBack moves them back. A paginated thread (`history_mode = 'paginated'` in the row, every thread Codex 0.166 starts) is listed and resumed on the provider its row names, never its files' (codex-rs thread-store `read_thread`: "Paginated history may contain only a suffix, so its display metadata lives in SQLite"), so the 30 days and the budget left an API-key user's older OpenAI threads refused in the Codex app (Parry_Moody and Cyrus on Discord). Every one now moves by its row alone, of any age, packed or not, an id of any length, its files neither written nor copied (`sessions.RetagPagedCodexThreads`, after the in-place relabel), in bringOver, bringBack, bringOfficial, bringBeside and giveBeside (`RetagPagedCodexThreadIDs`); one a Codex has open (its writer lock, which would write its provider back) or wrote to in the last minute waits for the next sync. The Sessions page lists a paginated thread on its row's provider (`codexPagedProviders`, read again when the database or its WAL changes). Tried with the real codex 0.166.0 (`codex exec resume`): refused on magpie with the row on openai, resumed after the retag, and back on OpenAI after the reverse (`TestCodexPagedThreadsFollowByRow`, `TestRetagPagedCodexThreads`). Codex rebuilds a row from the rollout when a search listing or a missing row reconciles it, which would put a retagged thread back on its file's provider until the next sync. A thread a move leaves where it was because it was written to in the last minute or a Codex holds it open gets one more Sync once it is quiet and let go (`sessions.CodexThreadsBusyOn`: a recent rollout, or its writer lock held, tried under Codex's coordination lock; `codexThreadsLater` looks every 15s for up to 12h, one wait per home and provider): no other Sync may come for hours. bringBack's (the thread a turn ran in during the takeover, as the account came back) otherwise stayed on magpie, and the Codex app couldn't resume it on OpenAI, so Retry failed each time and its model read unavailable (nb5p on Discord, `TestCodexTakeoverThreadComesBackOnceQuiet`). bringOver's and lendOwn's are the chats the Codex app had loaded as magpie became Codex's provider: the app holds every loaded thread's lock however long ago it was written (tried with codex 0.165's app-server), checks a loaded thread's provider against config.toml at each turn, and refuses it ("This chat uses OpenAI, but your current provider is magpie", crypto0xfish on Discord) until it lets the thread go; resumed after that, it was refused again on its row's `openai` until something else synced (`TestCodexOpenThreadFollowsMagpieOnceLetGo`). The chat open at the switch is moved by its row (a legacy one in place, at equal id length) just before the Codex app's app-server is ended for the route change (`provider.CodexBeforeAppEnd`, `codexRetagOpenThreads`, `sessions.RetagLoadedCodexThreads`): the app holds its lock, but the end is a clean SIGTERM that writes nothing back, and the next app-server resumes it on the new provider, in both directions (tried with the real codex 0.167.1 app-server: refused with `modelProviderMismatch` openai to magpie and `modelProviderNotConfigured` magpie to openai without the retag, resumed with it; hubo31377762 on X; `TestCodexOpenThreadsMoveBeforeAppServerEnds`, `TestCodexRouteChangeMovesOpenChatsFirst`). The resumed thread's sandbox falls back to config.toml's default whatever the provider (#6028, a separate bug). That is done for the provider Codex was on before magpie (stash `codex.provider`, `openai` when none), a provider of the user's own too: a relay's table or CC Switch's `custom`, whose threads the Codex app listed and refused to open on magpie ("This chat uses custom, but your current provider is magpie", hxy920830 on X). An id of magpie's length (`custom`) is relabelled in place; any other (`myrelay`) is rewritten with a copy kept, the threads of the last 30 days, 128 MB a sync, newest first (`sessions.MoveRecentCodexThreads`), and none moves of a provider a profile names. OpenAI's threads come to magpie too, since the Codex app lists them and refuses each one there as it did on that provider ("此聊天使用的是 OpenAI,但你当前的提供商是 magpie", Lice9735 on X, Codex on its own `openai-http` table before). They are recorded in stash `codex.lent` with the user's provider as `to`, as `lendOwn` records its own below: the Disconnect gives every thread on magpie to that provider, where Codex resumes them, and `giveLent` gives these back to OpenAI once Codex is on it again. None moves while a profile names `openai` (`TestCodexOpenAIThreadsFollowMagpieFromOwnProvider`). Before, they stayed on OpenAI there. The Disconnect puts the user's `model_provider` back and bringBack returns the threads to it; so does CC Switch switching back to that provider (`TestCodexThreadsFollowMagpieIn`, `TestMoveRecentCodexThreads`). A thread started on `cc-switch-official`, the id CC Switch 3.17 to 3.20 gave the official account, is moved to `openai` (or `magpie`, whichever Codex is on) while magpie wires Codex, as CC Switch 4 does itself (#7948 there), unless the user's own top-level `model_provider` or a profile names that id (`bringOfficial`, AcMilan on Discord, `TestCodexMovesCCSwitchOfficialThreads`). CC Switch's OpenAI mirror is the ChatGPT account's as much, and the Codex app names a provider by its table's `name`, so a thread on the mirror with Codex on `openai`, or the other way round, was refused as "This chat uses OpenAI, but your current provider is OpenAI" (Chris on Discord; codex 0.167 `exec resume` refuses both by id, 0.168 drops the check). Its threads move the same way: `bringOfficial` takes every mirror table's that isn't at the top, named by a profile, or the provider magpie took down (stash `codex.provider`, whose threads `bringBeside` and `bringOver` move with a record and give back at the Disconnect), and a mirror at the top takes OpenAI's through `lendOwn` (`TestCodexMirrorThreadsFollowOpenAI`, `TestCodexMirrorAtTopJoinsWithItsThreads`, `TestCodexMirrorAtTopTakesOpenAIThreads`). Before #4347 (v0.1.2652) the beside wiring took a provider of the user's (CC Switch's `custom`) down and kept it in stash `codex.provider`, leaving Codex on OpenAI by the base URL with every thread of that provider refused ("This chat uses custom, but your current provider is openai", yikelizi9438 on Discord). While Codex stays so (routed by `openai_base_url`, no top-level `model_provider`), `bringBeside` moves that provider's threads to `openai` the same way (in place at OpenAI's length, the last 30 days rewritten otherwise) and records them in stash `codex.brought`; the Disconnect puts the provider back and `giveBeside` returns exactly those threads to it (`sessions.MoveCodexThreadIDs`), and if magpie becomes Codex's provider instead they go on to `magpie` (`followBeside`), where bringBack returns them at the Disconnect (`TestCodexBesideBringsTakenProvidersThreads`). The other way round, Codex on a provider of the user's at the top (CC Switch's `custom`, kept since #4347, CC Switch's OpenAI mirror too; not magpie, `openai` or `cc-switch-official`) could not continue a thread started on OpenAI before ("This chat uses openai, but your current provider is custom. Switch to openai to continue", harris on Discord, after CC Switch). Each Sync moves OpenAI's threads to that provider the same way (`lendOwn`: in place at OpenAI's length, by the row for a paginated one, the last 30 days rewritten otherwise) and records them in stash `codex.lent`; once Codex is on OpenAI again `giveLent` returns exactly those (`sessions.MoveCodexThreadIDs`, `RetagPagedCodexThreadIDs`), the record kept while Codex is on that provider or on magpie and dropped on any other. None moves while a profile names `openai`, after the user disconnected Codex, or from a distro's Codex (`TestCodexOwnProviderTakesOpenAIThreads`, `TestCodexOwnProviderLeavesOpenAIThreads`). Each rewrite (`codexOnto`, shared by bringOver, bringBeside and lendOwn) goes `packedBudget` bytes a sync, newest first; when the budget stops it with threads left (`MovePackedCodexThreads` and `MoveRecentCodexThreads` say `more`), it asks for the next sync at once (`codexThreadsAgain`) instead of leaving them refused until something else syncs, which may be hours away (`TestCodexThreadsLeftByTheBudgetAskAgain`). Threads on any other provider, and ones older than 30 days that can't be relabelled in place, stay put: the Sessions page's Move or Resume takes them over. - 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. A window that is Long conversations (`TuneLong`) is stashed once as Long conversations was (`tune.long.compact`, one stash for both agents, as the value is one), and Undo puts it back, Full window included, unless the user changed it since. Codex's card is always Long conversations, unless config.toml has a `model_auto_compact_token_limit` of the user's, which Codex stops at first: that one is `locked`. A limit an older magpie's tune wrote there (`tune.codex.compact`) is moved by `tuneMigrateCodex`, from Codex's Sync and from the card: Long conversations at magpie's default, or under Full window, takes it as the user's own choice; one the user typed takes it only when it is lower, where Codex compacted; the file gets back what it had; and a limit the user changed after the click is theirs and stays. Claude Code's `CLAUDE_CODE_AUTO_COMPACT_WINDOW` is Long conversations when magpie wrote it from that value (`claude.compact_long` beside `claude.compact_window`, set by `writeCompact`), and its top-level `autoCompactWindow` when magpie wrote it (`claude.compact_default`) and it equals Long conversations; a window from a provider's Compact at, or the user's own, stays `locked`. A Claude model's own `modelSettings` window, under no such variable, is still per model, since Long conversations doesn't reach Claude models. 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). Codex's window is the one magpie's catalog lists for each model it ran (typed, or the vendor's), and with none in config.toml it runs now at what magpie tells Codex (`provider.CompactFor`, else Long conversations in the agent's opened row, as `codexcat` writes it); a model of magpie's whose window isn't known caps nothing short of 1M (or the user's own larger value), never the largest prompt seen (zhemu on Discord: a 1M model at 750K was offered up to 410K), and only Codex's own models, outside the catalog, keep 272K or the largest prompt (`codexWindow`, `TestTuneWindowsAreTheUsers`). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest; with the compactions timed, it never advises a window that compacts more often than the one now, so never a longer wait: of the windows that compact no more often it takes the cheapest, and of those within 3% of that (`sameCost`, the same bar as changing at all) the one that compacts least, the larger of two that compact as often. Tokens and seconds share no unit the files measure, so the advice doesn't trade one for the other at a guessed rate; a cheaper window that waits longer is said with its wait in the row and the picker, for the user to choose. The wait per compaction is taken as the same at every window: the files time compactions only near the window the user ran with, too narrow to fit how it grows with the prompt. 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. +- Tuned settings are written only on the user's click, never by Sync or Connect. A window that is Long conversations (`TuneLong`) is stashed once as Long conversations was (`tune.long.compact`, one stash for both agents, as the value is one), and Undo puts it back, Full window included, unless the user changed it since. Codex's card is always Long conversations, unless config.toml has a `model_auto_compact_token_limit` of the user's, which Codex stops at first: that one is `locked`. A limit an older magpie's tune wrote there (`tune.codex.compact`) is moved by `tuneMigrateCodex`, from Codex's Sync and from the card: Long conversations at magpie's default, or under Full window, takes it as the user's own choice; one the user typed takes it only when it is lower, where Codex compacted; the file gets back what it had; and a limit the user changed after the click is theirs and stays. Claude Code's `CLAUDE_CODE_AUTO_COMPACT_WINDOW` is Long conversations when magpie wrote it from that value (`claude.compact_long` beside `claude.compact_window`, set by `writeCompact`), and its top-level `autoCompactWindow` when magpie wrote it (`claude.compact_default`) and it equals Long conversations; a window from a provider's Compact at, or the user's own, stays `locked`. A Claude model's own `modelSettings` window, under no such variable, is still per model, since Long conversations doesn't reach Claude models. 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). Codex's window is the one magpie's catalog lists for each model it ran (typed, or the vendor's), and with none in config.toml it runs now at what magpie tells Codex (`provider.CompactFor`, else Long conversations in the agent's opened row, as `codexcat` writes it); a model of magpie's whose window isn't known caps nothing short of 1M (or the user's own larger value), never the largest prompt seen (zhemu on Discord: a 1M model at 750K was offered up to 410K), and only Codex's own models, outside the catalog, keep the window Codex's catalog gives them (`codexcat.OwnWindow`, else 272K) or the largest prompt (`codexWindow`, `TestTuneWindowsAreTheUsers`). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest; with the compactions timed, it never advises a window that compacts more often than the one now, so never a longer wait: of the windows that compact no more often it takes the cheapest, and of those within 3% of that (`sameCost`, the same bar as changing at all) the one that compacts least, the larger of two that compact as often. Tokens and seconds share no unit the files measure, so the advice doesn't trade one for the other at a guessed rate; a cheaper window that waits longer is said with its wait in the row and the picker, for the user to choose. The wait per compaction is taken as the same at every window: the files time compactions only near the window the user ran with, too narrow to fit how it grows with the prompt. 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. - A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. An object or array `connect` returns is taken as its JSON text (`agentplug.keys`), so it is written in the order the plugin gave it, not sorted as a Go map would be: Kilo lists its effort variants in key order (#1890, `TestPluggedKeepsPluginOrder`). What each key held before the first write is stashed under `plugin::`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). Its `agent.library` (instructions, `mcp` with `mcpFormat`, skills) gives it the Library's three as well, written by `internal/library` as any agent's are ([library](library.md)); a `mcpFormat` outside `agentplug.MCPFormats`, or an `mcp` without one, keeps the plugin from loading. Turning the plugin off or removing it (`provider.SetPluginOff`, `provider.RemovePlugin`, from the CLI or the Plugins page) first disconnects its agent as `magpie default` does (`provider.PluginAgentGoing`, set to `agent.UnwirePlugin` in [`plugged_gone.go`](../../internal/agent/plugged_gone.go)), since without the plugin magpie no longer knows the agent (#3810); a plugin already off is read from its module as it is, and one whose module is gone puts back each file whose stash names its spec. A failure keeps the plugin as it was. On again, the agent stays as the user had it, and connecting it puts back the model it was on (Disconnect's `.reconnect`). The stash records the plugin's spec and the file's format, so `magpie default` for the agent of a plugin deleted on disk puts the file back from the stash alone (`agent.RestoreGone`; an older stash's format is its file's name, `agentplug.FormatOf`); a file that no longer holds the gateway's key is the user's and left alone, and one that can't be read is put back over by nothing; with the plugin only switched off, it says the agent is off magpie already, not "unknown agent" (`TestPluginOffPutsItsAgentBack`, `TestRestoreGoneAgent`, `TestGoneAgentDefault`). - StepCode config root resolves to the parent of an absolute `STEP_CODING_AGENT_DIR` (agent resources directory differs from config root; relative values ignored), or `STEPCODE_CONFIG_DIR` under home when native, defaulting to `~/.stepcode` ([`stepcode.go`](../../internal/agent/stepcode.go)). Project configs override global configs in StepCode, but magpie manages global configuration only (`config.toml` and `models.json`). Detection is strictly directory-only via `agentDir`, avoiding collision with Smallstep's bare `step` command on `PATH`. Wiring performs an atomic two-file edit (`models.json` provider block and `config.toml` top-level defaults/scope) backed by `stash.json`. Custom fields within `providers.magpie` are preserved during sync, and the original provider block is restored on disconnect. A renamed provider's `magpie//` entries in `enabledModels` follow it, a glob or a thinking level included, and the scope remembered for disconnect follows too; the user's other entries stay. Disconnect restores original defaults, preserves user native changes and custom scope edits, and removes newly created files only when empty. - MothX's folder is `$MOTHX_DIR` as it is (no `~`), else `%APPDATA%\mothx` on Windows, else `~/.mothx`; a WSL distro's is its `~/.mothx` ([`mothx.go`](../../internal/agent/mothx.go)). Its `thinkingFormat` is `openai` unless the user set one: with it empty, MothX picks Qwen's `enable_thinking`, DeepSeek's `thinking` or Doubao's levels by the model id, which for magpie's ids says nothing of the vendor that serves them. MothX's `/model` and `/statusline … global` rewrite the whole file, so Disconnect after one takes out magpie's provider, the pick and a `providers` left empty (MothX omits an empty one), and keeps the rest. diff --git a/internal/codexcat/codexcat.go b/internal/codexcat/codexcat.go index 7f37b4238..19d0dceee 100644 --- a/internal/codexcat/codexcat.go +++ b/internal/codexcat/codexcat.go @@ -426,13 +426,16 @@ func entriesAt(ms []catalog.Model, after int, effort string) []any { } if c := m.Context; c > 0 { // the model's or its provider's threshold, else the one for - // every model (#876); one at or above c is its whole window. + // every model (#876), which by default holds an OpenAI model + // to the window Codex's own catalog does (Working: GPT-6.1 + // Terra's 500K, @flower__daisy on X); one at or above c is + // its whole window. // A DeepSeek model too, though DeepSeek's own Codex setup // compacts at none of its 1M: magpie's 272K came of a // DeepSeek report (e950eb080: turns of ~550K waited 70-90s // for a first token), and Full window or the model's own // Compact at gives it the whole window - w := work.Working(c) + w := Working(work, m.ID, c) if m.Compact > 0 { w = min(c, m.Compact) } @@ -440,7 +443,7 @@ func entriesAt(ms []catalog.Model, after int, effort string) []any { if w < c { e.AutoCompact = &w } - } else if w := cmp.Or(m.Compact, work.Compact()); w > 0 { + } else if w := cmp.Or(m.Compact, unknownWorking(work, m.ID)); w > 0 { // a window magpie doesn't know (a relay listing none, a // model models.dev lacks): Codex compacts at no point on an // entry with neither a window nor a limit, and after the diff --git a/internal/codexcat/ownwindow.go b/internal/codexcat/ownwindow.go new file mode 100644 index 000000000..be9ece1aa --- /dev/null +++ b/internal/codexcat/ownwindow.go @@ -0,0 +1,84 @@ +package codexcat + +import ( + "maps" + "strings" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +// bundledWindows is the context_window of each model in Codex's own +// bundled catalog (rust-v0.166.0, models-manager/models.json), by slug; +// TestBundledWindowsAreCodexOwn checks it against that file in testdata. +// Codex holds most of OpenAI's models to 272K, and GPT-6.1 Terra to 500K +// (@flower__daisy on X). +var bundledWindows = map[string]int{ + "gpt-6-astra": 272000, + "gpt-6.1-sol": 272000, + "gpt-6.1-terra": 500000, + "gpt-6-sol": 272000, + "gpt-6-luna": 272000, + "gpt-5.6-sol": 272000, + "gpt-5.6-terra": 272000, + "gpt-5.6-luna": 272000, + "gpt-daybreak-blue-latest": 272000, + "gpt-daybreak-red-latest": 372000, + "gpt-5.5": 272000, + "codex-auto-review": 272000, +} + +// OwnWindow is the context window official Codex holds the OpenAI model +// that id serves to (mycpa/gpt-6.1-terra, a ChatGPT account's +// codex/gpt-6.1-terra, a found auto/gpt-6.1-terra), matched as Codex +// matches a slug (longestPrefix): the window the ChatGPT account Codex last +// asked with lists (models_cache.json, which is this Codex version's), +// else Codex's bundled catalog's. 0 for a routing group, a model of +// another vendor's, or one Codex has no entry for. +func OwnWindow(id string) int { + if strings.HasPrefix(id, "group/") || !openAIModel(id) { + return 0 + } + slug := strings.ToLower(id[strings.LastIndex(id, "/")+1:]) + listed := map[string]int{} + for _, m := range catalog.CodexShared() { + if m.Context > 0 { + listed[strings.ToLower(m.ID)] = m.Context + } + } + if s := longestPrefix(slug, maps.Keys(listed)); s != "" { + return listed[s] + } + if s := longestPrefix(slug, maps.Keys(bundledWindows)); s != "" { + return bundledWindows[s] + } + return 0 +} + +// Working is where magpie has Codex compact a conversation on model id, of +// a window of c tokens, when neither the model nor its provider sets a +// threshold: Long conversations' (st.Working). Its default, the working +// window, is the 272K Codex holds OpenAI's models to, so an OpenAI model +// Codex holds to more (GPT-6.1 Terra's 500K) is held to that window, never +// above c. A size the user set (CompactAt) or Full window is as they set it. +func Working(st settings.Settings, id string, c int) int { + w := st.Working(c) + if st.FullContext || st.CompactAt > 0 { + return w + } + if n := OwnWindow(id); n > w { + return min(c, n) + } + return w +} + +// unknownWorking is Working for a model whose window magpie doesn't know: +// Long conversations' threshold, which by default is the window Codex's +// own catalog holds an OpenAI model to when that is more. +func unknownWorking(st settings.Settings, id string) int { + w := st.Compact() + if w > 0 && st.CompactAt == 0 { + w = max(w, OwnWindow(id)) + } + return w +} diff --git a/internal/codexcat/ownwindow_test.go b/internal/codexcat/ownwindow_test.go new file mode 100644 index 000000000..eeeea8a64 --- /dev/null +++ b/internal/codexcat/ownwindow_test.go @@ -0,0 +1,121 @@ +package codexcat + +import ( + "encoding/json" + "maps" + "os" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +// bundledWindows is Codex's own: every model of its bundled models.json +// with the context_window it has there. When Codex is updated, its +// models.json in testdata and this map change together. +func TestBundledWindowsAreCodexOwn(t *testing.T) { + b, err := os.ReadFile(codexDir + "models.json") + if err != nil { + t.Fatal(err) + } + var file struct { + Models []struct { + Slug string `json:"slug"` + Context int `json:"context_window"` + } `json:"models"` + } + if err := json.Unmarshal(b, &file); err != nil { + t.Fatal(err) + } + want := map[string]int{} + for _, m := range file.Models { + want[m.Slug] = m.Context + } + if !maps.Equal(bundledWindows, want) { + t.Errorf("bundledWindows = %v; Codex's models.json says %v", bundledWindows, want) + } + if want["gpt-6.1-terra"] != 500000 { + t.Errorf("Codex's models.json holds gpt-6.1-terra to %d; this test was written for 500000", want["gpt-6.1-terra"]) + } +} + +// @flower__daisy on X: Codex compacted early on magpie. Long +// conversations' default told every model with a longer window to compact +// at 272K, "what OpenAI does with its own models"; Codex's own catalog +// holds GPT-6.1 Terra to 500K. An OpenAI model magpie serves is held to +// the window Codex holds it to, never above its own; another vendor's +// model, and a size the user set, are as before. +func TestCodexCatalogHoldsOpenAIModelToCodexWindow(t *testing.T) { + models := []catalog.Model{ + {ID: "mycpa/gpt-6.1-terra", Name: "terra", Context: 922000}, + {ID: "auto/gpt-6.1-terra-2026-10-01", Name: "terra dated", Context: 922000}, + {ID: "mycpa/gpt-6.1-sol", Name: "sol", Context: 922000}, + {ID: "small/gpt-6.1-terra", Name: "terra small", Context: 400000}, + {ID: "codex/gpt-6.1-terra", Name: "terra account", Context: 500000}, + {ID: "relay/gpt-6.1-terra", Name: "terra unknown"}, + {ID: "relay/gpt-6.1-sol", Name: "sol unknown"}, + {ID: "deepseek/deepseek-v4-pro", Name: "ds", Context: 1000000}, + {ID: "anthropic/claude-sonnet-5-5", Name: "sonnet", Context: 1000000}, + {ID: "group/terra", Name: "group", Context: 922000}, + } + told := func() map[string][2]any { + t.Helper() + var got struct { + Models []map[string]any `json:"models"` + } + if err := json.Unmarshal(Catalog(models), &got); err != nil { + t.Fatal(err) + } + out := map[string][2]any{} + for _, e := range got.Models { + out[e["slug"].(string)] = [2]any{e["context_window"], e["auto_compact_token_limit"]} + } + return out + } + check := func(what string, want map[string][2]any) { + t.Helper() + got := told() + for id, w := range want { + if got[id] != w { + t.Errorf("%s: %s told %v; want %v", what, id, got[id], w) + } + } + } + work := float64(settings.WorkingWindow) + // no ChatGPT sign-in: Codex's bundled catalog + v1Home(t, `{"models":[]}`) + check("bundled", map[string][2]any{ + "mycpa/gpt-6.1-terra": {float64(922000), float64(500000)}, + "auto/gpt-6.1-terra-2026-10-01": {float64(922000), float64(500000)}, + "mycpa/gpt-6.1-sol": {float64(922000), work}, + "small/gpt-6.1-terra": {float64(400000), nil}, + "codex/gpt-6.1-terra": {float64(500000), nil}, + "relay/gpt-6.1-terra": {nil, float64(500000)}, + "relay/gpt-6.1-sol": {nil, work}, + "deepseek/deepseek-v4-pro": {float64(1000000), work}, + "anthropic/claude-sonnet-5-5": {float64(1000000), work}, + "group/terra": {float64(922000), work}, + }) + // the ChatGPT account's own list, which is this Codex's, comes first + v1Home(t, `{"models":[{"slug":"gpt-6.1-terra","display_name":"GPT-6.1-Terra","visibility":"list","context_window":400000,"max_context_window":872000}]}`) + check("account's list", map[string][2]any{ + "mycpa/gpt-6.1-terra": {float64(922000), float64(400000)}, + "mycpa/gpt-6.1-sol": {float64(922000), work}, + }) + // a size the user set is theirs, under the window Codex gives too + v1Home(t, `{"models":[]}`) + if err := settings.Save(settings.Settings{CompactAt: 300000}); err != nil { + t.Fatal(err) + } + check("compact at 300K", map[string][2]any{ + "mycpa/gpt-6.1-terra": {float64(922000), float64(300000)}, + "relay/gpt-6.1-terra": {nil, float64(300000)}, + }) + if err := settings.Save(settings.Settings{FullContext: true}); err != nil { + t.Fatal(err) + } + check("full window", map[string][2]any{ + "mycpa/gpt-6.1-terra": {float64(922000), nil}, + "relay/gpt-6.1-terra": {nil, nil}, + }) +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 1323cffdf..eff6a77d3 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -35,6 +35,7 @@ import ( "github.com/yetone/magpie/internal/autostart" "github.com/yetone/magpie/internal/bark" "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/codexcat" "github.com/yetone/magpie/internal/desktopiso" "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/fonts" @@ -849,7 +850,7 @@ func codexWindowUnder(st settings.Settings, model string) *codexRunWindow { if !ok && strings.HasPrefix(model, provider.GroupPrefix) { e, ok = provider.EntryOf(model) } - if !ok || e.Context <= 0 || provider.CompactFor(st, e, provider.GroupFinder()) > 0 || st.Working(e.Context) < e.Context { + if !ok || e.Context <= 0 || provider.CompactFor(st, e, provider.GroupFinder()) > 0 || codexcat.Working(st, e.ID, e.Context) < e.Context { return nil } return &codexRunWindow{Model: model, Window: e.Context, Size: tokensSize(e.Context)} diff --git a/internal/gui/tune.go b/internal/gui/tune.go index a329d8f6e..e52556776 100644 --- a/internal/gui/tune.go +++ b/internal/gui/tune.go @@ -6,6 +6,7 @@ package gui // config has now, and putting one in, or back, on their say. import ( + "cmp" "encoding/json" "hash/fnv" "net/http" @@ -17,6 +18,7 @@ import ( "time" "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/codexcat" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/sessions" "github.com/yetone/magpie/internal/settings" @@ -281,7 +283,8 @@ func pricedWeights(st settings.Settings) tune.Weigh { // (window 0): the largest prompt it had been sent was taken for its // window, and a 1M model set to compact at 750K was offered no more than // 412K (zhemu on Discord). Codex's own models, outside magpie's catalog, -// run to 272K or the largest prompt seen, as before. +// run to the window Codex's catalog gives them (codexcat.OwnWindow, 272K +// when it has none) or the largest prompt seen. func codexWindow(calls []tune.Call, st settings.Settings, entries []provider.Entry, find func(string) (provider.Group, []provider.Member, bool)) (window, told int, own string, apart []tuneOwn) { byID := make(map[string]provider.Entry, len(entries)) for _, e := range entries { @@ -296,7 +299,9 @@ func codexWindow(calls []tune.Call, st settings.Settings, entries []provider.Ent e, ok := byID[strings.TrimPrefix(m, "magpie/")] switch { case !ok: - window = max(window, 272000, p) + // Codex's own model: the window its catalog gives it (GPT-6.1 + // Terra's 500K), else 272K + window = max(window, cmp.Or(codexcat.OwnWindow(m), 272000), p) case e.Context <= 0: unknown = true default: @@ -307,7 +312,7 @@ func codexWindow(calls []tune.Call, st settings.Settings, entries []provider.Ent held = max(held, at) continue } - at := st.Working(e.Context) + at := codexcat.Working(st, e.ID, e.Context) if n := provider.CompactFor(st, e, find); n > 0 { at = min(e.Context, n) }