openmausbot: its engine's calls are counted as OpenMausBot's, not Claude Code's (@huangfuyafei on X)
huangfuyafei on X: in Usage → Requests, OpenBot's calls show OpenBot, but
OpenMausBot's show Claude Code. OpenMausBot (milind-soni/OpenMausBot,
read at 9f67fa5) runs the real Claude Code CLI as its engine.
server/drivers/claude.ts's claudeEnvironment deletes
CLAUDE_CODE_ENTRYPOINT and adds no header of its own, so a request
carries Claude Code's User-Agent and nothing else. magpie wrote the
"magpie" engine in ~/.openmausbot/config.json with the gateway's plain
token (keyAt), so the gateway's agentOf fell through to the User-Agent
and named Claude Code. OpenBot is told apart by its /agent/openbot path.
- internal/agent/openmausbot.go: the engine's ANTHROPIC_AUTH_TOKEN and
ANTHROPIC_API_KEY are agentKeyAt("openmausbot", gw), the key naming
OpenMausBot (as desktopKey does for Claude Desktop). An engine written
before gets the key at the next sync (ombMerged makes the routing keys
magpie's); OpenMausBot reads the file when it starts.
- internal/gateway: claudeCodeInside is Claude Code's User-Agent under
another agent's path or key (Claude Desktop apart). claudeTierStandIn
and observedKind (claudeCodeAs) treat such a call as Claude Code's, so
the haiku/sonnet/opus tier stand-in and the auxiliary marking of
tool-less helper calls still apply inside OpenMausBot. Real Claude Code
on the plain token or magpie-claude is unchanged.
- docs/subsystems/agent-wiring.md, gateway-routing.md say so.
Run (mote, through mote-run; mote at load 21-137 on 18 cores, mica at
92-108 on 12 with another session's full suite, so mote as the lesser):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/agent
./internal/usage at the pre-rebase head 3c9d79d28+change: agent ok,
usage ok; gateway FAIL on three known reds, none in this change's code:
TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117; 3 of 3 red on
a clean origin/main 6bb90df8e too), TestSearchQueueKeepsCodexAlive/
progress at load 137 (#7090, pings=3 complete=false; 3 of 3 green on
main and head after), and the doneHold fake's close-of-closed-channel
panic (#6505, #6690).
- At the rebased head (on 6bb90df8e): -count=3 of TestClaudeCodeInsideAnApp,
TestClaudeTier*, TestStandIn*, TestAgentInPath and the two reds above:
all ok but #7117; -run 'OMB|OpenMausBot|Omb' ./internal/agent ok;
GOOS=linux and GOOS=windows go vet of both packages ok; gofmt -l clean.
- Broken by hand: on the old openmausbot.go/gateway.go/observe.go,
TestOpenMausBotEngine and TestOpenMausBotKeepsTheUsers fail (token
"magpie") and TestClaudeCodeInsideAnApp fails (404 for
claude-haiku-4-5-20251001: no tier stand-in under the OpenMausBot key).
Not tried:
- a real OpenMausBot run against the gateway (the key and the agentOf
path are tested; the app was read, not run);
- OpenMausBot's own "claude" engine, inheriting ~/.claude/settings.json
pointed at magpie: it sends the plain token with Claude Code's
User-Agent and is still counted as Claude Code;
- the classifier stand-in (automode.go) stays keyed on agent=="claude":
it follows the user's ~/.claude /model, not OpenMausBot's Claude home;
- the observedKind assertion calls claudeCodeAs directly, not through
observeRequest;
- a key change alone doesn't offer Restart (ombPart leaves the key out);
a running OpenMausBot needs a restart to send the new key.
- No GUI change: OpenMausBot's name and icon already exist.
This commit is contained in:
@@ -157,7 +157,7 @@ something else shows up as drift.
|
||||
- Claude Code's tool search (`ENABLE_TOOL_SEARCH`, `claudeSearchEnv` in [`claude.go`](../../internal/agent/claude.go)) is written `"true"` while Claude Code is routed through magpie. On, MCP tools are named in a reminder and loaded by `ToolSearch` when the model needs them, not sent whole on every request. Claude Code before 2.1.304 keeps it off behind an `ANTHROPIC_BASE_URL` other than Anthropic's, so the MCP router's tools all went on each request (cybercaius on Discord: 245 tools, 124K tokens of a 341K context; 2.1.290 through a sandbox gateway sent 242,346 bytes of tools, 27,443 with it on); 2.1.304 and later turn it on there themselves, and `"true"` also keeps it on in a conversation begun without it. The gateway carries deferred tools to Anthropic upstreams and to a Responses upstream that loads them in place (`Tool.Deferred`, `withoutDeferredTools`); elsewhere it turns them away so Claude Code declares every tool and the prompt cache holds (`refusesDeferred`, gateway-routing.md). magpie's value is kept apart in the stash (`claude.tool_search`); a value the user set, an empty one too, is theirs; it goes when Claude Code is taken off magpie (`desktopOnly`, `unroute`; `TestClaudeToolSearchOn`). T3 Code's magpie instance carries `"true"` in its environment unless the user gave it a value there (`TestT3CodeToolSearchOn`).
|
||||
- Claude Desktop's Code tab gets tool search only with Desktop's own `toolSearchEnabled` policy on (3p only, off by default). Off, Desktop 2.7032 (`Ztr` "off") starts Claude Code with `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`, and Claude Code (2.1.312, 2.1.316: `oae` returns "standard") then keeps tool search off whatever `ENABLE_TOOL_SEARCH` says, so every MCP tool went whole on each request (bigcat1800 on Discord: 13 MCP servers, ~162K tokens; a sandbox CLI with 60 MCP tools sent 83 tools, 205KB). On, with the gateway provider and a bundled Claude Code of 2.1.247 or later, Desktop hands the CLI `ENABLE_TOOL_SEARCH=force` as a managed setting and the same CLI sent 13 tools, MCP ones behind `ToolSearch`, 56KB, asking only `tool-search-tool-2025-10-19` of the betas. magpie's profile gets `toolSearchEnabled: true` once, on a switch on and from Sync, as `claudeAiImport` is (`desktopSeedToolSearch`, `desktopSeedOnce`, mark `claude-desktop.tool-search`): a value the user set, false too, or took away since, stays theirs (`TestClaudeDesktopTurnsOnToolSearch`). A profile the user applied for magpie's gateway (`desktopAppliedGateway`) is not written.
|
||||
- Claude Desktop 5.11492 starts its Code tab's Claude Code with `CLAUDE_CODE_MAX_CONTEXT_TOKENS=200000` in its `--settings` file whenever the provider routes models itself, the gateway included (`Fcn`, `Lcn` in its app.asar; 4.16336 had none). Flag settings come before `~/.claude/settings.json`, so the window magpie writes there (`claudeContextEnv`) no longer reaches the Code tab: a 1M model picked by its plain entry ran at 200K (fwxkogaia on X, v0.1.4321). Claude Code takes a `[1m]` id for 1M whatever that variable says (2.1.322's `pT`), so magpie's profile gets Desktop's own "Use 1M wherever it's available" (`modelPrefer1mContext: true`, 3p only, Desktop 1.28929 and later) once, on a switch on and from Sync, as `toolSearchEnabled` is (`desktopSeedPrefer1M`, mark `claude-desktop.prefer-1m`; `TestClaudeDesktopPrefers1M`). Desktop then shows a model it offers a 1M entry for by that entry alone; it offers one only for a row whose `max_input_tokens` is 1M or more, so it does nothing for a smaller model. A model past 200K and under 1M that isn't Claude's (a 272K or 872K GPT) is listed by its `[1m]` id whatever `DesktopLongest` says (`desktopMidWindow` in [`desktop.go`](../../internal/gateway/desktop.go)), described by its own size ("872K context window"), because by its plain id it ran at 200K whatever its window was (RQuantum198888 on X: a GPT set to 872K showed 200K). Claude Code 2.1.326 then runs it in 1M (`peo` in `aV`, past the forced 200000), and it compacts within its own window through `modelSettings.<id>.autoCompactWindow` (`claudePlan`): the window the user typed whole, else the working window (`TestClaudeDesktopMidWindowRunsPast200K`). Its `/context` then reads "/ 872k" where the plain id read "/ 200k" (tried on 2.1.326 with Desktop's flag settings); a managed policy setting is the only thing that comes before flag settings, and magpie writes none. The user's own value, false too, or their taking it away, stays theirs.
|
||||
- OpenMausBot (`openmausbot.go`) runs each bot on an engine from `instances` in `~/.openmausbot/config.json` (`$OMB_DATA_DIR`, `server/config.ts` in its source). magpie writes the `magpie` engine as OpenMausBot's own Claude endpoint (`newClaudeEndpoint`, `claude-endpoints.ts`): driver `claudeAgent`, access `custom`, `config.configDir` under `providers/magpie` so OpenMausBot starts Claude Code with its own `CLAUDE_CONFIG_DIR` and strips account keys the engine doesn't set (`claudeEnvironment`, `claude.ts`), `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY` at the gateway, and magpie's models as `config.endpointModels`, kept to the ids OpenMausBot's `CLAUDE_MODEL_ID` accepts (one bad id makes it refuse the whole engine). A non-empty `instances` is the whole fleet, so with none saved magpie writes OpenMausBot's `DEFAULT_FLEET` beside it (`ombFleet`, stashed as `openmausbot.fleet`) and takes it out again on off if the user hasn't changed it (`TestOpenMausBotFleetChanged`). The name, a model picked from the list, other env and a `cli` are the user's. OpenMausBot reads the file once at start and writes back the fleet it holds whenever an engine is edited in it, so the switch is refused while it runs (`errOMBRunning`; not checked on Windows) and the notice asks to quit it first. That write-back, and an edit of magpie's engine there (`updateClaudeEndpoint` keeps only the model picked and its tiers), leave `endpointModels` without models picked in magpie, and no catalog change follows to sync it again: while magpie serves, `KeepOpenMausBotListed` runs the sync every 30 seconds when the saved list differs from magpie's (`ombListStale`; maxleebeta on Discord, 11-08: Antigravity's models missing from its search). A copy started before magpie's last change to the engine (`ombPart`: the gateway, the first model and the list) offers the row's Restart (`restartApps`, `OpenMausBot.app` and `OpenMausBot.exe`). Codex bots use `~/.codex`, which magpie's Codex wiring already covers.
|
||||
- OpenMausBot (`openmausbot.go`) runs each bot on an engine from `instances` in `~/.openmausbot/config.json` (`$OMB_DATA_DIR`, `server/config.ts` in its source). magpie writes the `magpie` engine as OpenMausBot's own Claude endpoint (`newClaudeEndpoint`, `claude-endpoints.ts`): driver `claudeAgent`, access `custom`, `config.configDir` under `providers/magpie` so OpenMausBot starts Claude Code with its own `CLAUDE_CONFIG_DIR` and strips account keys the engine doesn't set (`claudeEnvironment`, `claude.ts`), `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY` at the gateway with a key naming OpenMausBot (the Claude Code it runs sends nothing of OpenMausBot's, and with the plain token its calls were counted as Claude Code's, huangfuyafei on X; an engine written before gets the key at the next sync and OpenMausBot reads it at its next start), and magpie's models as `config.endpointModels`, kept to the ids OpenMausBot's `CLAUDE_MODEL_ID` accepts (one bad id makes it refuse the whole engine). A non-empty `instances` is the whole fleet, so with none saved magpie writes OpenMausBot's `DEFAULT_FLEET` beside it (`ombFleet`, stashed as `openmausbot.fleet`) and takes it out again on off if the user hasn't changed it (`TestOpenMausBotFleetChanged`). The name, a model picked from the list, other env and a `cli` are the user's. OpenMausBot reads the file once at start and writes back the fleet it holds whenever an engine is edited in it, so the switch is refused while it runs (`errOMBRunning`; not checked on Windows) and the notice asks to quit it first. That write-back, and an edit of magpie's engine there (`updateClaudeEndpoint` keeps only the model picked and its tiers), leave `endpointModels` without models picked in magpie, and no catalog change follows to sync it again: while magpie serves, `KeepOpenMausBotListed` runs the sync every 30 seconds when the saved list differs from magpie's (`ombListStale`; maxleebeta on Discord, 11-08: Antigravity's models missing from its search). A copy started before magpie's last change to the engine (`ombPart`: the gateway, the first model and the list) offers the row's Restart (`restartApps`, `OpenMausBot.app` and `OpenMausBot.exe`). Codex bots use `~/.codex`, which magpie's Codex wiring already covers.
|
||||
- Avibe (`avibe.go`, `avibe-os` on PyPI, the `vibe` CLI) keeps its model sources in `model_hub.sources` of `config/config.json` in its home (`$AVIBE_HOME`, else `~/.avibe`, else a legacy `~/.vibe_remote`: `config/paths.py`). A source can't be written there by hand: its key is sealed in the Model Hub's store and Avibe adds it to its agents' route chains as it is made. So magpie adds the `magpie` source through the same internal API Avibe's Models page uses (`POST /internal/model-hub`, `core/handlers/model_hub/rpc.py`) on the control socket `state/dispatch.sock` in its home, or on Windows the loopback port and bearer token in `runtime/control-ipc/endpoint.json` (`core/control_ipc.py`). `create_source` makes an `api_key` source of vendor `custom` at the gateway's `/v1` with `agentKey("avibe")`, protocol `openai_chat` and `save_unverified` (Avibe's probe can't tell which protocol a gateway serving all of them speaks); Avibe then lists the models from `/v1/models` itself. Chat completions, not Responses: for a Responses source its CLIProxyAPI runs Codex's executor, which sends `codex-tui` headers the gateway would take for Codex. Its id is stashed (`avibe.source:<home>`); a source of the custom vendor at the gateway's `/v1` counts as magpie's too. `delete_source` and `refresh_source` are sent with `force` and then again with the `would_remove_hops` and `would_interrupt` Avibe answers with, as its page confirms them. A gateway address change makes the source again (the key goes with the address and `patch_source` can't change it). Every change needs Avibe running (`avibeLive` probes `list_sources`; `errAvibeDown`); `Sync` refreshes the source's models while it runs.
|
||||
- Kun (`kun.go`, KunAgent/Kun, an Electron app, `com.xingyuzhong.deepseekgui`; zhongxingyuyes on X) keeps its model connections in `model-connections.v2.json` in its data folder (`$KUN_DATA_DIR`, not ~-expanded, else `~/.kun/data`). A connection's key goes to Kun's credential store as it is made, so the file isn't written by hand: magpie adds the `magpie` connection the way Settings > Providers does, through the runtime's admin API at the `baseUrl` of `runtime.json` in that folder, with its `runtimeToken` as a bearer (loopback only). `POST /v1/model-connections/connect` makes an `http` connection with `api-key` auth at the gateway's `/v1`, `endpointFormat` `chat_completions`, `agentKey("kun")`, the models picked for Kun (500 at most) and the pick selected; another of magpie's models is `PATCH` of the list and `POST /v1/model-connections/select`. Every change names the registry's revision (409 `revision_conflict` otherwise). Kun's default before magpie's is stashed (`kun.prev:<dir>`) and selected again when magpie steps out, then the connection is `DELETE`d. Kun refuses to delete the connection its default names ("still has references: default.providerId"), so with no default of Kun's own to go back to, magpie's goes as Kun's Settings retires one: a provider-config transaction (`POST /v1/provider-config/transactions/preview`, then `commit`) that clears the default and removes the connection (`kunClient.remove`, `TestKunFromNothing`). Its id is stashed (`kun.id:<dir>`); an HTTP connection at the gateway's `/v1` counts as magpie's too. Every change needs Kun running (`kunLive` probes the snapshot; `errKunDown`); reads go to the registry file first. A sync brings the list up to the picked models, and makes the connection again only from the gateway's own address on an older port (`kunMoved`, as `avibeMoved`). Every test of the package but Kun's own finds a Kun running per data folder (`runningKun`).
|
||||
- Nowledge Mem (`nowledgemem.go`, a Tauri app, `co.nowledge.mem.desktop`; xiaomaomiloulou on X) runs its own AI (search, distilling, its chat) on the remote LLM provider picked on its first page and in Settings > AI, kept in `remote_llm.json` in its config folder (`$NMEM_APP_CONFIG_DIR`, else `co.nowledge.mem.desktop` in the system's config folder) with each key encrypted, so the file is only read. Mem 0.10 has a provider type of magpie's own (`magpie`, default base `http://127.0.0.1:3425/v1`, `Bearer magpie-nowledge-mem` with no key), and the gateway reads that key as the agent `nowledge-mem`. magpie changes it through Mem's backend, nmem-server, at `127.0.0.1:14242` (`$NMEM_API_URL`, loopback only; `memLive` probes `/remote-llm/status`), as Settings and `nmem config provider` do: `POST /remote-llm/config` saves provider `magpie` with the model, the gateway's `/v1` and `agentKey("nowledge-mem")`, and always makes it active and turns the AI on. Left out, `temperature`, `max_tokens` and `timeout` go back to Mem's defaults, so every change sends the provider's own again (`memBody`). What Mem had is stashed once (`nowledge-mem.prev:<dir>`): the active provider, whether the AI was on, and a `magpie` provider the user made themselves, which keeps its own key and gets its model, base and parameters back. Stepping out activates the provider Mem had (`/remote-llm/activate`), unless one was picked in Mem since, removes magpie's provider (`/remote-llm/provider/remove`) and turns the AI off again (`/remote-llm/enabled`) if it was off. Every change needs Mem running (`errMemDown`); reads go to the API, else the file. A sync moves the base only from the gateway's own address on an older port (`avibeMoved`). Every test of the package but Mem's own finds a Mem running per config folder (`runningMem`).
|
||||
|
||||
@@ -45,7 +45,7 @@ another for the conversation instead of listing every id
|
||||
|
||||
| Part | Responsibility | Source |
|
||||
| --- | --- | --- |
|
||||
| Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-<agent>` (`TokenFor`). `agentOf` tells which agent asked: first by an agent named in the path, then by token, then by User-Agent. An agent that can be given neither a key nor a User-Agent of its own is given an address with its id in it, `/agent/<id>/v1` (`AgentPath`, `AgentURL` in [`agentpath.go`](../../internal/gateway/agentpath.go)): `lanGuard` takes `/agent/<id>` off the path when `<id>` is an agent magpie knows (`takeAgentPath`), and the request is served at the rest as that agent's; `startedByAgent` never takes it for a script. OpenBot is one: it seals an endpoint's key and headers where magpie can't write, and hands the endpoint to the OpenCode it runs, whose User-Agent is OpenCode's, so its requests were counted as OpenCode's (SSNQT on X; `TestAgentInPath`). A Codex turn that names itself Claude Code is Codex's: OpenAI's Codex plugin for Claude Code (/codex:rescue, /codex:review) runs `codex app-server` with clientInfo "Claude Code", which Codex sends as its originator and User-Agent, and only Codex's turn headers (`x-codex-window-id`, `x-codex-turn-metadata`) tell it apart from Claude Code's own requests (`codexForClaudeCode`); an app that runs Codex as its own engine under its own name (Lody) stays that app. VS Code's Agents window runs `codex app-server` as `vscode_agent_host`, its originator and User-Agent: its calls are counted under VS Code (`vscodeAgentHostUA` in [`vscode.go`](../../internal/agent/vscode.go)), and its turns are Codex's for every Codex rule (`fromCodex`, `hostedCodex`), so one of Codex's own models asked there goes on Codex's sign-in (`codexOwnOffMagpie`) rather than 404; only Codex's own names (`codexNamed`) are kept as Codex's shape for a test asked as Codex (`TestVSCodeAgentHostIsCodex`, `TestVSCodeAgentHostOwnModelGoesOnSignIn`, `TestVSCodeAgentHostNotCodexTestShape`). Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's `X-Anthropic-Surface: operon` (`isClaudeScience`). It is listed every model as `claude-magpie-<number>` (`scienceModels`; its picker keeps only a `claude-` id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (`scienceTurn`, kept in `claude-science.model`). | [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-<agent>` (`TokenFor`). `agentOf` tells which agent asked: first by an agent named in the path, then by token, then by User-Agent. An agent that can be given neither a key nor a User-Agent of its own is given an address with its id in it, `/agent/<id>/v1` (`AgentPath`, `AgentURL` in [`agentpath.go`](../../internal/gateway/agentpath.go)): `lanGuard` takes `/agent/<id>` off the path when `<id>` is an agent magpie knows (`takeAgentPath`), and the request is served at the rest as that agent's; `startedByAgent` never takes it for a script. OpenBot is one: it seals an endpoint's key and headers where magpie can't write, and hands the endpoint to the OpenCode it runs, whose User-Agent is OpenCode's, so its requests were counted as OpenCode's (SSNQT on X; `TestAgentInPath`). A Codex turn that names itself Claude Code is Codex's: OpenAI's Codex plugin for Claude Code (/codex:rescue, /codex:review) runs `codex app-server` with clientInfo "Claude Code", which Codex sends as its originator and User-Agent, and only Codex's turn headers (`x-codex-window-id`, `x-codex-turn-metadata`) tell it apart from Claude Code's own requests (`codexForClaudeCode`); an app that runs Codex as its own engine under its own name (Lody) stays that app. An app that runs the real Claude Code with a key naming the app (OpenMausBot's engine) is counted as that app, and is still Claude Code for its tiers and helper calls (`claudeCodeInside`: Claude Code's User-Agent under another agent's path or key, Claude Desktop apart; `TestClaudeCodeInsideAnApp`). VS Code's Agents window runs `codex app-server` as `vscode_agent_host`, its originator and User-Agent: its calls are counted under VS Code (`vscodeAgentHostUA` in [`vscode.go`](../../internal/agent/vscode.go)), and its turns are Codex's for every Codex rule (`fromCodex`, `hostedCodex`), so one of Codex's own models asked there goes on Codex's sign-in (`codexOwnOffMagpie`) rather than 404; only Codex's own names (`codexNamed`) are kept as Codex's shape for a test asked as Codex (`TestVSCodeAgentHostIsCodex`, `TestVSCodeAgentHostOwnModelGoesOnSignIn`, `TestVSCodeAgentHostNotCodexTestShape`). Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's `X-Anthropic-Surface: operon` (`isClaudeScience`). It is listed every model as `claude-magpie-<number>` (`scienceModels`; its picker keeps only a `claude-` id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (`scienceTurn`, kept in `claude-science.model`). | [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| WSL under NAT | On Windows, while the gateway listens on loopback alone, `serveWSL` also serves it, in plain HTTP, at each address Windows has on a WSL network (`WSLNets`: the `vEthernet (WSL…)` adapters, looked for every 10s, since WSL's VM brings its adapter up and down). That is where a distro in NAT networking reaches Windows, and what `place` writes into its agents (zaidu259434 on X: Codex in WSL failed with sharing off). A distro in bridged networking is a peer on the LAN, and its default route is the LAN's router, not Windows: `wslrun.HostAt` takes Windows' address on the bridge's adapter (`vEthernet (WSL_Bridge_Switch)`), the one whose network holds that route (ecalpal_ on Discord). `lanGuard` takes a request there as this computer's (`fromWSL`) only when it arrives at that address, from inside that network, with the WSL key: `WSLKey`, a `wsl-` secret in magpie's folder (`wsl-key`, 0600), optionally followed by `-<agent>`. It becomes a loopback request carrying `magpie` or `magpie-<agent>` (`asFromLoopback`). A client that can only send its own key (Claude Science in WSL, which sends its Claude sign-in) puts the WSL key first in the path instead, `/<WSL key>/v1/…`: `takeWSLPathKey` takes it off before `fromWSL` judges the request, and the request goes on without it. Anything else there, a Docker Desktop container on the same network included, is judged as another machine's. Windows' firewall still decides whether WSL gets in: WSL's network is a Public one. | [`wsl.go`](../../internal/gateway/wsl.go) |
|
||||
| TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.go) |
|
||||
| HTTPS | With Settings → Network and sharing → HTTPS on (settings `HTTPS`, `magpie https on`; zhangly1 on X) `TLSOn` is true, so the listener serves other computers TLS as with mTLS, without a client certificate asked. Without `--tls-cert`, `settingsCert` serves the pair imported to `<settings>/https` (`ImportCert`: PEM in any split, the leaf the key matches first; refuses an encrypted key, a mismatch, an expired leaf; read again through `certFiles`), else `ownServerCert` from magpie's CA (made when HTTPS is turned on). A WSL distro's connection is sniffed, so its plain HTTP still works. `GET /magpie-ca.crt` (`caFile`) serves the CA to any address `lanGuard` lets in without a key (`caFileOpen`), 404 before one exists. The Settings routes (`internal/gui/https.go`) refuse a page from another computer that would flip the switch under itself (`errFarPage`). `TestHTTPSOtherComputer`, `TestHTTPSThisComputerPlain`, `TestHTTPSImportedCert`, `TestHTTPSCAFile`, `TestSettingsHTTPSFarPage`, `https-settings.test.cjs`. | [`https.go`](../../internal/gateway/https.go), [`tls.go`](../../internal/gateway/tls.go) |
|
||||
|
||||
@@ -19,8 +19,8 @@ package agent
|
||||
// OpenMausBot's own "Claude endpoint" (server/claude-endpoints.ts's
|
||||
// newClaudeEndpoint) writes one: a claudeAgent instance with access
|
||||
// "custom", a Claude home of its own under the data folder, requireApiKey,
|
||||
// the gateway's address and key as ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN
|
||||
// and ANTHROPIC_API_KEY, and every magpie model in endpointModels, its
|
||||
// the gateway's address and a key naming OpenMausBot (gateway.TokenFor) as
|
||||
// ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY, and every magpie model in endpointModels, its
|
||||
// picker. An instance with any of those keys owns its routing: neither the
|
||||
// user's settings nor a provider switch in OpenMausBot's environment
|
||||
// reaches it (claudeEnvironment, claudeInstanceOwnsRouting).
|
||||
@@ -262,7 +262,11 @@ func ombInstanceJSON(path, dir, gw string) map[string]any {
|
||||
}
|
||||
}
|
||||
}
|
||||
key := keyAt(gw)
|
||||
// a key naming OpenMausBot: the Claude Code it runs sends nothing of
|
||||
// OpenMausBot's own, so with the gateway's plain token its calls were
|
||||
// counted as Claude Code's (huangfuyafei on X); the gateway still
|
||||
// treats them as Claude Code's for its tiers (claudeCodeInside)
|
||||
key := agentKeyAt("openmausbot", gw)
|
||||
return map[string]any{
|
||||
"driver": "claudeAgent", "displayName": "magpie", "access": "custom",
|
||||
"config": config,
|
||||
|
||||
@@ -127,7 +127,9 @@ func TestOpenMausBotEngine(t *testing.T) {
|
||||
}
|
||||
insts := ombRead(t, path)
|
||||
e := ombFormat(t, insts[magpieID])
|
||||
if e.Environment["ANTHROPIC_BASE_URL"] != gateway.URL() || e.Environment["ANTHROPIC_AUTH_TOKEN"] != gateway.Token || e.Environment["ANTHROPIC_API_KEY"] != gateway.Token {
|
||||
if e.Environment["ANTHROPIC_BASE_URL"] != gateway.URL() || e.Environment["ANTHROPIC_AUTH_TOKEN"] != gateway.TokenFor("openmausbot") || e.Environment["ANTHROPIC_API_KEY"] != gateway.TokenFor("openmausbot") {
|
||||
// a key naming OpenMausBot: the Claude Code it runs sends nothing
|
||||
// else of it, and was counted as Claude Code (huangfuyafei on X)
|
||||
t.Errorf("environment: %v", e.Environment)
|
||||
}
|
||||
if e.Config.ConfigDir != filepath.Join(dir, "providers", magpieID) {
|
||||
@@ -233,6 +235,8 @@ func TestOpenMausBotKeepsTheUsers(t *testing.T) {
|
||||
env["HTTPS_PROXY"] = "http://proxy:8080"
|
||||
env["CLAUDE_CODE_USE_BEDROCK"] = "1"
|
||||
env["ANTHROPIC_AUTH_TOKEN"] = "sk-elsewhere"
|
||||
// an engine magpie wrote before it named OpenMausBot in the key
|
||||
env["ANTHROPIC_API_KEY"] = gateway.Token
|
||||
env["ANTHROPIC_MODEL"] = "gone/old"
|
||||
edit.SetJSON(path, edit.KV{Path: ombInstance, Value: mine})
|
||||
for range 2 {
|
||||
@@ -257,7 +261,7 @@ func TestOpenMausBotKeepsTheUsers(t *testing.T) {
|
||||
if got.Environment["HTTPS_PROXY"] != "http://proxy:8080" {
|
||||
t.Errorf("the user's environment not kept: %v", got.Environment)
|
||||
}
|
||||
if _, ok := got.Environment["CLAUDE_CODE_USE_BEDROCK"]; ok || got.Environment["ANTHROPIC_AUTH_TOKEN"] != gateway.Token {
|
||||
if _, ok := got.Environment["CLAUDE_CODE_USE_BEDROCK"]; ok || got.Environment["ANTHROPIC_AUTH_TOKEN"] != gateway.TokenFor("openmausbot") || got.Environment["ANTHROPIC_API_KEY"] != gateway.TokenFor("openmausbot") {
|
||||
t.Errorf("the routing is the user's: %v", got.Environment)
|
||||
}
|
||||
if slices.Contains(got.Config.EndpointModels, "gone/old") || got.Environment["ANTHROPIC_MODEL"] != got.Config.EndpointModels[0] {
|
||||
|
||||
@@ -88,6 +88,28 @@ func agentOf(r *http.Request) string {
|
||||
return usage.AgentOf(ua)
|
||||
}
|
||||
|
||||
// claudeCodeInside is whether r is Claude Code's own request (its
|
||||
// User-Agent) sent under a key or address naming another agent: an app
|
||||
// that runs the real Claude Code as its engine, given a key of its own so
|
||||
// its requests are counted as the app's. OpenMausBot runs Claude Code with
|
||||
// CLAUDE_CODE_ENTRYPOINT taken out and no header of its own
|
||||
// (server/drivers/claude.ts's claudeEnvironment), so with the gateway's
|
||||
// plain token its calls were listed as Claude Code's (huangfuyafei on X,
|
||||
// beside OpenBot's under its own name). What magpie does for Claude Code
|
||||
// alone still applies to it: its tiers (claudeTierStandIn) and its helper
|
||||
// calls (observedKind). Claude Desktop's Code tab, which has handling of
|
||||
// its own, is not one.
|
||||
func claudeCodeInside(r *http.Request, agent string) bool {
|
||||
if agent == "claude" || agent == "claude-desktop" || !fromClaudeCode(r.Header) {
|
||||
return false
|
||||
}
|
||||
if pathAgent(r) != "" {
|
||||
return true
|
||||
}
|
||||
id, ok := strings.CutPrefix(callerKey(r), Token+"-")
|
||||
return ok && id != ""
|
||||
}
|
||||
|
||||
// codexForClaudeCode is a Codex turn that Claude Code started under its
|
||||
// own name. OpenAI's Codex plugin for Claude Code (/codex:review,
|
||||
// /codex:rescue) runs `codex app-server` with clientInfo named "Claude
|
||||
@@ -264,12 +286,16 @@ var claudeFamily = lazyre.New(`^claude-(?:[0-9][0-9.-]*-)?(?:opus|sonnet|haiku|f
|
||||
// which went nowhere, a 404 (tbxark on X). It gets Claude Code's tier too.
|
||||
// An id the user does serve (a Claude account, an Anthropic key) goes
|
||||
// where it is served, and an agent magpie knows keeps its own models.
|
||||
//
|
||||
// Claude Code an app runs under a key naming the app (claudeCodeInside:
|
||||
// OpenMausBot's magpie engine) is Claude Code here, as it was while its
|
||||
// requests were counted as Claude Code's.
|
||||
func claudeTierStandIn(r *http.Request, agent, asked string) string {
|
||||
if StandIn == nil || !claudeFamily.MatchString(strings.ToLower(strings.TrimSuffix(asked, "[1m]"))) {
|
||||
return ""
|
||||
}
|
||||
if agent != "claude" {
|
||||
if !startedByAgent(r, agent) || !unserved(asked) {
|
||||
if !claudeCodeInside(r, agent) && (!startedByAgent(r, agent) || !unserved(asked)) {
|
||||
return ""
|
||||
}
|
||||
agent = "claude"
|
||||
|
||||
@@ -34,7 +34,7 @@ func observeRequest(r *http.Request, kind string, body []byte) (*http.Request, *
|
||||
// the agent it is recorded as, another magpie's own (callerFrom)
|
||||
agent := callerOf(r).agent
|
||||
who := access.Caller(r.Context())
|
||||
q := usage.Request{Header: r.Header, Agent: agent, Session: observedSession(r.Header), Kind: observedKind(agent, kind, body),
|
||||
q := usage.Request{Header: r.Header, Agent: agent, Session: observedSession(r.Header), Kind: observedKind(claudeCodeAs(r, agent), kind, body),
|
||||
Plain: local(r) && who.KeyID == "" && callerOf(r).via == ""}
|
||||
o := &observed{keyName: who.KeyName}
|
||||
for _, ob := range observers {
|
||||
@@ -56,6 +56,15 @@ func observedSession(h http.Header) string {
|
||||
return sessionOf(h)
|
||||
}
|
||||
|
||||
// claudeCodeAs is agent, or "claude" for Claude Code an app runs under its
|
||||
// own key (claudeCodeInside).
|
||||
func claudeCodeAs(r *http.Request, agent string) string {
|
||||
if claudeCodeInside(r, agent) {
|
||||
return "claude"
|
||||
}
|
||||
return agent
|
||||
}
|
||||
|
||||
// Claude's tool-less small tasks (titles, suggestions, haiku helpers) may
|
||||
// reuse the parent session but aren't recorded in its transcript. Keep their
|
||||
// gateway spans; a model name alone doesn't identify a helper or a subagent.
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// a model the agent names that magpie doesn't serve goes to the one the
|
||||
@@ -291,3 +293,69 @@ func TestClaudeTierForAScriptClaudeCodeStarted(t *testing.T) {
|
||||
t.Errorf("not routed: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// huangfuyafei on X: OpenMausBot's calls were listed as Claude Code's,
|
||||
// while OpenBot's showed under its own name. OpenMausBot runs the real
|
||||
// Claude Code, which sends nothing of OpenMausBot's, so magpie gives its
|
||||
// engine a key naming it. Its requests are then OpenMausBot's, and still
|
||||
// Claude Code's for the tiers (claudeTierStandIn) and its helper calls
|
||||
// (observedKind); Claude Code's own stays Claude Code.
|
||||
func TestClaudeCodeInsideAnApp(t *testing.T) {
|
||||
setHome(t, t.TempDir())
|
||||
f := &fake{t: t, ctype: "application/json", reply: `{"id":"msg","type":"message","role":"assistant","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`}
|
||||
setup(t, provider.Anthropic, f)
|
||||
p, _ := provider.Find("fake")
|
||||
p.Models = []string{"main", "flash"}
|
||||
if err := provider.Save(*p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
StandIn = func(agent, model string) string {
|
||||
if agent != "claude" {
|
||||
return ""
|
||||
}
|
||||
return "fake/flash"
|
||||
}
|
||||
t.Cleanup(func() { StandIn = nil })
|
||||
// package agent lists the agents (usage.Agents), and isn't linked here
|
||||
was := usage.PluginAgents
|
||||
usage.PluginAgents = func() []usage.Known {
|
||||
return []usage.Known{{ID: "claude", Names: []string{"claude"}, UA: []string{"claude-cli"}}, {ID: "openmausbot", Names: []string{"openmausbot"}}}
|
||||
}
|
||||
t.Cleanup(func() { usage.PluginAgents = was })
|
||||
const cc = "claude-cli/2.1.300 (external, cli)"
|
||||
ask := func(ua, key string) (*http.Request, int, string) {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"claude-haiku-4-5-20251001","max_tokens":5,"messages":[{"role":"user","content":"hi"}]}`))
|
||||
req.Header.Set("User-Agent", ua)
|
||||
req.Header.Set("Authorization", "Bearer "+key)
|
||||
req.Header.Set("x-api-key", key)
|
||||
New().Handler().ServeHTTP(rec, req)
|
||||
return req, rec.Code, rec.Body.String()
|
||||
}
|
||||
for _, c := range []struct{ ua, key, agent string }{
|
||||
{cc, TokenFor("openmausbot"), "openmausbot"},
|
||||
{cc, Token, "claude"},
|
||||
{cc, TokenFor("claude"), "claude"},
|
||||
} {
|
||||
req, code, body := ask(c.ua, c.key)
|
||||
if got := agentOf(req); got != c.agent {
|
||||
t.Errorf("%s: agent %q, want %q", c.key, got, c.agent)
|
||||
}
|
||||
if code != 200 || modelOf(f.got) != "flash" {
|
||||
t.Errorf("%s: %d %s, upstream got %q, want the haiku tier", c.key, code, body, modelOf(f.got))
|
||||
}
|
||||
if k := observedKind(claudeCodeAs(req, agentOf(req)), "", []byte(`{"max_tokens":5,"messages":[{"role":"user","content":"hi"}]}`)); k != "auxiliary" {
|
||||
t.Errorf("%s: a helper call's kind %q", c.key, k)
|
||||
}
|
||||
}
|
||||
// an app's own client under its key, not Claude Code: no tier
|
||||
req, _, _ := ask("ai-sdk/anthropic/2.0.0", TokenFor("openmausbot"))
|
||||
if claudeCodeInside(req, agentOf(req)) {
|
||||
t.Error("an app's own client taken for Claude Code")
|
||||
}
|
||||
// Claude Desktop's Code tab keeps its own handling
|
||||
req, _, _ = ask(cc, TokenFor("claude-desktop"))
|
||||
if claudeCodeInside(req, "claude-desktop") {
|
||||
t.Error("Claude Desktop taken for Claude Code inside an app")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user