routing: DimCode's requests read as DimCode, with its mark, by key too

Yayoi_no_yume on X, a Docker magpie (v0.1.4350): DimCode (dimcode.dev)
on another computer, calling with a gateway key named "Magpie", drew
the Routing page's client node as the cube and "Magpie", and the
request's story said "DimAgent asked for the routing group Step 5
Preview".

Two causes:
- DimCode was no client magpie knew, so usage.AgentOf named it by its
  product name: npm's dimagent 0.5.29 sends "DimAgent/<version>" to a
  provider set to send its identity (resolveDimOAuthIdentityHeaders)
  and "DimCode/<version>" otherwise (read from the published binary).
  A client "dimcode" (DimCode, UA dimagent/dimcode) now names it,
  apart from the Dim alpha magpie starts ("dima"/"dimcode-alpha" stay
  Dim's, by name first). Its icon is dim-color: dimcode.dev's favicon
  (dimagent-favicon.svg, "Official DimAgent mark") is the same artwork.
  Routes and ledger records kept before are named again through
  AgentOf (Route.routedAgain), so old "DimAgent" rows read as DimCode.
- A keyed request's node read the key's name alone (eadc6cdb9, for a
  script's key behind "Python-urllib"). An agent magpie knows now
  reads "agent · key", as Usage's ledger rows already do; a script's
  key keeps the key's name alone. The tooltip names the agent once.
  The tray panel's stage and rows share callerName and read the same.

The icon comes from the embedded assets, which the web (Docker) build
serves the same way; the GUI test checks the image loads.

Run on mote:
- go vet ./internal/agent, GOOS=linux -tags nogui and GOOS=windows:
  ok. go test -count=1 ./internal/agent ./internal/usage: ok (agent 463s, usage 124s)
- TestDimCodeByUserAgent is red with the dimcode entry taken out
  (AgentOf("DimAgent/0.5.29") = "DimAgent").
- GUI, chromium and webkit, every language, 1100 and 420:
  routing-agent-with-key.test.cjs (new), i18n-keys, i18n-en-no-cjk:
  30 of 30 pass. Earlier, on mica, with the same client.js: the 28 other
  files that read callerKey, .rt-src, .ps-name/.ps-ag or .pr-who pass
  but api-key-usage (#7083) and usage-ledger's return-to-live case
  (#5048), both red on origin/main 2416beed6 too.
  routing-agent-with-key is red on the old client.js ('Magpie' for
  'DimCode · Magpie').

Not tried: a real DimCode against a real Docker magpie; the
User-Agents come from the published binary and the reporter's log.
This commit is contained in:
yetone
2026-11-18 18:03:16 +08:00
parent bdefdc3191
commit bfddc9cfba
5 changed files with 182 additions and 4 deletions
+1 -1
View File
@@ -43,7 +43,7 @@ something else shows up as drift.
| WSL CLI versions and updates | A twin's CLI is read and updated in its distro, as the host's is (`cliupdate_wsl.go`; mewcoder on X): the Agents row shows the version, the newest and an Update button for every `cliSpecs` kind a distro has a command for, and Update all takes them in. Where the binary is comes from the probe (`distro.Paths`, else the command asked of the distro's PATH); one `wsl.exe -d <distro> -e sh` script says where its links lead, its `--version` and exit code (`wslCLIScript`, kept ten minutes in `wslProbes`, asked again by Rescan and after an update), with the CLI's own folder, its npm prefix, `~/.local/bin` and `~/.bun/bin` first on PATH, since `wsl.exe -e` has no login PATH and a node CLI would not find node. How it was installed is read from that Linux path by the same rules (`wslHowInstalled`: its own updater via `cliSpec.self`, Homebrew's Cellar, npm, bun or pnpm; volta, yarn and an npm prefix the user can't write, `/usr/lib`, are left alone), and the update runs in the distro through wsl.exe (`wslRunUpdate`) with a Linux brew asked for its newest in the distro too. A distro that isn't running is never started to be asked: its rows show no version and an update says to start it. Not carried over: the host's proxy settings (the distro has its own network), and Grok Build's newest is read from this computer's channel setting. Kinds with no command of their own (Goose, mu) show nothing, as on the host. | [`cliupdate_wsl.go`](../../internal/agent/cliupdate_wsl.go), [`cliupdate.go`](../../internal/agent/cliupdate.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`), each model's tokens weighed at what magpie bills them where the agent asked for a model magpie wrote (a provider/model id resolves as the gateway resolves it and is weighed at that provider's price, `pricedWeights`, so a Claude model on Copilot has its 1-hour cache write at the 5-minute one Copilot bills, #3435), else at its maker's list ratios (`tune.WeightsFor`); `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.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) |
| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. One whose agent keeps the model a new session starts on in a file apart from its provider list says so with `startup` (`config`, `format`, `model`, and `keys` written beside the model as they are) and has no `model`: PiG keeps its providers in `models.json` and `defaultProvider`/`defaultModel` in `settings.json` (str_ on Discord: its row only listed models, where Pi's picks the one it starts on). Its field is `model` again; picking one of magpie's writes `connect`'s keys into `config` and the model and `startup.keys` into `startup.config`, each file stashed under its own `plugin:<id>:<path>` (the startup one marked by its first string key, so a model picked in the agent among magpie's, with `defaultProvider` still `magpie`, reads as magpie's). A model of the agent's own picked in it while `connect`'s keys are still in `config` is `Beside`: connected, not drift, and Disconnect leaves that pick and takes the rest out. A magpie without `startup` reads the same module as connect only (`TestPluggedStartupModel`, `TestPluggedStartupOwnPickKept`, `TestPluggedStartupRestoreGone`). `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`; a routing group's, `provider.GroupEndpoints`, the APIs every member relays as it is; carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). Decision models are never in `models`; `connect` gets them as `decisionModels` (`pluggedDecisionModels`: `provider.OfferedDeciders`, what `/v1/models` lists under `X-Magpie-Deciders`, then the decision routing groups, each with `id`, `name`, `provider` or `group: true`, and `endpoints` `/v1/systemone` and `/v1/decisions`; `TestPluggedConnectSeesDecisionModels`). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) |
| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL`, `--settings <~/.gemini/antigravity-cli/magpie-settings.json>` and `--model` (no `--model` when the user gives one) while that file's model is magpie's, and unchanged otherwise. magpie writes `modelProvider`, `model` and the custom models (the user's own too, as agy takes the key whole) only into that file of its own, never into agy's `settings.json`: `modelProvider: gemini` there made every agy an API-key session with no Google account, so no remote control, which needs the sign-in (baysonfox on X). A `settings.json` an older magpie wired is given back (the stashed model and provider) at the next `Sync` or pick. A model of magpie's in `settings.json` while `magpie-settings.json` is already on magpie's is agy's own `/model` pick, which agy writes there even under `--settings`: it moves into magpie's file, and `settings.json`'s model goes back to the one `connect.was` kept (the user's own) or out; the old stash isn't read for it, which put a stale model and `modelProvider: gemini` back or took the user's out (LolingVerse on X, `TestAgyOwnPickKeepsSettings`). agy's `/effort` is turned away for every custom model, so a model with two or more of low, medium and high gets a custom model per level too, `magpie/<ref>:<level>` with `thinkingLevel` (the only levels agy 1.5.9 takes there), which agy sends as `thinkingConfig.thinkingLevel` and the gateway asks over the row's (`agyLevelAsked`); the row's model field shows such a pick as its model (`agyLevelOf`). `agy remote-control …` and `--remote-control` go through the function and `magpie agy run` as plain agy, on the user's sign-in (`AgyRemote`); remote control inside a session on magpie's models is not possible. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Dim alpha (`dima`, [`dim.go`](../../internal/agent/dim.go)) gets the same kind of function from `launchSpec`, with no model flag: `magpie dim run` starts it with the variables Dim documents for an OpenAI-compatible endpoint (`DIM_BASE_URL` = the gateway's `/v1`, `DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY` = `agentKey("dim")`, `DIM_MODEL`, and `DIM_MAX_CONTEXT_TOKENS`/`DIM_MAX_OUTPUT_TOKENS`, which Dim needs for a model it doesn't know), read for that run only and beside a running daemon. The pick is in magpie's own `dim.json`; nothing in Dim's home or database is written, and Dim's own account (DimAgent, dropped at its vendor's request in v0.1.471) is never read or used. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) |
| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL`, `--settings <~/.gemini/antigravity-cli/magpie-settings.json>` and `--model` (no `--model` when the user gives one) while that file's model is magpie's, and unchanged otherwise. magpie writes `modelProvider`, `model` and the custom models (the user's own too, as agy takes the key whole) only into that file of its own, never into agy's `settings.json`: `modelProvider: gemini` there made every agy an API-key session with no Google account, so no remote control, which needs the sign-in (baysonfox on X). A `settings.json` an older magpie wired is given back (the stashed model and provider) at the next `Sync` or pick. A model of magpie's in `settings.json` while `magpie-settings.json` is already on magpie's is agy's own `/model` pick, which agy writes there even under `--settings`: it moves into magpie's file, and `settings.json`'s model goes back to the one `connect.was` kept (the user's own) or out; the old stash isn't read for it, which put a stale model and `modelProvider: gemini` back or took the user's out (LolingVerse on X, `TestAgyOwnPickKeepsSettings`). agy's `/effort` is turned away for every custom model, so a model with two or more of low, medium and high gets a custom model per level too, `magpie/<ref>:<level>` with `thinkingLevel` (the only levels agy 1.5.9 takes there), which agy sends as `thinkingConfig.thinkingLevel` and the gateway asks over the row's (`agyLevelAsked`); the row's model field shows such a pick as its model (`agyLevelOf`). `agy remote-control …` and `--remote-control` go through the function and `magpie agy run` as plain agy, on the user's sign-in (`AgyRemote`); remote control inside a session on magpie's models is not possible. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Dim alpha (`dima`, [`dim.go`](../../internal/agent/dim.go)) gets the same kind of function from `launchSpec`, with no model flag: `magpie dim run` starts it with the variables Dim documents for an OpenAI-compatible endpoint (`DIM_BASE_URL` = the gateway's `/v1`, `DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY` = `agentKey("dim")`, `DIM_MODEL`, and `DIM_MAX_CONTEXT_TOKENS`/`DIM_MAX_OUTPUT_TOKENS`, which Dim needs for a model it doesn't know), read for that run only and beside a running daemon. The pick is in magpie's own `dim.json`; nothing in Dim's home or database is written, and Dim's own account (DimAgent, dropped at its vendor's request in v0.1.471) is never read or used. DimCode (dimcode.dev), the vendor's own app, is a client apart from Dim alpha (`dimcode` in `agents.go`, `TestDimCodeByUserAgent`): its User-Agent, `DimCode/<version>` or `DimAgent/<version>`, names it, drawn with the same mark as Dim (its site's favicon); unknown, a DimCode calling a Docker magpie by a gateway key read as a client named DimAgent, drawn as the cube (Yayoi_no_yume on X). Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) |
| Built-ins a plugin serves | `agentMovers` names the community agent plugin a built-in agent moves onto (`agy`: `@magpie-community/agent-agy`). While that plugin is installed and on, `dropMoved` leaves the built-in out (`onMachine`, and `wslKind.served` in a distro), and the plugin's agent takes its id and aliases. Its desc says what the built-in did in code. `config` is magpie's own `magpie-settings.json` and `base` agy's `settings.json` (`Desc.Base`, `bf` in `plugged`): `connect` and `own` get `base` parsed, the user's own model is written there, `get` reads it off magpie, and stepping out removes the config whole, so `settings.json` is never written while on magpie and remote control keeps its Google sign-in (0cc91af3d). `launch` (`{env, model, args, plain}`) gives it the same shell function and `magpie <id> run`/`env` (`launchSpec` in [`plugged_launch.go`](../../internal/agent/plugged_launch.go); `startCmd` in [`start_cli.go`](../../internal/cli/start_cli.go) finds any agent with `Start` by id or alias, `agent.Starter`): `args` `{"--settings": "{config}"}` go before the model flag, filled with the config as the agent's system spells it (`env` prints them as `settings=<file>`, which the PowerShell function reads), and a `plain` argument (`remote-control`) runs the agent as it is, in `startRun` (`Starting.Plained`) and in a distro's or PowerShell's function, which have no magpie to ask (`TestPluggedDistroFunctionArgsAndPlain`, `TestPluggedPowerShellFunctionArgsAndPlain`). `effort`, `wsl` and `aliases` are the rest. A `launch.env` value is `{key}`, `{url}` or `{v1}` with a path at most (`envValueOK`), an `args` value only `{config}`, and a `plain` word a subcommand or flag, so nothing else a plugin says reaches a shell profile (`TestLaunchSaysOnlyWhatAShellTakesAsItIs`, `TestBaseIsForAHandedConfig`). What the built-in wired is handed over the first time the plugin's agent reads its file with nothing stashed (`handedOver`, `agyHandover` in [`plugged_moved.go`](../../internal/agent/plugged_moved.go)): a `settings.json` an older built-in wired is given back first, by the built-in's own `Sync` (its `migrate`, then `magpie-settings.json` written); then, while `magpie-settings.json` names one of magpie's models, its keys become the plugin's `Had` as not there before, so the plugin's own model or Disconnect takes the file away and leaves `settings.json` as the user had it. Turning the plugin off disconnects it as any plugin agent's (below), and the built-in is back (`TestAgyPlugin`, `TestAgyHandedToPlugin`, `TestAgyOldWiringHandedToPlugin`, `TestAgyHandedOverUnwire`). | [`plugged_moved.go`](../../internal/agent/plugged_moved.go), [`plugged_launch.go`](../../internal/agent/plugged_launch.go) |
| Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer). The app (0.1.72, Electron) attaches its window to a daemon running; with none it starts its own (`serve --stdio --adopt-install`, `launch_context` `app-child`) in its own environment, without the variable, and its "let the app run it instead" (and its offer once the app updated past the daemon) stops magpie's to do the same (shuitunlulu_ on Discord: Claude Science went back off magpie). So the keeper also puts magpie's daemon back, on the port the other was on, in place of one with another pid, one started for the gateway's old address, or its own older than the program installed (`--version`, asked again only when the file changed) (`scienceStale`), but only when `status` says no session runs in it (`active_frames` and `active_conversations` 0; a status without them is busy), never one launchd or systemd keeps (`launch_context`), and at most three times an hour (`scienceRetakes`). It reads `operon.lock` every 10 s and asks `status` when the lock's pid changed or a minute went by. A window on the daemon stopped shows the app's "stopped from the command line" screen, whose "start it again in the app" attaches it to magpie's. `Check` reads the daemon's `operon.lock`, not `status` (most of a second for a 130 MB Bun program), and calls a daemon with another pid drift until the keeper replaces it. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). In a WSL distro (shuitunlulu_ on Discord) it is a WSL twin (`wslKinds`, found by `claude-science` on the probe's PATH, keeping its own notice) whose daemon magpie runs there through `wsl.exe` (`scienceInWSL`, `scienceWSLScript`; the same `scienceHost` steps as this machine's, its note `claude-science-wsl-<distro>.json`). The daemon takes http only to a loopback address, so in mirrored networking it gets the gateway's address, and under NAT a relay magpie starts in the distro: `socat` on `127.0.0.1:<gateway port>` to Windows' address on the WSL network (`scienceRelayScript`, its pid and target in `~/.claude-science/magpie-relay`, stopped with its forks as a process group on Disconnect or when the target moved). It is given `http://127.0.0.1:<port>/<WSL key>`, the key in the path, as it sends its own sign-in as the key (gateway-routing's WSL under NAT). Connect says so when the distro has no socat. The keeper runs nothing in WSL until a distro's note exists, then starts both again in each running distro (`wslScienceHosts`). Its `Check` adds the firewall drift any agent pointed at Windows' WSL address gets (`unreachable`), as its one value isn't a model of magpie's, which is what `Drift` asks that of. | [`claudescience.go`](../../internal/agent/claudescience.go), [`claudescience_wsl.go`](../../internal/agent/claudescience_wsl.go), [`science.go`](../../internal/gateway/science.go) |
| Claude Code beside its own account | `claude-magpie` (baranwang on X) starts Claude Code through magpie while a plain `claude` stays on the user's own account, nothing switched back and forth. `magpie claude run [args…]` writes `<config>/claude-launch/settings.json` as `claude#launch`, an agent `claudeIn` makes at that folder (`place.dir`) and lists nowhere, so the Agents page, Check and Notice see only the user's settings.json: connected the first time as Connect would (`ConnectHow`), set again when the gateway's address or key moved (`claudeLaunchStale`, the LAN key included), synced after that, with `ANTHROPIC_API_KEY` and the cloud switches (`agentenv.ClaudeProviders`) blanked. It then runs `claude --settings <file> args…` as a child (not exec, so it can tidy after): Claude Code puts a --settings file's env and model over the user's settings.json, a claude.ai sign-in and the shell (tried on 2.1.318). `/model` saves to the user's settings.json, never the --settings file, so `ClaudeLaunchAfter` moves a magpie model picked there into the launch file and gives the user's file its model back while magpie isn't wired into it; it also undoes Claude Code's own one-time `opus` → `opus[1m]` rewrite (`migration_opus_to_opus1m`), which the launch file's 1M opus tier sets off. A Claude alias picked (`sonnet`) stays. On Unix a stopped child stops magpie too (^Z, fg), and its exit code is magpie's; on Windows magpie ignores Ctrl+C while claude runs. The command `claude-magpie` is a launcher beside the `magpie` command (`update.Launchers`): a `#!/bin/sh` `exec` of `Program()`, or on Windows a `.cmd` running `"%~dp0magpie"`. `AddCLI` writes it, and `magpie claude launcher add` puts it there for a command added before; a file by that name without `written by magpie` is never written over. StandIn falls back to the launch file's tiers. | [`claude_launch.go`](../../internal/agent/claude_launch.go), [`claude_launch_cli.go`](../../internal/cli/claude_launch_cli.go), [`claude_run_unix.go`](../../internal/cli/claude_run_unix.go), [`launcher.go`](../../internal/update/launcher.go) |
+7
View File
@@ -208,6 +208,13 @@ var others = []*Agent{
// Icons are the apps' own App Store icons (#shannnnnks on X).
{ID: "flowdown", Name: "FlowDown", Icon: "flowdown-color", UA: []string{"flowdown"}},
{ID: "bob", Name: "Bob", Icon: "bob-color", UA: []string{"bob/"}},
// DimCode (dimcode.dev) says "DimCode/<version>", or "DimAgent/<version>"
// to a provider set to send its identity (npm's dimagent 0.5.29,
// resolveDimOAuthIdentityHeaders). It is arcships' own app, apart from
// the Dim alpha magpie starts (dim.go); dimcode.dev's favicon is the
// same mark as dim-color. Unknown, it read as the cube and "DimAgent"
// on a Docker magpie's Routing page (Yayoi_no_yume on X)
{ID: "dimcode", Name: "DimCode", Icon: "dim-color", UA: []string{"dimagent", "dimcode"}},
// Kimi Code Desktop runs Kimi Code's engine on ~/.kimi-code, so it
// reaches magpie through Kimi Code's config, under a client name of
// its own ("kimi-code-desktop/…", jiabubu on Discord). Its icon is the
+32
View File
@@ -0,0 +1,32 @@
package agent
import (
"slices"
"testing"
"github.com/yetone/magpie/internal/usage"
)
// Yayoi_no_yume on X: DimCode (dimcode.dev) calling a Docker magpie by a
// gateway key read as the cube and "DimAgent". Its requests are DimCode's,
// drawn with its mark, and are not the Dim alpha magpie starts.
func TestDimCodeByUserAgent(t *testing.T) {
for ua, want := range map[string]string{
"DimAgent/0.5.29": "dimcode",
"DimCode/0.5.29": "dimcode",
"DimAgent": "dimcode",
"dimcode/dev": "dimcode",
"dimcode-alpha/0.1.0": "dim",
"dima/0.1.0": "dim",
"dimmer/1.0": "dimmer",
} {
if got := usage.AgentOf(ua); got != want {
t.Errorf("%q: %q, want %q", ua, got, want)
}
}
if !slices.ContainsFunc(Clients(), func(a *Agent) bool {
return a.ID == "dimcode" && a.Name == "DimCode" && a.Icon == "dim-color"
}) {
t.Error("DimCode isn't a client the Routing and Usage views draw")
}
}
+14 -3
View File
@@ -816,10 +816,21 @@ function routingPage(part) {
// a script's key read "Python-urllib"). srcOf is the stage's node for
// it: each key's its own, two keys' scripts saying one User-Agent too.
// Never the key's secret: a route carries its id and name alone.
// An agent magpie knows keeps its name beside the key's, as Usage's
// rows read ("DimCode · Server"): DimCode calling a Docker magpie by a
// key named "Magpie" read as that alone (Yayoi_no_yume on X).
function callerName(r) {
const k = r.callerKey && (callerKeys.find((x) => x.id === r.callerKey)?.name || r.callerKeyName);
return k || agentName(r.agent);
if (!k) return agentName(r.agent);
const ag = agentOf(r.agent);
return ag?.name && ag.name !== k ? `${ag.name} · ${k}` : k;
}
// callerLines head a caller's tooltip: its name, then its agent's when
// the name doesn't say it already
const callerLines = (r) => {
const c = callerName(r), a = agentName(r.agent);
return c === a || c.startsWith(a + " · ") ? [c] : [c, a];
};
const srcOf = (r) => r.callerKey ? r.agent + "\u0001" + r.callerKey : r.agent;
// userShown is an account of provider as the user named it in magpie
// (provider.AccountNames, #1515), else as its plugin's usage names it
@@ -2921,7 +2932,7 @@ function routingPage(part) {
const fs = foldersOf([...new Set([...going, ...rs.filter((x) => srcOf(x) === id)])].sort((x, y) => x.id - y.id));
// told again every second (countdown): only what changed is written
setText(a.sub, fs.length > 1 ? fs.map(lastLevel).join(", ") : r.model);
const tip = [...new Set([callerName(r), agentName(r.agent)]), r.model, ...fs.map((f) => t("Folder") + ": " + f)].join("\n");
const tip = [...callerLines(r), r.model, ...fs.map((f) => t("Folder") + ": " + f)].join("\n");
if (a.node.title !== tip) a.node.title = tip;
}
// the account sets, the latest of each
@@ -9615,7 +9626,7 @@ function routingPage(part) {
n.node.style.setProperty("--agent", hueOf(id));
n.wire.style.setProperty("--agent", hueOf(id));
n.node.replaceChildren(icon(ag?.icon || "generic"), el("span", "ps-name", callerName(r)));
n.node.title = [...new Set([callerName(r), agentName(r.agent)]), ...foldersOf(recent.filter((x) => srcOf(x) === id).slice(0, 20).reverse()).map((f) => t("Folder") + ": " + f)].join("\n");
n.node.title = [...callerLines(r), ...foldersOf(recent.filter((x) => srcOf(x) === id).slice(0, 20).reverse()).map((f) => t("Folder") + ": " + f)].join("\n");
return n.node;
}));
pTo.replaceChildren(...pDst.map((k) => {
@@ -0,0 +1,128 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A request from an agent magpie knows, sent with a named gateway key, is
// drawn with the agent's icon and reads "agent · key" (Yayoi_no_yume on X:
// DimCode on another computer, calling a Docker magpie by a key named
// "Magpie", read as the cube and "Magpie" alone). A script's key keeps the
// key's name alone, as before (acezan). The request's story names the
// agent, and the tray panel's stage and rows read the same. In every
// language, at 1100 and 420; the API is faked, and the icon is the file
// the web build serves.
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");
function fixture() {
const now = Date.now(), at = (s) => new Date(now - s * 1000).toISOString();
const seat = { id: "sf", provider: "stepfun-cn", name: "StepFun (China)", who: "k1", kind: "key", model: "step-5-preview" };
const req = (id, agent, key) => ({ id, seq: id, time: at(5 - id), agent,
...(key ? { callerKey: key.id, callerKeyName: key.name } : {}),
model: "auto/step-5-preview", provider: "stepfun-cn", order: [seat], tries: [{ id: seat.id, model: "step-5-preview", start: at(4), done: false }],
group: { name: "Step 5 Preview", members: [] },
done: false, status: 0 });
return [
req(1, "dimcode", { id: "k-magpie", name: "Magpie" }),
req(2, "Python-urllib", { id: "k-nightly", name: "nightly" }),
];
}
const keys = [{ id: "k-magpie", name: "Magpie" }, { id: "k-nightly", name: "nightly" }];
const clients = [{ id: "claude", name: "Claude Code", icon: "claude-color" }, { id: "dimcode", name: "DimCode", icon: "dim-color" }];
function serve(lang) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "claude", name: "Claude Code", fields: [] }], clients, profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.has("wait") || Number(url.searchParams.get("after"))) return new Promise(() => {});
return json({ mine: true, now: new Date().toISOString(), seq: 2, totals: { requests: 2, rerouted: 0, errors: 0 }, routes: fixture() });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/caller-keys") return json({ keys, accountNames: {} });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname.startsWith("/api/window/")) return route.fulfill({ status: 204 });
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)];
return route.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}: an agent's request with a key reads as the agent and the key`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const errors = [];
const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=routing");
await page.waitForFunction(() => document.querySelectorAll(".rt-src").length === 2);
// the icon is drawn once its file has loaded
await page.waitForFunction(() => [...document.querySelectorAll(".rt-src .ic img")].some((i) => i.complete && i.naturalWidth > 0));
const nodes = await page.locator(".rt-src").evaluateAll((es) => es.map((e) => ({
name: e.querySelector("b").textContent, title: e.title, icon: e.querySelector(".ic")?.dataset.icon,
loaded: [...e.querySelectorAll(".ic img")].some((i) => i.naturalWidth > 0),
})));
const dim = nodes.find((n) => n.icon === "dim-color");
assert(dim, "DimCode's node has its icon: " + JSON.stringify(nodes));
assert(dim.loaded, "dim-color.svg is served");
assert.equal(dim.name, "DimCode · Magpie");
assert.match(dim.title, /^DimCode · Magpie\nauto\/step-5-preview/, "the agent once under the pointer");
const script = nodes.find((n) => n !== dim);
assert.equal(script.name, "nightly", "a script's key alone");
assert.equal(script.icon, "generic");
assert.match(script.title, /^nightly\nPython-urllib\n/);
// the story names the agent
await page.locator(".rt-req").first().click();
await page.waitForFunction(() => /\bDimCode\b/.test(document.body.innerText));
const body = await page.evaluate(() => document.body.innerText);
assert.doesNotMatch(body, /DimAgent/);
const fit = await page.evaluate(() => ({ client: document.documentElement.clientWidth, scroll: document.documentElement.scrollWidth }));
assert(fit.scroll <= fit.client + 1, `the page overflows at ${width}: ${JSON.stringify(fit)}`);
const inside = await page.locator(".rt-src").evaluateAll((es) => es.every((e) => {
const b = e.querySelector("b").getBoundingClientRect(), n = e.getBoundingClientRect();
return b.right <= n.right + 1 && b.left >= n.left - 1;
}));
assert(inside, "each name inside its node");
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-agent-key.png`) });
}
assert.deepEqual(errors, []);
});
}
}
test(`${engine}: the tray panel reads an agent's keyed request as the agent and the key`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const ctx = await browser.newContext({ viewport: { width: 360, height: 560 }, reducedMotion: "no-preference" });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.panelTab", "routing"); } catch {} });
const page = await ctx.newPage();
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
await page.route("**/*", serve("en"));
await page.goto("http://magpie.test/?mode=panel");
await page.locator("#panelRouting .pr-req").nth(1).waitFor();
const who = await page.locator("#panelRouting .pr-who").allTextContents();
assert.deepEqual(who.slice().sort(), ["DimCode · Magpie", "nightly"].sort(), JSON.stringify(who));
await page.waitForFunction(() => document.querySelectorAll("#panelRouting .ps-ag").length === 2);
const ag = await page.locator("#panelRouting .ps-ag").evaluateAll((es) => es.map((e) => [e.querySelector(".ps-name").textContent, e.querySelector(".ic")?.dataset.icon]));
assert.deepEqual(ag.slice().sort(), [["DimCode · Magpie", "dim-color"], ["nightly", "generic"]].sort(), JSON.stringify(ag));
assert.deepEqual(errors, []);
});
}