diff --git a/Dockerfile b/Dockerfile index 1daa2a719..9199eac4e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,31 +12,25 @@ RUN CGO_ENABLED=0 go build -tags nogui -trimpath \ -ldflags "-s -w -X main.version=${VERSION}" -o /out/magpie . \ && mkdir -p /config/home /config/cache /config/data /config/state -# A shell for the container's terminal: NAS panels (Synology, 1Panel, -# Portainer) open /bin/bash or /bin/sh, and distroless has neither, so a -# terminal there failed with "stat /bin/bash: no such file or directory". -# Debian 12's bash (with the libtinfo it links), which runs on the glibc of -# distroless's own Debian 12, and busybox for ls, cat and the like. -FROM debian:12-slim AS shell -RUN mkdir -p /out/bin /out/lib \ - && cp /bin/bash /out/bin/bash \ - && cp -L "$(ldd /bin/bash | awk '/libtinfo/ {print $3}')" /out/lib/ +# Debian, not distroless: a subscription's CLI is installed with its +# vendor's `curl … | bash` (Cursor, Devin, Grok Build), and the CLI it +# installs is a glibc binary that needs a full system's loader and +# libraries. distroless with a copied curl ran the installer, but Cursor's +# cursor-agent then failed with "cannot execute: required file not found". +# Debian 12 has the glibc, libgcc and libstdc++ the plugins' Bun needs too, +# and bash for a NAS panel's terminal. nonroot keeps distroless's uid 65532, +# so a volume made by an older image stays writable. +FROM debian:12-slim -FROM busybox:1.37-uclibc AS busybox - -# cc, not static: plugins run on Bun, which magpie downloads on first use -# and which needs glibc (static has no libc at all, and Bun's musl build -# would need musl). cc is static plus glibc, libgcc and libstdc++. -FROM gcr.io/distroless/cc-debian12:nonroot +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd -g 65532 nonroot \ + && useradd -u 65532 -g nonroot -d /config/home -s /bin/bash nonroot COPY --from=build /out/magpie /magpie -COPY --from=busybox /bin/busybox /bin/busybox -COPY --from=shell /out/bin/bash /bin/bash -COPY --from=shell /out/lib/ /usr/lib/ -# busybox's commands, and magpie on PATH, so `magpie accounts add …` works -# in that terminal -USER root -RUN ["/bin/busybox", "sh", "-c", "/bin/busybox --install -s /bin && mkdir -p /usr/local/bin && ln -s /magpie /usr/local/bin/magpie"] +# magpie on PATH, so `magpie accounts add …` works in that terminal +RUN ln -s /magpie /usr/local/bin/magpie USER nonroot COPY --from=build --chown=65532:65532 /config /config diff --git a/README.md b/README.md index 038b13367..bcd0466d0 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,7 @@ and when a quota runs out, it quietly moves on to the next account. ![macOS](https://img.shields.io/badge/macOS-000000?logo=apple&logoColor=white) ![Windows](https://img.shields.io/badge/Windows-0078D4?logo=windows&logoColor=white) ![Linux](https://img.shields.io/badge/Linux-FCC624?logo=linux&logoColor=black) ![Docker](https://img.shields.io/badge/Docker-2496ED?logo=docker&logoColor=white) ![Termux](https://img.shields.io/badge/Termux-000000?logo=android&logoColor=white) Sponsors
-APINEBULA -零词元 +APINEBULA  零词元 **[Download](https://usemagpie.ai)**  ·  **[Docs](https://usemagpie.ai/docs/start)**  ·  **[Reference](docs/reference.md)**  ·  **[Plugins](https://github.com/magpie-community/plugins)**  ·  **[Discord](https://discord.gg/vGSnD3ZKQF)**  ·  **English** · [简体中文](README.zh-CN.md) diff --git a/README.zh-CN.md b/README.zh-CN.md index 145473b39..8235a4c81 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -14,8 +14,7 @@ ![macOS](https://img.shields.io/badge/macOS-000000?logo=apple&logoColor=white) ![Windows](https://img.shields.io/badge/Windows-0078D4?logo=windows&logoColor=white) ![Linux](https://img.shields.io/badge/Linux-FCC624?logo=linux&logoColor=black) ![Docker](https://img.shields.io/badge/Docker-2496ED?logo=docker&logoColor=white) ![Termux](https://img.shields.io/badge/Termux-000000?logo=android&logoColor=white) 赞助商
-APINEBULA -零词元 +APINEBULA  零词元 **[下载](https://usemagpie.ai/zh/)**  ·  **[文档](https://usemagpie.ai/docs/zh/start)**  ·  **[完整参考(英文)](docs/reference.md)**  ·  **[插件](https://github.com/magpie-community/plugins)**  ·  **[Discord](https://discord.gg/vGSnD3ZKQF)**  ·  [English](README.md) · **简体中文** diff --git a/docs/reference.md b/docs/reference.md index bfd30b4f3..67a32afc2 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -89,7 +89,7 @@ line; agents connected to magpie lose it when it quits. | Agent | File | Fields | | ------------ | --------------------------------- | --------------- | -| Claude Code | `~/.claude/settings.json` | provider, model, opus/sonnet/haiku/fable, sign-in (through magpie) | +| Claude Code | `~/.claude/settings.json` | provider, model, opus/sonnet/haiku/fable, auto mode, sign-in (through magpie) | | Claude Desktop | `Claude/` + `Claude-3p/configLibrary/` in `~/Library/Application Support` (`%LOCALAPPDATA%` on Windows, `~/.config` on Linux). A Desktop installed as an MSIX package on Windows keeps them in its package instead (`%LOCALAPPDATA%\Packages\Claude_\LocalCache\Local`, or `AnthropicPBC.Claude_` for the Store's package, its own data in `LocalCache\Roaming\Claude`). Desktop 2.31226 and later, packaged, reads the real `%LOCALAPPDATA%\Claude-3p` instead, so for a packaged Desktop magpie writes both ([`desktopdir`](../internal/desktopdir/desktopdir.go)) | provider (its third-party gateway mode: Code and Cowork on magpie, no Anthropic sign-in; restart Desktop), opus/sonnet/haiku/fable, subagent model and subagent effort (magpie's settings, applied by the gateway to subagent tool turns; no restart) | | Codex | `~/.codex/config.toml` | provider, model, effort | | Gemini CLI | `~/.gemini/settings.json`, `~/.gemini/.env` | auth, model | @@ -1693,6 +1693,7 @@ It exposes: | `/v1/audio/transcriptions`, `/v1/audio/translations` | OpenAI speech to text (multipart, passed through) | | `/v1/models`, `/v1beta/models` | the catalog | | `/v1/codex/models` | the catalog as Codex's `model_catalog_url` reads it ([Codex on another computer](#providers-and-the-gateway)) | +| `/api/version`, `/api/tags`, `/api/show` | the catalog as an Ollama server lists it, for a client that takes a custom endpoint only as Ollama (below) | Each `/v1/models` entry includes `reasoning` and `supported_reasoning_levels` (`[{"effort":"low"}, ...]`), and the same levels as plain names in @@ -1709,6 +1710,16 @@ what the agent asked, as before. `native_endpoints` straight through on; it is left out of a routing group, and of a model every request to which is translated anyway. +A client that takes a custom endpoint only as an Ollama server (Visual +Studio's and VS Code's Copilot: Manage Models, then Ollama) is given +`http://127.0.0.1:3425` as the Ollama URL, no `/v1`. It reads the models +from `/api/tags`, each one's tools, vision, thinking and window from +`/api/show`, and chats on `/v1/chat/completions`. Ollama's own chat +(`/api/chat`, `/api/generate`, so `ollama run`) isn't served. Copilot sends +no key, so this works on this computer only; behind a reverse proxy with a +single public URL, `/api` goes to `magpie web`'s page, so give the +gateway's own port. + Requests pass straight through when the vendor speaks the agent's API and are translated otherwise, streaming, tool calls and reasoning included. The key is `magpie` (any value works; the gateway only listens on loopback), and @@ -2230,9 +2241,10 @@ uses the service's gateway. ### Docker -`docker build` makes a server image: the terminal-only binary on -distroless (`cc`, for the glibc the plugins' Bun needs) with bash and -busybox for a terminal in the container (`docker exec -it magpie bash`, or a +`docker build` makes a server image: the terminal-only binary on Debian 12 +slim, with bash and curl, so a vendor's `curl … | bash` installer runs and +the CLI it installs (Cursor's, Devin's, Grok Build) finds the glibc it links, +as the plugins' Bun does, and a terminal opens in the container (`docker exec -it magpie bash`, or a NAS panel's terminal; `magpie` is on its PATH), run as nonroot, with everything it keeps in a volume at `/config`: magpie's own files (`/config/magpie`), the sign-ins kept where their agent keeps them (HOME is diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 51ba4f7aa..e1fd5f48e 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -48,11 +48,13 @@ something else shows up as drift. - Qoder's `providers.magpie` keeps `routing`, the timeouts, `type`, `authType`, `anthropic` and a non-empty `displayName` (`qoderKept`). - fx keeps `reviewer_model` and a `tool_choice_mode` of `omit`. Its `auth` is magpie's whole, since fx refuses an `env` beside `type: none` (`fxKept`). - Hermes keeps the `default_model` that `hermes model` writes there, `key_cmd`, the timeouts, `extra_body`, a name and headers beside magpie's (`hermesKept`). This holds in every profile. + - Hermes's `api_key` may be a reference, `${VAR}` or `${env:VAR}`, which Hermes expands from the `.env` beside the config (its own or a profile's) and then the environment. `Check` and a sync read the key it names (`hermesKey`): one that holds (`keyHolds`) stays and isn't drift, and so does one naming a variable magpie can't see (only a shell profile sets it), which is unknown. One naming a key the gateway doesn't take is drift, and a sync keeps the reference and writes magpie's key into that `.env` under the variable, made `0600` when there is none (`hermesKeptKey`; PaulT on Discord, `TestHermesWithAKeyInItsEnvFile`). A value with more than the one reference in it is replaced by magpie's key, as before. - omp's `models.yml` keeps `modelOverrides`, `discovery`, `disableStrictTools`, headers and compat flags (`ompKept`). Its `auth` and `apiKey` are magpie's, or gone. - Kimi Code's `[providers.magpie]` has magpie's three keys set in place, so `custom_headers`, `env` and `default_model` stay (`kimiProvider`). - Cline's `models.json` keeps the provider's other keys, and on each model magpie lists what magpie doesn't write, such as a VS Code override (`clineKept`). - Goose's custom provider file keeps a name, `timeout_seconds`, `toolshim`, headers and the like (`gooseProviderKept`). - ZCode's provider rule keeps its name, logo, visibility, API headers and the key's management link (`zcodeRules`). + - Each model magpie writes into ZCode's `providerModelRules` has native web search (`properties.supportsNativeWebSearch`, "原生联网搜索") on while the provider's format is Anthropic Messages, the only format ZCode sends it on (`zcodeWebSearch`). The models magpie turned it on for are kept in the stash under `zcode.web_search`, so a model the user unticked in ZCode (which takes the key out of the rule) stays off, a value in the rule stays, a manual rule is left alone, and a stash that can't be read turns nothing on. On another format magpie's own on is taken out. Disconnect forgets the list. - The YAML ones go through `yamlKept` and `mergeKept` in [`sync.go`](../../internal/agent/sync.go). Each is tested by a `TestKeepsTheUsersSettings`. - Copilot in JetBrains IDEs keeps its Bring Your Own Key providers in the Copilot language server's `byok.json`, shared with Xcode's and Eclipse's Copilot (`copilotJetBrains` in [`copilotjetbrains.go`](../../internal/agent/copilotjetbrains.go)). magpie writes its own three keys there, `magpie-provider-config`, `magpie-api-key` and `magpie-models-config`, in the bytes the server itself writes, and only when they differ; the user's providers and keys stay. A magpie model the user hid in Manage Models (`isRegistered: false`) stays hidden through a sync. A new file is made 0600 in a 0700 folder, as the server makes it. - dsh (DeepSeek Harness) sets one API per llm-pi-ai route, so magpie writes a route per protocol (`dshKinds` in [`dsh.go`](../../internal/agent/dsh.go); 01huadalang on Discord): `magpie` (Chat Completions) for most models, `magpie-responses` (`openai-responses`) for a model served on Responses, `magpie-anthropic` (`anthropic-messages`, the gateway root, `forceAdaptiveThinking` where `AdaptiveThinking`) for one served on Messages, by the model's `APIs` (`dshRouteOf`). A model's `APIs` is the one its provider serves it on best (`Provider.Native`, in `magpieModels`, [`route.go`](../../internal/agent/route.go)), and Pi, omp and droid read it the same way. A routing group has `responses` when every member is best on Responses (`allResponses`, #1594), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, a Messages-only group too, as a Claude member's thinking is known by its own model. A route with no models is taken out. An api the user picked for a route in dsh's Models page is kept, and so are keys they added there. The start (`agent-default-model`) names its model's route, and Sync moves a start on one of magpie's routes to the route its model is now on (`dshStartOnItsRoute`), its effort and marks kept. Check asks the route the start names to list its model. A dsh session resumed on a model that has since moved routes asks for the model to be picked again, since dsh finds a model by route and id. @@ -72,6 +74,7 @@ something else shows up as drift. - A Claude Code tier or its subagents given a model of their own keep it when the main model moves onto that model and on again (`ownKey` in `claudeIn`), whether the main model is picked in magpie or in Claude Code's `/model`. Same as model, picked for them, has them follow again. - While this machine's Claude Desktop is on magpie, Claude Code's shared settings get `CLAUDE_CODE_DISABLE_EXPLORE_INHERIT_CAP="1"` (`writeExplore` in `claudeIn`, [`claude.go`](../../internal/agent/claude.go)). Claude Code 2.1.295's Explore inherit cap can otherwise replace Desktop's `mythos-magpie` compatibility alias with Opus. This disables that cap, not the model choices of all subagents. It applies with Desktop alone or beside a connected Claude Code, including model picks and Sync; WSL twins do not get it. A user's existing value, including an empty string, stays. The stash (`claude.explore_inherit_cap`) marks only magpie's value: taking Claude Code off magpie leaves it while Desktop is on, and taking Desktop off removes it only if the user has not changed it. Since the settings file is shared, other Claude Code sessions reading it see the flag while Desktop is connected too. - Claude Code's tier and subagent models the user had set for their own endpoint (`claudeOwnEnv`) are stashed with that endpoint and token when magpie is wired in, and come back with them when magpie steps out, by Disconnect or by Claude Code's own model (#1050). So does their main model in the env (`ANTHROPIC_MODEL`, a Bedrock model id beside `CLAUDE_CODE_USE_BEDROCK` for one), which magpie takes out while wired in because it outranks a pick in `/model`. +- Claude Code's auto mode field (`auto_mode`, `claudeAutoModeEnv` in [`claude.go`](../../internal/agent/claude.go)) is `CLAUDE_CODE_AUTO_MODE_MODEL`, the model Claude Code 2.1.302's client-side auto mode classifier judges each action with (Linka on Discord). It changes nothing about server-side auto mode, and a classifier model Anthropic configures for the account comes before it. Unset, Claude Code picks its own (the sonnet tier's model, else Sonnet), so it follows no field and isn't `Follows`. It is set only while Claude Code is routed through magpie, only to one of magpie's models, dashed as the other model keys are, and never to Sonnet 5.5, Opus 5.5 or Opus 5 (`claudeNoClassifier`), which Claude Code 2.1.303 refuses there and replaces with its own pick. A value the user had before magpie routed Claude Code is stashed and taken out with their tiers (`claudeOwnEnv`), and comes back when magpie steps out, unless they set one again since; magpie's own value (`claude.auto_mode_model` in the stash, or any of magpie's models) goes then, and one the user set while wired in is left alone. Claude Code reads it as it goes, so it is Quiet and needs no restart. - Claude Code's provider switches (`agentenv.ClaudeProviders`: `CLAUDE_CODE_USE_BEDROCK`, `_VERTEX`, `_FOUNDRY`, `_ANTHROPIC_AWS`, `_ANTHROPIC_GOOGLE_CLOUD`, `_MANTLE`, Claude Code 2.1.300) send it to that cloud's own endpoint and pass `ANTHROPIC_BASE_URL` over, so with one on it never reaches magpie (jw1dev on X: Bedrock refused magpie's model, and magpie showed nothing). Claude Code reads 1, true, yes and on as on (`claudeSwitchOn`). One that is on in the settings magpie writes is taken out on every route that writes the wiring (`dropClouds` in `writeTiers` and `Sync`), its raw value stashed (`claude.cloud.`, under the distro's id for a WSL twin), and put back as written when magpie steps out (`putClouds` in `unroute`), unless the user set it again since. The cloud's own variables (`AWS_*`, `ANTHROPIC_VERTEX_PROJECT_ID`, …) and a switch that is off stay. Where magpie doesn't write it, Check says so, naming the variable, the cloud and where (`claudeCloud`): the managed settings, which win over the user's; `~/.claude.json`'s env, under the user's settings; and, for this machine's Claude Code, the login shell's environment (`proc.LoginEnv`, read but never set in magpie's), under every settings file. A project's `.claude/settings.json` isn't read: magpie doesn't know which folders Claude Code runs in. T3 Code's Check says the same of the user's `~/.claude` settings, which are put over its magpie instance's environment, and a switch put on that instance goes at its next write; that Check first says when the instance's `ANTHROPIC_BASE_URL` no longer reaches the gateway (`t3EnvOf`), as every agent's Check does, so a port move rewrites it too. The drift's detail is shown in the row's line and its pill through `tNotice` (`claude-cloud-drift.test.cjs`). Claude Desktop's Code tab runs with `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`, under which Claude Code ignores a switch in settings files, so Desktop needs neither. - Claude Code's sign-in (`login`) is magpie's key (`""`, the default) or claude.ai (`claudeai`). claude.ai writes `ANTHROPIC_AUTH_TOKEN` empty, which Claude Code reads as no key: it keeps its claude.ai login and sends that to magpie, which never passes it on (`claudeSignIn` in the gateway). Every later write keeps the token empty (`wiredKey`), and a caller key of the gateway's own put there by hand is taken for magpie's, by Check and a model pick alike, kept as the user left it (`keyHolds`, #2545); a key the gateway would refuse is reported by Check and wired over, and so is the sharing key magpie itself made (`access.Default`), once sharing is off — magpie's own, however well the gateway still takes it. It's offered only where the gateway takes any key (`gwKey() == gateway.Token`: loopback, a WSL distro mirrored), not from a distro under NAT while magpie is shared on the network, where only the sharing key gets in. The choice is stashed, so it survives Disconnect and a port move. An empty token counts as magpie's only beside the address magpie last wrote (`claude.wired_at` in the stash, which Rewire carries to the new port, `keyOurs`): an endpoint of the user's own with an empty token stays theirs when the model goes back to Claude Code's own. - Claude Code's auto mode review (`CLAUDE_CODE_AUTO_MODE_SERVER`, `claudeReviewEnv` in [`claude.go`](../../internal/agent/claude.go)) is written `"0"` while Claude Code is routed through magpie and none of the models it can reach there is one Anthropic reviews (`claudeReviewed`, by `gateway.AutoModeReviewed`): those it is shown (and Claude Desktop's while Desktop is on magpie), a shown group's members, those providers' fallbacks, and the models it is set to, each judged on the provider (or group, or fallback) it resolves to, as the gateway judges its requests, so a Claude model on Copilot or Kiro alone writes `"0"` and a name magpie doesn't know is judged by the name (`TestClaudeReviewedJudgesTheSetModelWhereItGoes`). Off, it classifies locally from the start, as it does anyway behind a gateway that doesn't answer, without the "isn't eligible because your requests go through 127.0.0.1:3425" notice (1EFLOPS on X). Any reviewed model leaves it unset, since `/model` can take the session there; a model hidden from Claude Code doesn't count. It is rewritten on every model set and `Sync`, so adding a Claude provider turns the review back on. magpie's value is kept apart in the stash (`claude.auto_mode_server`), a user's own is left alone, and it goes when Claude Code is taken off magpie (`desktopOnly`, `unroute`). T3 Code's magpie instance, which runs Claude Code on the gateway through its own environment, carries the same `"0"` there by the models it lists (`t3InstanceJSON` in [`t3code.go`](../../internal/agent/t3code.go)); a value in the user's `~/.claude` settings comes after it. @@ -79,11 +82,12 @@ something else shows up as drift. - Claude Code is told what each of magpie's models can do in `CLAUDE_CODE_MODEL_CAPABILITIES` (`claudeCapsEnv`, `claudeCapabilities` in [`claude.go`](../../internal/agent/claude.go)): `=effort[,xhigh_effort][,max_effort]` for those it is shown, and, while Claude Desktop is on magpie, for Desktop's `mythos-magpie-` ids its Code tab hands it. A Claude model Claude Code knows gets no more than Claude Code gives it (Opus and Sonnet 4.6: no xhigh), and one with no known levels isn't named. A model that reaches max without xhigh (GLM-5.3 at low/high/max, DeepSeek V4 at high/max) is said to have xhigh too: the gateway runs xhigh at max for it (`fitEffort`), and Claude Code 2.1.299 turns Ultracode down without `xhigh_effort` ("Ultracode isn't available on …"), which in Desktop is the Ultracode level and dynamic workflows (leesunrise2364 on Discord; `TestClaudeModelCapabilities`). A value of the user's is left alone. - MiniMax Code takes a model ref with one slash in the whole (a SubAgent's `model` must match `^[^/\s]+\/[^/\s]+$`, #1387), and magpie's refs there are `custom_provider:magpie/`. So a model under `custom_provider.magpie` is written with `~` for each slash of its catalog id (`bb-codex~gpt-6.1-sol`, `provider.FlatID`), only when that spelling stands for one served id (`provider.Flattened`); the gateway takes it back. A config an older magpie wrote moves over on the next sync: the user's keys on a model go to its new key, `defaultModel`, `defaultLightModel` and `memory.captureModel`/`consolidationModel` follow (`mcodeRefs`), and the slashed key stays, switched off (`enabled: false`), so a session begun on it still resumes. magpie never edits the user's own `agents//agent.md`. No other agent was found with this limit ([`minimax.go`](../../internal/agent/minimax.go)). - Claude Code's `/model` list (`modelPicker` in its settings.json) is magpie's while it is marked in the stash (`claude.model_picker`, `claude@wsl:.model_picker` for a WSL distro) or while every row's description ends "via magpie", as every row magpie writes does (`magpiesPicker` in [`claude.go`](../../internal/agent/claude.go)). magpie keeps its own list up to date on every model set and `Sync`, and removes it when Claude Code is taken off magpie; a list the user wrote is left alone. The fingerprint covers a list whose mark an older magpie's stash lost, which otherwise stayed without every model added since (#2046). -- Claude Code 2.1.296 reads a Claude model whose version has a dot (`relay/claude-opus-4.6-us`) as Claude Opus 4: a retired warning, budget thinking, 32000 output tokens, no effort. With dashes (`relay/claude-opus-4-6-us`) it knows the model (misteer_ti. on Discord). So every model magpie writes into its settings (`model`, the tier envs, `ANTHROPIC_SMALL_FAST_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL`, `modelPicker`), T3 Code's Claude slugs and Claude Desktop's Code-tab ids (`claudeLooking`) spell a dotted Claude version with dashes (`provider.ClaudeSpelled`), only when that spelling stands for one served id. A Claude model listed to Desktop with reasoning levels is given as `magpie-.anthropic.`, its dotted version dashed as well (`claudeModel`: Copilot's `claude-opus-5.5` is `…anthropic.claude-opus-5-5`, which Claude Code knows; it was `mythos-magpie-`, an unknown model, and Haiku 4.5 got an effort Copilot refuses, #1819); a request for it is served by `` alone (`aliased`), so that spelling needn't be unique. Mythos counts as Claude here too: Claude Code matches `claude-mythos-5-1` by substring, so `claude-mythos-5.1` would read as Mythos 5. Every read of those keys takes it back (`provider.ClaudeRead`: `claudeIn`'s `env`, `claudeMain`, `claudeStandInAt`), so magpie's fields, applied state and Drift keep the dotted id. The user's own values are stashed and given back as written. Values an older magpie wrote dotted are rewritten on the next Sync. Other vendors' ids are never respelled ([`claudedash.go`](../../internal/provider/claudedash.go)). +- Claude Code 2.1.296 reads a Claude model whose version has a dot (`relay/claude-opus-4.6-us`) as Claude Opus 4: a retired warning, budget thinking, 32000 output tokens, no effort. With dashes (`relay/claude-opus-4-6-us`) it knows the model (misteer_ti. on Discord). So every model magpie writes into its settings (`model`, the tier envs, `ANTHROPIC_SMALL_FAST_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL`, `CLAUDE_CODE_AUTO_MODE_MODEL`, `modelPicker`), T3 Code's Claude slugs and Claude Desktop's Code-tab ids (`claudeLooking`) spell a dotted Claude version with dashes (`provider.ClaudeSpelled`), only when that spelling stands for one served id. A Claude model listed to Desktop with reasoning levels is given as `magpie-.anthropic.`, its dotted version dashed as well (`claudeModel`: Copilot's `claude-opus-5.5` is `…anthropic.claude-opus-5-5`, which Claude Code knows; it was `mythos-magpie-`, an unknown model, and Haiku 4.5 got an effort Copilot refuses, #1819); a request for it is served by `` alone (`aliased`), so that spelling needn't be unique. Mythos counts as Claude here too: Claude Code matches `claude-mythos-5-1` by substring, so `claude-mythos-5.1` would read as Mythos 5. Every read of those keys takes it back (`provider.ClaudeRead`: `claudeIn`'s `env`, `claudeMain`, `claudeStandInAt`), so magpie's fields, applied state and Drift keep the dotted id. The user's own values are stashed and given back as written. Values an older magpie wrote dotted are rewritten on the next Sync. Other vendors' ids are never respelled ([`claudedash.go`](../../internal/provider/claudedash.go)). - Codex's "subagents" field is `[agents] default_subagent_model`: only the model a subagent starts on when its lead names none in `spawn_agent` (codex-rs `core/src/agent/child_config.rs`). Unset, it isn't "same as model": the lead may still name another, so the GUI calls it the lead's pick, else the model (`leadPicks` in app.js), and its title points at the "subagent model" field. - Codex's "subagent model" field writes nothing to Codex's config: its lead names each subagent's model in `spawn_agent`, which `[agents]` can't overrule. It is magpie's setting (`settings.CodexSubagentModel`, [`codex_subagent.go`](../../internal/provider/codex_subagent.go)), and the gateway moves the subagent's request onto it (see [gateway routing](gateway-routing.md)). Its options are every model and routing group Codex's own lists show (`CatalogFor("codex")`, so a model taken out of them or not picked is left out here too), ChatGPT accounts' first (#1633: a lead on a chat provider wants its subagents there too). A task a ChatGPT-backed lead sealed opens only on a ChatGPT account, so the gateway keeps such a subagent on its own model when the one set is another provider's. Its setter takes any `provider/model` or `group/`, also one magpie doesn't serve now, so a profile or backup put back on another computer still applies (`ApplyFields` stops at the first failed Set), and refuses one of Codex's own bare names. - Claude Desktop's "subagent model" field (`subagent_model`, `desktopSubagentField` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)) writes nothing to Desktop's config: Desktop runs its Code tab's Claude Code with `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1`, under which Claude Code ignores `CLAUDE_CODE_SUBAGENT_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL_FORCE` and the tier variables in its settings files' `env` ("Ignoring … this session's provider routing is managed by the host", Claude Code 2.1.295), and the env Desktop builds for the Code tab has no key for it (Desktop 2.31226). It is magpie's setting (`settings.DesktopSubagentModel`, [`desktop_subagent.go`](../../internal/provider/desktop_subagent.go)), and the gateway moves each subagent's turn onto it (see [gateway routing](gateway-routing.md)). It is labelled as Codex's, so the Agents page gives it the same square. Its options are magpie's models and groups as Desktop's list shows them (`viaMagpie("claude-desktop")`), while Desktop is on magpie, as for the tiers. A Desktop alias picked is kept by its catalog id (`DesktopCatalogID`). Like Codex's, its setter takes any `provider/model` or `group/`, also one magpie doesn't serve now, so a profile or backup still applies, and refuses a bare name. It is `Live`: the gateway reads it on each request. - Claude Desktop's "subagent effort" (`desktopSubagentEffortField`, `settings.DesktopSubagentEffort`) is also Quiet and Live. Default keeps the effort the request asks for, including disabled thinking; it never selects a new default. A picked level works independently of the subagent model: no model pick, the same model and an unavailable model pick all still take the effort. While wired, the field offers the selected model's levels, or the standard levels when its model is inherited or unavailable; a model marked reasonless offers none. The stored pick survives model changes. A disconnected preference can be saved or cleared without connecting Desktop or showing restart advice, so profile restoration and Disconnect can restore a value saved before connecting; reconnect returns to the last live pick. `subEffortTitle` gives Desktop the Claude Code default explanation; Codex's default meaning is unchanged. The gateway fits each attempt to its actual model and preserves fixed group-member efforts (see [gateway routing](gateway-routing.md)). +- Claude Desktop's 3p mode runs in a userData of its own (`Claude-3p`), whose `config.json` (Desktop's own settings, not `claude_desktop_config.json`) starts with no `locale`, so Desktop on magpie came up in the system's language rather than the one picked signed in with Anthropic (memory and Osal on Discord). Turning Desktop onto magpie copies that one key, `locale`, from the signed-in userData's `config.json` (`Claude`, `%APPDATA%\Claude` on Windows, the first set's before the others) into `Claude-3p/config.json` when that file is missing or a JSON object without one (`desktopCarryLocale` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)); only a name Desktop takes for a catalog is carried. A `locale` already in `Claude-3p`, Desktop's or set by hand, is never written over, and no other key of that file is ever written. Off removes the file only when magpie made it and it still holds nothing but the language carried (`TestClaudeDesktopCarriesTheLanguage`, `TestClaudeDesktopKeepsThe3pLanguage`, `TestClaudeDesktopUserEditsThenReapply`). Desktop shows the language only where its build bundles that catalog (2.7032 has 11, no Chinese). - Claude Desktop names a Claude model with reasoning levels after its own catalog ("Opus 5.5"), not by the `display_name` magpie lists, because magpie lists it as `magpie-.anthropic.` to keep its effort picker (`claudeLooking` in [`desktop.go`](../../internal/gateway/desktop.go)). Two providers' rows of one model then differ in Desktop's menu only by that number, so the provider editor shows it on the model's chip (`gateway.DesktopNumber`, `desktopNumbers` in [`providers.go`](../../internal/gui/providers.go), #2578). The chip shows it only while Claude Desktop is installed and is shown that model. Every other model Desktop is shown carries no number on the chip: Desktop names it by `display_name`, which already says the provider, or by its own id. - Codex's `spawn_agent` tool names only the first five models of its catalog to the lead (codex-rs `MAX_SPAWN_AGENT_MODEL_OVERRIDES` in `child_config.rs`, `spawn_agent_models_description`), Codex's own ahead of magpie's, though it takes any catalog model by name (`find_spawn_agent_model_name`). So a lead could put its subagents on none of magpie's models (Gearclickist on Discord). The gateway adds the rest of the catalog Codex was handed to that tool's description, after Codex's own list, at most 200 (`spawnAgentModels` in [`codex_spawn_models.go`](../../internal/gateway/codex_spawn_models.go)). A model that can search tools (`supports_search_tool`) isn't handed it in the request's tools: Codex defers its multi-agent V1 tools behind `tool_search` (codex-rs `core/src/tools/spec_plan.rs`), and the lead gets `spawn_agent` in the `tool_search_output` Codex puts in the conversation and sends again every turn, so that one is widened too. That text goes upstream with the prompt, to OpenAI too for a ChatGPT lead, so its header (`spawnMore`) stays neutral: it names neither magpie nor Codex's limit. At `CodexPath` that is Codex's own listed models less the hidden ones, then `CodexListed` unless Codex is held to its own. At `/v1` it is `CodexCatalog` under the key's allowance. A lead the ChatGPT backend answers in multi-agent V2 seals its subagents' tasks for a ChatGPT account (#619), so it gets Codex's own only. The model catalog Codex puts in context under `model_catalog_in_context` (under development, off by default) is capped at five too, and isn't widened. - Snow CLI runs on one profile at a time (`profiles/.json` in `~/.snow` or `$SNOW_CONFIG_DIR`, named in `active-profile.json`) and copies the active one over `config.json` at every start, `snow --ask` too ([`snow.go`](../../internal/agent/snow.go)). magpie writes a `magpie` profile, makes it the active one, and copies it to `config.json` itself, so a Snow already running and Snow App's "Sync Snow CLI API config" see the same. It is made from the profile the user was on, their settings kept and its OAuth sign-in left out. A vision model of that profile comes along only with an endpoint and key of its own (`snowOwnVision`), since one on the profile's would now go to the gateway. `maxContextTokens`, `maxTokens` and `supportsVision` follow the model from the catalog (`snowSynced`; `supportsVision` as every agent is told, true while magpie's Vision describes images); what magpie last wrote of them is stashed, and one the user changed since in Snow's own settings is kept through later picks and syncs. The small field is magpie's profile's `basicModel`, Snow's light model for summaries, compaction and file search: empty while it follows the main model, a model through magpie of its own kept through new main models and syncs; on a profile of the user's it offers nothing and is hidden. The thinking field is magpie's profile's `chatThinking` (`{enabled: true, reasoning_effort}`), the only thinking setting Snow reads on the chat protocol; empty deletes it, Snow's default, which sends thinking disabled. A chatThinking the user brought from their profile is shown, not written over. The profile they were on (or that there was no `active-profile.json`) and a `magpie.json` of their own are stashed and put back by Disconnect. A Snow from before profiles (`config.json` alone) gets the `default.json` Snow itself would have made of it, so its next start doesn't take magpie's for the user's. Picking a model of another of the user's profiles switches Snow to that profile. On magpie's profile, a value that is neither a model through magpie nor the model of one of the user's profiles is refused and changes nothing (#1457: `magpie snow --help` used to take magpie out and write `--help` as the model of the profile it went back to). Gemini CLI's auth field refuses an auth it doesn't know before it unroutes, for the same reason. On the CLI, `-h`/`--help` after any command or agent only prints its usage, before `run` reads or moves anything, and any other flag given to `magpie …` is refused (`help_cli.go`; `TestHelpOnEveryCommandDoesNothing` walks `run`'s switch and every agent). diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 4aeec877d..b010b2f99 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -28,15 +28,16 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | --- | --- | --- | | Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. 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-` (`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) | | 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) | -| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | +| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; the client then chats on `/v1/chat/completions`, and Ollama's `/api/chat` and `/api/generate` aren't served), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`ollama.go`](../../internal/gateway/ollama.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | +| A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`, preferring a spelling models.dev lists), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). Its old id `group/auto-` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/` by the old id. An agent field magpie set to `group/auto-` moves to `auto/` on the next `SyncCatalog` (`agent.renameFoundGroups`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/` is its model and found groups list as `group/auto-` (`autoRefsOn`). Hand-made groups stay `group/`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight`. `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | | Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | -| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | +| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | | Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) | -| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) | +| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) | | Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) | | Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) | | Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini alone. A request goes to `/publishers/google/models/:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) | @@ -93,9 +94,10 @@ recorded as a prediction failure (`noPrediction`). - The classifier's requests are magpie's own (#1839). Asked in words, they go out with `RouterAgent`'s User-Agent (`magpie-router/1`), so their records' agent is magpie and `callKind` marks them `routing`; a decision model's (Jev, System One) record is written with `Kind: "routing"` too. They go to the same key or account as any other request and count in its totals, while `usage.Group.Own` (`Record.ByMagpie`: agent `magpie` or one of its `magpie-` User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (`modelRef.Sub`, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (`classifierSub` in `plugins/routing/client.js`). `TestIntentRoutesATurn`, `TestJevPicksTheIntent`, `TestSummaryCountsMagpiesOwnCallsApart`, `TestByMagpie`, `TestServedRefSaysASubscription`, `own-requests.test.cjs`. - A rule can set the reasoning its member is asked for (`Rule.UseEffort`, `useEffort` in the group's JSON, `use-effort=low` typed; #2633, dengtongcai: an intent picks the model and the effort as a pair). It is an output like `Use`, not a condition like `Effort`. `ruleFor` copies it onto the hit (`RuleHit.UseEffort`) from the rule that put a member first, outer or nested; `ruleOver` keeps that rule's members, and `ruleEffort` gives each candidate of them the level fitted to its model's own (`fitLevel`), which `withFixedEffort` writes into the request's field for its protocol (Chat's `reasoning_effort`, Responses' `reasoning.effort`, Anthropic's thinking budget or `output_config.effort`) even when the agent asked none. A member fixed at an effort keeps its own; otherwise the rule's beats the model's suffix, the turn's pick and the agent's pick, and isn't bounded by the group's levels. A model whose levels aren't known (`Efforts` empty) is asked as the agent asked, as with the auto verdict. The members the group fails over to are asked as the agent asked. A Gemini-protocol client's request is left as it came, as for every effort magpie sets. `cleanRules` refuses a value outside `provider.Efforts` and a pause with one. The try records it (`Try.RuleEffort`), and the Routing page says the rule set it. `rule_effort_test.go`, `grouprule_useeffort_test.go`, `routing-rule-effort.test.cjs`. - A rule by folder (`Rule.Folders`, `folders=~/work/acme,~/oss`; Cario0x on X: routing by the project being worked on) matches when the folder the agent works in is one of them or inside one (`provider.FolderUnder`, [`rulefolder.go`](../../internal/provider/rulefolder.go)): at a path's boundary, so `/a/b` is not under `/a/bc`; `~` is the home folder; a Windows drive is one with its WSL mount (`C:\work` is `/mnt/c/work`) and a `\\wsl$\` or `\\wsl.localhost\` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (`Rule.ExceptFolders`, `except-folders=~/big-task`; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (`Rule.ByFolder`, `inFolders`). The folder is read from the request only when a rule of the group has folders or except-folders (`workDir` in [`workdir.go`](../../internal/gateway/workdir.go)), in each agent's own words, taken from captured requests: Claude Code's ` - Primary working directory: ` (its `<`/`>` as entities; ` (was )` after a change dropped), Codex's `` ``, Pi's `` in the system prompt, and OpenCode's `Working directory:` inside its `` block. Only the system prompt and the user's and system messages' text count, never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no `folders=` rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works ([provider-plugins](provider-plugins.md#where-the-agent-works-for-a-plugins-fetch)). A pause rule may hold by folder too (below). The trace's `RuleHit.Folder` is the folder read, and the Routing page tells it beside the rule's `folder …` condition. `TestFolderUnder`, `TestRuleMatchesByFolder`, `TestParseRuleFolders`, `TestWorkDirOfEachAgent`, `TestRuleByFolder`, `TestRuleMatchesExceptFolders`, `routing-folder.test.cjs`. Rules by folder are never in a shared group (`ShareGroup` drops every `ByFolder` rule). + - A rule by agent (`Rule.Agents`, `agents=codex,sillytavern`) matches the agent the gateway names the request's (`agentOf` in [`gateway.go`](../../internal/gateway/gateway.go): its `magpie-` key, else its User-Agent), in lower case (`cleanRules`, `MatchesBesidesIntent`, `Pauses`). A client magpie doesn't know is named by its User-Agent's product name, before the first `/` or space (`usage.AgentOf`), so a rule can hold SillyTavern or one's own app (raikyou on Discord). The editor's agent picker lists the agents magpie knows, then those `/api/usage?period=30d` heard from that it doesn't (not `other`, nor `magpie`), and takes a name typed in its filter as the gateway reads a User-Agent (`uaName` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), through the picker's `field.typed`): "MyApp/2.0 (Linux)" is `myapp`. `routing-rule-agent-typed.test.cjs`. - A pause rule (`Rule.Pause`, `pause=`; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (`provider.PausedOut`, on `ruleClock`): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (`cleanRules` refuses another condition), and is not a send-to rule: `Matches`, `MatchRule`, `ThenUses`, `Ruled` and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (`GroupRef.Paused`), and the Routing page says so. Every model paused answers 503 (`pausedError`) naming each rule. Embeddings go by the same pauses; manual groups have no rules (`Live`), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder, `pause= except-folders=~/big-task`) reads the folder only when such a pause is on the way (`provider.PausesByFolder`, then `workDir`): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; with `folders=`, only requests known to be in them. Embeddings and System One's decision calls have no folder. `Paused.Folder`/`ByFolder` carry what was read, and the Routing page says the folder or that none was said. `rules_pause_test.go`, `TestPauseByFolder`, `TestPauseByFolderRule`, `TestParsePauseByFolder`, `routing-pause-folder.test.cjs`. 3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`); otherwise a capped or barred set returns `cappedError` or `barredError`. Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. -4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: doubled each time, up to `longestRetry` (10 minutes) for a failure and `longestRateRest` (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own `restCap` in minutes (`Provider.RestCapOr`, at most `MaxQuotaRest`; `magpie provider rest-cap 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). The failure count is kept per key or account (`restKey`), and any of its models' answers clears it (`served`). Each model's own count (`restID`) is kept beside it and cleared only by that model's answer (`servedCandidate`): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; `TestModelLadderClimbsPastSiblingAnswers`). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. `rest-cap off` (`provider.RestCapOff`, `restCap: -1`) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (`failOther`: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest `by: "off"` with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (`TestRestCapOff`). The shortest cap otherwise is a minute, the first rest; `rest-cap 30s` is turned away and names `off`. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 `NOT_FOUND` ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (`codeAssistModelMissing`; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; `TestCodeAssistMissingModelRestsTheModel`). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (`remoteModelRest`, keyed by `restID`, in `restAfterMarked` and `rateRest`): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; `TestRemoteMagpieQuotaRestsTheModel`, `TestRemoteMagpieRestrictedRestsTheModel`). Its key refused, the computer unreachable, or the key's own limit there (`keyLimited`'s 429, which carries `X-Magpie-Limit-Reset`, `remoteKeyLimitHeader`), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (`TestRemoteMagpieRestsTheModel`, two gateways over HTTP; `TestRemoteMagpieKeyLimitRestsTheKey`). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (`shapeWords`: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (`wrongEndpoint`, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and `none` too), rests nobody: the next candidate is asked once (`shapeRefused`, `failShape`), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: ","type":"invalid_request_error"}`, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with `max_completion_tokens` 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, `TestGroupFailsOverCommandCodesBare400`). Its overflow, which names the model's context length before the trace id, and an error that names a `param`, aren't one. A relay's own cap on one request's input that says so (`tooLongRe`: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (`overflowed`), which no word list of `retryable` matched: a group's next member that may hold the request is asked (`withRoom`, `failOverflow`), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest only: the backoff count stays, and a refusal after it rests the key again the usual way. The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' `RefusalRetries` (`refusalAsksAgain`, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with `stop_reason` `refusal` and its `stop_details`, streamed or whole (`holdWriter.handBack`), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get `failTo`'s 400 (`refusedStatus`), which they don't ask again for. `TestRefusalRetries*` in [`refusal_retries_test.go`](../../internal/gateway/refusal_retries_test.go) cover keys, a group and the Claude subscription. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged. siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. +4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: doubled each time, up to `longestRetry` (10 minutes) for a failure and `longestRateRest` (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own `restCap` in minutes (`Provider.RestCapOr`, at most `MaxQuotaRest`; `magpie provider rest-cap 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). The failure count is kept per key or account (`restKey`), and any of its models' answers clears it (`served`). Each model's own count (`restID`) is kept beside it and cleared only by that model's answer (`servedCandidate`): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; `TestModelLadderClimbsPastSiblingAnswers`). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. `rest-cap off` (`provider.RestCapOff`, `restCap: -1`) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (`failOther`: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest `by: "off"` with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (`TestRestCapOff`). The shortest cap otherwise is a minute, the first rest; `rest-cap 30s` is turned away and names `off`. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 `NOT_FOUND` ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (`codeAssistModelMissing`; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; `TestCodeAssistMissingModelRestsTheModel`). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (`remoteModelRest`, keyed by `restID`, in `restAfterMarked` and `rateRest`): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; `TestRemoteMagpieQuotaRestsTheModel`, `TestRemoteMagpieRestrictedRestsTheModel`). Its key refused, the computer unreachable, or the key's own limit there (`keyLimited`'s 429, which carries `X-Magpie-Limit-Reset`, `remoteKeyLimitHeader`), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (`TestRemoteMagpieRestsTheModel`, two gateways over HTTP; `TestRemoteMagpieKeyLimitRestsTheKey`). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (`shapeWords`: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (`wrongEndpoint`, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and `none` too), rests nobody: the next candidate is asked once (`shapeRefused`, `failShape`), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: ","type":"invalid_request_error"}`, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with `max_completion_tokens` 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, `TestGroupFailsOverCommandCodesBare400`). Its overflow, which names the model's context length before the trace id, and an error that names a `param`, aren't one. A relay's own cap on one request's input that says so (`tooLongRe`: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (`overflowed`), which no word list of `retryable` matched: a group's next member that may hold the request is asked (`withRoom`, `failOverflow`), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. A 401 or 403 is the exception: one that names a quota is out of quota already (`usedUpWords`), and one that doesn't is about the key or the request, so it rests on the backoff ladder whatever the reading says (plugins#243, zygs1083-dotcom: a Factory account read at 98% sat out its week over one plain 403; `TestPlain403DoesNotRestUntilTheWindow`). A plain 403 (`plainForbidden`: no quota, credit, rate, verification, restriction or model not served) from a second key or account of the same provider, model and reasoning in one request is the request refused, not each account: neither rests, the first one's rest and counted failure are taken back (`forbiddenAlike`, `unforbid`), and the provider's other mates are asked last (`matesLast`). Before, that one request walked every account of the provider into backoff (`TestPlain403OnTwoMatesRestsNeither`). One account's plain 403 alone still rests it. Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest only: the backoff count stays, and a refusal after it rests the key again the usual way. The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' `RefusalRetries` (`refusalAsksAgain`, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with `stop_reason` `refusal` and its `stop_details`, streamed or whole (`holdWriter.handBack`), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get `failTo`'s 400 (`refusedStatus`), which they don't ask again for. `TestRefusalRetries*` in [`refusal_retries_test.go`](../../internal/gateway/refusal_retries_test.go) cover keys, a group and the Claude subscription. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged. siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. Command Code turning a model away for its Zero Data Retention setting (its plugin's switch, 0.1.14, which sends `x-cmd-zdr: 1`; magpie-community/plugins#246) is a refusal of that request's setting, not of the model or the account: the Provider API's 422 with `"code":"cmd_zdr_no_providers"` and the 400 the plugin makes of Go's error line with `"type":"cmd_zdr_no_providers"` (`zdrCoded`, matched as the error's code or type, never by its words, whose "…a different model.","type":"invalid_request_error" read as a model unserved and rested the model on the account). `keepRetry` notes it beside the error (`zdrHeader`), since the error the agent gets may keep no code (Anthropic's shape, or the 400's numeric code). It rests nobody, anywhere (`restAfterMarked` returns `by: "off"`), so the model answers as soon as the switch is off; it isn't asked of the provider's other accounts at that model, which carry the same header (`notMates`), nor again after a moment; another member, the provider's other models among them, is asked once, and with none left the agent gets Command Code's words (`TestCommandCodeZDRRefusalRestsNothing`, `TestZDRRefusalNeverRests`). Another vendor's refusal in the same words, without the code, still rests the model (`TestZDRRefusalIsCommandCodesCodeOnly`). 5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`). When every member has failed in a way that passes (`busy`: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (`didNotStream`; the same-one retries of `passing` leave it alone too, `TestStreamlessMemberIsAskedOnce`), or a 429 that is a short rate limit, not a plan or credit), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest()` (30 times `retryPause`, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's `Patience` lasts. A member of a group in the group uses the innermost that sets `Patience` (`innerPatience`, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner `PatienceOff` skips replan for that member (`TestNestedGroupPatienceThroughOuter`, `TestNestedGroupPatienceInnerOff`, `TestNestedGroupPatienceFallsBackToOuter`). `replanRounds` (12) is only a backstop that never comes first: the pauses alone add up to `PatienceLongest` in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; `TestPatienceIsUsedUp`). The budget is the group's `Patience`, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 is `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error. While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider keeps only the same-one retries `passing` gives the last one left. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked `Gone` (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (`TestAgentGoneInTheRetryPause`, `routing-agent-gone.test.cjs`). A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. A try is added to the route's `Tries` only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked `Earlier` (`routing-went-on.test.cjs`). ## Constraints and failure behavior @@ -173,11 +175,35 @@ recorded as a prediction failure (`noPrediction`). - A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (`buildCodeAssistSent`: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, `continueText`, or `compactLastText` when an agent is compacting with its ask in the system prompt (`modelLastAsk`), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's `functionResponse` with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (`hasResponse`), except for a Claude model on Antigravity, whose tool_result turn holds both. - A tool's `strict` that an upstream turns away (`toolStrictRefusal` in [`strict_refused.go`](../../internal/gateway/strict_refused.go): "Unsupported Chat Completions API field: tools[0].function.strict", OpenAI-style unknown_parameter, "Extra inputs are not permitted" and pydantic's extra_forbidden on it) is asked once more without it, in Chat's `tools[].function` and Responses' `tools[]` alike, and marked for that provider and API (`toolStrictRefused`): its next requests go without it at once. OpenCode 2 sends `"strict": false` on every tool through `@ai-sdk/openai-compatible`, and a custom provider that refused it ended the session (#1980). An upstream that hasn't refused it still gets it, as the ChatGPT backend needs it (#383). `TestToolStrictLeftOutWhereRefused` (real OpenCode 2.0.25 requests), `TestToolStrictRefusalWordings`. - A Codex custom tool (exec, apply_patch) that a Responses upstream turns away (`customToolRefusal` in [`custom_tool.go`](../../internal/gateway/custom_tool.go): DeepSeek's 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.", #2656) ends the relay: `passthrough` marks the model (`customToolRefused`) and returns not done, and `attempt` translates the request on the same API (`ownAPI`), where each custom tool is offered as a function taking its `input` and a call comes back as the `custom_tool_call` Codex runs, its name kept. A marked model's next requests with a custom tool are translated at once; one without stays relayed, and an upstream that never refused them still gets them as sent. A compaction (`keepsCompaction`) isn't translated, and gets the refusal. Where the refusal reaches a group untranslated it is a shape refusal (`shapeRefused`): the next member is asked. `TestCustomToolTranslatedWhereRefused`, `TestCustomToolRefusalInGroup`, `TestCustomToolRefusalWordings`. +- A tool call's arguments reach the client as the vendor writes them, translated too (echo_ts on Discord: Codex on Copilot about 10x slower, an apply_patch shown only once whole). The Responses decoder hands each `function_call_arguments.delta` and `custom_tool_call_input.delta` on as a `KToolArgs` delta (`argsDelta`), holding back only the one that would make the JSON whole until `.done`, which `endCall` checks against the final arguments; the Responses encoder streams a custom tool's input as `custom_tool_call_input.delta` (`customStream` in [`custom_tool.go`](../../internal/gateway/custom_tool.go)) before its `.done`. A Copilot account's Responses request is relayed with a `web_search` tool in it (`searchesItself`; checked on a real account 2026-10-17), and Copilot is never picked to search for another provider's model (`searchRank`). It is translated instead when a tool marks a parameter `"encrypted": true` (`asksSealing`, MultiAgentV2's `spawn_agent`): Copilot seals such an argument and can't read its own seal on the subagent's turn. `TestCallArgsStreamWhenTranslated`, `TestCustomInputStreams`, `TestResponsesCallArgsStream`, `TestCopilotRelayedUnlessAskedToSeal`, `TestCopilotUltraSubagentWithWebSearch`. +- A relayed Responses stream gives each output item the one id its `response.output_item.added` gave it, in every event after that carries an `item_id` or an `item`, and in the `output` of `response.completed`, `response.incomplete` or `response.failed` (`idTidy` in [`itemids.go`](../../internal/gateway/itemids.go), applied in `passthrough` before `phaseTidy`). GitHub Copilot's `/responses` gives an item another id in every event (checked 2026-10-19 on a real account, gpt-5.5 with web_search), and Codex starts an item by the added's id and ends one by the done's, so a commentary message was shown twice and a web search never ended (echo_ts on Discord, `TestCopilotItemKeepsItsID`). An upstream whose ids agree goes through byte for byte (`TestItemIDsThatAgreeGoAsTheyCame`); a translated reply's ids are magpie's own. - A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`). Outside a group, only a Max output the user set for the model (`Entry.OutputSet`) lowers a request (`userOutput`): Claude Code asks a claude-* model for its own full limit (128000 on Opus 5.5) and is told no figure of magpie's for it (`claudeOutput`), and a key whose quota is held per request as max_tokens times the price turned every turn away (YaCo on Discord, `TestUserMaxOutputLowersAPlainProvidersRequest`). A vendor's or models.dev's figure doesn't lower it, since it may be stale. - A request that names no reply limit, translated to Anthropic's Messages API, which needs `max_tokens` (`forwardTranslated`), is sent the model's published limit (`askedOutput` in [`maxoutput.go`](../../internal/gateway/maxoutput.go)): the user's Max output, else the vendor's list or models.dev, within the window. `anthropicBody`'s `defaultMaxTokens` (16384) is left only for a model whose limit isn't known. Every Codex turn on a Claude went at 16384 before, and a long thinking and tool turn ran out of it: `stop_reason: max_tokens` reaches a Responses client as `incomplete_details.reason: "max_output_tokens"` (#1792, tensornull). A limit the client names goes as it is. The thinking budget fits under the filled limit as under one the client named (`TestAnthropicMaxTokensIsTheModels`). ## Remote magpie APIs +`GET /v1/magpie/trace` answers the routing this gateway has decided, for a +magpie on the same computer that does not serve it, whose console plays it as +its own Routing page (#2606). A trace names accounts and their emails, what +they served, session ids, a folder's last two parts and why accounts rest; it +holds no prompt text and no key. So it answers `local(r)` alone: a request +from another address is refused 403, and so is one from loopback that carries +a proxy's forwarding header (a tunnel or Tailscale Serve here), or a LAN +request while the gateway is shared, whatever key it holds. Rebinding, +`Origin: null` and `*.localhost` pages are stopped before it by `lanGuard` and +`corsGuard`, as on every route. A gateway key held to a budget, models or +accounts is refused with `KeyHeldCode`, as `/v1/magpie/concurrency` and +`/v1/magpie/quotas` refuse it. It answers what `Server.Trace` holds, plus +this process's `pid` and `serves` (the command that started it, `Serves`), so +a caller long-polls it with `after` and `wait` the way the page's own +`/api/gateway/trace` does. `/` adds `pid` and `serves` too, to a loopback +request alone. `Server.gatewayTrace` in +[`trace.go`](../../internal/gateway/trace.go), and +`TestGatewayTraceIsLoopbackOnly` in +[`trace_peer_test.go`](../../internal/gateway/trace_peer_test.go) and +`TestHeldKeyToldNoAccounts` in +[`quotas_held_key_test.go`](../../internal/gateway/quotas_held_key_test.go). + A remote provider serves the conversation, token-counting, System One, embeddings, rerank, speech-to-text, image generation/edit and video creation/status/content APIs. Gemini clients enter through the local Gemini adapter and follow the @@ -214,7 +240,7 @@ plans the members' keys and accounts with `planGroup` (`perKeyBarred` keeps a decision-only provider's keys: `DecidesModel`), applies a gateway key's model and account limits and pause rules as for a chat, and tries each candidate in turn: a `retryable` failure that is not the request's own -(`shapeRefused`, `promptRefused`, `protectionRefused`) rests it +(`shapeRefused`, `promptRefused`, `protectionRefused`, `zdrRefused`) rests it (`decideFailed` → `restAfter`) and the next is asked; the last one's answer is passed on. Every try is a `Try` of one route; one usage row is written for the answer. A group classifier of decision models fails over the same @@ -715,6 +741,7 @@ the row of the entry that id reaches, with its label, under the bare id. ```sh go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEach|TestLoneRestingMemberStillAsked|TestRetrievalGroupAsksOneRestingMember|TestProbeOne|TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|TestSub2APIThinkingOffRefused|TestRefusesThinkingOff|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls' go test -tags nogui ./internal/gateway -run 'TestMemberTooSmallIsNotAsked|TestMemberTooSmallIsTheLastResort|TestClaudeAccountsSpentFallBackToCodex|TestConversationOutgrowingItsMemberMoves|TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge|TestOverflow|TestContextOverflow|TestRelayInputCap|TestEveryVendorsOverflow' +go test -tags nogui ./internal/gateway -run 'TestPlain403|TestOrderedKeepsAnAccountAt98|TestPromptRefusalRestsNobody' go test -tags nogui ./internal/gateway -run 'TestVertex' go test -tags nogui ./internal/gateway -run 'TestBedrock' go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer|TestFetchPrivateEntries|TestVendorImageURLAtPrivateAddress|TestVideoContentAtPrivateAddress' diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 812e620dc..e26c7672b 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -40,7 +40,12 @@ by its prompt. `passOnCaller` sends the mark on to a remote magpie beside the session, and no vendor is sent either (`TestDshMarksSessionAndCompaction`). When the same identity is present in a native session, the native session wins -and the gateway projection is omitted. Gateway projections have no path, +and the gateway projection is omitted. On `/api/sessions/manage`, in its +counts as in its list, and on `/api/sessions/delete`, a native session is any +session file the agent keeps, one nothing was said in too, with no limit +(`sessions.NativeIDs`); one pass over the agents' files (`sessions.Manage`) +reads only the agent shown and the agents with gateway sessions (#2776). +Gateway projections have no path, resume command or terminal action: the agent's own files of them are not on this computer. Their rows carry `gateway: true`; the Sessions page groups them under "Seen through the gateway" rather than "No folder", and their size is the diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 7039c52d1..563b7412e 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -397,6 +397,38 @@ leaving suggested plugin cards in place so a click begun before the answer still opens the intended plugin. `plugin-market.test.cjs` holds the search response between pointerdown and pointerup to check this in Chromium and WebKit. +### Routing shown by the magpie that serves the gateway + +A magpie on this computer that does not serve the gateway shows the serving +one's routing in its Routing page, instead of the notice that its routing +cannot be watched here (#2606). The trigger is `served.Load()` being nil while +a magpie answers at the gateway's address. Then `/api/gateway/trace` reads +the serving magpie's `GET /v1/magpie/trace` over loopback +([`OwnerTrace`](../../internal/gateway/trace.go)) and answers with it as its +own (`mine` true, so the page plays it), and `/api/lanes` reads +`GET /v1/magpie/concurrency` ([`OwnerLanes`](../../internal/gateway/trace.go)) +so a provider's rows show the same pills. Both are read on loopback alone +(`ownerURL`): a gateway address on another interface or host is never asked, +whatever `MAGPIE_ADDR` says, and one listening everywhere is read at +127.0.0.1. `OwnerTrace` lets a hung magpie go 5s past the 25s long poll, or +when the page stops asking; `OwnerLanes` waits 700ms, as `ServedBy` does, and +is asked only when a magpie answers. The state read carries the serving +magpie's `serves` and `pid` ([`gatewayJSON`](../../internal/gui/providers.go)), +and the trace carries them as `by`. The Routing page's heading names the +magpie from `by` ("serve (pid 49217) is routing · 127.0.0.1:3525"), so the +name goes with the trace: when the page's trace comes from another magpie +than before (a takeover, either way), it drops the routes it had and reads +the new one's whole trace. Nothing is written; serving and takeover are +unchanged. A +magpie that serves the gateway keeps its own trace, and one older than the +endpoint keeps the notice as before (a refused or unreadable read is unknown, +never empty: `OwnerTrace` says so with its second result). See +`TestConsoleShowsTheServingMagpiesRouting` and +`TestConsoleKeepsTheNoticeFromAnOlderGateway` in +[`trace_peer_test.go`](../../internal/gui/trace_peer_test.go), and +`TestGatewayTraceIsLoopbackOnly` in +[`trace_peer_test.go`](../../internal/gateway/trace_peer_test.go). + ## Verification The session readers include Cursor CLI chat stores, Cursor editor project diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 93632e6bf..ce474ca27 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -20,11 +20,11 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid and Cline. A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away, and what it made is listed in the project's `.gitignore`. | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go) | | Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). | [`instructions.go`](../../internal/library/instructions.go) | | MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) | -| Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), and a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) | +| Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree//`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- ` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), and a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) | | Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`) go first, marked official: `magpie-quota`, in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills/magpie-quota), lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) | | Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) | | Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | -| Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skills.go`](../../internal/library/skills.go) | +| Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. A skill from another git repository (`kind: git`) keeps the repository's head commit it was fetched at in `Commit`, and `Hash`. A check runs `git ls-remote` for the ref (`gitRemoteHead`): the same head is current; another one is fetched shallowly, once per repository and ref in a check, and the skill's folder hashed, so a commit that left the skill as it was is current and its head is kept as `Commit` (`checkGitSkill`). Its `*EditedError` and the page's Changed here, Update and the question before replacing a change name that repository, not GitHub (`editedError`, `skill-git-source.test.cjs`). New skills in such a repository (`findNew`), Group again, icons and the market are GitHub's only. | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skills.go`](../../internal/library/skills.go) | | Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.]]` array tables with a `[[hooks..hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) | | Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`.agent.md`); a TOML role (`name`, `description`, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. The page lists, per agent, whether it binds skills and servers (`SubagentAgentView`) and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) | | Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) | @@ -41,7 +41,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. - magpie takes away only what `Applied` or its mark says it wrote. A folder of the user's with a skill's name is never touched. The user's own fields in an MCP entry are kept. - An edit never silently loses. When an agent's copy of a skill and the library both changed, the newest edit wins, and the losing one is kept with the backups. -- An update from GitHub never silently replaces a skill changed here. It is refused, or skipped in an update of several, until the user says to replace it, and the version replaced goes to the backups. +- An update from GitHub or a git repository never silently replaces a skill changed here. It is refused, or skipped in an update of several, until the user says to replace it, and the version replaced goes to the backups. - A copy's mark establishes that it is unchanged only after its whole folder was scanned. If a subtree or its metadata can't be read, the copy stays in place and the sync reports a `Problem`; it isn't replaced, relinked or removed. A later sync tries again once it can be read. The same scan failure stops replacing a project's or Claude Desktop's copy. - A failure for one agent is a `Problem` in the result. It doesn't stop the others. - An MCP OAuth sign-in canceled or timed out before its callback commits never saves a late token or changes an existing sign-in. The callback's write and the flow's ending share a lock (`flow.keep` in [`mcpauth.go`](../../internal/mcpauth/mcpauth.go)); if the write wins first, it completes and tells the agents before saying done. A cancellation is not a sign-out of credentials already committed. @@ -75,10 +75,10 @@ agents RTK, a CLI that cuts shell output down before the model reads it. ## Verification ```sh -go test -tags nogui ./internal/library -run 'TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckSaysSignInRanOut|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut' +go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckSaysSignInRanOut|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut' go test -race ./internal/mcpauth go test -tags nogui ./internal/library -node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs +node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs ``` The package's `TestMain` runs in a home of its own (`testenv`), never the diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index 8e38dbdc2..68ad1bf45 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -150,7 +150,12 @@ says one of its words, which goes back to i18n.js. it, `refresh(again)` is `load()`'s read of it (coming back to the Overview is opening the allowances, #1588), `reload` is Refresh now, `costs` draws the costs again when Settings' currency changes, and - `tab` says which tab it is on, for `focusQuotaCard`. Still in app.js, + `tab` says which tab it is on, for `focusQuotaCard`, and `leave`, which + `show()` calls on the page it leaves, gives back what a click lent the + Requests (`ledLeave`, TJHHHH on Discord): a filter a ranking or chart + click set, or one brought in by the address or Routing's View usage, + goes when the reader leaves the Requests for another page or tab. One + picked in its own menu or typed stays. Still in app.js, since the tray panel draws them too: the allowance cards, `quotasOpened`, `panelQuotaFocus` and `panelUseFocus`. With the plugin off, its nav tab goes, and so do the ways to the page @@ -193,7 +198,7 @@ the core. The five other routings are the built-in plugin `rotation`'s. | `plugins/rotation` | Requires `providers` and `gateway`, `Essential`. Apply registers every `routes.Builtin` and removes them when turned off. `InUse` counts the providers and groups providers.json routes by one of them (`provider.Routings`, the file alone, not the catalog); an unreadable providers.json is an error, so it stays on. The gateway's `KeepFresh` watches providers.json too, so a routing set from the CLI or the TUI turns it on within 2s. Off, the window's routing pickers (the provider editor, the Routing page's pools and groups) offer Smart alone: their options are marked `data-feature="rotation"` (`routingSegs`). | [`rotation.go`](../../plugins/rotation/rotation.go), [`provider.go`](../../internal/provider/provider.go), [`app.js`](../../internal/gui/assets/app.js) | The user's own routing groups are the `groups` plugin's on this point. The -groups magpie finds (a model two providers serve, `auto-`) stay the +groups magpie finds (a model two providers serve, `auto/`) stay the core's, as Smart does: they are how a model several providers serve is one model with failover, which a user has with the Essentials preset, where `groups` is off. `planGroup` and the walk over a group's members are diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index f18f675f2..b6cfbf4ae 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -178,6 +178,8 @@ What a plugin writes with `console.log`, `console.warn` and the rest goes to the A plugin's account whose sign-in its vendor refused (`lapsed`, or an allowance read saying so) keeps Sign in again and Remove on its row, whether it is in use or the agent's own (`signedOut` in `renderAccounts`, `app.js`). +A plugin sign-in's page is opened once. An `authorize` result may say `opened: true` (not OpenCode's field): the plugin's own CLI opened the page already. Grok's `grok login --device-auth` does this on macOS and Windows, where nothing turns it off, and magpie's opening it too showed two pages (andyfmyth on X; plugin 0.1.17, which on other systems gives grok a `BROWSER` that opens nothing instead). `host.js` passes it on as `Authorization.Opened`, then `SignInState.Opened`, and the desktop's `/api/plugin-signin`, `magpie plugin login` and the window in a browser tab (`startPluginSignIn`, and `followSignIn` after an install) then open nothing; the page's link is still shown (`TestPluginSignInPageOpensOnce`, `plugin-signin-opened.test.cjs`). + The GUI's plugin integration includes `subOf`, `pluginSubs`, and `startPluginSignIn`. A change to sign-in or provider presentation must follow these paths as well as the built-in paths it affects. ## Verification diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index cc0cf0e30..f95a3eda0 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -25,7 +25,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Native compaction | `NativeCompaction` (`nativeCompaction` in providers.json, the editor's *Compaction* row, `magpie provider set compaction=native\|magpie`; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (`CarriesCompaction`: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and `CompactsOn(model)` also needs the model asked on Responses. `SetNativeCompaction`, the CLI and the GUI's save refuse it elsewhere. An account keeps it through `Save`'s picks (`withPicks`), and `AddCopy` carries it. The gateway's half is in [gateway-routing](gateway-routing.md). | [`native_compaction.go`](../../internal/provider/native_compaction.go) | | providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) | | The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) | -| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) | +| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models (`waitsForPicks`), not the vendor's list. `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) | | List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, any case, or `re:` matching the whole id; a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) | | Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. | [`keys.go`](../../internal/provider/keys.go) | | Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https:///v1/projects//locations/`, its host following the location (`vertexHost`). It speaks Gemini alone (`Speaks`, `Base`). It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider ` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) | @@ -104,9 +104,19 @@ apart, so its decision models are the ones its `/v1/models/status` gives [`omlx_decide.go`](../../internal/provider/omlx_decide.go)). MLX-Serve marks them in its `/v1/models` with `capabilities: ["decisions"]`, kept under `.decisions` (`mlxServeDecides`, `listedMLXServeDecide` in -[`mlxserve_decide.go`](../../internal/provider/mlxserve_decide.go)). A server -with none lists none, and no Jev is made up for it. An oMLX or MLX-Serve -provider saved before the preset had a decision base gets its chat base as one. +[`mlxserve_decide.go`](../../internal/provider/mlxserve_decide.go)). Ollama +and Ollama Cloud (Nanka on Discord; Ollama 0.35.0+, 0.40.5+ for cloud models) +serve System One at `/v1/systemone` beside their chat API, and list decision +models (Tev, Nimble, Clef) in `/v1/models` like any other. Their `/api/tags`, +asked with the same key, gives each model `capabilities`, `decision` for +these and `vision` for one that reads images. Those are kept under +`.decisions`, with the cloud's 65,536-token window when the list gives +none (`ollamaDecides`, `listedOllamaDecide` in +[`ollama_decide.go`](../../internal/provider/ollama_decide.go)). An Ollama +older than its System One lists no capabilities, so none. A server +with none lists none, and no Jev is made up for it. An oMLX, MLX-Serve or +Ollama provider saved before the preset had a decision base gets its chat +base as one. The CLI and TUI report model-list fetch errors for remote and other mixed providers (such as OpenRouter, serving conversation and decision models). Only a diff --git a/internal/agent/agent.go b/internal/agent/agent.go index dab9fc01f..66ca4edfd 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -591,6 +591,10 @@ func (a *Agent) Spell(key, v string) (string, error) { if r := provider.RenamedRef(ref); r != ref { refs = append(refs, r) } + // a found group by its id before (group/auto-) is its auto/ + if r := provider.PublicRef(ref); r != ref { + refs = append(refs, r) + } for _, r := range refs { for _, o := range opts { if o.Ref != "" && o.Ref == r { @@ -623,7 +627,7 @@ func (a *Agent) notOffered(ref string, opts []Option) error { if slices.ContainsFunc(opts, func(o Option) bool { return Own(o) && strings.HasPrefix(o.Value, pid+"/") }) { return nil } - ids := []string{ref, provider.RenamedRef(ref)} + ids := []string{ref, provider.RenamedRef(ref), provider.PublicRef(ref)} shown, _ := provider.CatalogFor(a.ListsFor()) if slices.ContainsFunc(shown, func(e provider.Entry) bool { return slices.Contains(ids, e.ID) }) { return nil // shown the agent: a field may offer fewer (Claude Desktop's tiers) @@ -633,7 +637,7 @@ func (a *Agent) notOffered(ref string, opts []Option) error { return fmt.Errorf("%s is one of magpie's models, but %s isn't shown it: magpie models %s says why, and magpie visible %s all shows it every model", ref, a.Name, a.ID, a.ID) } } - if pid+"/" == provider.GroupPrefix { + if pid+"/" == provider.GroupPrefix || provider.IsGroupRef(ref) { return fmt.Errorf("magpie has no routing group %s (magpie models lists them)", ref) } if p, err := provider.Find(pid); err == nil && (p.ID == pid || slices.Contains(p.Was, pid)) { diff --git a/internal/agent/agentenv_test.go b/internal/agent/agentenv_test.go index 0c6e4e3f5..6c16903c5 100644 --- a/internal/agent/agentenv_test.go +++ b/internal/agent/agentenv_test.go @@ -35,6 +35,8 @@ var notAnAgent = map[string]string{ "MAGPIE_SITE_ORIGIN": "a site origin magpie's Omarchy theme answers, to try the site locally", "MAGPIE_PARTNERS": "where magpie's own partner list is read from (a URL, or off), not a folder", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "Claude Code's behaviour flag, not an agent's folder", + "GIT_SSH": "the user's own SSH program for git, which a skill fetched with their git keeps", + "GIT_SSH_COMMAND": "the same, as a command", } // TestFolderVarsAreListed says every variable the packages that find an diff --git a/internal/agent/ante.go b/internal/agent/ante.go index ecc264248..cacfdb520 100644 --- a/internal/agent/ante.go +++ b/internal/agent/ante.go @@ -339,7 +339,7 @@ func anteProviderJSON(gw string) map[string]any { // what it reasons at (anteProviderJSON says why), so its levels are left out // with the rest of its capabilities. func anteModelJSON(m catalog.Model) map[string]any { - group := strings.HasPrefix(m.ID, provider.GroupPrefix) + group := provider.IsGroupRef(m.ID) e := map[string]any{"id": m.ID} if m.Name != "" && m.Name != m.ID { e["display_name"] = m.Name diff --git a/internal/agent/applied.go b/internal/agent/applied.go index 4057b0c8c..23fdc0ce2 100644 --- a/internal/agent/applied.go +++ b/internal/agent/applied.go @@ -101,6 +101,11 @@ func (a *Agent) Apply(key, v string) error { if f == nil { return nil } + // a found group named by its old id is written as it is listed now, + // auto/ (autoref.go) + if pub, ok := a.publicValue(v); ok { + v = pub + } was := a.Values() if err := f.Set(v); err != nil { return err @@ -314,8 +319,8 @@ func groupNamed(v string) string { // magpie set (GroupFor takes it off; so does GroupFinder) v = strings.TrimSuffix(strings.TrimSpace(v), "[1m]") v = strings.TrimPrefix(v, magpieID+"/") - if strings.HasPrefix(v, provider.GroupPrefix) { - return v + if provider.IsGroupRef(v) { + return provider.CanonicalRef(v) // auto/ and group/auto- are one group } g, _ := provider.GroupFor(v) return g diff --git a/internal/agent/autoref.go b/internal/agent/autoref.go new file mode 100644 index 000000000..29a48377e --- /dev/null +++ b/internal/agent/autoref.go @@ -0,0 +1,95 @@ +package agent + +import ( + "strings" + + "github.com/yetone/magpie/internal/provider" +) + +// A group magpie found is listed as auto/ (provider.Group.Ref); it +// was group/auto-, and agents magpie set to it then still say so. +// The gateway serves that id as it did, but the lists magpie writes into +// an agent's files name the group by its new id only, so an agent that +// checks its model against its list (OpenCode) would find it gone. On its +// next write of the agent's lists (SyncCatalog), magpie moves each field +// it set to the old id onto the new one; a field the user set themselves, +// or changed since magpie set it, stays as they left it. + +// setToFoundGroups are the agents magpie set a field of to a found +// group's group/auto-, by id: those renameFoundGroups looks at, so +// a sync reads no other agent's files for it. None while a provider of +// the user's is called auto, and auto/ is its. +func setToFoundGroups() map[string]bool { + if !provider.AutoRefsOn() { + return nil + } + appliedMu.Lock() + defer appliedMu.Unlock() + var out map[string]bool + for id, ap := range appliedLoad() { + for _, v := range ap.Fields { + if strings.Contains(v, provider.GroupPrefix+"auto-") { + if out == nil { + out = map[string]bool{} + } + out[id] = true + break + } + } + } + return out +} + +// renameFoundGroups moves a's fields that magpie set to a found group's +// group/auto- onto the group's auto/, the agent's prefix and +// suffix kept. It answers whether it moved any. +func (a *Agent) renameFoundGroups() bool { + if a.Native != nil || len(a.Fields) == 0 { + return false + } + rec := appliedOf(a.ID).Fields + if len(rec) == 0 { + return false + } + moved := false + vals := a.Values() + for _, f := range a.Fields { + v := vals[f.Key] + // what magpie set, as it set it: a value of the user's own, or + // one changed since, is theirs + if want, ok := rec[f.Key]; !ok || v == "" || v != want || f.Set == nil { + continue + } + now, ok := a.publicValue(v) + if !ok { + continue + } + if a.Apply(f.Key, now) == nil { + moved = true + vals = a.Values() + } + } + return moved +} + +// publicValue is v, an agent's value for a field, with a found group's +// group/auto- in it as the group's auto/: its prefix +// (magpie/), an effort or [1m] after the id, and the agent's own suffix +// kept. ok is false when v names no such group, or one magpie has no +// group for now. +func (a *Agent) publicValue(v string) (string, bool) { + model, suffix, one := a.split(v) + if !one { + return v, false + } + i := strings.Index(model, provider.GroupPrefix+"auto-") + if i < 0 || i > 0 && model[i-1] != '/' { + return v, false + } + ref := model[i:] + pub := provider.PublicRef(ref) + if pub == ref { + return v, false + } + return model[:i] + pub + suffix, true +} diff --git a/internal/agent/autoref_test.go b/internal/agent/autoref_test.go new file mode 100644 index 000000000..e3780c093 --- /dev/null +++ b/internal/agent/autoref_test.go @@ -0,0 +1,82 @@ +package agent + +import ( + "encoding/json" + "testing" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/provider" +) + +// An agent magpie set to a found group by its old id, group/auto-, +// is moved onto the group's auto/ on the next catalog sync, its +// other settings kept (ZeroClover on X); one whose field the user set +// themselves, or changed since magpie set it, keeps their value. +func TestFoundGroupRenamedOnlyWhereMagpieSetIt(t *testing.T) { + syncHome(t) + // relay and spare both serve glm-4.6: magpie finds the group + if err := provider.Save(provider.Provider{ID: "spare", Name: "Spare", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"glm-4.6"}}); err != nil { + t.Fatal(err) + } + if got := provider.PublicRef("group/auto-glm-4-6"); got != "auto/glm-4.6" { + t.Fatalf("the found group is listed as %q", got) + } + a, err := Find("opencode") + if err != nil { + t.Fatal(err) + } + if err := a.Apply("model", "relay/glm-4.6"); err != nil { + t.Fatal(err) + } + set := a.Values()["model"] + if set == "" { + t.Fatalf("nothing set: %v", a.Values()) + } + // what an older magpie wrote and recorded: the group by its old id, + // beside a key of the user's own + old := "magpie/group/auto-glm-4-6" + if err := edit.SetJSON(a.Path, edit.KV{Path: "model", Value: old}, edit.KV{Path: "theme", Value: "mine"}); err != nil { + t.Fatal(err) + } + record(a.ID, "model", old) + + SyncCatalog() + if got := a.Values()["model"]; got != "magpie/auto/glm-4.6" { + t.Fatalf("magpie's own value became %q, want magpie/auto/glm-4.6\n%s", got, readFile(a.Path)) + } + if got := appliedOf(a.ID).Fields["model"]; got != "magpie/auto/glm-4.6" { + t.Errorf("applied.json holds %q", got) + } + var doc map[string]any + if err := json.Unmarshal([]byte(readFile(a.Path)), &doc); err != nil || doc["theme"] != "mine" { + t.Errorf("the user's own key: %v %v", doc["theme"], err) + } + if d := a.Drift(); d != nil { + t.Errorf("drift after the move: %+v", d) + } + + // the user's own value, the group by its old id at an effort of their + // choosing, where magpie had set the group plain: theirs, kept + theirs := "magpie/group/auto-glm-4-6:high" + if err := edit.SetJSON(a.Path, edit.KV{Path: "model", Value: theirs}); err != nil { + t.Fatal(err) + } + record(a.ID, "model", old) + SyncCatalog() + if got := a.Values()["model"]; got != theirs { + t.Fatalf("the user's %q became %q", theirs, got) + } + // and one magpie never set: no record of the field at all + appliedMu.Lock() + m := appliedLoad() + delete(m, a.ID) + appliedSave(m) + appliedMu.Unlock() + if err := edit.SetJSON(a.Path, edit.KV{Path: "model", Value: old}); err != nil { + t.Fatal(err) + } + SyncCatalog() + if got := a.Values()["model"]; got != old { + t.Fatalf("the user's own %q became %q", old, got) + } +} diff --git a/internal/agent/claude.go b/internal/agent/claude.go index 2d74224eb..61f76c043 100644 --- a/internal/agent/claude.go +++ b/internal/agent/claude.go @@ -62,14 +62,31 @@ var claudeAboutEnv = func() []string { // own endpoint, which magpie's take the place of while it is wired in and // gives back when it steps out, with what the user's env says about each // tier's model. ANTHROPIC_MODEL, their main model, too: magpie takes it -// out while wired in (writeTiers), and it was lost for good. +// out while wired in (writeTiers), and it was lost for good. So is their +// auto mode classifier's model (claudeAutoModeEnv), which isn't in +// claudeEnv: one set while magpie is wired in is left to the user. var claudeOwnEnv = append([]string{ "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_FABLE_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", + claudeAutoModeEnv, }, claudeAboutEnv...) +// claudeAutoModeEnv is the model Claude Code's client-side auto mode +// classifier runs on, the one that judges each action before it runs +// (2.1.302; Linka on Discord). Unset, Claude Code picks its own (the +// sonnet tier's model, else Sonnet). It doesn't move server-side auto +// mode, and a classifier model Anthropic configures for the account +// comes before it. +const claudeAutoModeEnv = "CLAUDE_CODE_AUTO_MODE_MODEL" + +// claudeNoClassifier are the Claude models Claude Code 2.1.303 won't run +// its classifier on from claudeAutoModeEnv ("the API's safeguards refuse +// the classifier's escalated check on it"): it warns and takes its own +// pick instead, so the auto mode field doesn't offer them. +var claudeNoClassifier = []string{"claude-sonnet-5-5", "claude-opus-5-5", "claude-opus-5"} + // claudeClouds are the clouds Claude Code's provider switches // (agentenv.ClaudeProviders) send its requests to, named as Claude Code // 2.1.300 names them. Each has an endpoint variable of its own @@ -509,7 +526,7 @@ func tierEnv(tier string) string { return "ANTHROPIC_DEFAULT_" + strings.ToUpper // claudeModelEnv are the keys of Claude Code's env that name a model, each // written as Claude Code is given it (provider.ClaudeSpelled). var claudeModelEnv = []string{ - "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", + "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", claudeAutoModeEnv, "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_FABLE_MODEL", } @@ -648,6 +665,14 @@ func claudeIn(at place) *Agent { // model changes ownKey := func(t string) string { return at.key("claude.tier_own." + t) } own := func(t string) bool { return stashLoad()[ownKey(t)] != "" } + // the auto mode classifier's model as magpie last wrote it (the auto + // mode field); autoOurs: the env's is that one or another of magpie's + // models, which goes when magpie steps out. Any other is the user's. + autoKey := at.key("claude.auto_mode_model") + autoOurs := func() bool { + v := rawEnv(claudeAutoModeEnv) + return v != "" && (v == stashLoad()[autoKey] || isMagpie(env(claudeAutoModeEnv))) + } // set once magpie has taken what the env said about each tier's model // from before it routed Claude Code (claudeAbout): what is there after // that the user wrote about magpie's model, and stays while the tier @@ -1098,10 +1123,12 @@ func claudeIn(at place) *Agent { return cmp.Or(s.Compact(), -1) } var models []claudeBudget - shown, _ := provider.CatalogFor("claude-desktop") - for _, e := range shown { - if id := gateway.DesktopID(e); claudeName(id) == "" { - models = append(models, claudeBudget{id: id, window: e.Context, long: gateway.DesktopListed1M(e), compact: work(e.ID)}) + if desktopOn() { + shown, _ := provider.CatalogFor("claude-desktop") + for _, e := range shown { + if id := gateway.DesktopID(e); claudeName(id) == "" { + models = append(models, claudeBudget{id: id, window: e.Context, long: gateway.DesktopListed1M(e), compact: work(e.ID)}) + } } } if main != "" { @@ -1115,13 +1142,13 @@ func claudeIn(at place) *Agent { for _, t := range claudeTiers { refs = append(refs, tiers[t]) } - for _, v := range refs { + for i, v := range refs { m, _ := tierAt(v) bare := strings.TrimSuffix(m, "[1m]") if v == "" || claudeModel(bare) || provider.ClaudeGroup(bare) { continue } - models = append(models, claudeBudget{id: spell(v), window: window[bare], long: strings.HasSuffix(v, "[1m]"), compact: work(bare)}) + models = append(models, claudeBudget{id: spell(v), window: window[bare], long: strings.HasSuffix(v, "[1m]"), main: i == 0, compact: work(bare)}) } // the one for every model else, as the variable gave it: none // on a Claude main model, which Anthropic runs to its own @@ -1152,16 +1179,22 @@ func claudeIn(at place) *Agent { // writeWindow tells Claude Code the window of the models it runs on // (claudeWindow). While Claude Desktop runs on magpie too, it is the // largest of theirs and each model below it gets its own - // (desktopPlan); with a CLAUDE_CODE_AUTO_COMPACT_WINDOW of the user's, - // which takes precedence over those, the least of them, as one value - // serves them all. One the user set is theirs. + // (desktopPlan), and so while the main model is a [1m] one beside a + // tier that isn't: the main's own window, with each tier below it held + // to the tier's (多喝热水 on Discord: the least tier's 246K beside a + // [1m] DeepSeek read as the main's window under Full window, and was + // the one it fell back to whenever Claude Code stopped taking it for + // 1M). With a + // CLAUDE_CODE_AUTO_COMPACT_WINDOW of the user's, which takes + // precedence over those, the least of them, as one value serves them + // all. One the user set is theirs. writeWindow := func(main string, tiers map[string]string) error { budgeted = false if env(claudeContextEnv) != "" && !windowOurs() { forget(windowKey) return dropBudgets() } - if desktopOn() && (env(claudeCompactEnv) == "" || compactOurs()) { + if (desktopOn() || claudeLongMain(main) && claudeWindow(main, tiers) > 0) && (env(claudeCompactEnv) == "" || compactOurs()) { top, def, entries := desktopPlan(main, tiers) if top <= 0 { return dropWindow() @@ -1336,10 +1369,18 @@ func claudeIn(at place) *Agent { return "", err } forget(aboutKey) + // the auto mode classifier's model goes only where it is magpie's + if autoOurs() { + if err := edit.DelJSON(path, "env."+claudeAutoModeEnv); err != nil { + return "", err + } + } + forget(autoKey) was := unstash(at.key("claude.model")) var back []edit.KV for _, k := range claudeOwnEnv { - if v := unstash(at.key("claude.env." + k)); v != "" { + // one the user set again since is theirs as it is + if v := unstash(at.key("claude.env." + k)); v != "" && rawEnv(k) == "" { back = append(back, edit.KV{Path: "env." + k, Value: v}) } } @@ -1399,7 +1440,19 @@ func claudeIn(at place) *Agent { // as the user wrote it, never respelled kept[at.key("claude.env."+k)] = rawEnv(k) } + // the auto mode classifier's model of their own + // endpoint waits in the stash, out of the env, as + // their tiers' do; one of magpie's stays as it is + theirs := rawEnv(claudeAutoModeEnv) != "" && !autoOurs() + if !theirs { + kept[at.key("claude.env."+claudeAutoModeEnv)] = "" + } stash(kept) + if theirs { + if err := edit.DelJSON(path, "env."+claudeAutoModeEnv); err != nil { + return err + } + } } } // tiers that followed the old model follow the new one; the @@ -1862,6 +1915,49 @@ func claudeIn(at place) *Agent { fields = append(fields, effortField(tier+"_effort", tier+" effort", tier, at, put)) } fields = append(fields, effortField("subagent_effort", "subagent effort", "its subagents", subagentAt, setSubagent)) + // auto mode: the model Claude Code's client-side auto mode classifier + // runs on (claudeAutoModeEnv). Unset, Claude Code's own pick; it + // follows no field, so it isn't Follows "model". The env is read as a + // session goes, so a pick needs no restart. + fields = append(fields, Field{ + Key: "auto_mode", Label: "auto mode", Quiet: true, + Get: func() string { + if !routed() { + return "" + } + return env(claudeAutoModeEnv) + }, + Set: func(v string) error { + v = strings.TrimSpace(v) + if !routed() { + if v == "" { + return nil + } + return fmt.Errorf("pick a model through magpie for Claude Code first; its auto mode can then have a model of its own") + } + if v != "" && !isMagpie(v) { + return fmt.Errorf("auto mode: %q is not a model magpie serves", v) + } + if contains(claudeNoClassifier, claudeName(v)) { + return fmt.Errorf("auto mode: Claude Code doesn't run its classifier on %s, and would take its own pick instead", v) + } + if v == "" { + forget(autoKey) + return edit.DelJSON(path, "env."+claudeAutoModeEnv) + } + w := spell(v) + stash(map[string]string{autoKey: w}) + return edit.SetJSON(path, edit.KV{Path: "env." + claudeAutoModeEnv, Value: w}) + }, + Options: func(map[string]string) []Option { + if !routed() { + return nil + } + return slices.DeleteFunc(claudeViaMagpie(false), func(o Option) bool { + return contains(claudeNoClassifier, claudeName(o.Value)) + }) + }, + }) // its sign-in while it runs through magpie: magpie's key, or its own // claude.ai sign-in kept (loginKey), where the gateway takes any key fields = append(fields, Field{ @@ -2329,6 +2425,14 @@ func claudeOwnCompact(path, model string) bool { return false } +// claudeLongMain says main is a model of magpie's Claude Code takes for 1M +// by its "[1m]", not one of Claude's own, which Anthropic runs to its own. +func claudeLongMain(main string) bool { + m, _ := tierAt(main) + bare := strings.TrimSuffix(m, "[1m]") + return bare != m && !claudeModel(bare) && !provider.ClaudeGroup(bare) +} + // claudeWindow is the context window to tell Claude Code for the models it // runs on, 0 when magpie doesn't know it. One value serves every model not // marked [1m]: the main model's, or when that one is marked, the smallest of diff --git a/internal/agent/claude_automode_test.go b/internal/agent/claude_automode_test.go new file mode 100644 index 000000000..07471e470 --- /dev/null +++ b/internal/agent/claude_automode_test.go @@ -0,0 +1,173 @@ +package agent + +import ( + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/provider" +) + +// claudeAutoModeHome is a sandbox HOME with a provider serving a Claude +// model the classifier runs on, one Claude Code refuses for it, and +// another vendor's, and Claude Code's settings.json holding before. +func claudeAutoModeHome(t *testing.T, before string) (*Agent, string, func(string) string) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example/v1", Key: "k", Models: []string{"claude-haiku-4-5", "claude-opus-5-5", "deepseek-pro"}}); err != nil { + t.Fatal(err) + } + path := filepath.Join(home, ".claude", "settings.json") + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(before), 0o644); err != nil { + t.Fatal(err) + } + env := func(k string) string { v, _ := edit.GetJSON(path, "env."+k); return v } + return claude(home), path, env +} + +// Claude Code's auto mode classifier can have a model of its own +// (CLAUDE_CODE_AUTO_MODE_MODEL, 2.1.302; Linka on Discord): only while +// magpie routes Claude Code, only one of magpie's models, never one Claude +// Code refuses to run its classifier on, and gone again with magpie. +func TestClaudeAutoModeModel(t *testing.T) { + a, _, env := claudeAutoModeHome(t, `{}`) + f := a.Field("auto_mode") + if f == nil { + t.Fatal("no auto_mode field") + } + if err := f.Set("relay/claude-haiku-4-5"); err == nil { + t.Fatal("an auto mode model before Claude Code is routed should fail") + } + if len(f.Options(nil)) != 0 || f.Get() != "" { + t.Fatalf("unrouted: %q %v", f.Get(), f.Options(nil)) + } + if err := a.Field("model").Set("relay/deepseek-pro"); err != nil { + t.Fatal(err) + } + // unset, Claude Code's own pick: magpie writes nothing for it + if f.Get() != "" || env(claudeAutoModeEnv) != "" { + t.Fatalf("auto mode should be unset: %v", a.Values()) + } + opts := f.Options(nil) + if !containsOption(opts, "relay/claude-haiku-4-5") || !containsOption(opts, "relay/deepseek-pro") { + t.Fatalf("options miss magpie's models: %v", opts) + } + if containsOption(opts, "relay/claude-opus-5-5") { + t.Fatalf("Opus 5.5 is offered, which Claude Code won't classify with: %v", opts) + } + if err := f.Set("relay/claude-opus-5-5"); err == nil || env(claudeAutoModeEnv) != "" { + t.Fatalf("Opus 5.5 taken: %v %q", err, env(claudeAutoModeEnv)) + } + if err := f.Set("claude-haiku-4-5"); err == nil || env(claudeAutoModeEnv) != "" { + t.Fatalf("a model magpie doesn't serve taken: %v %q", err, env(claudeAutoModeEnv)) + } + if err := f.Set("relay/claude-haiku-4-5"); err != nil { + t.Fatal(err) + } + // written as Claude Code is given a model, with dashes + if got := env(claudeAutoModeEnv); got != provider.ClaudeSpelled("relay/claude-haiku-4-5") { + t.Fatalf("env %q", got) + } + if f.Get() != "relay/claude-haiku-4-5" { + t.Fatalf("get %q", f.Get()) + } + // a new main model leaves it be: it follows no field + if err := a.Field("model").Set("relay/claude-haiku-4-5"); err != nil { + t.Fatal(err) + } + if f.Get() != "relay/claude-haiku-4-5" { + t.Fatalf("a new model moved auto mode: %v", a.Values()) + } + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if env(claudeAutoModeEnv) != "" { + t.Fatal("clearing left the env behind") + } + if err := f.Set("relay/deepseek-pro"); err != nil { + t.Fatal(err) + } + // back to Claude Code as installed: magpie's pick goes with it + if err := a.Field("model").Set(""); err != nil { + t.Fatal(err) + } + if env(claudeAutoModeEnv) != "" { + t.Fatalf("reset left the auto mode model behind") + } + if err := f.Set(""); err != nil { + t.Fatalf("clearing while unrouted: %v", err) + } +} + +// An auto mode model the user set before magpie routed Claude Code waits +// out of the env while magpie is wired in (it would name a model magpie +// doesn't serve) and comes back after; one they set while magpie is wired +// in is theirs, and magpie never takes it out. +func TestClaudeAutoModeUserValue(t *testing.T) { + t.Run("before", func(t *testing.T) { + a, path, env := claudeAutoModeHome(t, `{"env":{"CLAUDE_CODE_AUTO_MODE_MODEL":"claude-sonnet-4-6"}}`) + if err := a.Field("model").Set("relay/deepseek-pro"); err != nil { + t.Fatal(err) + } + if env(claudeAutoModeEnv) != "" || a.Field("auto_mode").Get() != "" { + t.Fatalf("the user's own auto mode model stayed in while routed: %q", env(claudeAutoModeEnv)) + } + if err := a.Field("auto_mode").Set("relay/claude-haiku-4-5"); err != nil { + t.Fatal(err) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if got := env(claudeAutoModeEnv); got != "claude-sonnet-4-6" { + b, _ := os.ReadFile(path) + t.Fatalf("the user's own auto mode model not back: %q\n%s", got, b) + } + }) + t.Run("while routed", func(t *testing.T) { + a, _, env := claudeAutoModeHome(t, `{}`) + if err := a.Field("model").Set("relay/deepseek-pro"); err != nil { + t.Fatal(err) + } + v := "claude-sonnet-4-6" + if err := edit.SetJSON(filepath.Join(os.Getenv("HOME"), ".claude", "settings.json"), edit.KV{Path: "env." + claudeAutoModeEnv, Value: v}); err != nil { + t.Fatal(err) + } + // another main model, then Claude Code as installed + if err := a.Field("model").Set("relay/claude-haiku-4-5"); err != nil { + t.Fatal(err) + } + if env(claudeAutoModeEnv) != v { + t.Fatalf("a new model took the user's auto mode model: %q", env(claudeAutoModeEnv)) + } + if err := a.Field("model").Set(""); err != nil { + t.Fatal(err) + } + if env(claudeAutoModeEnv) != v { + t.Fatalf("stepping out took the user's auto mode model: %q", env(claudeAutoModeEnv)) + } + }) + t.Run("set again before stepping out", func(t *testing.T) { + a, _, env := claudeAutoModeHome(t, `{"env":{"CLAUDE_CODE_AUTO_MODE_MODEL":"claude-sonnet-4-6"}}`) + if err := a.Field("model").Set("relay/deepseek-pro"); err != nil { + t.Fatal(err) + } + v := "claude-haiku-4-5" + if err := edit.SetJSON(filepath.Join(os.Getenv("HOME"), ".claude", "settings.json"), edit.KV{Path: "env." + claudeAutoModeEnv, Value: v}); err != nil { + t.Fatal(err) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if env(claudeAutoModeEnv) != v { + t.Fatalf("the stash wrote over the user's newer auto mode model: %q", env(claudeAutoModeEnv)) + } + }) +} diff --git a/internal/agent/claude_budget.go b/internal/agent/claude_budget.go index d9bd14b77..07f78823e 100644 --- a/internal/agent/claude_budget.go +++ b/internal/agent/claude_budget.go @@ -1,6 +1,7 @@ package agent import ( + "cmp" "encoding/json" "strconv" "strings" @@ -25,6 +26,10 @@ type claudeBudget struct { id string // as Claude Code is handed it: its key under modelSettings window int // its window, 0 when unknown long bool // Claude Code takes it for 1M by its id ("[1m]") + // Claude Code's main model: a long one's window is the one told too, + // so the main runs to its own should Claude Code stop taking it for + // 1M, and nothing written reads as holding it to a smaller tier's + main bool // the auto-compact window magpie gives it: 0 for the top-level one // (base), below 0 for none, its whole window compact int @@ -58,8 +63,11 @@ func budgetPath(id string) string { // top to its own window, as magpie can't put theirs right. func claudePlan(models []claudeBudget, base int, theirs map[string]string) (top int, entries map[string]int) { for _, m := range models { - if !m.long && m.window > top { + switch { + case !m.long && m.window > top: top = m.window + case m.long && m.main: + top = max(top, cmp.Or(m.window, claudeLong)) } } for _, m := range models { diff --git a/internal/agent/claude_context_test.go b/internal/agent/claude_context_test.go index fede63d5f..4ecc985ac 100644 --- a/internal/agent/claude_context_test.go +++ b/internal/agent/claude_context_test.go @@ -7,6 +7,7 @@ import ( "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" ) // TestClaudeContextWindow: Claude Code takes a model it doesn't know for a @@ -53,14 +54,39 @@ func TestClaudeContextWindow(t *testing.T) { t.Fatalf("a model of no known window keeps the last one's: %q", window()) } // a 1M model is marked [1m], which Claude Code takes for 1M whatever - // the window says; a tier that isn't is told its own + // the window says; beside a tier that isn't, the window told is the + // main's own, and the tier compacts by its own (多喝热水 on Discord: + // the tier's read as the main's), under Full window and without it set("model", "v/big[1m]") if window() != "" { t.Fatalf("[1m]: %q", window()) } + budget := func(id string) string { v, _ := edit.GetJSON(path, budgetPath(id)); return v } + compact := func() (env, top string) { + env, _ = edit.GetJSON(path, "env."+claudeCompactEnv) + top, _ = edit.GetJSON(path, "autoCompactWindow") + return env, top + } set("haiku", "v/small") - if window() != "128000" { - t.Fatalf("haiku on small beside a [1m] model: %q", window()) + if e, top := compact(); window() != "1000000" || budget("v/small") != "128000" || budget("v/big[1m]") != "" || e != "" || top != "272000" { + t.Fatalf("haiku on small beside a [1m] model: window %q, small %q, big %q, compact env %q, top-level %q", + window(), budget("v/small"), budget("v/big[1m]"), e, top) + } + if err := settings.Save(settings.Settings{FullContext: true}); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if e, top := compact(); window() != "1000000" || budget("v/small") != "128000" || e != "" || top != "" { + t.Fatalf("full window: window %q, small %q, compact env %q, top-level %q", window(), budget("v/small"), e, top) + } + if err := settings.Save(settings.Settings{}); err != nil { + t.Fatal(err) + } + set("haiku", "") + if e, top := compact(); window() != "" || budget("v/small") != "" || e != "272000" || top != "" { + t.Fatalf("the tier gone: window %q, small %q, compact env %q, top-level %q", window(), budget("v/small"), e, top) } set("model", "v/mid") if window() != "400000" { diff --git a/internal/agent/claude_picker_group_test.go b/internal/agent/claude_picker_group_test.go index ccafe3c0d..946c4043e 100644 --- a/internal/agent/claude_picker_group_test.go +++ b/internal/agent/claude_picker_group_test.go @@ -61,7 +61,7 @@ func TestClaudePickerListsRoutingGroups(t *testing.T) { t.Fatal(err) } main, _ := edit.GetJSON(path, "model") - if !strings.HasPrefix(main, "group/auto-deepseek-v4-1-flash") { + if !strings.HasPrefix(main, "auto/deepseek-v4.1-flash") { t.Fatalf("model: %q\n%s", main, readFile(path)) } opts := picker() diff --git a/internal/agent/claudedesktop.go b/internal/agent/claudedesktop.go index 97e9cdd9f..760fd63af 100644 --- a/internal/agent/claudedesktop.go +++ b/internal/agent/claudedesktop.go @@ -36,6 +36,7 @@ import ( "net/url" "os" "path/filepath" + "regexp" "slices" "strings" "time" @@ -56,6 +57,11 @@ type desktopPaths struct { dir, dir3p string // Claude, Claude-3p config, config3p string // their claude_desktop_config.json library, meta, prof string // configLibrary, its _meta.json, magpie's profile + // Desktop's own settings (config.json, its "locale" among them) in its + // userData signed in with Anthropic (desktopdir's Data: Claude, or + // %APPDATA%\Claude on Windows) and in Claude-3p, its userData in 3p + // mode. magpie only ever adds the language to the second. + app, app3p string } func desktopPathsOf(dir, dir3p string) desktopPaths { @@ -65,6 +71,7 @@ func desktopPathsOf(dir, dir3p string) desktopPaths { config: filepath.Join(dir, "claude_desktop_config.json"), config3p: filepath.Join(dir3p, "claude_desktop_config.json"), library: lib, meta: filepath.Join(lib, "_meta.json"), prof: filepath.Join(lib, desktopProfileID+".json"), + app: filepath.Join(dir, "config.json"), app3p: filepath.Join(dir3p, "config.json"), } } @@ -82,6 +89,7 @@ func desktopSets(goos, home string, getenv func(string) string) []desktopPaths { var out []desktopPaths for _, d := range desktopdir.Sets(goos, home, getenv) { p := desktopPathsOf(d.Mode, d.ThreeP) + p.app = filepath.Join(d.Data, "config.json") if d.Package != "" { p.key = ".package" } @@ -156,7 +164,11 @@ func claudeDesktop(home string) *Agent { on = desktopOff } desktopAdoptStash(ps) + src := desktopLocaleFrom(ps) for _, p := range ps { + if src != "" { + p.app = src + } if err := on(p); err != nil { return err } @@ -373,9 +385,10 @@ const ( desktopApplied = "claude-desktop.applied" desktopMade = "claude-desktop.made" desktopProfile = "claude-desktop.profile" + desktopLocale = "claude-desktop.locale" ) -var desktopStashKeys = []string{desktopStashed, desktopMode, desktopMode3p, desktopApplied, desktopMade, desktopProfile} +var desktopStashKeys = []string{desktopStashed, desktopMode, desktopMode3p, desktopApplied, desktopMade, desktopProfile, desktopLocale} // desktopAdoptStash moves the stash a packaged Desktop's folders got // before they had keys of their own (when magpie wrote only one set) onto @@ -421,7 +434,7 @@ func desktopOn(p desktopPaths) error { wired := slices.ContainsFunc(entries, desktopOurs) if !wired { var made []string - for _, f := range []string{p.dir, p.config, p.dir3p, p.config3p, p.library, p.meta} { + for _, f := range []string{p.dir, p.config, p.dir3p, p.config3p, p.library, p.meta, p.app3p} { if _, err := os.Stat(f); err != nil { made = append(made, f) } @@ -430,7 +443,7 @@ func desktopOn(p desktopPaths) error { mode3p, _ := edit.GetJSON(p.config3p, "deploymentMode") applied, _ := edit.GetJSON(p.meta, "appliedId") k := p.key - forget(desktopMode+k, desktopMode3p+k, desktopApplied+k, desktopMade+k) + forget(desktopMode+k, desktopMode3p+k, desktopApplied+k, desktopMade+k, desktopLocale+k) stash(map[string]string{desktopStashed + k: "1", desktopMode + k: mode, desktopMode3p + k: mode3p, desktopApplied + k: applied, desktopMade + k: strings.Join(made, "\n")}) } @@ -481,6 +494,8 @@ func desktopOn(p desktopPaths) error { return err } + desktopCarryLocale(p) + // the mode last: until here Desktop still starts as it did for _, f := range []string{p.config3p, p.config} { if err := edit.SetJSON(f, edit.KV{Path: "deploymentMode", Value: "3p"}); err != nil { @@ -490,6 +505,55 @@ func desktopOn(p desktopPaths) error { return nil } +// desktopLocaleName is a language Desktop takes for its "locale": the +// names of its catalogs (lit in Desktop 2.7032's main process, +// /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*\.json$/). +var desktopLocaleName = regexp.MustCompile(`^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$`) + +// desktopLocaleFrom is the config.json, of every set's signed-in +// userData, that names a language: the first set's (where Desktop runs) +// before the others, so a packaged Desktop's language reaches the real +// Claude-3p too, which 2.31226 reads. "" for none. +func desktopLocaleFrom(ps []desktopPaths) string { + for _, p := range ps { + if loc, ok := edit.GetJSON(p.app, "locale"); ok && desktopLocaleName.MatchString(loc) { + return p.app + } + } + return "" +} + +// desktopCarryLocale gives Desktop's 3p mode the language the user picked +// signed in with Anthropic. Claude-3p is a userData of its own, so its +// config.json starts with no "locale" and Desktop falls back to the +// system's languages: the user's Chinese was gone once magpie turned 3p +// on (memory and Osal on Discord). Only "locale" is written, only into a +// config.json that is missing or a JSON object without one: a language +// set in 3p mode, by Desktop or by hand, is the user's and stays. What +// can't be read is left alone. The value written is stashed, so switching +// off can take a config.json magpie made for it away again. +func desktopCarryLocale(p desktopPaths) { + if p.app == "" || p.app3p == "" || p.app == p.app3p { + return + } + loc, ok := edit.GetJSON(p.app, "locale") + if !ok || !desktopLocaleName.MatchString(loc) { + return + } + if desktopObject(p.app3p) != nil { + return + } + if _, has := edit.GetJSON(p.app3p, "locale"); has { + return + } + if err := os.MkdirAll(p.dir3p, 0o755); err != nil { + return + } + if edit.SetJSON(p.app3p, edit.KV{Path: "locale", Value: loc}) == nil { + stash(map[string]string{desktopLocale + p.key: loc}) + } +} + // desktopOff puts Claude Desktop back as it was before magpie: each // deploymentMode as it was (gone where there was none), the profile it had // applied, magpie's profile and entry removed, and the files and folders @@ -565,6 +629,18 @@ func desktopOff(p desktopPaths) error { return err } + // Claude-3p's config.json magpie made only to carry the language: + // gone again when it still holds nothing but that language + if loc := unstash(desktopLocale + k); loc != "" && slices.Contains(made, p.app3p) { + if b, err := os.ReadFile(p.app3p); err == nil { + var m map[string]json.RawMessage + var only string + if json.Unmarshal(b, &m) == nil && len(m) == 1 && json.Unmarshal(m["locale"], &only) == nil && only == loc { + os.Remove(p.app3p) + } + } + } + // what magpie made, deepest first: a file only if it is an empty // object now, a folder only if it is empty for _, f := range slices.Backward(made) { diff --git a/internal/agent/claudedesktop_test.go b/internal/agent/claudedesktop_test.go index c8b947308..3f17e530f 100644 --- a/internal/agent/claudedesktop_test.go +++ b/internal/agent/claudedesktop_test.go @@ -657,3 +657,104 @@ func TestClaudeDesktopMSIXChecksTheFoldersDesktopRuns(t *testing.T) { t.Errorf("sonnet: %q", got) } } + +// Claude-3p is a userData of its own, so Desktop on magpie started in the +// system's language, not the one picked signed in with Anthropic (memory +// and Osal on Discord: Chinese gone). The language is carried into +// Claude-3p's config.json, nothing else of Claude's is, and off takes the +// file magpie made for it away again. +func TestClaudeDesktopCarriesTheLanguage(t *testing.T) { + home, p := desktopSandbox(t) + own := "{\n \"locale\": \"zh-CN\",\n \"userThemeMode\": \"dark\"\n}\n" + desktopWrite(t, p.app, own) + before := desktopTree(t, p) + + f := claudeDesktop(home).Field("provider") + if err := f.Set("magpie"); err != nil { + t.Fatal(err) + } + if m := desktopJSON(t, p.app3p); !reflect.DeepEqual(m, map[string]any{"locale": "zh-CN"}) { + t.Errorf("Claude-3p's config.json: %v", m) + } + if b, _ := os.ReadFile(p.app); string(b) != own { + t.Errorf("Claude's config.json changed:\n%s", b) + } + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if after := desktopTree(t, p); !reflect.DeepEqual(after, before) { + t.Fatalf("off left:\n%v\nwas:\n%v", after, before) + } +} + +// A language already set in 3p mode (Desktop's, or the user's by hand) is +// theirs: no write of magpie's changes Claude-3p's config.json, on, again, +// off and on again, and off leaves it there. +func TestClaudeDesktopKeepsThe3pLanguage(t *testing.T) { + home, p := desktopSandbox(t) + desktopWrite(t, p.app, `{"locale":"zh-CN"}`) + mine := "{\n \"locale\": \"ja-JP\",\n \"windowBounds\": {\n \"width\": 900\n }\n}\n" + desktopWrite(t, p.app3p, mine) + + f := claudeDesktop(home).Field("provider") + for i, v := range []string{"magpie", "magpie", "", "magpie"} { + if err := f.Set(v); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(p.app3p); string(b) != mine { + t.Fatalf("step %d (%q): Claude-3p's config.json is now\n%s", i, v, b) + } + } +} + +// Wired, and Desktop has written its config.json since: the user then +// sets the language there by hand. Applying magpie again keeps every key; +// off keeps the file, which is no longer magpie's alone. +func TestClaudeDesktopUserEditsThenReapply(t *testing.T) { + home, p := desktopSandbox(t) + f := claudeDesktop(home).Field("provider") + if err := f.Set("magpie"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(p.app3p); err == nil { + t.Fatal("config.json written with no language to carry") + } + desktopWrite(t, p.app, `{"locale":"zh-CN"}`) + edited := "{\n \"locale\": \"zh-TW\",\n \"hasCompletedOnboarding\": true\n}\n" + desktopWrite(t, p.app3p, edited) + for _, v := range []string{"magpie", "", "magpie"} { + if err := f.Set(v); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(p.app3p); string(b) != edited { + t.Fatalf("%q: the user's edit is gone:\n%s", v, b) + } + } +} + +// Only a language Desktop can name is carried, and a Claude-3p config.json +// magpie can't read as an object is left as it is, the takeover going on. +func TestClaudeDesktopLanguageOddValues(t *testing.T) { + for _, own := range []string{`{"locale":"../../x"}`, `{"locale":7}`, `{"locale":""}`, `not json`} { + home, p := desktopSandbox(t) + desktopWrite(t, p.app, own) + if err := claudeDesktop(home).Field("provider").Set("magpie"); err != nil { + t.Fatal(err) + } + if b, err := os.ReadFile(p.app3p); err == nil { + t.Errorf("%s: carried %s", own, b) + } + } + home, p := desktopSandbox(t) + desktopWrite(t, p.app, `{"locale":"zh-CN"}`) + desktopWrite(t, p.app3p, `[1]`) + if err := claudeDesktop(home).Field("provider").Set("magpie"); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(p.app3p); string(b) != `[1]` { + t.Errorf("odd config.json written: %s", b) + } + if m := desktopJSON(t, p.config3p); m["deploymentMode"] != "3p" { + t.Errorf("takeover stopped: %v", m) + } +} diff --git a/internal/agent/cliupdate.go b/internal/agent/cliupdate.go index ffbd1ef21..dcebb7e47 100644 --- a/internal/agent/cliupdate.go +++ b/internal/agent/cliupdate.go @@ -82,6 +82,17 @@ type cliSpec struct { // latest is the newest version its own updater would install, for one // not published on npm latest func() string + // target: its own updater takes the version to install (opencode + // upgrade 1.19.3), so magpie gives it the one it already knows, as the + // row promised, when that updater is what runs (via "self"): npm's, + // bun's, pnpm's and brew's commands take no version after them. An opencode 1.19.0 from its own installer (method curl) + // asks GitHub's API for the newest release, which answers an address 60 + // times an hour without a token and 403s once that is spent; opencode's + // current source asks opencode.ai instead, but only an update gets + // there (#2837, ggbdpq: + // "opencode upgrade: ... 403 GET https://api.github.com/repos/ + // anomalyco/opencode/releases/latest") + target bool // only are the systems (GOOS) its vendor builds it for, when not all: // on any other its package installs nothing that runs only []string @@ -121,7 +132,7 @@ var cliSpecs = map[string]cliSpec{ } return nil }}, - "opencode": {npm: []string{"opencode-ai"}, brew: []string{"opencode"}, + "opencode": {npm: []string{"opencode-ai"}, brew: []string{"opencode"}, target: true, self: func(bin, real string) []string { if strings.Contains(real, "/.opencode/bin/") { return []string{bin, "upgrade"} @@ -948,6 +959,14 @@ func (a *Agent) UpdateCLI() (CLI, error) { } defer updating.Delete(a.ID) before := installedVersion(real) + if spec.target && u.via == "self" { + // the version the row promised, so its own updater needn't ask + // GitHub's API for the newest (see cliSpec.target); npm, bun, + // pnpm and brew take no version after their command + if v := latestVersion(u); Newer(v, before) { + u.cmd = append(u.cmd, v) + } + } ctx, cancel := context.WithTimeout(context.Background(), updateTimeout) defer cancel() run := runUpdate diff --git a/internal/agent/cliupdate_test.go b/internal/agent/cliupdate_test.go index cf97ef9db..b29cea6f3 100644 --- a/internal/agent/cliupdate_test.go +++ b/internal/agent/cliupdate_test.go @@ -365,6 +365,100 @@ func TestUpdateCLI(t *testing.T) { } } +// An opencode 1.19.0's upgrade asks GitHub's API for the newest release, +// which answers an address 60 times an hour without a token before a 403 +// (ggbdpq: "opencode upgrade: ... 403 GET https://api.github.com/repos/ +// anomalyco/opencode/releases/latest"). magpie gives it the version the row +// promised, which its installer downloads from the release itself. +func TestUpdateCLIOpenCodeTakesVersion(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script as the CLI") + } + tmp, _ := filepath.EvalSymlinks(t.TempDir()) + verFile := filepath.Join(tmp, "version") + os.WriteFile(verFile, []byte("1.19.2\n"), 0o644) + oc := file(t, filepath.Join(tmp, "home/.opencode/bin/opencode"), "#!/bin/sh\n/bin/cat "+verFile+"\n") + bin := link(t, oc, filepath.Join(tmp, "bin/opencode")) + t.Setenv("PATH", filepath.Dir(bin)) + + reg := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/opencode-ai/latest" { + http.NotFound(w, r) + return + } + w.Write([]byte(`{"name":"opencode-ai","version":"1.19.3"}`)) + })) + defer reg.Close() + oldReg, oldRun := npmRegistry, runUpdate + npmRegistry = reg.URL + "/" + versions, latests = memo{}, memo{} + var ran [][]string + runUpdate = func(_ context.Context, u *updater) ([]byte, error) { + ran = append(ran, u.cmd) + os.WriteFile(verFile, []byte("1.19.3\n"), 0o644) + return nil, nil + } + t.Cleanup(func() { npmRegistry, runUpdate = oldReg, oldRun; versions, latests = memo{}, memo{} }) + + a := &Agent{ID: "opencode", Name: "OpenCode", Bin: "opencode"} + if c, ok := a.CLI(); !ok || c.Via != "self" || c.Version != "1.19.2" || c.Latest != "1.19.3" || !c.Update { + t.Fatalf("before: %+v", c) + } + if c, err := a.UpdateCLI(); err != nil || c.Version != "1.19.3" || c.Update { + t.Fatalf("after: %+v, %v", c, err) + } + if len(ran) != 1 || !reflect.DeepEqual(ran[0], []string{bin, "upgrade", "1.19.3"}) { + t.Errorf("ran %q", ran) + } +} + +// An opencode npm installed is updated by npm as it was: the version +// opencode's own upgrade takes is never put after npm's install, where npm +// would read it as one more package to install. +func TestUpdateCLIOpenCodeByNpmTakesNoVersion(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script as the CLI") + } + tmp, _ := filepath.EvalSymlinks(t.TempDir()) + prefix := filepath.Join(tmp, "node") + verFile := filepath.Join(tmp, "version") + os.WriteFile(verFile, []byte("1.19.2\n"), 0o644) + file(t, filepath.Join(prefix, "lib/node_modules/opencode-ai/bin/opencode"), "#!/bin/sh\n/bin/cat "+verFile+"\n") + file(t, filepath.Join(prefix, "bin/npm"), "#!/bin/sh\nexit 1\n") + link(t, "../lib/node_modules/opencode-ai/bin/opencode", filepath.Join(prefix, "bin/opencode")) + t.Setenv("PATH", filepath.Join(prefix, "bin")) + + reg := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/opencode-ai/latest" { + http.NotFound(w, r) + return + } + w.Write([]byte(`{"name":"opencode-ai","version":"1.19.3"}`)) + })) + defer reg.Close() + oldReg, oldRun := npmRegistry, runUpdate + npmRegistry = reg.URL + "/" + versions, latests = memo{}, memo{} + var ran [][]string + runUpdate = func(_ context.Context, u *updater) ([]byte, error) { + ran = append(ran, u.cmd) + os.WriteFile(verFile, []byte("1.19.3\n"), 0o644) + return nil, nil + } + t.Cleanup(func() { npmRegistry, runUpdate = oldReg, oldRun; versions, latests = memo{}, memo{} }) + + a := &Agent{ID: "opencode", Name: "OpenCode", Bin: "opencode"} + if c, ok := a.CLI(); !ok || c.Via != "npm" || c.Latest != "1.19.3" || !c.Update { + t.Fatalf("before: %+v", c) + } + if _, err := a.UpdateCLI(); err != nil { + t.Fatal(err) + } + if len(ran) != 1 || !strings.HasSuffix(strings.Join(ran[0], " "), "install -g --prefix "+prefix+" opencode-ai@latest") { + t.Errorf("ran %q", ran) + } +} + // An agent's CLI installed with bun is updated by bun add -g, which can't // use a SOCKS5 proxy (#1409): it is given the bridge in front of it. npm, // which can, is given the proxy as it is. diff --git a/internal/agent/codex.go b/internal/agent/codex.go index b4e9a2e81..5add9467f 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -1665,7 +1665,7 @@ func codexOwnViaMagpie(model string) string { // codexOwnOf is the model of Codex's own a catalog id serves on a ChatGPT // account (codexOwnViaMagpie's way back); "" for any other. func codexOwnOf(id string) string { - if !isMagpie(id) || strings.HasPrefix(id, provider.GroupPrefix) { + if !isMagpie(id) || provider.IsGroupRef(id) { return "" } p, model, ok := provider.Resolve(id) diff --git a/internal/agent/codex_group_alias_test.go b/internal/agent/codex_group_alias_test.go index 432490c78..2a1aaa1c4 100644 --- a/internal/agent/codex_group_alias_test.go +++ b/internal/agent/codex_group_alias_test.go @@ -38,11 +38,11 @@ func TestCodexGroupByItsModelName(t *testing.T) { } path := filepath.Join(home, ".codex", "config.toml") cfg := read() - if !strings.Contains(cfg, `model = "group/auto-gpt-6-1-sol"`) { + if !strings.Contains(cfg, `model = "auto/gpt-6.1-sol"`) { t.Fatalf("set:\n%s", cfg) } // Codex names the group's model by its own name, nothing else changed - os.WriteFile(path, []byte(strings.Replace(cfg, `model = "group/auto-gpt-6-1-sol"`, `model = "gpt-6.1-sol"`, 1)), 0o644) + os.WriteFile(path, []byte(strings.Replace(cfg, `model = "auto/gpt-6.1-sol"`, `model = "gpt-6.1-sol"`, 1)), 0o644) if !cx.Wired() { t.Errorf("auth %q: not wired on gpt-6.1-sol:\n%s", auth, read()) } @@ -58,7 +58,7 @@ func TestCodexGroupByItsModelName(t *testing.T) { // has; beside the ChatGPT sign-in either is a pick in Codex's /model // that still goes through magpie, not a change from outside (#2424) for _, m := range []string{"gpt-6.1", "gpt-5.5"} { - os.WriteFile(path, []byte(strings.Replace(cfg, `model = "group/auto-gpt-6-1-sol"`, `model = "`+m+`"`, 1)), 0o644) + os.WriteFile(path, []byte(strings.Replace(cfg, `model = "auto/gpt-6.1-sol"`, `model = "`+m+`"`, 1)), 0o644) d := cx.Drift() if auth != "" && d != nil { t.Errorf("auth %q: %s beside the sign-in: %+v", auth, m, d) @@ -84,7 +84,7 @@ func TestCodexGroupByItsModelNameDisconnect(t *testing.T) { t.Fatal(err) } path := filepath.Join(home, ".codex", "config.toml") - os.WriteFile(path, []byte(strings.Replace(read(), `model = "group/auto-gpt-6-1-sol"`, `model = "gpt-6.1-sol"`, 1)), 0o644) + os.WriteFile(path, []byte(strings.Replace(read(), `model = "auto/gpt-6.1-sol"`, `model = "gpt-6.1-sol"`, 1)), 0o644) if err := cx.Disconnect(); err != nil { t.Fatal(err) } diff --git a/internal/agent/disconnect_test.go b/internal/agent/disconnect_test.go index d9efb494c..907d95942 100644 --- a/internal/agent/disconnect_test.go +++ b/internal/agent/disconnect_test.go @@ -90,12 +90,16 @@ func TestCodexDisconnect(t *testing.T) { // The tier and subagent models the user set for their relay come back with // it (#1050), whether magpie steps out by Disconnect or by Claude Code's // own model. So does the main model set for the relay in the env -// (ANTHROPIC_MODEL), which magpie takes out while wired in. +// (ANTHROPIC_MODEL), which magpie takes out while wired in, and the auto +// mode classifier's model (CLAUDE_CODE_AUTO_MODE_MODEL). func TestClaudeDisconnect(t *testing.T) { for name, before := range map[string]string{ "own relay": `{"theme":"dark","model":"opus","env":{"ANTHROPIC_BASE_URL":"https://relay.example","ANTHROPIC_AUTH_TOKEN":"sk-relay","DISABLE_TELEMETRY":"1"}}`, "own tiers": `{"model":"sonnet","env":{"ANTHROPIC_BASE_URL":"https://relay.example","ANTHROPIC_AUTH_TOKEN":"sk-relay","ANTHROPIC_DEFAULT_OPUS_MODEL":"relay-opus","ANTHROPIC_DEFAULT_SONNET_MODEL":"relay-sonnet","ANTHROPIC_DEFAULT_HAIKU_MODEL":"relay-haiku","ANTHROPIC_SMALL_FAST_MODEL":"relay-haiku","CLAUDE_CODE_SUBAGENT_MODEL":"relay-sonnet"}}`, "nothing set": `{"theme":"dark"}`, + // the auto mode classifier's model the user set themselves, which + // magpie takes out while wired in and puts back + "own auto mode": `{"env":{"ANTHROPIC_BASE_URL":"https://relay.example","ANTHROPIC_AUTH_TOKEN":"sk-relay","CLAUDE_CODE_AUTO_MODE_MODEL":"relay-haiku"}}`, // the main model set for the relay in the env (with no settings // model, and beside one), which magpie takes out while wired in: // it outranks a pick in /model @@ -150,6 +154,9 @@ func TestClaudeDisconnect(t *testing.T) { if err := a.Apply("subagent", "deepseek/flash"); err != nil { t.Fatal(err) } + if err := a.Apply("auto_mode", "deepseek/flash"); err != nil { + t.Fatal(err) + } if !a.Wired() { t.Fatal("not wired on a magpie model") } diff --git a/internal/agent/hermes.go b/internal/agent/hermes.go index 05517a03c..b1bd7a73c 100644 --- a/internal/agent/hermes.go +++ b/internal/agent/hermes.go @@ -29,6 +29,7 @@ import ( "regexp" "strings" + "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/dirent" "github.com/yetone/magpie/internal/edit" ) @@ -41,7 +42,7 @@ func hermes(home string) *Agent { return hermesIn(here(home)) } func hermesIn(at place) *Agent { dir := at.hermesHome() path := filepath.Join(dir, "config.yaml") - hermesProvider := func(p string) any { return hermesKept(p, hermesProviderAt(at.gw())) } + hermesProvider := func(p string) any { return hermesKept(at, p, hermesProviderAt(at.gw())) } // spread puts magpie's provider, as it is now, into every other // profile's config beside the one magpie connects spread := func() error { @@ -116,8 +117,23 @@ func hermesIn(at place) *Agent { if !onMagpie() { return "" } - return wiringOff("Hermes", path, func(k string) (string, bool) { return edit.GetYAML(path, "providers."+magpieID+"."+k) }, - "base_url", at.v1(), "api_key", at.gwKey()) + get := func(k string) (string, bool) { + v, ok := edit.GetYAML(path, "providers."+magpieID+"."+k) + if k != "api_key" || !hermesEnvRef.MatchString(v) { + return v, ok + } + // a reference to a variable: the key it names, as Hermes + // reads it (PaulT on Discord: "${MAGPIE_API_KEY}" with the + // key in Hermes's .env was said not to reach magpie). One + // magpie can't see (a variable of the shell's alone) is + // unknown, never drift. + key, known := hermesKey(at, path, v) + if !known { + return at.gwKey(), true + } + return key, true + } + return wiringOff("Hermes", path, get, "base_url", at.v1(), "api_key", at.gwKey()) }, Fields: []Field{{ Key: "model", Label: "model", @@ -284,14 +300,102 @@ func hermesProviderAt(gw string) hermesProviderEntry { // key_cmd, request_timeout_seconds, extra_body, context_length, enabled or // ssl_* (hermes_cli/config_providers.py _KNOWN_PROVIDER_KEYS). Each stays, // as does a name of their own and a header beside magpie's User-Agent; the -// address, key, API mode and model list are magpie's (#2030). -func hermesKept(path string, e hermesProviderEntry) any { +// address, key, API mode and model list are magpie's (#2030), but for a +// key the user keeps as a reference to a variable (hermesKeptKey). +func hermesKept(at place, path string, e hermesProviderEntry) any { + e.APIKey = hermesKeptKey(at, path, e.APIKey) if name, ok := edit.GetYAML(path, "providers."+magpieID+".name"); ok && strings.TrimSpace(name) != "" { e.Name = name } return yamlKept(path, "providers."+magpieID, e, "base_url", "api_key", "api_mode", "models") } +// hermesEnvRef is a reference in a value of Hermes's config.yaml, which +// Hermes expands as it loads it: ${VAR}, or ${env:VAR} +// (hermes_cli/config.py _ENV_REF_RE, _env_expand_match). +var hermesEnvRef = regexp.MustCompile(`\$\{([^}]+)\}`) + +// hermesSecretSource starts a reference to a secret source other than the +// environment (${vault:...}, ${bitwarden:...}), which Hermes leaves as it +// is in config.yaml (_is_non_env_secret_ref). +var hermesSecretSource = regexp.MustCompile(`^[a-z][a-z0-9_-]*:`) + +// hermesRefVar is the variable the body of a reference reads, "" for +// another source or an empty ${env:} (_env_ref_var_name). +func hermesRefVar(body string) string { + body = strings.TrimSpace(body) + if v, ok := strings.CutPrefix(body, "env:"); ok { + return strings.TrimSpace(v) + } + if hermesSecretSource.MatchString(body) { + return "" + } + return body +} + +// hermesEnvFile is the .env beside the config at path, Hermes's or a +// profile's own, where Hermes keeps keys (load_hermes_dotenv). +func hermesEnvFile(path string) string { return filepath.Join(filepath.Dir(path), ".env") } + +// hermesKey is the api_key v in the config at path as Hermes sends it, each +// reference expanded: from the .env beside it, which Hermes loads over its +// environment, then from the environment, this machine's only. known is +// false when a reference names a variable magpie can't see there (one only +// a shell profile sets) or another source; Hermes would expand it, or send +// it as it is, and magpie can't tell which. +func hermesKey(at place, path, v string) (key string, known bool) { + known = true + key = hermesEnvRef.ReplaceAllStringFunc(v, func(ref string) string { + name := hermesRefVar(ref[2 : len(ref)-1]) + if name == "" { + known = false + return ref + } + if val, ok := edit.GetEnvFile(hermesEnvFile(path), name); ok { + return val + } + if at.spell == nil { + if val, ok := appdir.LookupEnv(name); ok { + return val + } + } + known = false + return ref + }) + return key, known +} + +// hermesKeptKey is the api_key magpie writes into the config at path, where +// want is its own key: a reference the user put there stays, whenever the +// key it names holds (keyHolds) or magpie can't see it. One naming a key +// the gateway doesn't take stays too, and magpie's key goes into the .env +// beside the config under its variable, which Hermes reads over the +// environment; a value with more than the one reference in it is magpie's +// key again. +func hermesKeptKey(at place, path, want string) string { + raw, _ := edit.GetYAML(path, "providers."+magpieID+".api_key") + if !hermesEnvRef.MatchString(raw) { + return want + } + if key, known := hermesKey(at, path, raw); !known || keyHolds(key, want) { + return raw + } + m := hermesEnvRef.FindStringSubmatch(raw) + name := hermesRefVar(m[1]) + if m[0] != strings.TrimSpace(raw) || name == "" { + return want + } + // a .env made here holds a key, so only its owner reads it, as + // Hermes writes its own (_write_env_lines) + if f, err := os.OpenFile(hermesEnvFile(path), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600); err == nil { + f.Close() + } + if edit.SetEnvFile(hermesEnvFile(path), edit.KV{Path: name, Value: want}) != nil { + return want + } + return raw +} + // what hermes says after a change (notice.go) var ( noticeHermes = newNotice("Hermes reads its settings at start-up — restart open Hermes sessions to use this.") diff --git a/internal/agent/hermes_test.go b/internal/agent/hermes_test.go index cfba910f0..495db7e2f 100644 --- a/internal/agent/hermes_test.go +++ b/internal/agent/hermes_test.go @@ -415,6 +415,117 @@ func TestHermesWithAGatewayKeyOfTheUsers(t *testing.T) { } } +// PaulT on Discord: Hermes's provider written as Hermes keeps keys, the +// api_key "${MAGPIE_API_KEY}" with the key in Hermes's .env, was marked as +// needing attention. A reference names the key Hermes sends: one that +// reaches magpie is not drift and a sync keeps it; one magpie can't see is +// unknown, kept and not drift; one naming a key the gateway doesn't take +// is drift, and a sync puts magpie's key into the .env, the reference kept. +func TestHermesWithAKeyInItsEnvFile(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("HERMES_HOME", "") + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("MAGPIE_API_KEY", "") + os.Unsetenv("MAGPIE_API_KEY") + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + dir := appdir.HermesHomeIn(home) + path := filepath.Join(dir, "config.yaml") + env := filepath.Join(dir, ".env") + os.MkdirAll(dir, 0o755) + os.WriteFile(path, []byte("model:\n default: x\n"), 0o644) + a := hermes(home) + if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + secret, err := access.Update("add-key", access.Change{Name: "hermes"}) + if err != nil { + t.Fatal(err) + } + // the reporter's provider, as he wrote it + mine := "model:\n default: deepseek/pro\n provider: magpie\nproviders:\n magpie:\n name: magpie\n api_key: \"${MAGPIE_API_KEY}\"\n api_mode: chat_completions\n base_url: " + here(home).v1() + "\n" + if err := os.WriteFile(path, []byte(mine), 0o644); err != nil { + t.Fatal(err) + } + ref := func(what string) { + t.Helper() + if v, _ := edit.GetYAML(path, "providers.magpie.api_key"); v != "${MAGPIE_API_KEY}" { + t.Fatalf("%s: the user's reference was written over: %q", what, v) + } + } + for _, c := range []struct{ name, line string }{ + {"a gateway key", "MAGPIE_API_KEY=" + secret}, + {"magpie's own key, quoted", "export MAGPIE_API_KEY=\"" + gateway.Token + "\""}, + } { + os.WriteFile(env, []byte("OPENROUTER_API_KEY=sk-or\n"+c.line+"\n"), 0o600) + if d := a.Check(); d != "" { + t.Fatalf("%s in .env is drift: %s", c.name, d) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + ref(c.name) + if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + ref(c.name + ", then a pick") + } + // ${env:VAR}, Hermes's other spelling, from the environment + os.Remove(env) + if err := edit.SetYAML(path, edit.KV{Path: "providers.magpie.api_key", Value: "${env:MAGPIE_API_KEY}"}); err != nil { + t.Fatal(err) + } + t.Setenv("MAGPIE_API_KEY", secret) + if d := a.Check(); d != "" { + t.Fatalf("a gateway key in the environment is drift: %s", d) + } + os.Unsetenv("MAGPIE_API_KEY") + if err := edit.SetYAML(path, edit.KV{Path: "providers.magpie.api_key", Value: "${MAGPIE_API_KEY}"}); err != nil { + t.Fatal(err) + } + // a variable only the shell sets, which magpie doesn't see: unknown + if d := a.Check(); d != "" { + t.Fatalf("a variable magpie can't see is drift: %s", d) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + ref("a variable magpie can't see") + if _, err := os.Stat(env); err == nil { + t.Fatal("a sync made a .env for a variable magpie can't see") + } + // a key the gateway doesn't take + os.WriteFile(env, []byte("# keys\nMAGPIE_API_KEY=sk-not-this-gateways\nOTHER=1\n"), 0o600) + if d := a.Check(); !strings.Contains(d, "api_key") { + t.Fatalf("a key the gateway doesn't take is not reported: %q", d) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + ref("a key the gateway doesn't take") + b, _ := os.ReadFile(env) + if want := "# keys\nMAGPIE_API_KEY=" + gateway.Token + "\nOTHER=1\n"; string(b) != want { + t.Fatalf(".env after a sync:\n%s\nwant:\n%s", b, want) + } + if d := a.Check(); d != "" { + t.Fatalf("after a sync: %s", d) + } + // more than the one reference: magpie's key, as before + if err := edit.SetYAML(path, edit.KV{Path: "providers.magpie.api_key", Value: "x${MAGPIE_API_KEY}"}); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if v, _ := edit.GetYAML(path, "providers.magpie.api_key"); v != gateway.Token { + t.Fatalf("a value that doesn't reach magpie is kept: %q", v) + } +} + // keyHolds, which every agent's check of magpie's key goes through: a key // of the gateway's own stands in for magpie's, never for a URL or another // value, and one the gateway doesn't take doesn't. diff --git a/internal/agent/image_input_test.go b/internal/agent/image_input_test.go index 1a1adf6ca..1d45ce581 100644 --- a/internal/agent/image_input_test.go +++ b/internal/agent/image_input_test.go @@ -155,7 +155,7 @@ func TestInferredGroupImagesReachAgentCatalogs(t *testing.T) { if err := catalog.SaveLive("unknown", "https://example.test/v1", []catalog.Model{{ID: "claude-sonnet-4-5"}}); err != nil { t.Fatal(err) } - id := "group/auto-claude-sonnet-4-5" + id := "auto/claude-sonnet-4-5" oc := magpieProviderJSON("opencode").(map[string]any)["models"].(map[string]any)[id].(map[string]any) if _, ok := oc["attachment"]; ok || !reflect.DeepEqual(oc["modalities"].(map[string]any)["input"], []string{"text", "image"}) { t.Fatalf("OpenCode group image input: %v", oc) diff --git a/internal/agent/inuse.go b/internal/agent/inuse.go index 6eeffd8a0..831d6007d 100644 --- a/internal/agent/inuse.go +++ b/internal/agent/inuse.go @@ -54,7 +54,10 @@ func (a *Agent) Models() []string { func modelRef(v string) string { v = strings.TrimSuffix(strings.TrimSpace(v), "[1m]") v = strings.TrimPrefix(v, magpieID+"/") - if strings.HasPrefix(v, provider.GroupPrefix) || isMagpie(v) { + if provider.IsGroupRef(v) { + return provider.CanonicalRef(v) // a found group by one id, whichever it was set to + } + if isMagpie(v) { return v } return "" diff --git a/internal/agent/omp_api_test.go b/internal/agent/omp_api_test.go index 5db8b8a76..fb6e4737e 100644 --- a/internal/agent/omp_api_test.go +++ b/internal/agent/omp_api_test.go @@ -68,7 +68,7 @@ func TestOmpModelsAskedOnTheirNativeAPI(t *testing.T) { "anth/claude-sonnet-5": "anthropic-messages", "anth/claude-sonnet-4-5": "anthropic-messages", "anth/kimi-k3": "anthropic-messages", - "group/auto-gpt-5-5": "openai-responses", + "auto/gpt-5.5": "openai-responses", "group/mixed": nil, } { e, ok := entries[id] diff --git a/internal/agent/pi_api_test.go b/internal/agent/pi_api_test.go index 4ab53e501..b26b0aede 100644 --- a/internal/agent/pi_api_test.go +++ b/internal/agent/pi_api_test.go @@ -62,7 +62,7 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { "relay/glm-4.6": nil, "anth/claude-sonnet-5": "anthropic-messages", "anth/kimi-k3": "anthropic-messages", - "group/auto-gpt-5-5": "openai-responses", + "auto/gpt-5.5": "openai-responses", "group/gpts": "openai-responses", "group/outer": "openai-responses", "group/mixed": nil, diff --git a/internal/agent/reseat.go b/internal/agent/reseat.go index e5b121253..43e448296 100644 --- a/internal/agent/reseat.go +++ b/internal/agent/reseat.go @@ -98,7 +98,7 @@ func Reseat(change func() error) ([]Move, error) { f := p.a.Field(p.key) vals := p.a.Values() // changed already, with another field - if f == nil || vals[p.key] != p.val { + if f == nil || !p.a.samePick(vals[p.key], p.val) { continue } var to Option @@ -121,6 +121,22 @@ func Reseat(change func() error) ([]Move, error) { return moves, nil } +// samePick: a field's value now is still the pick read before the change. +// A found group's auto/ reads back as written while the group is +// served, but Claude Code is given a dotted Claude version dashed +// (ClaudeSpelled), and with the group gone nothing takes +// auto/claude-sonnet-4-5 back to auto/claude-sonnet-4.5. Both are the one +// group by its canonical id, so the agent is still moved off it. +func (a *Agent) samePick(now, before string) bool { + if now == before { + return true + } + m1, s1, one1 := a.split(now) + m2, s2, one2 := a.split(before) + return one1 && one2 && s1 == s2 && provider.IsGroupRef(m1) && + provider.CanonicalRef(m1) == provider.CanonicalRef(m2) +} + // served: magpie takes requests for the catalog model. func served(ref string) bool { _, _, ok := provider.Resolve(ref) @@ -142,7 +158,7 @@ func sameModel(opts []Option, ref string) Option { return Option{} } for _, o := range opts { - if o.Ref == "" || strings.HasPrefix(o.Ref, provider.GroupPrefix) || !served(o.Ref) { + if o.Ref == "" || provider.IsGroupRef(o.Ref) || !served(o.Ref) { continue } if pid, m, _ := strings.Cut(o.Ref, "/"); provider.AutoGroupOf(pid, m) == gid { @@ -158,7 +174,7 @@ func sameModel(opts []Option, ref string) Option { want := modelKey(model) var alike Option for _, o := range opts { - if o.Ref == "" || strings.HasPrefix(o.Ref, provider.GroupPrefix) || !served(o.Ref) { + if o.Ref == "" || provider.IsGroupRef(o.Ref) || !served(o.Ref) { continue } _, m, _ := strings.Cut(o.Ref, "/") diff --git a/internal/agent/reseat_test.go b/internal/agent/reseat_test.go index f9af1e13d..10d849431 100644 --- a/internal/agent/reseat_test.go +++ b/internal/agent/reseat_test.go @@ -68,12 +68,19 @@ func mustFind(t *testing.T, id string) *Agent { } func mustApply(t *testing.T, a *Agent, key, v string) { + t.Helper() + mustApplyAs(t, a, key, v, v) +} + +// mustApplyAs applies v and expects want written: a found group picked by +// its old id is written as auto/ +func mustApplyAs(t *testing.T, a *Agent, key, v, want string) { t.Helper() if err := a.Apply(key, v); err != nil { t.Fatalf("%s %s=%s: %v", a.ID, key, v, err) } - if got := a.Field(key).Get(); got != v { - t.Fatalf("%s %s: %q, want %q", a.ID, key, got, v) + if got := a.Field(key).Get(); got != want { + t.Fatalf("%s %s: %q, want %q", a.ID, key, got, want) } } @@ -214,9 +221,12 @@ func TestReseatUnmovable(t *testing.T) { func TestReseatFoundGroupsOff(t *testing.T) { reseatHome(t) c, h := mustFind(t, "claude"), mustFind(t, "hermes") - mustApply(t, c, "model", "group/auto-gpt-5") - mustApply(t, c, "opus", "group/auto-claude-sonnet-4-5") - mustApply(t, h, "model", "magpie/group/auto-gpt-5") + // picked by the old ids, written as they are listed now. Opus's + // auto/claude-sonnet-4.5 is given Claude Code dashed, and with the + // group gone reads back as auto/claude-sonnet-4-5: still moved + mustApplyAs(t, c, "model", "group/auto-gpt-5", "auto/gpt-5") + mustApplyAs(t, c, "opus", "group/auto-claude-sonnet-4-5", provider.PublicRef("group/auto-claude-sonnet-4-5")) + mustApplyAs(t, h, "model", "magpie/group/auto-gpt-5", "magpie/auto/gpt-5") moves, err := Reseat(func() error { return provider.SetAutoGroups(false) }) if err != nil { t.Fatal(err) @@ -229,7 +239,7 @@ func TestReseatFoundGroupsOff(t *testing.T) { if got := h.Field("model").Get(); got != "magpie/cop/gpt-5" { t.Errorf("hermes: %q", got) } - if len(moves) != 3 || moves[0].From != "group/auto-gpt-5" || moves[0].To != "cop/gpt-5" { + if len(moves) != 3 || moves[0].From != "auto/gpt-5" || moves[0].To != "cop/gpt-5" { t.Errorf("moves: %+v", moves) } // on again, nobody is moved back or elsewhere @@ -246,17 +256,17 @@ func TestReseatFoundGroupsOff(t *testing.T) { func TestReseatKeepsAFoundGroupWithAProviderOff(t *testing.T) { reseatHome(t) c, h := mustFind(t, "claude"), mustFind(t, "hermes") - mustApply(t, c, "model", "group/auto-gpt-5") + mustApplyAs(t, c, "model", "group/auto-gpt-5", "auto/gpt-5") mustApply(t, c, "haiku", "cop/only-here") - mustApply(t, h, "model", "magpie/group/auto-gpt-5") + mustApplyAs(t, h, "model", "magpie/group/auto-gpt-5", "magpie/auto/gpt-5") moves, err := Reseat(func() error { return provider.SetOff("cop", true) }) if err != nil { t.Fatal(err) } - if got := c.Field("model").Get(); got != "group/auto-gpt-5" { + if got := c.Field("model").Get(); got != "auto/gpt-5" { t.Errorf("claude model with cop off: %q", got) } - if got := h.Field("model").Get(); got != "magpie/group/auto-gpt-5" { + if got := h.Field("model").Get(); got != "magpie/auto/gpt-5" { t.Errorf("hermes with cop off: %q", got) } if len(moves) != 1 || moves[0].Field != "haiku" || moves[0].From != "cop/only-here" { @@ -269,7 +279,7 @@ func TestReseatKeepsAFoundGroupWithAProviderOff(t *testing.T) { if moves, err = Reseat(func() error { return provider.SetOff("cop", false) }); err != nil || len(moves) != 0 { t.Fatalf("on again: %+v %v", moves, err) } - if got := c.Field("model").Get(); got != "group/auto-gpt-5" { + if got := c.Field("model").Get(); got != "auto/gpt-5" { t.Errorf("claude model on again: %q", got) } } diff --git a/internal/agent/sync.go b/internal/agent/sync.go index d1d0aa0c2..409da3932 100644 --- a/internal/agent/sync.go +++ b/internal/agent/sync.go @@ -45,10 +45,15 @@ func SyncCatalog() { // the catalog built once for every agent's lists, not for each // look-up of each (thousands at magpie's start, with 30 providers) release := provider.Hold() + renaming := setToFoundGroups() for _, a := range All() { if a.Sync != nil { _ = synced(a.Sync) } + // a field magpie set to a found group's id before (autoref.go) + if renaming[a.ID] { + a.renameFoundGroups() + } } release() syncing.Lock() diff --git a/internal/agent/window_typed_test.go b/internal/agent/window_typed_test.go index 9c7f7e16c..ab683b2e1 100644 --- a/internal/agent/window_typed_test.go +++ b/internal/agent/window_typed_test.go @@ -159,3 +159,81 @@ func TestSmallestMemberTypedWindow(t *testing.T) { } } } + +// Osal on Discord: a routing group that names no size of its own is told +// its largest member's window, and when the user typed that one (872K on +// the provider for GPT-6 Astra, its most) Codex and Claude run to it +// whole, as for a group following its smallest member (#2224), not to +// magpie's default 272K (Codex showed "258k", 95% of it). A group whose +// largest member's window nobody typed keeps the default, even with a +// typed member smaller than it. +func TestLargestMemberTypedWindow(t *testing.T) { + home, path := desktopWindowSandbox(t) + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + must(provider.Save(provider.Provider{ID: "w", Name: "W", Key: "k", Chat: "http://127.0.0.1:1/v1", + Models: []string{"astra"}, Contexts: map[string]int{"astra": 872000}})) + must(catalog.SaveLive("w", "http://127.0.0.1:1/v1", []catalog.Model{{ID: "astra", Context: 272000}})) + must(provider.SaveGroup(provider.Group{ID: "ultra", Name: "Ultra", Members: []string{"w/astra", "v/gpt"}})) + must(provider.SaveGroup(provider.Group{ID: "loose", Name: "Loose", Members: []string{"w/astra", "v/glm"}})) + + // Codex: the gateway's list, and its context_window on disk + must(codex(home).Fields[0].Set("group/ultra")) + compacts := map[string]int{} + for _, m := range provider.CodexListed() { + compacts[m.ID] = m.Compact + } + for id, want := range map[string]int{"group/ultra": 872000, "group/loose": 0} { + if compacts[id] != want { + t.Errorf("Codex: the gateway's list compacts %s at %d; want %d", id, compacts[id], want) + } + } + var disk struct { + Models []struct { + Slug string `json:"slug"` + Context int `json:"context_window"` + Max int `json:"max_context_window"` + } `json:"models"` + } + raw := readFile(filepath.Join(home, ".codex", "magpie-models.json")) + must(json.Unmarshal([]byte(raw), &disk)) + for _, m := range disk.Models { + want := map[string][2]int{"group/ultra": {872000, 0}, "group/loose": {272000, 1000000}} + if w, ok := want[m.Slug]; ok && [2]int{m.Context, m.Max} != w { + t.Errorf("Codex: on disk %s is told %d (max %d); want %v", m.Slug, m.Context, m.Max, w) + } + } + + // Claude Code: no compaction window for the typed one + cpath := filepath.Join(home, ".claude", "settings.json") + a := claude(home) + env := func(k string) string { v, _ := edit.GetJSON(cpath, "env."+k); return v } + must(a.Field("model").Set("group/ultra")) + if c, w := env(claudeCompactEnv), env(claudeContextEnv); c != "" || w != "872000" { + t.Errorf("Claude Code on the group: compact %q, window %q; want none and 872000", c, w) + } + must(a.Field("model").Set("group/loose")) + if c := env(claudeCompactEnv); c != "272000" { + t.Errorf("Claude Code on the loose group: compact %q; want the default 272000", c) + } + + // Claude Desktop: the typed group's own autoCompactWindow; the + // other is left to the top-level one, the default + must(claudeDesktop(home).Field("provider").Set("magpie")) + ids := map[string]string{} + for _, e := range provider.Catalog() { + ids[e.ID] = gateway.DesktopID(e) + } + if v, _ := edit.GetJSON(path, "autoCompactWindow"); v != "272000" { + t.Errorf("Claude Desktop: top-level autoCompactWindow %q; want 272000", v) + } + for id, want := range map[string]string{"group/ultra": "872000", "group/loose": ""} { + if v, _ := edit.GetJSON(path, budgetPath(ids[id])); v != want { + t.Errorf("Claude Desktop: %s (%s) compacts at %q; want %q", id, ids[id], v, want) + } + } +} diff --git a/internal/agent/zcode.go b/internal/agent/zcode.go index 0841d980e..fe5a04db1 100644 --- a/internal/agent/zcode.go +++ b/internal/agent/zcode.go @@ -2,6 +2,8 @@ package agent import ( "encoding/json" + "errors" + "io/fs" "net" "net/url" "os" @@ -42,7 +44,7 @@ import ( // "personalModelIds":[…],"modelOrder":[…]}}]}, // "modelConfigRules":{"providerModelRules":[{"providerId":"magpie", // "modelId":…,"config":{"properties":{"contextWindow":…, -// "inputFormat":{"supportsImage":…}}, +// "inputFormat":{"supportsImage":…},"supportsNativeWebSearch":true}, // "optionSpecs":{"maxOutputTokens":{"max":…},"reasoningLevel":{"values":[…]}}}}], // "manualProviderModelRules":[…]}}} // @@ -103,6 +105,9 @@ func zcode(home string) *Agent { return err } if v == "" { + if _, ok := stashLoad()[zcodeSearchedKey]; ok { + forget(zcodeSearchedKey) + } return edit.DelJSON(path, key) } return edit.SetJSON(path, edit.KV{Path: key, Value: zcodeProviderJSON(path, false)}) @@ -414,23 +419,37 @@ func zcodeRules(path string, on, keep bool) error { } manual = append(manual, r) } + // magpie's model rules as they are now, which ZCode's own settings + // write a model's edits into while it keeps its recommended config + ours := map[any]map[string]any{} for _, r := range zcodeList(mcr, "providerModelRules") { if !mine(r) { models = append(models, r) + continue } + m := r.(map[string]any) + ours[m["modelId"]] = m } if on { + format := zcodeFormat(filepath.Dir(path)) + searched, known := zcodeSearched() var ids []string for _, m := range magpieModels("zcode") { ids = append(ids, m.ID) if byHand[m.ID] { + // set by hand in ZCode: its own settings, and the default + // again should it go back to its recommended config + delete(searched, m.ID) continue } props := map[string]any{"inputFormat": map[string]any{"supportsImage": m.Images}} if m.Context > 0 { props["contextWindow"] = m.Context } + if v, set := zcodeWebSearch(ours[m.ID], m.ID, format == "anthropic-messages" && known, searched); set { + props["supportsNativeWebSearch"] = v + } config := map[string]any{"properties": props} // ZCode's own rules give a model it doesn't know 32000 tokens // out and thinking only on or off @@ -449,6 +468,9 @@ func zcodeRules(path string, on, keep bool) error { if ids == nil { ids = []string{} } + if known { + zcodeSearchedPut(searched, ids) + } base, token := gateway.URL(), hereKey() if keep { base, token = zcodeKept(filepath.Dir(path)) @@ -457,7 +479,7 @@ func zcodeRules(path string, on, keep bool) error { "config": map[string]any{ "group": "standard-personal", "access": map[string]any{"type": "api-key", "apiKey": token}, - "api": map[string]any{"type": zcodeFormat(filepath.Dir(path)), "baseUrl": base}, + "api": map[string]any{"type": format, "baseUrl": base}, "personalModelIds": ids, "modelOrder": ids, }} // turned off in ZCode, it stays off @@ -507,6 +529,89 @@ func zcodeRules(path string, on, keep bool) error { return edit.WriteAtomic(path, out) } +// ZCode offers a model its WebSearch tool only where the model's rule says +// it has native web search (properties.supportsNativeWebSearch, 原生联网搜索 +// in a model's settings), off by default. Its tool then asks the model +// again with Anthropic's web_search tool, which only an Anthropic Messages +// provider is sent: on another API format ZCode fails the search. magpie's +// gateway runs that tool for any of its models, so it turns native web +// search on for each model it lists while the format is Anthropic Messages +// (Gearclickist on Discord: every magpie model had to be ticked by hand). +// +// ZCode writes a change to a model with its recommended config into the +// model's rule, magpie's, and leaves a value equal to ZCode's default out of +// it: unticking native web search takes the key out. So the models magpie +// turned it on for are kept in the stash (zcodeSearchedKey), and one of +// them whose rule has no key now was unticked in ZCode and stays off. A +// value in the rule is kept as it is. +const zcodeSearchedKey = "zcode.web_search" + +// zcodeWebSearch is what magpie's rule for model id, which says old now, +// says of native web search: v, or nothing when set is false. anthropic is +// whether ZCode sends the model's provider-native search (the provider's +// format is Anthropic Messages, and the stash could be read). searched holds +// the models magpie turned it on for and is updated. +func zcodeWebSearch(old map[string]any, id string, anthropic bool, searched map[string]bool) (v, set bool) { + props, _ := old["config"].(map[string]any) + props, _ = props["properties"].(map[string]any) + was, had := props["supportsNativeWebSearch"].(bool) + switch { + case !anthropic: + // magpie's on can't be used there; the user's own value stays + if had && was && searched[id] { + delete(searched, id) + return false, false + } + return was, had + case had: + if was { + searched[id] = true + } + return was, true + case searched[id]: + // unticked in ZCode + return false, false + } + searched[id] = true + return true, true +} + +// zcodeSearched is the models magpie turned ZCode's native web search on +// for, and whether the stash could be read: a stash there that can't be +// read or parsed is unknown, and nothing is turned on. +func zcodeSearched() (map[string]bool, bool) { + out := map[string]bool{} + b, err := os.ReadFile(stashPath()) + if errors.Is(err, fs.ErrNotExist) { + return out, true + } + var m map[string]string + if err != nil || json.Unmarshal(b, &m) != nil { + return out, false + } + if v := m[zcodeSearchedKey]; v != "" { + for _, id := range strings.Split(v, "\n") { + out[id] = true + } + } + return out, true +} + +// zcodeSearchedPut keeps searched in the stash, only for models magpie +// still lists (ids), and writes it only when that changes it. +func zcodeSearchedPut(searched map[string]bool, ids []string) { + var keep []string + for _, id := range ids { + if searched[id] { + keep = append(keep, id) + } + } + v := strings.Join(keep, "\n") + if stashLoad()[zcodeSearchedKey] != v { + stash(map[string]string{zcodeSearchedKey: v}) + } +} + func zcodeObj(m map[string]any, k string) map[string]any { o, ok := m[k].(map[string]any) if !ok { diff --git a/internal/agent/zcode_websearch_test.go b/internal/agent/zcode_websearch_test.go new file mode 100644 index 000000000..51b40d01f --- /dev/null +++ b/internal/agent/zcode_websearch_test.go @@ -0,0 +1,154 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// Every model magpie lists in ZCode has native web search (原生联网搜索) on, +// so ZCode offers it its WebSearch tool (Gearclickist on Discord: each model +// had to be ticked by hand). A model the user unticked in ZCode, which +// takes the key out of magpie's rule, stays unticked through syncs; a value +// in the rule stays; a manual rule is the user's; and on a format other +// than Anthropic Messages, where ZCode can't send the search, magpie's on +// goes while the user's own value stays. +func TestZCodeWebSearch(t *testing.T) { + home := syncHome(t) + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", + Models: []string{"pro", "flash", "lite", "mine"}}); err != nil { + t.Fatal(err) + } + dir := filepath.Join(home, ".zcode", "v2") + rules := filepath.Join(dir, "provider_config.json") + os.MkdirAll(dir, 0o755) + // a rule an older magpie wrote, without the key, and one the user set + // by hand in ZCode + os.WriteFile(rules, []byte(`{"schemaVersion":1,"config":{ + "providerConfigRules":{"providerRules":[{"providerId":"magpie","providerName":"magpie","enabled":true,"config":{"group":"standard-personal", + "access":{"type":"api-key","apiKey":"magpie"},"api":{"type":"anthropic-messages","baseUrl":"http://127.0.0.1:3425"}, + "personalModelIds":["deepseek/pro"],"modelOrder":["deepseek/pro"]}}]}, + "modelConfigRules":{"providerModelRules":[{"providerId":"magpie","modelId":"deepseek/pro","config":{"properties":{"contextWindow":128000,"inputFormat":{"supportsImage":false}}}}], + "manualProviderModelRules":[{"providerId":"magpie","modelId":"deepseek/mine","config":{"enabled":true,"properties":{"contextWindow":64000,"supportsNativeWebSearch":false,"inputFormat":{"supportsImage":false}}}}]}}}`), 0o600) + os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"provider":{"magpie":{"name":"magpie","kind":"anthropic","enabled":true,"models":{}}}}`), 0o600) + + doc := func() map[string]any { + b, _ := os.ReadFile(rules) + d := map[string]any{} + if err := json.Unmarshal(b, &d); err != nil { + t.Fatalf("%v: %s", err, b) + } + return d + } + mcr := func(d map[string]any) map[string]any { + return d["config"].(map[string]any)["modelConfigRules"].(map[string]any) + } + props := func(d map[string]any, id string) map[string]any { + for _, r := range mcr(d)["providerModelRules"].([]any) { + if r := r.(map[string]any); r["providerId"] == "magpie" && r["modelId"] == "deepseek/"+id { + return r["config"].(map[string]any)["properties"].(map[string]any) + } + } + return nil + } + search := func() map[string]any { + d, out := doc(), map[string]any{} + for _, id := range []string{"pro", "flash", "lite", "mine"} { + if p := props(d, id); p != nil { + out[id] = p["supportsNativeWebSearch"] + } else { + out[id] = "no rule" + } + } + return out + } + // what ZCode's model settings write: the rule changed, after magpie's + // write + edit := func(id string, change func(p map[string]any)) { + d := doc() + change(props(d, id)) + b, _ := json.Marshal(d) + os.WriteFile(rules, b, 0o600) + later := time.Now().Add(time.Minute) + os.Chtimes(rules, later, later) + } + want := func(step string, w map[string]any) { + t.Helper() + got := search() + for id, v := range w { + if got[id] != v { + t.Fatalf("%s: %s is %v, want %v (all %v)", step, id, got[id], v, got) + } + } + } + a := zcode(home) + sync := func() { + t.Helper() + if err := a.Sync(); err != nil { + t.Fatal(err) + } + } + + // an older magpie's rule and new models get it; the manual one is left + sync() + want("first sync", map[string]any{"pro": true, "flash": true, "lite": true, "mine": "no rule"}) + d := doc() + manual := mcr(d)["manualProviderModelRules"].([]any) + if len(manual) != 1 || manual[0].(map[string]any)["config"].(map[string]any)["properties"].(map[string]any)["supportsNativeWebSearch"] != false { + t.Fatalf("manual rule changed: %v", manual) + } + + // unticked in ZCode: its value equals ZCode's default, so the key goes + edit("flash", func(p map[string]any) { delete(p, "supportsNativeWebSearch") }) + // set off outright + edit("lite", func(p map[string]any) { p["supportsNativeWebSearch"] = false }) + for range 2 { + sync() + want("unticked", map[string]any{"pro": true, "flash": nil, "lite": false}) + } + + // ticked again + edit("flash", func(p map[string]any) { p["supportsNativeWebSearch"] = true }) + sync() + want("ticked again", map[string]any{"pro": true, "flash": true, "lite": false}) + + // on Chat Completions ZCode can't send the search: magpie's on goes, + // the user's off stays + d = doc() + for _, r := range d["config"].(map[string]any)["providerConfigRules"].(map[string]any)["providerRules"].([]any) { + if r := r.(map[string]any); r["providerId"] == "magpie" { + r["config"].(map[string]any)["api"].(map[string]any)["type"] = "openai-chat-completions" + } + } + b, _ := json.Marshal(d) + os.WriteFile(rules, b, 0o600) + later := time.Now().Add(2 * time.Minute) + os.Chtimes(rules, later, later) + sync() + want("chat completions", map[string]any{"pro": nil, "flash": nil, "lite": false}) + + // back on Anthropic Messages, it is on again + d = doc() + for _, r := range d["config"].(map[string]any)["providerConfigRules"].(map[string]any)["providerRules"].([]any) { + if r := r.(map[string]any); r["providerId"] == "magpie" { + r["config"].(map[string]any)["api"].(map[string]any)["type"] = "anthropic-messages" + } + } + b, _ = json.Marshal(d) + os.WriteFile(rules, b, 0o600) + later = time.Now().Add(3 * time.Minute) + os.Chtimes(rules, later, later) + sync() + want("anthropic again", map[string]any{"pro": true, "flash": true, "lite": false}) + + // a stash that can't be read is unknown: nothing is turned on, and + // what the rules say stays + edit("flash", func(p map[string]any) { delete(p, "supportsNativeWebSearch") }) + os.WriteFile(stashPath(), []byte("{not json"), 0o600) + sync() + want("unreadable stash", map[string]any{"pro": true, "flash": nil, "lite": false}) +} diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 82da1d966..34b74a024 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -615,12 +615,18 @@ func load() map[string]mdProvider { return mdev } -// Reset forgets the loaded catalog so the next call re-reads the cache. +// Reset forgets the loaded catalog so the next call re-reads the cache, +// and tells Forget: what the provider package built of the old one (the +// windows and output limits of its entries) is kept between requests +// for a moment, and would answer for the old catalog meanwhile. func Reset() { loadMu.Lock() - defer loadMu.Unlock() loaded = false mdev, images, windows, outputs, efforts, thinks, names, listed, canonical = nil, nil, nil, nil, nil, nil, nil, nil, nil + loadMu.Unlock() + if Forget != nil { + Forget() + } } // Sync downloads the models.dev catalog into CachePath. It serializes with @@ -958,6 +964,14 @@ func Knows(id string) bool { return ContextOf(id) > 0 || len(EffortsOf(id)) > 0 || Thinks(id) } +// Lists reports whether models.dev lists a model by this very id (its +// last part, any case), not one found by another spelling: claude-opus-5.5 +// only when that is how one of its providers spells it. +func Lists(id string) bool { + load() + return listed[bareID(id)] +} + // SeesImages reports whether models.dev says a model of this id takes // images, as most of the providers it lists serving it do; for a vendor it // doesn't list, serving a model it knows from others ("z-ai/glm-5.3" is diff --git a/internal/cli/groups_cli.go b/internal/cli/groups_cli.go index a80b6a346..d09c21d41 100644 --- a/internal/cli/groups_cli.go +++ b/internal/cli/groups_cli.go @@ -260,7 +260,7 @@ func memberResolver(keep []string) func(string) (string, error) { } if model, effort := provider.MemberEffort(id); effort != "" { // a model at an effort of its own: the model as any other is - if strings.HasPrefix(model, provider.GroupPrefix) { + if provider.IsGroupRef(model) { return "", fmt.Errorf("%s is a group: its models reason as it says, so it takes no :%s", model, effort) } m, err := resolve(model) @@ -269,8 +269,8 @@ func memberResolver(keep []string) func(string) (string, error) { } return provider.WithMemberEffort(m, effort), nil } - if gid, ok := strings.CutPrefix(id, provider.GroupPrefix); ok { - // a group in the group: SaveGroup refuses one it would be in itself through + if gid, ok := strings.CutPrefix(provider.CanonicalRef(id), provider.GroupPrefix); ok { + // a group in the group: auto/ as group/auto-;: SaveGroup refuses one it would be in itself through for _, g := range provider.Groups() { if strings.EqualFold(g.ID, gid) && !g.Hidden { return provider.GroupPrefix + g.ID, nil @@ -583,7 +583,7 @@ func pickMember(members []string, v string) (string, error) { // findGroup looks a group up by its id, its catalog id or its name. func findGroup(ref string) (provider.Group, error) { all := provider.Groups() - ref = strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(ref), "magpie/"), provider.GroupPrefix) + ref = strings.TrimPrefix(provider.CanonicalRef(strings.TrimPrefix(strings.TrimSpace(ref), "magpie/")), provider.GroupPrefix) for _, match := range []func(provider.Group) bool{ func(g provider.Group) bool { return g.ID == ref }, func(g provider.Group) bool { return strings.EqualFold(g.ID, ref) }, @@ -647,7 +647,7 @@ func groupCmd(args []string) error { if err != nil { return err } - fmt.Println(green.Render("✓"), verb, bold.Render(g.Name), muted.Render("· agents pick it as "+provider.GroupPrefix+g.ID)) + fmt.Println(green.Render("✓"), verb, bold.Render(g.Name), muted.Render("· agents pick it as "+g.Ref())) return showGroup(g) case "set", "edit": if len(rest) < 2 { @@ -660,7 +660,7 @@ func groupCmd(args []string) error { fmt.Println(green.Render("✓"), "saved", bold.Render(g.Name)) if slices.ContainsFunc(rest[1:], func(kv string) bool { return strings.HasPrefix(strings.ToLower(kv), "name=") }) { // a new name isn't a new id: say what agents still ask for - fmt.Println(muted.Render(" its id stays " + g.ID + ": agents ask for " + provider.GroupPrefix + g.ID + " (a client given the name may ask by the name too)")) + fmt.Println(muted.Render(" its id stays " + g.ID + ": agents ask for " + g.Ref() + " (a client given the name may ask by the name too)")) } return showGroup(g) case "rm", "remove", "delete": @@ -704,7 +704,7 @@ func groupCmd(args []string) error { if err != nil { return err } - fmt.Println(green.Render("✓"), "copied", bold.Render(src.Name), "to", bold.Render(g.Name), muted.Render("· agents pick it as "+provider.GroupPrefix+g.ID)) + fmt.Println(green.Render("✓"), "copied", bold.Render(src.Name), "to", bold.Render(g.Name), muted.Render("· agents pick it as "+g.Ref())) return showGroup(g) case "template", "templates", "tpl": return templateCmd(rest) @@ -814,7 +814,7 @@ func setGroup(ref string, pairs []string) (provider.Group, error) { // removedOnly is a removed found group magpie doesn't find now (its model // is down to one provider): only its record is left, to keep it removed. func removedOnly(ref string) (string, bool) { - ref = strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(ref), "magpie/"), provider.GroupPrefix) + ref = strings.TrimPrefix(provider.CanonicalRef(strings.TrimPrefix(strings.TrimSpace(ref), "magpie/")), provider.GroupPrefix) for _, id := range provider.RemovedGroups() { if strings.EqualFold(id, ref) { return id, true @@ -1001,7 +1001,7 @@ func groups() error { var rows []row w := [3]int{} for _, g := range shown { - r := row{name: bold.Render(g.Name), id: muted.Render(provider.GroupPrefix + g.ID)} + r := row{name: bold.Render(g.Name), id: muted.Render(g.Ref())} if g.Auto { r.name += " " + faint.Render("found") } @@ -1077,7 +1077,7 @@ func groups() error { func showGroup(g provider.Group) error { kv := func(k, v string) { fmt.Printf(" %s %s\n", muted.Render(pad(k, 9)), v) } - head := bold.Render(g.Name) + muted.Render(" "+provider.GroupPrefix+g.ID) + head := bold.Render(g.Name) + muted.Render(" "+g.Ref()) if g.Auto { head += faint.Render(" found by magpie — changing it makes it yours") } @@ -1173,7 +1173,7 @@ func showGroup(g provider.Group) error { // +` puts right (MOMO on Discord: opencode-go/deepseek-flash). func whyNotServed(member string) string { pid, model, ok := strings.Cut(member, "/") - if !ok || strings.HasPrefix(member, provider.GroupPrefix) { + if !ok || provider.IsGroupRef(member) { return "not served" } p, err := provider.Find(pid) @@ -1218,6 +1218,6 @@ func templateCmd(rest []string) error { if err != nil { return err } - fmt.Println(green.Render("✓"), "added", bold.Render(g.Name), muted.Render("· agents pick it as "+provider.GroupPrefix+g.ID)) + fmt.Println(green.Render("✓"), "added", bold.Render(g.Name), muted.Render("· agents pick it as "+g.Ref())) return showGroup(g) } diff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.go index 33d261f04..beee87327 100644 --- a/internal/cli/library_cli.go +++ b/internal/cli/library_cli.go @@ -139,7 +139,7 @@ func libraryCmd(args []string) error { if res, err = library.UpdateSkill(rest[1], len(rest) == 3); err == nil { fmt.Println(green.Render("✓"), rest[1], "is up to date") } else if errors.As(err, &edited) { - err = fmt.Errorf("%w\n magpie library skill update %s --replace-edits takes GitHub's in its place, keeping yours with the backups", err, rest[1]) + err = fmt.Errorf("%w\n magpie library skill update %s --replace-edits takes the fetched one in its place, keeping yours with the backups", err, rest[1]) } case len(rest) == 1 && rest[0] == "update": res, err = library.UpdateSkills() diff --git a/internal/cli/main.go b/internal/cli/main.go index 7a06ebb50..72ed5448f 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -292,6 +292,7 @@ func run(args []string) error { if hasGUI { return runGUI(true, "") } + gateway.Serves = "tui" return runTUI() } // a magpie:// link the system handed over (Windows, Linux): the app @@ -302,6 +303,14 @@ func run(args []string) error { } return runGUI(false, args[0]) } + // how this process was started, for the Routing page of another magpie on + // this computer to name the one that serves the gateway (#2606) + switch args[0] { + case "tui", "web", "serve", "tray": + gateway.Serves = args[0] + case "app", "gui", "panel", "-Embedding": + gateway.Serves = "app" + } switch args[0] { case "tui": return runTUI() diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.go index 64e40dfdb..af0cc8e1e 100644 --- a/internal/cli/plugins_cli.go +++ b/internal/cli/plugins_cli.go @@ -480,7 +480,9 @@ func pluginLogin(ctx context.Context, name, method string) error { if a.URL != "" { fmt.Println("Sign in in your browser. If it didn't open, go to:") fmt.Println(faint.Render(a.URL)) - openInBrowser(a.URL) + if !a.Opened { + openInBrowser(a.URL) + } } if a.Instructions != "" { fmt.Println(a.Instructions) diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index e5f948ad2..29ed8e25f 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -236,7 +236,7 @@ func usesByProvider() map[string][]string { } v := a.Fields[0].Get() v = strings.TrimPrefix(v, "magpie/") - if strings.HasPrefix(v, provider.GroupPrefix) { + if provider.IsGroupRef(v) { continue // a routing group, of no one provider } if pid, _, ok := strings.Cut(v, "/"); ok { diff --git a/internal/cli/signals.go b/internal/cli/signals.go index f001214d6..d27102608 100644 --- a/internal/cli/signals.go +++ b/internal/cli/signals.go @@ -8,7 +8,9 @@ import ( "sync/atomic" "syscall" + "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/provider" ) // endProbesOnSignal: the probes magpie asks a CLI with lead a session of @@ -39,6 +41,8 @@ func endProbesOnSignal() { handled := s == os.Interrupt && interrupts.Load() > 0 proc.EndProbes() if !handled { + provider.FlushServed() // a gateway's last answers, noted and not yet written + gateway.FlushSticks() // and who answered which conversation die(s) } } diff --git a/internal/cli/visible_cli.go b/internal/cli/visible_cli.go index c68ea6ae6..50920e361 100644 --- a/internal/cli/visible_cli.go +++ b/internal/cli/visible_cli.go @@ -105,7 +105,7 @@ func visibleCmd(args []string) error { } else { known := visibleNames() for i, n := range list { - n = strings.TrimPrefix(n, provider.GroupPrefix) + n = strings.TrimPrefix(provider.CanonicalRef(n), provider.GroupPrefix) if !slices.ContainsFunc(known, func(k string) bool { return strings.EqualFold(k, n) }) { return fmt.Errorf("%s is no family, provider or group (families: %s; magpie provider set family=%s makes one)", n, orNone(provider.Families()), n) diff --git a/internal/codexcat/codexcat.go b/internal/codexcat/codexcat.go index 480cac78e..c6ee81253 100644 --- a/internal/codexcat/codexcat.go +++ b/internal/codexcat/codexcat.go @@ -239,7 +239,7 @@ func entriesAt(ms []catalog.Model, after int, effort string) []any { } if m.Images { e.Modalities = append(e.Modalities, "image") - } else if !strings.HasPrefix(m.ID, "group/") { + } else if !strings.HasPrefix(m.ID, "group/") && !strings.HasPrefix(m.ID, "auto/") { // a routing group, a found one as auto/ // Codex turns a pasted image away itself, saying only that the // model doesn't take images; /model says where that is changed // (KimYx0207 on X). The description still ends " via magpie", diff --git a/internal/codexcat/codexcat_test.go b/internal/codexcat/codexcat_test.go index 3285f5e29..6d1b9fc3a 100644 --- a/internal/codexcat/codexcat_test.go +++ b/internal/codexcat/codexcat_test.go @@ -187,15 +187,16 @@ func TestCodexCatalogSaysTextOnly(t *testing.T) { {ID: "probe/text", Name: "Text"}, {ID: "probe/sees", Name: "Sees", Images: true}, {ID: "group/words", Name: "Words"}, + {ID: "auto/found", Name: "Found"}, // a group magpie found, as it is listed }), &got) - if len(got.Models) != 3 { + if len(got.Models) != 4 { t.Fatalf("%+v", got.Models) } - text, sees, group := got.Models[0], got.Models[1], got.Models[2] + text, sees, group, found := got.Models[0], got.Models[1], got.Models[2], got.Models[3] if !strings.Contains(text.Description, "text only") || !strings.Contains(text.Description, "Names & levels") || !catalog.MagpieAdded("", text.Slug, text.Description) { t.Errorf("text-only model: %q", text.Description) } - if sees.Description != "Sees via magpie" || group.Description != "Words via magpie" { - t.Errorf("a model that sees, and a group: %q, %q", sees.Description, group.Description) + if sees.Description != "Sees via magpie" || group.Description != "Words via magpie" || found.Description != "Found via magpie" { + t.Errorf("a model that sees, a group and a found one: %q, %q, %q", sees.Description, group.Description, found.Description) } } diff --git a/internal/filememo/filememo.go b/internal/filememo/filememo.go index 6449e18e3..3623f57d3 100644 --- a/internal/filememo/filememo.go +++ b/internal/filememo/filememo.go @@ -9,6 +9,7 @@ import ( "os" "strings" "sync" + "sync/atomic" "time" "github.com/yetone/magpie/internal/steady" @@ -44,8 +45,23 @@ var ( // on again (steady.Stat): one there before and not now may be being // replaced (Windows), and is gone = map[string]bool{} + // missing is the files found not there while a request held what was + // read, when, and in which of Forget's generations: taken as still + // not there as a file found unchanged is, not looked at again. A + // provider with no list fetched has no file of one, and a request + // asked after it for each of its models, each time a look at the disk + // (a third of a request's CPU with 30 providers of 60 models). + missing = map[string]missingFile{} + // stats counts the looks at the disk, for tests + stats int ) +type missingFile struct { + err error + checked time.Time + gen uint64 +} + // heldFor is how long a file found unchanged is taken as unchanged, while // a request holds what was read, before it is looked at again. const heldFor = time.Second @@ -71,9 +87,17 @@ func Hold() (release func()) { func Forget() { mu.Lock() gen++ + gens.Store(gen) mu.Unlock() } +// gens is gen, read without mu. +var gens atomic.Uint64 + +// Gen is moved on by every Forget: what is built from files read here, and +// kept past one read, is built again when it moved. +func Gen() uint64 { return gens.Load() } + // Look has the file at path looked at on its next read, even while a // request holds what was read (Hold): another magpie may have written it, // which Forget, moved on by this one's writes alone, can't know of. @@ -86,6 +110,7 @@ func Look(path string) { seen[k] = e } } + delete(missing, path) } // Read is parse of the file at path, from what it gave last time when the @@ -101,10 +126,21 @@ func Read[T any](kind, path string, parse func([]byte) (T, error)) (T, error) { mu.Unlock() return e.v.(T), nil } + if m, ok := missing[path]; ok && holds > 0 && m.gen == gen && time.Since(m.checked) < heldFor { + mu.Unlock() + return zero, m.err + } g := gen mu.Unlock() fi, err := statFile(path) if err != nil { + if errors.Is(err, fs.ErrNotExist) { + mu.Lock() + if holds > 0 && g == gen { + missing[path] = missingFile{err, time.Now(), g} + } + mu.Unlock() + } return zero, err } if ok && e.mod.Equal(fi.ModTime()) && e.size == fi.Size() && e.raw == nil { @@ -153,6 +189,7 @@ func Read[T any](kind, path string, parse func([]byte) (T, error)) (T, error) { func statFile(path string) (os.FileInfo, error) { mu.Lock() wasGone := gone[path] + stats++ mu.Unlock() var fi os.FileInfo var err error @@ -166,6 +203,7 @@ func statFile(path string) (os.FileInfo, error) { gone[path] = true } else { delete(gone, path) + delete(missing, path) } mu.Unlock() return fi, err diff --git a/internal/filememo/filememo_test.go b/internal/filememo/filememo_test.go index aee28c79a..f539abf41 100644 --- a/internal/filememo/filememo_test.go +++ b/internal/filememo/filememo_test.go @@ -96,3 +96,58 @@ func TestHold(t *testing.T) { t.Fatalf("a file written just now: %q", v) } } + +// A file not there is, while a request holds what was read, taken as +// still not there as a file found unchanged is: a provider with no list +// fetched was a look at the disk for each of its models, each request. A +// write magpie makes (Forget), another's (Look), or the hold's end has it +// looked at again; unheld, every read looks. +func TestHoldMissing(t *testing.T) { + p := filepath.Join(t.TempDir(), "none") + parse := func(b []byte) (string, error) { return string(b), nil } + looks := func() int { + mu.Lock() + defer mu.Unlock() + return stats + } + release := Hold() + before := looks() + for range 100 { + if _, err := Read("missing", p, parse); !os.IsNotExist(err) { + t.Fatalf("a file not there: %v", err) + } + } + if n := looks() - before; n != 1 { + t.Fatalf("%d looks at a file not there, held", n) + } + os.WriteFile(p, []byte("a"), 0o600) + if _, err := Read("missing", p, parse); !os.IsNotExist(err) { + t.Fatalf("looked at again while held: %v", err) + } + Forget() + if v, err := Read("missing", p, parse); v != "a" || err != nil { + t.Fatalf("after a write magpie made: %q %v", v, err) + } + os.Remove(p) + Read("missing", p, parse) + os.WriteFile(p, []byte("b"), 0o600) + Look(p) + if v, err := Read("missing", p, parse); v != "b" || err != nil { + t.Fatalf("after another's write: %q %v", v, err) + } + os.Remove(p) + Read("missing", p, parse) + release() + os.WriteFile(p, []byte("c"), 0o600) + if v, err := Read("missing", p, parse); v != "c" || err != nil { + t.Fatalf("released: %q %v", v, err) + } + os.Remove(p) + before = looks() + for range 3 { + Read("missing", p, parse) + } + if n := looks() - before; n != 3 { + t.Fatalf("unheld, %d looks for 3 reads", n) + } +} diff --git a/internal/gateway/advisor.go b/internal/gateway/advisor.go index b224c6fc1..6cea1f1db 100644 --- a/internal/gateway/advisor.go +++ b/internal/gateway/advisor.go @@ -92,7 +92,7 @@ func advisorModel(p provider.Provider, model string, wires map[string]string) (s if model == "" { return "", false } - if q, m, ok := provider.Resolve(model); ok && !strings.HasPrefix(model, provider.GroupPrefix) { + if q, m, ok := provider.Resolve(model); ok && !provider.IsGroupRef(model) { if q.ID != p.ID { return "", false } diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index 2e6508318..4352c4d6f 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -36,6 +36,7 @@ import ( "slices" "strings" "sync" + "testing" "time" "github.com/yetone/magpie/internal/edit" @@ -141,6 +142,69 @@ var sticks = struct { // sticksSaving keeps one write of the file at a time, the latest last. var sticksSaving sync.Mutex +// sticksFlushAfter is how long a conversation answered waits before the +// file is written: what is answered meanwhile goes in the same write, so a +// gateway answering many requests a second writes it once in a while, not +// once a request (up to 512 conversations marshalled, written and renamed +// on every answer, each after the last). A crash loses the last moment's; +// flushSticks, as the gateway ends, loses nothing. In a test binary it is +// 0, the file written at once, as it was: a write left waiting would +// outlive the test and write into its temp folder as it is removed. +var sticksFlushAfter = func() time.Duration { + if testing.Testing() { + return 0 + } + return 2 * time.Second +}() + +// sticksFlush is the write noteSticks has waiting, for the file at path. +var sticksFlush struct { + sync.Mutex + pending bool + path string +} + +// noteSticks has the file written within sticksFlushAfter: what this +// magpie answered is in memory at once. +func noteSticks() { + if sticksFlushAfter <= 0 { + saveSticks() + return + } + path := sticksPath() + sticksFlush.Lock() + if sticksFlush.pending && sticksFlush.path == path { + sticksFlush.Unlock() + return + } + sticksFlush.pending, sticksFlush.path = true, path + sticksFlush.Unlock() + time.AfterFunc(sticksFlushAfter, func() { flushSticksAt(path) }) +} + +// flushSticks writes what noteSticks has waiting: the gateway calls it as +// it ends, so the magpie it hands over to, or the next start, reads it. +func flushSticks() { flushSticksAt(sticksPath()) } + +// FlushSticks is flushSticks, for magpie ending on a signal before the +// gateway's own end. +func FlushSticks() { flushSticks() } + +// flushSticksAt writes the file at path when a write for it is waiting: +// one waiting for another (a test's HOME before this one's) is dropped. +func flushSticksAt(path string) { + sticksFlush.Lock() + if !sticksFlush.pending || sticksFlush.path != path { + sticksFlush.Unlock() + return + } + sticksFlush.pending = false + sticksFlush.Unlock() + if path == sticksPath() { + saveSticks() + } +} + // savedStick is a stick as the file has it. type savedStick struct { Rest string `json:"rest"` @@ -201,6 +265,11 @@ func stickOf(key string) (stick, bool) { func saveSticks() { sticksSaving.Lock() defer sticksSaving.Unlock() + sticksFlush.Lock() + if sticksFlush.path == sticksPath() { + sticksFlush.pending = false // this write is the one waiting + } + sticksFlush.Unlock() now := time.Now() type kept struct { k string @@ -600,7 +669,7 @@ func answered(key string, c candidate, turn int, u Usage) { } } sticks.Unlock() - saveSticks() + noteSticks() } // unanswered forgets that c answered a conversation, when its reply to it @@ -626,7 +695,7 @@ func unanswered(key string, c candidate) { } sticks.Unlock() if ok { - saveSticks() + noteSticks() } } diff --git a/internal/gateway/affinity_write_behind_test.go b/internal/gateway/affinity_write_behind_test.go new file mode 100644 index 000000000..2ff7c90b6 --- /dev/null +++ b/internal/gateway/affinity_write_behind_test.go @@ -0,0 +1,79 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "os" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// Who answered a conversation is written to affinity.json behind the +// answer, once in a while: each answer marshalled up to 512 conversations +// and wrote and renamed the file, one answer after another. +func TestSticksWrittenBehind(t *testing.T) { + fresh(t) + was := sticksFlushAfter + sticksFlushAfter = 2 * time.Second // as outside a test binary + t.Cleanup(func() { flushSticks(); sticksFlushAfter = was }) + sticks.Lock() + sticks.m = map[string]stick{} + sticks.Unlock() + os.Remove(sticksPath()) + c := candidate{p: provider.Provider{ID: "a", Key: "k"}, model: "m", rest: "a"} + for i := range 200 { + answered(fmt.Sprintf("conv-%d", i), c, 1, Usage{}) + } + if _, err := os.Stat(sticksPath()); err == nil { + t.Fatal("affinity.json written on a request answered") + } + sticks.Lock() + _, ok := stickOf("conv-199") + sticks.Unlock() + if !ok { + t.Fatal("the last answer isn't known in memory") + } + flushSticks() // as the gateway ends + b, err := os.ReadFile(sticksPath()) + if err != nil { + t.Fatalf("not written as the gateway ends: %v", err) + } + var saved map[string]savedStick + if err := json.Unmarshal(b, &saved); err != nil || len(saved) != 200 { + t.Fatalf("written %d conversations (%v), want 200", len(saved), err) + } + + // and by itself, a moment later + sticksFlushAfter = 10 * time.Millisecond + os.Remove(sticksPath()) + answered("conv-late", c, 1, Usage{}) + for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) { + if b, err := os.ReadFile(sticksPath()); err == nil && json.Unmarshal(b, &saved) == nil && saved["conv-late"].Who != "" { + break + } + if time.Now().After(deadline) { + t.Fatal("an answer never written") + } + } +} + +func BenchmarkAnswered(b *testing.B) { + was := sticksFlushAfter + sticksFlushAfter = 2 * time.Second // as outside a test binary + b.Cleanup(func() { flushSticks(); sticksFlushAfter = was }) + sticks.Lock() + sticks.m = map[string]stick{} + for i := range sticksKept { + sticks.m[fmt.Sprintf("conv-%d", i)] = stick{rest: "a", who: "a#k", model: "m", turn: 3, at: time.Now()} + } + sticks.Unlock() + c := candidate{p: provider.Provider{ID: "a", Key: "k"}, model: "m", rest: "a"} + b.ReportAllocs() + for i := 0; b.Loop(); i++ { + answered(fmt.Sprintf("conv-%d", i%sticksKept), c, 3, Usage{Input: 100}) + } + b.StopTimer() + flushSticks() +} diff --git a/internal/gateway/autoref_test.go b/internal/gateway/autoref_test.go new file mode 100644 index 000000000..506dd34fd --- /dev/null +++ b/internal/gateway/autoref_test.go @@ -0,0 +1,89 @@ +package gateway + +import ( + "encoding/json" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// A group magpie found is listed as auto/ (ZeroClover on X), and +// served by that id and by its old group/auto- alike: one group, one +// route, one name in the usage log, whichever an agent sent. +func TestFoundGroupServedByBothIDs(t *testing.T) { + fresh(t) + a, b := &keyed{}, &keyed{} + serveOn(t, "a", "ka", []string{"glm-5.3"}, a) + serveOn(t, "b", "kb", []string{"glm-5.3"}, b) + s := New() + + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil)) + var list struct{ Data []struct{ ID string } } + if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil { + t.Fatal(err) + } + var ids []string + for _, m := range list.Data { + ids = append(ids, m.ID) + } + if !slices.Contains(ids, "auto/glm-5.3") || slices.Contains(ids, "group/auto-glm-5-3") { + t.Fatalf("/v1/models: %v", ids) + } + + for _, model := range []string{"auto/glm-5.3", "group/auto-glm-5-3", "auto/GLM-5.3", "auto/glm-5-3"} { + code, body := postAs(t, s, "", `{"model":"`+model+`","messages":[{"role":"user","content":"hi `+model+`"}]}`) + if code != 200 { + t.Fatalf("%s: %d %s", model, code, body) + } + r := s.trace.routes[len(s.trace.routes)-1] + if r.Group == nil || r.Group.ID != "auto-glm-5-3" { + t.Fatalf("%s, not routed as the found group: %+v", model, r) + } + if u := lastUsage(t); u.Requested != "group/auto-glm-5-3" { + t.Errorf("%s logged as asked for %q", model, u.Requested) + } + } +} + +// A gateway key held to a found group passes for it by either id: one +// naming auto/, as the lists now give it, for an agent left on the +// old id, and one naming the old id, or group/*, for auto/. auto/* +// holds every found group by its new id. A key held to another group gets +// neither. +func TestKeyHeldToAFoundGroupByEitherID(t *testing.T) { + fresh(t) + serveOn(t, "a", "ka", []string{"glm-5.3", "x"}, &keyed{}) + serveOn(t, "b", "kb", []string{"glm-5.3", "x"}, &keyed{}) + if err := provider.SaveGroup(provider.Group{Name: "Other", Members: []string{"a/x"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + keys, secrets := newCaller(t, "k") + post := func(model string) int { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`)) + req.Header.Set("Authorization", "Bearer "+secrets[0]) + s.Handler().ServeHTTP(rec, req) + return rec.Code + } + for _, held := range [][]string{{"auto/glm-5.3"}, {"auto/glm-5-3"}, {"group/auto-glm-5-3"}, {"group/*"}, {"auto/*"}, {"group/other"}} { + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: held}); err != nil { + t.Fatal(err) + } + want := 200 + if held[0] == "group/other" { + want = 403 + } + for _, model := range []string{"auto/glm-5.3", "group/auto-glm-5-3"} { + if code := post(model); code != want { + t.Errorf("a key held to %v asking for %s: %d, want %d", held, model, code, want) + } + } + } +} diff --git a/internal/gateway/call_args_stream_test.go b/internal/gateway/call_args_stream_test.go new file mode 100644 index 000000000..e3da10263 --- /dev/null +++ b/internal/gateway/call_args_stream_test.go @@ -0,0 +1,217 @@ +package gateway + +import ( + "bufio" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// gatedCall is a Responses upstream that streams a call's first argument +// delta and then waits, before the rest of the call, until the test has +// seen that delta reach the client (or gives up). +type gatedCall struct { + name string // the function the upstream calls + first string // its first argument delta + rest string // the rest of its arguments + seen chan struct{} // closed by the test once the client has the first delta + wrote chan struct{} // closed by the upstream as it goes on to the rest +} + +func (g *gatedCall) ServeHTTP(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + f := w.(http.Flusher) + q := func(s string) string { b, _ := json.Marshal(s); return string(b) } + write := func(lines ...string) { + io.WriteString(w, sse(lines...)) + f.Flush() + } + write(`data: {"type":"response.created","response":{"id":"r1","model":"m"}}`, + `data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"`+g.name+`","arguments":""}}`, + `data: {"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":`+q(g.first)+`}`) + select { + case <-g.seen: + case <-time.After(20 * time.Second): + case <-r.Context().Done(): + return + } + close(g.wrote) + args := q(g.first + g.rest) + write(`data: {"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":`+q(g.rest)+`}`, + `data: {"type":"response.function_call_arguments.done","output_index":0,"item_id":"fc_1","arguments":`+args+`}`, + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"`+g.name+`","arguments":`+args+`,"status":"completed"}}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":5}}}`) +} + +// A call's arguments reach Codex as the upstream writes them, on the +// translated path its web_search sends a request down (echo_ts on Discord: +// on Copilot, Codex saw nothing for the minutes the model wrote a patch or +// a command, then all of it at once). A function's arguments come as +// function_call_arguments deltas, a custom tool's input (apply_patch) as +// custom_tool_call_input deltas, each before the upstream's call is done; +// the finished items are what they were. +func TestCallArgsStreamWhenTranslated(t *testing.T) { + const patch = "*** Begin Patch\n*** Add File: a.go\n+package a\n+// \"quoted\" \\ é 😀\n*** End Patch\n" + whole, _ := json.Marshal(map[string]string{"input": patch}) + split := 24 // inside the patch: {"input":"*** Begin Pat + for _, c := range []struct { + name, fn string + first, rest string + delta string // the event the client is given the call's text by + wantFirst string // what that event's first delta says + wantItemType string + }{ + {"function", "exec_command", `{"cmd":"go test ./...",`, `"yield_time_ms":1000}`, + "response.function_call_arguments.delta", `{"cmd":"go test ./...",`, "function_call"}, + {"custom", "apply_patch", string(whole[:split]), string(whole[split:]), + "response.custom_tool_call_input.delta", patch[:split-len(`{"input":"`)], "custom_tool_call"}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + up := &gatedCall{name: c.fn, first: c.first, rest: c.rest, seen: make(chan struct{}), wrote: make(chan struct{})} + vendor := httptest.NewServer(up) + t.Cleanup(vendor.Close) + if err := provider.Save(provider.Provider{ID: "rel", Name: "Rel", Key: "k", Responses: vendor.URL + "/v1", Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(New().Handler()) + t.Cleanup(srv.Close) + body := `{"model":"rel/m","stream":true,"input":[{"role":"user","content":"add a.go"}], + "tools":[{"type":"function","name":"exec_command","description":"Runs a command.","strict":false, + "parameters":{"type":"object","properties":{"cmd":{"type":"string"},"yield_time_ms":{"type":"number"}},"required":["cmd"]}}, + {"type":"custom","name":"apply_patch","description":"Edits files.","format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}}, + {"type":"web_search"}],"tool_choice":"auto"}` + res, err := http.Post(srv.URL+"/v1/responses", "application/json", strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if res.StatusCode != 200 { + b, _ := io.ReadAll(res.Body) + t.Fatalf("%d %s", res.StatusCode, b) + } + var deltas []string + var done map[string]any + early := false + sc := bufio.NewScanner(res.Body) + sc.Buffer(make([]byte, 1<<20), 1<<20) + for sc.Scan() { + data, ok := strings.CutPrefix(sc.Text(), "data: ") + if !ok { + continue + } + var ev struct { + Type string `json:"type"` + Delta string `json:"delta"` + Item map[string]any `json:"item"` + } + if json.Unmarshal([]byte(data), &ev) != nil { + continue + } + switch { + case ev.Type == c.delta: + if len(deltas) == 0 { + select { + case <-up.wrote: + default: + early = true // the upstream is still holding the rest + } + close(up.seen) + } + deltas = append(deltas, ev.Delta) + case ev.Type == "response.output_item.done" && ev.Item["type"] == c.wantItemType: + done = ev.Item + case ev.Type == "response.output_item.done" && done == nil: + // another kind of item: what the call came back as + done = ev.Item + } + } + if !early { + t.Fatalf("no %s before the upstream's call was done: deltas %q", c.delta, deltas) + } + if deltas[0] != c.wantFirst { + t.Errorf("first delta %q, want %q", deltas[0], c.wantFirst) + } + if done == nil || done["type"] != c.wantItemType { + t.Fatalf("finished item %v", done) + } + if c.wantItemType == "custom_tool_call" { + if done["input"] != patch || strings.Join(deltas, "") != patch { + t.Errorf("input %q, deltas %q, want %q", done["input"], strings.Join(deltas, ""), patch) + } + } else if done["arguments"] != c.first+c.rest || strings.Join(deltas, "") != c.first+c.rest { + t.Errorf("arguments %q, deltas %q", done["arguments"], strings.Join(deltas, "")) + } + }) + } +} + +// A custom tool's input read out of its arguments a piece at a time is +// the input the whole arguments hold, wherever the pieces are cut: in an +// escape, between a surrogate pair's halves, inside a character. +func TestCustomInputStreams(t *testing.T) { + patch := "*** Begin Patch\n+\"q\" \\ é 😀 &\t\n*** End Patch\n" + marshalled, _ := json.Marshal(map[string]string{"input": patch}) + for _, c := range []struct{ args, want string }{ + {string(marshalled), patch}, + {`{"input":"\ud83d\ude00 \u00e9\u0041\/\n"}`, "😀 éA/\n"}, + {`{"path":"a.go","input":"x\"y"}`, `x"y`}, + {`{"meta":{"input":"no","list":["input"]},"input":"yes"}`, "yes"}, + {`{ "input" : "spaced" }`, "spaced"}, + {`"a lone string"`, "a lone string"}, + {`{"input":"lone \ud83d half"}`, "lone \ufffd half"}, + {`{"input":5}`, ""}, + {`{"other":"x"}`, ""}, + {`not json`, ""}, + } { + for _, size := range []int{1, 2, 3, 5, 7, len(c.args)} { + var s customStream + var got strings.Builder + for i := 0; i < len(c.args); i += size { + got.WriteString(s.feed(c.args[i:min(i+size, len(c.args))])) + } + if got.String() != c.want { + t.Errorf("%s in pieces of %d: %q, want %q", c.args, size, got.String(), c.want) + } + if c.want != "" && customInput(c.args) != c.want { + t.Errorf("%s: customInput %q", c.args, customInput(c.args)) + } + } + } +} + +// A Responses upstream's argument deltas are given as they come, except +// those that make the arguments whole JSON, which wait for the call's done +// events: what was given and what follows add up to the fuller arguments. +func TestResponsesCallArgsStream(t *testing.T) { + var d responsesDecoder + var got []string + emit := func(ev Event) { + if ev.Kind == KToolArgs { + got = append(got, ev.Text) + } + } + d.decode(`{"type":"response.output_item.added","item":{"type":"function_call","call_id":"c1","name":"f"}}`, emit) + for _, x := range []string{`{"cmd":"a}`, `\"]{",`, `"n":[1,{}]`} { + q, _ := json.Marshal(x) + d.decode(`{"type":"response.function_call_arguments.delta","delta":`+string(q)+`}`, emit) + } + if want := []string{`{"cmd":"a}`, `\"]{",`, `"n":[1,{}]`}; strings.Join(got, "|") != strings.Join(want, "|") { + t.Fatalf("before the end %q, want %q", got, want) + } + d.decode(`{"type":"response.function_call_arguments.delta","delta":"}"}`, emit) + if len(got) != 3 { + t.Fatalf("the delta that makes it whole was given before the call's done: %q", got) + } + d.decode(`{"type":"response.output_item.done","item":{"type":"function_call","call_id":"c1","name":"f","arguments":"{\"cmd\":\"a}\\\"]{\",\"n\":[1,{}],\"more\":true}"}}`, emit) + if all := strings.Join(got, ""); all != `{"cmd":"a}\"]{","n":[1,{}],"more":true}` { + t.Fatalf("arguments %s", all) + } +} diff --git a/internal/gateway/cline_pin.go b/internal/gateway/cline_pin.go index 8c665e169..c78cdc075 100644 --- a/internal/gateway/cline_pin.go +++ b/internal/gateway/cline_pin.go @@ -8,8 +8,8 @@ import ( "github.com/yetone/magpie/internal/provider" ) -// clinePin is body with its DeepSeek model pinned to DeepSeek's own API -// on the Cline API, when the provider asks it (provider.PinUpstream): +// clinePin is body with its DeepSeek or GLM model pinned to its maker's +// own API (DeepSeek's, Z.ai's) on the Cline API, when the provider asks it (provider.PinUpstream): // providerOptions.gateway.only, which Cline's AI gateway reads to serve // the model from that host alone, as ClinePass + ProviderPin set it // (linux.do/t/topic/2918145). A body naming providerOptions itself is diff --git a/internal/gateway/cline_pin_test.go b/internal/gateway/cline_pin_test.go index 95b7bb41d..e1a0e4f06 100644 --- a/internal/gateway/cline_pin_test.go +++ b/internal/gateway/cline_pin_test.go @@ -15,10 +15,11 @@ import ( // the provider pins them (White Immortal on Discord, as ClinePass + // ProviderPin does): each request for one carries // providerOptions.gateway.only ["deepseek"], on Chat and when an Anthropic -// or Responses request is built into one. Its other models, Cline's free -// ones, a provider that doesn't pin, and a body naming providerOptions -// itself go as they were. -func TestClinePinsDeepSeek(t *testing.T) { +// or Responses request is built into one. Its GLM models are pinned to +// Z.ai's the same way, ["zai"] (sdytman on Discord). Its other makers' +// models, Cline's free ones, a provider that doesn't pin, and a body +// naming providerOptions itself go as they were. +func TestClinePinsDeepSeekAndGLM(t *testing.T) { t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("XDG_CACHE_HOME", t.TempDir()) cline, err := provider.FromPreset("clinepass") @@ -26,7 +27,7 @@ func TestClinePinsDeepSeek(t *testing.T) { t.Fatal(err) } cline.ID, cline.Key, cline.PinUpstream = "cline", "clp_key", true - cline.Models = []string{"cline-pass/deepseek-v4-pro", "cline-pass/glm-5.3", "cline-free/deepseek-v4.1-flash"} + cline.Models = []string{"cline-pass/deepseek-v4-pro", "cline-pass/glm-5.3", "cline-pass/glm-5.3-flash", "cline-pass/kimi-k3", "cline-pass/qwen3.8-max", "cline-free/deepseek-v4.1-flash", "cline-free/glm-5.3-flash"} plain := cline plain.ID, plain.Name, plain.PinUpstream = "cline2", "ClinePass 2", false for _, p := range []provider.Provider{cline, plain} { @@ -69,12 +70,25 @@ func TestClinePinsDeepSeek(t *testing.T) { if got := ask("/v1/responses", `{"model":"cline/cline-pass/deepseek-v4-pro","input":"Say pong","stream":false}`); got != pinned { t.Errorf("responses: providerOptions %s, want %s", got, pinned) } - for _, m := range []string{"cline/cline-pass/glm-5.3", "cline/cline-free/deepseek-v4.1-flash", "cline2/cline-pass/deepseek-v4-pro"} { + const zai = `{"gateway":{"only":["zai"]}}` + for _, m := range []string{"cline/cline-pass/glm-5.3", "cline/cline-pass/glm-5.3-flash"} { + if got := chat(m, ""); got != zai { + t.Errorf("%s: providerOptions %s, want %s (sent %s)", m, got, zai, sent) + } + } + if got := ask("/v1/messages", `{"model":"cline/cline-pass/glm-5.3","max_tokens":64,"messages":[{"role":"user","content":"Say pong"}]}`); got != zai { + t.Errorf("messages, GLM: providerOptions %s, want %s", got, zai) + } + for _, m := range []string{"cline/cline-pass/kimi-k3", "cline/cline-pass/qwen3.8-max", "cline/cline-free/deepseek-v4.1-flash", "cline/cline-free/glm-5.3-flash", "cline2/cline-pass/deepseek-v4-pro", "cline2/cline-pass/glm-5.3"} { if got := chat(m, ""); got != "" { t.Errorf("%s: providerOptions %s, want none", m, got) } } - if got := chat("cline/cline-pass/deepseek-v4-pro", `,"providerOptions":{"gateway":{"order":["novita"]}}`); got != `{"gateway":{"order":["novita"]}}` { - t.Errorf("the client's own providerOptions became %s", got) + for _, m := range []string{"cline/cline-pass/deepseek-v4-pro", "cline/cline-pass/glm-5.3"} { + // a second providerOptions after the client's would be the one a + // JSON reader keeps, so the body must hold the client's alone + if got := chat(m, `,"providerOptions":{"gateway":{"order":["novita"]}}`); got != `{"gateway":{"order":["novita"]}}` || strings.Count(string(sent), `"providerOptions"`) != 1 { + t.Errorf("%s: the client's own providerOptions became %s (sent %s)", m, got, sent) + } } } diff --git a/internal/gateway/codex_images.go b/internal/gateway/codex_images.go index c2e0554ce..e7c2e844b 100644 --- a/internal/gateway/codex_images.go +++ b/internal/gateway/codex_images.go @@ -2,17 +2,23 @@ package gateway import ( "bytes" + "container/list" "crypto/sha256" "encoding/base64" - "fmt" + "encoding/binary" "image" "image/draw" "image/gif" "image/jpeg" "image/png" + "io" "math" + "runtime" + "slices" "strings" "sync" + "sync/atomic" + "time" "github.com/tidwall/gjson" @@ -37,61 +43,153 @@ func codexImagesFit(p provider.Provider, to provider.Protocol, body []byte) []by if p.Account == nil || p.Account.Agent != "codex" || to != provider.Responses || !bytes.Contains(body, []byte(`input_image`)) { return body } - type swap struct { - at, end int - with string - } - var swaps []swap - var with []int // the input items with an image in them - i := 0 + // One walk of the body: each input item, and the parts of the items + // with an image in them, read where they sit. Looking each part up + // again by its path from the top read the body from its start for + // every image: in a Computer Use turn of 160 screenshots, gigabytes of + // JSON read for one request (fflake33, Discord). + var jobs []fitJob gjson.GetBytes(body, "input").ForEach(func(_, item gjson.Result) bool { - if strings.Contains(item.Raw, "input_image") { - with = append(with, i) + if !strings.Contains(item.Raw, "input_image") { + return true } - i++ + item.ForEach(func(key, parts gjson.Result) bool { + if key.Str != "content" && key.Str != "output" || !parts.IsArray() { + return true + } + parts.ForEach(func(_, part gjson.Result) bool { + // the part's members read once, not once for each + var kind, detail, url gjson.Result + part.ForEach(func(k, v gjson.Result) bool { + // the first of a key given twice, as Get reads it + switch { + case k.Str == "type" && !kind.Exists(): + kind = v + case k.Str == "detail" && !detail.Exists(): + detail = v + case k.Str == "image_url" && !url.Exists(): + url = v + } + return true + }) + if kind.String() != "input_image" { + return true + } + end := url.Index + len(url.Raw) + if url.Type != gjson.String || url.Index <= 0 || end > len(body) || string(body[url.Index:end]) != url.Raw || !strings.HasPrefix(url.Str, "data:") { + return true + } + if limits, ok := codexImageLimits(detail.String()); ok { + jobs = append(jobs, fitJob{at: url.Index, end: end, url: url.Str, l: limits}) + } + return true + }) + return true + }) return true }) - for _, i := range with { - for _, key := range []string{"content", "output"} { - parts := gjson.GetBytes(body, fmt.Sprintf("input.%d.%s", i, key)) - if !parts.IsArray() { - continue - } - for j := range parts.Array() { - part := gjson.GetBytes(body, fmt.Sprintf("input.%d.%s.%d", i, key, j)) - if part.Get("type").String() != "input_image" { - continue - } - url := gjson.GetBytes(body, fmt.Sprintf("input.%d.%s.%d.image_url", i, key, j)) - if url.Type != gjson.String || url.Index <= 0 || !strings.HasPrefix(url.Str, "data:") { - continue - } - limits, ok := codexImageLimits(part.Get("detail").String()) - if !ok { - continue - } - if fit, ok := codexImageFit(url.Str, limits); ok { - swaps = append(swaps, swap{url.Index, url.Index + len(url.Raw), `"` + fit + `"`}) - } - } - } - } - if len(swaps) == 0 { + if len(jobs) == 0 { return body } + fitAll(jobs) + slices.SortFunc(jobs, func(a, b fitJob) int { return a.at - b.at }) // the rest of the request goes byte for byte as it came, for the // prompt cache var out bytes.Buffer - last := 0 - for _, s := range swaps { - out.Write(body[last:s.at]) - out.WriteString(s.with) - last = s.end + last, swapped := 0, false + for _, j := range jobs { + if !j.changed || j.at < last { + continue + } + if !swapped { + out.Grow(len(body)) + swapped = true + } + out.Write(body[last:j.at]) + out.WriteByte('"') + out.WriteString(j.with) + out.WriteByte('"') + last = j.end + } + if !swapped { + return body } out.Write(body[last:]) return out.Bytes() } +// fitJob is one image of a request: where its data URL's JSON string +// sits, the URL, the limits it is fitted to, and what it is sent as. +type fitJob struct { + at, end int + url string + l imageLimits + key [32]byte + with string + changed bool +} + +// fitWorkers is how many images of a request are made again at once: +// each holds a decoded screenshot and its resize, near 100 MB for a +// Retina one. +const fitWorkers = 4 + +// fitAll fits each job's image: as it was kept (fitted), or else made +// again, the images not kept made side by side. +func fitAll(jobs []fitJob) { + fitted.letGo() + var todo []int + for i := range jobs { + j := &jobs[i] + comma := strings.IndexByte(j.url, ',') + if comma < 0 || !strings.HasSuffix(j.url[:comma], ";base64") { + continue + } + j.key = fitKey(j.url, j.l) + if e, ok := fitted.get(j.key); ok { + j.with, j.changed = e.url(), e.data != nil + continue + } + todo = append(todo, i) + } + if len(todo) == 0 { + return + } + // the same screenshot twice in a request is made once + made := map[[32]byte]*fitEntry{} + var order []int + for _, i := range todo { + if _, ok := made[jobs[i].key]; !ok { + made[jobs[i].key] = &fitEntry{} + order = append(order, i) + } + } + next := make(chan int) + var wg sync.WaitGroup + for range min(fitWorkers, runtime.GOMAXPROCS(0), len(order)) { + wg.Add(1) + go func() { + defer wg.Done() + for i := range next { + j := jobs[i] + *made[j.key] = codexImageRefit(j.url[strings.IndexByte(j.url, ',')+1:], j.l) + } + }() + } + for _, i := range order { + next <- i + } + close(next) + wg.Wait() + for _, i := range order { + fitted.put(jobs[i].key, *made[jobs[i].key]) + } + for _, i := range todo { + e := made[jobs[i].key] + jobs[i].with, jobs[i].changed = e.url(), e.data != nil + } +} + type imageLimits struct{ side, patches int } // codexPatch is the patch a Responses model reads an image in. @@ -138,52 +236,130 @@ func (l imageLimits) size(w, h int) (int, int) { // to hold: one past it goes as it came. const codexImageMaxPixels = 80 << 20 -// fitted holds what codexImageFit made of the images a conversation -// sends again on every turn. -var fitted = struct { - sync.Mutex - m map[[32]byte]string -}{m: map[[32]byte]string{}} - -// codexImageFit is a data URL's image as Codex's client would send it, -// and whether that differs from what came. -func codexImageFit(url string, l imageLimits) (string, bool) { - comma := strings.IndexByte(url, ',') - if comma < 0 || !strings.HasSuffix(url[:comma], ";base64") { - return "", false - } - key := sha256.Sum256([]byte(fmt.Sprint(l.side, l.patches, url))) - fitted.Lock() - got, ok := fitted.m[key] - fitted.Unlock() - if ok { - return got, got != "" - } - got = codexImageRefit(url[comma+1:], l) - fitted.Lock() - if len(fitted.m) >= 64 { - clear(fitted.m) - } - fitted.m[key] = got - fitted.Unlock() - return got, got != "" +// fitEntry is what an image is sent as: data in mime, or, with no data, +// the image as it came. +type fitEntry struct { + mime string + data []byte } -// codexImageRefit is the data URL of an image's base64 resized and -// written again, or "" when it goes as it came. -func codexImageRefit(b64 string, l imageLimits) string { +// url is the entry's data URL, or "" for the image as it came. +func (e fitEntry) url() string { + if e.data == nil { + return "" + } + return "data:" + e.mime + ";base64," + base64.StdEncoding.EncodeToString(e.data) +} + +// fitKey names an image's data URL fitted to l. +func fitKey(url string, l imageLimits) [32]byte { + h := sha256.New() + var n [16]byte + binary.LittleEndian.PutUint64(n[:8], uint64(l.side)) + binary.LittleEndian.PutUint64(n[8:], uint64(l.patches)) + h.Write(n[:]) + io.WriteString(h, url) + var k [32]byte + h.Sum(k[:0]) + return k +} + +// fitted holds what codexImageRefit made of the images a conversation +// sends again on every turn, so that a past screenshot is decoded, resized +// and encoded once, not on each turn. It is bounded by the bytes it holds +// (fittedBudget), dropping the least recently used first, and drops what +// no request has sent for fittedIdle. The 64-entry map it replaces was +// cleared when full, so past 64 screenshots every turn made each of them +// again (fflake33, Discord). +// +// A request looks up all its images before it keeps any it made, so a +// conversation larger than the budget still finds the images kept since +// its last turn, rather than dropping each just before it is sent again. +var fitted = &fitCache{m: map[[32]byte]*list.Element{}} + +// fittedBudget is how many bytes of fitted images are kept, and +// fittedIdle how long one is kept unsent. fittedMost bounds the entries, +// as most images go as they came and hold no bytes. +var ( + fittedBudget = 256 << 20 + fittedIdle = time.Hour + fittedMost = 8192 +) + +type fitCache struct { + sync.Mutex + m map[[32]byte]*list.Element + order list.List // of *fitItem, the most recently used first + bytes int +} + +type fitItem struct { + key [32]byte + e fitEntry + used time.Time +} + +// letGo drops what has gone unsent for fittedIdle. +func (c *fitCache) letGo() { + c.Lock() + defer c.Unlock() + now := time.Now() + for back := c.order.Back(); back != nil && now.Sub(back.Value.(*fitItem).used) > fittedIdle; back = c.order.Back() { + c.drop(back) + } +} + +func (c *fitCache) get(k [32]byte) (fitEntry, bool) { + c.Lock() + defer c.Unlock() + el, ok := c.m[k] + if !ok { + return fitEntry{}, false + } + it := el.Value.(*fitItem) + it.used = time.Now() + c.order.MoveToFront(el) + return it.e, true +} + +func (c *fitCache) put(k [32]byte, e fitEntry) { + c.Lock() + defer c.Unlock() + if _, ok := c.m[k]; ok || len(e.data) > fittedBudget { + return + } + for c.bytes+len(e.data) > fittedBudget || len(c.m) >= fittedMost { + c.drop(c.order.Back()) + } + c.m[k] = c.order.PushFront(&fitItem{key: k, e: e, used: time.Now()}) + c.bytes += len(e.data) +} + +func (c *fitCache) drop(el *list.Element) { + it := c.order.Remove(el).(*fitItem) + delete(c.m, it.key) + c.bytes -= len(it.e.data) +} + +// refits counts the images codexImageRefit decodes and writes again. +var refits atomic.Int64 + +// codexImageRefit is an image's base64 resized and written again, or an +// entry with no data when it goes as it came. +func codexImageRefit(b64 string, l imageLimits) fitEntry { raw, err := base64.StdEncoding.DecodeString(b64) if err != nil { - return "" + return fitEntry{} } cfg, format, err := image.DecodeConfig(bytes.NewReader(raw)) if err != nil || cfg.Width*cfg.Height > codexImageMaxPixels { - return "" + return fitEntry{} } w, h := l.size(cfg.Width, cfg.Height) if w == cfg.Width && h == cfg.Height && format != "gif" { - return "" + return fitEntry{} } + refits.Add(1) var src image.Image switch format { case "png": @@ -193,10 +369,10 @@ func codexImageRefit(b64 string, l imageLimits) string { case "gif": src, err = gif.Decode(bytes.NewReader(raw)) default: - return "" + return fitEntry{} } if err != nil { - return "" + return fitEntry{} } if w != cfg.Width || h != cfg.Height { src = triangleResize(src, w, h) @@ -210,9 +386,9 @@ func codexImageRefit(b64 string, l imageLimits) string { err = png.Encode(&out, src) } if err != nil { - return "" + return fitEntry{} } - return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(out.Bytes()) + return fitEntry{mime: mime, data: out.Bytes()} } // triangleResize scales src to w by h with a triangle (linear) filter diff --git a/internal/gateway/codex_images_test.go b/internal/gateway/codex_images_test.go index 47b381868..4c0e815cf 100644 --- a/internal/gateway/codex_images_test.go +++ b/internal/gateway/codex_images_test.go @@ -2,8 +2,10 @@ package gateway import ( "bytes" + "container/list" "encoding/base64" "encoding/json" + "fmt" "image" "image/color" "image/jpeg" @@ -14,6 +16,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/tidwall/gjson" @@ -265,3 +268,133 @@ func TestCodexAccountGetsScreenshotAtCodexSize(t *testing.T) { } t.Logf("%d bytes from the agent, %d to ChatGPT", len(body), len(got)) } + +// freshFitted gives a test a cache of fitted images of its own, with +// budget bytes, and counts the images made again from here. +func freshFitted(t *testing.T, budget int) func() int64 { + t.Helper() + was, wasBudget := fitted, fittedBudget + fitted, fittedBudget = &fitCache{m: map[[32]byte]*list.Element{}}, budget + t.Cleanup(func() { fitted, fittedBudget = was, wasBudget }) + from := refits.Load() + return func() int64 { return refits.Load() - from } +} + +// computerUseRequest is a Responses turn with each of shots as a +// Computer Use tool's screenshot, as Codex sends a conversation's every +// past screenshot again on each turn. +func computerUseRequest(shots []string) []byte { + var input []any + for i, shot := range shots { + id := fmt.Sprintf("call_%d", i) + input = append(input, + map[string]any{"type": "function_call", "call_id": id, "name": "computer", "arguments": `{"action":"screenshot"}`}, + map[string]any{"type": "function_call_output", "call_id": id, "output": []any{ + map[string]any{"type": "input_image", "image_url": shot}}}) + } + b, _ := json.Marshal(map[string]any{"model": "gpt-5.5", "stream": true, "input": input}) + return b +} + +// wideShots are n distinct PNGs wider than Codex sends, each made +// smaller once it is fitted: cheap to make, as a test needs. +func wideShots(t *testing.T, n int) []string { + t.Helper() + out := make([]string, n) + for i := range out { + m := image.NewRGBA(image.Rect(0, 0, 2100, 4)) + for x := 0; x < 2100; x++ { + m.SetRGBA(x, i%4, color.RGBA{byte(i), byte(i >> 8), byte(x), 255}) + } + out[i] = shotURL(t, m, "png") + } + return out +} + +// A long Computer Use conversation (fflake33, Discord: hundreds of +// screenshots) sends every past screenshot again on each turn. Each is +// decoded, resized and written again once; the next turn makes only its +// new one, past the 64 images the cache held, and sends the others as the +// same bytes as before, which the prompt cache needs. +func TestCodexScreenshotsAreNotFittedAgainEachTurn(t *testing.T) { + made := freshFitted(t, fittedBudget) + shots := wideShots(t, 101) + first := codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[:100])) + if n := made(); n != 100 { + t.Fatalf("the first turn made %d images, want 100", n) + } + next := codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots)) + if n := made() - 100; n != 1 { + t.Errorf("the next turn made %d images again, want only its new one", n) + } + for i := range 100 { + path := fmt.Sprintf("input.%d.output.0.image_url", 2*i+1) + was, now := gjson.GetBytes(first, path).String(), gjson.GetBytes(next, path).String() + if was == shots[i] || now != was { + t.Fatalf("screenshot %d: not the same fitted bytes on the next turn", i) + } + } + m, _ := shotDecode(t, gjson.GetBytes(next, "input.201.output.0.image_url").String()) + if m.Bounds().Dx() != 2048 { + t.Errorf("the new screenshot went at %v", m.Bounds()) + } +} + +// Past what the cache may hold, each turn still finds the screenshots kept +// since the last and makes only the rest again. Keeping each image as it +// is made, in a conversation whose images come in the same order each +// turn, would drop each one just before it is sent again and find none. +// What is held stays within the budget. +func TestCodexFittedImagesPastTheBudget(t *testing.T) { + shots := wideShots(t, 30) + one := len(fitKeyEntry(t, shots[0]).data) + made := freshFitted(t, 10*one+one/2) + body := computerUseRequest(shots) + was := int64(0) + for turn := 1; turn <= 3; turn++ { + codexImagesFit(codexAccount(), provider.Responses, body) + n := made() - was + was += n + if turn == 1 && n != 30 || turn > 1 && n != 20 { + t.Errorf("turn %d made %d of 30 images, with 10 kept", turn, n) + } + fitted.Lock() + held := fitted.bytes + fitted.Unlock() + if held > fittedBudget { + t.Errorf("turn %d: %d bytes held, past the budget of %d", turn, held, fittedBudget) + } + } +} + +// fitKeyEntry is shot fitted to Codex's high limits, made directly. +func fitKeyEntry(t *testing.T, shot string) fitEntry { + t.Helper() + e := codexImageRefit(shot[strings.IndexByte(shot, ',')+1:], imageLimits{2048, 2500}) + if e.data == nil { + t.Fatal("the screenshot fits as it came") + } + return e +} + +// What no request has sent for fittedIdle is let go. +func TestCodexFittedImagesLetGoWhenIdle(t *testing.T) { + made := freshFitted(t, fittedBudget) + shots := wideShots(t, 2) + codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[:1])) + fitted.Lock() + for el := fitted.order.Front(); el != nil; el = el.Next() { + el.Value.(*fitItem).used = time.Now().Add(-fittedIdle - time.Minute) + } + fitted.Unlock() + codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[1:])) + fitted.Lock() + n, held := len(fitted.m), fitted.bytes + fitted.Unlock() + if n != 1 || made() != 2 { + t.Errorf("%d kept after the first went idle, %d made", n, made()) + } + if want := len(fitKeyEntry(t, shots[1]).data); held != want { + t.Errorf("%d bytes held, want %d", held, want) + } +} diff --git a/internal/gateway/codex_images_timing_test.go b/internal/gateway/codex_images_timing_test.go new file mode 100644 index 000000000..1d08b5f62 --- /dev/null +++ b/internal/gateway/codex_images_timing_test.go @@ -0,0 +1,203 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "image" + "image/jpeg" + "io" + "math/rand/v2" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime/pprof" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// computerUseShots are n distinct w×h JPEG screenshots as data URLs: a +// desktop with noise along its top, so each is as large as a real one, +// and a stamp that makes each its own. +func computerUseShots(n, w, h int) []string { + base := shotImage(w, h) + noise := rand.New(rand.NewPCG(3, 4)) + for i := 0; i < 200*base.Stride; i++ { + if i%4 != 3 { + base.Pix[i] = byte(noise.Uint32()) + } + } + out := make([]string, n) + var wg sync.WaitGroup + sem := make(chan struct{}, 8) + for i := range n { + wg.Add(1) + sem <- struct{}{} + go func() { + defer wg.Done() + defer func() { <-sem }() + m := image.NewRGBA(base.Rect) + copy(m.Pix, base.Pix) + for y := 300; y < 364; y++ { + for x := 0; x < 64; x++ { + o := y*m.Stride + (x+(i%40)*64)*4 + m.Pix[o], m.Pix[o+1], m.Pix[o+2] = byte(i), byte(i*7), byte(i*13) + } + } + var b bytes.Buffer + jpeg.Encode(&b, m, &jpeg.Options{Quality: 85}) + out[i] = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(b.Bytes()) + }() + } + wg.Wait() + return out +} + +// computerUseTurn is a long Computer Use conversation as Codex sends it on +// the Responses API: each step a user or assistant message, a tool call +// and the tool's output with its screenshot. +func computerUseTurn(model string, shots []string) []byte { + para := strings.Repeat("Clicked the button in the toolbar, waited for the sheet and read what it says. ", 30) + var input []any + for i, shot := range shots { + id := fmt.Sprintf("call_%04d", i) + input = append(input, + map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": para}}}, + map[string]any{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": para}}}, + map[string]any{"type": "function_call", "call_id": id, "name": "computer", "arguments": `{"action":"screenshot"}`}, + map[string]any{"type": "function_call_output", "call_id": id, "output": []any{ + map[string]any{"type": "input_text", "text": "screenshot taken"}, + map[string]any{"type": "input_image", "image_url": shot}}}, + ) + } + input = append(input, map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "go on"}}}) + b, _ := json.Marshal(map[string]any{"model": model, "stream": true, "instructions": para, "input": input}) + return b +} + +// turnTimer stands in for an upstream that answers at once, and notes when +// each request reached it: the time from the agent's request to then is +// magpie's own work on it, the upload to a local server aside. +type turnTimer struct { + mu sync.Mutex + arrived time.Time +} + +func (tt *turnTimer) handler(w http.ResponseWriter, r *http.Request) { + tt.mu.Lock() + tt.arrived = time.Now() + tt.mu.Unlock() + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6.1-sol"}}`, + `data: {"type":"response.output_text.delta","delta":"ok"}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":7,"output_tokens":2}}}`)) +} + +// turn sends body to s and says how long magpie took before the upstream +// had it, and in all. Its CPU profile samples carry the label turn=name, +// for pprof's -tagfocus: on a loaded machine the time a turn's work took +// says more than how long it waited. +func (tt *turnTimer) turn(t *testing.T, s *Server, body []byte, name string) (local, all time.Duration) { + t.Helper() + start := time.Now() + rec := httptest.NewRecorder() + pprof.Do(context.Background(), pprof.Labels("turn", name), func(context.Context) { + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", bytes.NewReader(body))) + }) + all = time.Since(start) + if rec.Code != 200 { + t.Fatalf("status %d: %.300s", rec.Code, rec.Body.String()) + } + tt.mu.Lock() + defer tt.mu.Unlock() + return tt.arrived.Sub(start), all +} + +// TestComputerUseTurnTiming times magpie's own work on a long Computer +// Use turn to a ChatGPT account, as fflake33's (Discord): the first turn, +// and the next, which sends every past screenshot again. Run it with +// MAGPIE_TURN_TIMING=1 (and -cpuprofile/-memprofile to see where). +func TestComputerUseTurnTiming(t *testing.T) { + if os.Getenv("MAGPIE_TURN_TIMING") == "" { + t.Skip("MAGPIE_TURN_TIMING=1 times a long Computer Use turn") + } + codexSignedIn(t) + tt := &turnTimer{} + up := httptest.NewServer(http.HandlerFunc(tt.handler)) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + + n := 160 + fmt.Sscan(os.Getenv("MAGPIE_TURN_SHOTS"), &n) + start := time.Now() + shots := computerUseShots(n+3, 2940, 1912) + t.Logf("%d screenshots made in %v", n+3, time.Since(start)) + s := New() + for turn := 1; turn <= 4; turn++ { + // each turn adds a screenshot to those sent before + body := computerUseTurn("codex/gpt-5.5", shots[:n+turn-1]) + local, all := tt.turn(t, s, body, fmt.Sprint(turn)) + t.Logf("turn %d: %d images, %d MB: magpie %v before the upstream had it, %v in all", turn, n+turn-1, len(body)>>20, local, all) + } +} + +// TestCopilotLongTurnTiming times magpie's own work on a long Codex turn +// with no images to a Copilot account (echo_ts, Discord). Run it with +// MAGPIE_TURN_TIMING=1. +func TestCopilotLongTurnTiming(t *testing.T) { + if os.Getenv("MAGPIE_TURN_TIMING") == "" { + t.Skip("MAGPIE_TURN_TIMING=1 times a long Copilot turn") + } + fresh(t) + cfg := os.Getenv("XDG_CONFIG_HOME") + os.MkdirAll(filepath.Join(cfg, "github-copilot"), 0o755) + os.WriteFile(filepath.Join(cfg, "github-copilot", "apps.json"), mustJSON(map[string]any{ + "github.com:Iv1.x": map[string]any{"user": "echo", "oauth_token": "gho_timing"}, + }), 0o600) + tt := &turnTimer{} + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/models" { + io.WriteString(w, `{"data":[{"id":"gpt-6.1-sol","name":"GPT-6.1 Sol","model_picker_enabled":true,"policy":{"state":"enabled"},"supported_endpoints":["/responses"],"capabilities":{"type":"chat","supports":{"reasoning_effort":["low","medium","high"]}}}]}`) + return + } + tt.handler(w, r) + })) + t.Cleanup(api.Close) + gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/token") { + json.NewEncoder(w).Encode(map[string]any{"token": "sess", "expires_at": time.Now().Add(time.Hour).Unix(), "endpoints": map[string]string{"api": api.URL}}) + return + } + io.WriteString(w, `{"copilot_plan":"individual","access_type_sku":"monthly_subscriber_quota"}`) + })) + t.Cleanup(gh.Close) + oldTok, oldUser := provider.CopilotTokenURL, provider.CopilotUserURL + provider.CopilotTokenURL, provider.CopilotUserURL = gh.URL+"/token", gh.URL+"/user" + t.Cleanup(func() { provider.CopilotTokenURL, provider.CopilotUserURL = oldTok, oldUser }) + p, err := provider.Find("copilot") + if err != nil { + t.Fatal(err) + } + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + s := New() + for _, words := range []int{2_000, 30_000, 150_000} { + body := largeConversation(provider.Responses, "copilot/gpt-6.1-sol", words) + for turn := 1; turn <= 3; turn++ { + local, all := tt.turn(t, s, body, fmt.Sprintf("%dk-%d", words/1000, turn)) + t.Logf("%d KB, turn %d: magpie %v before the upstream had it, %v in all", len(body)>>10, turn, local, all) + } + } +} diff --git a/internal/gateway/codex_ultra_test.go b/internal/gateway/codex_ultra_test.go index b6e13dbc2..925cb4830 100644 --- a/internal/gateway/codex_ultra_test.go +++ b/internal/gateway/codex_ultra_test.go @@ -25,6 +25,7 @@ import ( type copilotUp struct { mu sync.Mutex bodies []map[string]any + reply string // a stream to answer with, in place of the made one } func (c *copilotUp) last(t *testing.T) map[string]any { @@ -59,7 +60,13 @@ func copilotSol(t *testing.T) *copilotUp { json.Unmarshal(b, &body) c.mu.Lock() c.bodies = append(c.bodies, body) + reply := c.reply c.mu.Unlock() + if reply != "" { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, reply) + return + } message := "Find the release date of Codex 0.159 and report it." if strings.Contains(string(b), `"encrypted"`) { message = "gAAAAAsealed==" @@ -177,12 +184,13 @@ func TestCopilotSolOffersUltra(t *testing.T) { } } -// Ultra's subagents with Codex's web_search kept (#656): a request offering -// the search is made again for Copilot rather than relayed, and on that -// path a Copilot lead's spawn_agent comes back to Codex unsealed, with the -// task as written (Copilot not asked to seal it), and the subagent's -// request — the task as MultiAgentV2's agent_message — reaches Copilot as -// the task's text. +// Ultra's subagents with Codex's web_search kept (#656): a lead whose +// spawn_agent marks its message "encrypted" is made again for Copilot +// rather than relayed, as Copilot can't open what it seals, and on that +// path its spawn_agent comes back to Codex unsealed, with the task as +// written (Copilot not asked to seal it). The subagent's request, which +// marks nothing, is relayed with the search (Copilot runs web_search +// itself), the task as MultiAgentV2's agent_message as Codex sent it. func TestCopilotUltraSubagentWithWebSearch(t *testing.T) { c := copilotSol(t) s := New() @@ -240,10 +248,52 @@ func TestCopilotUltraSubagentWithWebSearch(t *testing.T) { if code != 200 { t.Fatalf("subagent: %d %s", code, out) } - sent, _ := json.Marshal(c.last(t)["input"]) - if !strings.Contains(string(sent), task) || strings.Contains(string(sent), "encrypted_content") { + sub := c.last(t) + sent, _ := json.Marshal(sub["input"]) + if !strings.Contains(string(sent), task) || !strings.Contains(string(sent), `"agent_message"`) || strings.Contains(string(sent), "encrypted_content") { t.Fatalf("subagent's input to Copilot: %s", sent) } + if offered, _ := json.Marshal(sub["tools"]); string(offered) != `[{"type":"web_search"}]` { + t.Fatalf("subagent's tools to Copilot: %s", offered) + } +} + +// A Codex turn on Copilot offering web_search is relayed as Codex sent it, +// as Copilot runs the search itself (echo_ts on Discord: translated for +// magpie's search, every turn lost the relay); one whose tools mark an +// argument "encrypted" is made again unmarked, with the search or without, +// since Copilot seals that argument and can't open it on the next turn. +func TestCopilotRelayedUnlessAskedToSeal(t *testing.T) { + c := copilotSol(t) + s := New() + spawn := `{"type":"namespace","name":"collaboration","description":"Sub-agents.","tools":[ + {"type":"function","name":"spawn_agent","strict":false,"description":"Spawns an agent.", + "parameters":{"type":"object","properties":{"message":{"type":"string","encrypted":true}},"required":["message"]}}]}` + exec := `{"type":"function","name":"exec_command","description":"Runs a command, \"encrypted\" or not.","strict":false, + "parameters":{"type":"object","properties":{"cmd":{"type":"string"},"encrypted":{"type":"boolean"}},"required":["cmd"]}}` + for _, tc := range []struct { + name, tools string + relayed bool + }{ + {"search", exec + `,{"type":"web_search"}`, true}, + {"search and a sealed argument", spawn + `,` + exec + `,{"type":"web_search"}`, false}, + {"a sealed argument alone", spawn, false}, + } { + code, out := postTo(t, s, "/v1/responses", `{"model":"copilot/gpt-6-luna","stream":true,"input":[{"role":"user","content":"hi"}],"probe":"as sent","tools":[`+tc.tools+`]}`) + if code != 200 { + t.Fatalf("%s: %d %s", tc.name, code, out) + } + // a field magpie doesn't know goes on only as Codex sent it + body := c.last(t) + sent, _ := json.Marshal(body["tools"]) + relayed := body["probe"] == "as sent" + if relayed != tc.relayed { + t.Errorf("%s: relayed %v, tools to Copilot %s", tc.name, relayed, sent) + } + if !tc.relayed && strings.Contains(string(sent), `"encrypted":true`) { + t.Errorf("%s: Copilot was asked to seal: %s", tc.name, sent) + } + } } // Ultra is Codex's, no API's: a model whose list says "ultra" (ChatGPT's diff --git a/internal/gateway/collector_text_test.go b/internal/gateway/collector_text_test.go new file mode 100644 index 000000000..5a5efc67d --- /dev/null +++ b/internal/gateway/collector_text_test.go @@ -0,0 +1,88 @@ +package gateway + +import ( + "runtime" + "strings" + "testing" +) + +// collectStream is a streamed reply as the collector takes it: n deltas +// of thinking, then n of text, then a tool call and more text. +func collectStream(c *collector, n int) { + c.add(Event{Kind: KStart, MsgID: "m", Model: "x"}) + for i := range n { + c.add(Event{Kind: KThink, Text: "think " + string(rune('a'+i%26)) + " "}) + } + c.add(Event{Kind: KSig, Text: "sig"}) + for i := range n { + c.add(Event{Kind: KText, Text: "word " + string(rune('a'+i%26)) + " of the reply, "}) + } + c.add(Event{Kind: KToolStart, ID: "t1", Name: "Read"}) + c.add(Event{Kind: KToolArgs, Text: `{"path":"/a"}`}) + c.add(Event{Kind: KText, Text: "after "}) + c.add(Event{Kind: KText, Text: "the call"}) + c.add(Event{Kind: KStop, Stop: "stop"}) +} + +// The collector's reply is the stream's, delta for delta: each part's +// text whole, in its own part, a part begun after a call its own. +func TestCollectorKeepsEveryDelta(t *testing.T) { + var c collector + collectStream(&c, 500) + res := c.finish() + var think, text strings.Builder + for i := range 500 { + think.WriteString("think " + string(rune('a'+i%26)) + " ") + text.WriteString("word " + string(rune('a'+i%26)) + " of the reply, ") + } + if len(res.Parts) != 4 { + t.Fatalf("parts %+v", res.Parts) + } + if p := res.Parts[0]; p.Kind != Thinking || p.Text != think.String() || p.Signature != "sig" { + t.Errorf("thinking %q sig %q", p.Text[:min(40, len(p.Text))], p.Signature) + } + if p := res.Parts[1]; p.Kind != Text || p.Text != text.String() { + t.Errorf("text %d bytes, want %d", len(p.Text), text.Len()) + } + if p := res.Parts[2]; p.Kind != ToolCall || string(p.Args) != `{"path":"/a"}` { + t.Errorf("call %+v", p) + } + if p := res.Parts[3]; p.Kind != Text || p.Text != "after the call" { + t.Errorf("last text %q", p.Text) + } +} + +// A streamed reply's text is gathered in time linear in its length: the +// collector used to add each delta to the part's string, copying the whole +// reply so far every time, about 57 KB a delta on a 4000-delta reply (a +// Chat upstream to an Anthropic client copied 229 MB to stream 88 KB). +func TestCollectorTextLinear(t *testing.T) { + const n = 4000 + var ms runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&ms) + before := ms.TotalAlloc + var c collector + collectStream(&c, n) + res := c.finish() + runtime.ReadMemStats(&ms) + got := ms.TotalAlloc - before + size := 0 + for _, p := range res.Parts { + size += len(p.Text) + } + // the strings themselves, the builder's doublings, the parts: a few + // times the reply. The quadratic copy was ~150× it here. + if got > uint64(16*size) { + t.Fatalf("collecting a %d-byte reply allocated %d bytes (%.0f×)", size, got, float64(got)/float64(size)) + } +} + +func BenchmarkCollectorText(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + var c collector + collectStream(&c, 4000) + c.finish() + } +} diff --git a/internal/gateway/custom_tool.go b/internal/gateway/custom_tool.go index da54f83a6..715395018 100644 --- a/internal/gateway/custom_tool.go +++ b/internal/gateway/custom_tool.go @@ -4,6 +4,8 @@ import ( "bytes" "encoding/json" "regexp" + "strconv" + "unicode/utf8" ) // Codex offers custom tools on Responses (exec in code mode, apply_patch): @@ -64,3 +66,144 @@ func customIn(v any) bool { } return false } + +// customStream gives a custom tool's input as its call's arguments come, +// a piece at a time: the text of the input string in {"input":"…"} (or of +// a lone JSON string), unescaped, as the custom_tool_call_input deltas a +// client reads while the model writes a patch. What can't be read yet (an +// escape or a character cut off) waits for the next piece. The finished +// item's input is still customInput's of the whole arguments; arguments +// of another shape stream nothing. +type customStream struct { + pend []byte // of the input string, read and not given yet + depth int + str bool // in a string that isn't the input + esc bool // after its backslash + key []byte // the depth-1 key being read, raw + inKey bool // the string being read is that key + want bool // a key is next, at depth 1 + last string // the last depth-1 key + value bool // the depth-1 value next is the input's + in bool // in the input string + over bool // the input is given, or there is none +} + +// feed reads the next piece of the arguments and gives what it adds to +// the input. +func (c *customStream) feed(s string) string { + if c.over { + return "" + } + if c.in { + c.pend = append(c.pend, s...) + return c.take() + } + for i := 0; i < len(s); i++ { + b := s[i] + switch { + case c.str: + if c.inKey { + c.key = append(c.key, b) + } + switch { + case c.esc: + c.esc = false + case b == '\\': + c.esc = true + case b == '"': + c.str = false + if c.inKey { + c.inKey = false + c.last = "" + json.Unmarshal(append([]byte{'"'}, c.key...), &c.last) + } + } + case b == '"' && (c.depth == 0 || c.depth == 1 && c.value): + c.in = true + c.pend = append(c.pend, s[i+1:]...) + return c.take() + case b == '"': + c.str = true + if c.depth == 1 && c.want { + c.inKey, c.key, c.want = true, c.key[:0], false + } + case b == '{' || b == '[': + c.depth++ + if c.depth == 1 && b == '{' { + c.want = true + } + case b == '}' || b == ']': + if c.depth--; c.depth <= 0 { + c.over = true + return "" + } + case b == ':' && c.depth == 1: + c.value = c.last == "input" + case b == ',' && c.depth == 1: + c.want, c.value = true, false + case b == ' ' || b == '\t' || b == '\n' || b == '\r': + case c.depth == 0: + c.over = true // not JSON this reads + return "" + case c.depth == 1: + c.value = false // the input isn't a string + } + } + return "" +} + +// take unescapes what can be read of the input string so far, up to its +// closing quote. +func (c *customStream) take() string { + n, end := 0, false +scan: + for n < len(c.pend) { + switch c.pend[n] { + case '"': + end = true + break scan + case '\\': + switch { + case n+1 >= len(c.pend): + break scan + case c.pend[n+1] != 'u': + n += 2 + case n+6 > len(c.pend): + break scan + case !highSurrogate(c.pend[n+2 : n+6]): + n += 6 + case n+8 > len(c.pend): + break scan + case c.pend[n+6] != '\\' || c.pend[n+7] != 'u': + n += 6 // a lone half, read as JSON reads it + case n+12 > len(c.pend): + break scan // the low half is cut off + default: + n += 12 + } + default: + n++ + } + } + // a character cut off waits too + for k := 0; k < utf8.UTFMax-1 && n > 0 && !end && !utf8.Valid(c.pend[:n]); k++ { + n-- + } + var text string + if json.Unmarshal(append(append([]byte{'"'}, c.pend[:n]...), '"'), &text) != nil { + c.over = true // not a string JSON reads: the finished item says it + return "" + } + c.pend = c.pend[n:] + if end { + c.over, c.pend = true, nil + } + return text +} + +// highSurrogate is whether the four hex digits of a \u escape are the +// first half of a pair. +func highSurrogate(hex []byte) bool { + r, err := strconv.ParseUint(string(hex), 16, 16) + return err == nil && r >= 0xD800 && r < 0xDC00 +} diff --git a/internal/gateway/decide_group.go b/internal/gateway/decide_group.go index a76461d18..14f24efe5 100644 --- a/internal/gateway/decide_group.go +++ b/internal/gateway/decide_group.go @@ -28,7 +28,7 @@ import ( // one switched off or gone), with its status. func decisionGroupOf(asked string) (g provider.Group, ms []provider.Member, ok bool, status int, err error) { ref := strings.TrimSpace(asked) - explicit := strings.HasPrefix(ref, provider.GroupPrefix) + explicit := provider.IsGroupRef(ref) if !explicit { gid, found := provider.GroupFor(ref) if !found { @@ -74,7 +74,7 @@ func (s *Server) decideTries(g provider.Group, ms []provider.Member) ([]candidat // would fail the same at any. It returns why it failed, and its rest when // it rests. func (s *Server) decideFailed(c candidate, status int, header http.Header, body []byte) (string, *Rest) { - if shapeRefused(status, body) || promptRefused(status, body) || protectionRefused(status, body) || !retryable(status, body) { + if shapeRefused(status, body) || promptRefused(status, body) || protectionRefused(status, body) || zdrRefused(status, body) || !retryable(status, body) { return failureOf(c, status, body), nil } rest := s.restAfter(c, status, header, body) @@ -262,7 +262,7 @@ func (e decideRefused) Unwrap() error { return e.err } // answers, the one that failed resting as it would for a chat. ok is false // when model names no decision group. func (s *Server) askDecisionGroup(model string, intents []string, prev before, effort bool, text string) (v verdict, ok bool, err error) { - if !strings.HasPrefix(model, provider.GroupPrefix) { + if !provider.IsGroupRef(model) { return verdict{}, false, nil } g, ms, found := provider.FindGroup(model) diff --git a/internal/gateway/desktop_models_test.go b/internal/gateway/desktop_models_test.go index 2e756e774..9c191c94d 100644 --- a/internal/gateway/desktop_models_test.go +++ b/internal/gateway/desktop_models_test.go @@ -75,7 +75,7 @@ func TestClaudeDesktopPickedModels(t *testing.T) { // its provider after it hide := []string{"relay/deepseek-v4.1-flash", "opencode-go/glm-5"} for id := range all { - if strings.HasPrefix(id, provider.GroupPrefix) { + if provider.IsGroupRef(id) { hide = append(hide, id) } } diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 8c3a505a1..80aa9fb98 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -40,8 +40,43 @@ import ( const DrawAgent = "magpie-image/1" // drawTimeout is how long a vendor is given to draw: to answer, and to send -// all of its answer. -var drawTimeout = 5 * time.Minute +// all of its answer. It is Settings' Image generation timeout (neighbads on +// X: a slow image endpoint needs more than the 5 minutes it was fixed at), +// read as each request comes, in drawUnits. +func drawTimeout() time.Duration { + return settings.Load().ImageWait() / time.Minute * drawUnit +} + +// drawUnit is a minute of drawTimeout: a test makes it shorter, rather than +// wait the minutes out. +var drawUnit = time.Minute + +// drawWaitKey marks a request's context as a drawing's (or a video's), +// given the time it holds: the vendor is waited on for that long, past the +// 10 minutes upstreamTransport gives any other request to begin answering +// (an images API answers only once it has drawn), and what ran out of time +// says how long it was given. +type drawWaitKey struct{} + +// drawWithin is ctx with d to draw in: its deadline, and the mark. +func drawWithin(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) { + return context.WithTimeout(context.WithValue(ctx, drawWaitKey{}, d), d) +} + +// drawWaitOf is the time ctx was given to draw in, if it was. +func drawWaitOf(ctx context.Context) (time.Duration, bool) { + d, ok := ctx.Value(drawWaitKey{}).(time.Duration) + return d, ok +} + +// givenTo says how long the drawing in ctx was given, or, for a request +// that isn't one, how long it ran since start. +func givenTo(ctx context.Context, start time.Time) time.Duration { + if d, ok := drawWaitOf(ctx); ok { + return d + } + return time.Since(start).Round(time.Second) +} // maxDrawings is how many images one request may ask for. const maxDrawings = 4 @@ -440,7 +475,7 @@ func (s *Server) images(edit bool) http.HandlerFunc { return } call.Provider, call.To = p.ID, provider.Chat - ctx, cancel := context.WithTimeout(r.Context(), drawTimeout) + ctx, cancel := drawWithin(r.Context(), drawTimeout()) defer cancel() // the account that drew, or refused last, is the one recorded var ( @@ -532,7 +567,7 @@ func (s *Server) images(edit bool) http.HandlerFunc { // other names a model on its own. func drawingGroup(asked string, p provider.Provider, model string) (provider.Group, []provider.Member, bool) { ref := asked - if !strings.HasPrefix(ref, provider.GroupPrefix) { + if !provider.IsGroupRef(ref) { gid, ok := provider.GroupFor(ref) if !ok { return provider.Group{}, nil, false @@ -991,7 +1026,7 @@ func (s *Server) sendWith(ctx context.Context, p provider.Provider, method, url, res, err := p.Do(s.client, req) // a plugin's through the plugin if err != nil { if ctx.Err() != nil { - return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, drawTimeout) + return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, givenTo(ctx, asked)) } return nil, 502, err } @@ -1003,7 +1038,7 @@ func (s *Server) sendWith(ctx context.Context, p provider.Provider, method, url, if ctx.Err() != nil { // not a bare "context deadline exceeded" (#1576): the vendor // began answering, and its answer is what ran out of time - return nil, 504, fmt.Errorf("%s began answering after %s (%d %s) but hadn't sent all of its answer in %s: %s", p.Name, answered.Round(time.Second), res.StatusCode, http.StatusText(res.StatusCode), drawTimeout, stalledAt(b, time.Since(rb.last))) + return nil, 504, fmt.Errorf("%s began answering after %s (%d %s) but hadn't sent all of its answer in %s: %s", p.Name, answered.Round(time.Second), res.StatusCode, http.StatusText(res.StatusCode), givenTo(ctx, asked), stalledAt(b, time.Since(rb.last))) } return nil, 502, err } @@ -1312,15 +1347,21 @@ func (s *Server) fetchPicture(ctx context.Context, url string) ([]byte, string, func inline(format string) bool { return strings.EqualFold(format, "b64_json") } // ImageStall is how long an image being downloaded may send nothing before -// the download is given up, and ImageLongest how long it may take in all. -// A slow download goes on while it moves: a 4K PNG is 10 MB and more, and -// a cap on the whole of it (generate_image's was 2 minutes) lost one that -// was still coming (#1576). +// the download is given up, and ImageLongest how long it may take in all +// at the least: as long as drawTimeout where Settings gives drawing longer, +// as a vendor slow to draw can be as slow to hand the image over. A slow +// download goes on while it moves: a 4K PNG is 10 MB and more, and a cap +// on the whole of it (generate_image's was 2 minutes) lost one that was +// still coming (#1576). var ( ImageStall = time.Minute ImageLongest = 5 * time.Minute ) +// imageLongest is how long a download may take in all: ImageLongest, or +// drawTimeout where that is longer. +func imageLongest() time.Duration { return max(ImageLongest, drawTimeout()) } + // maxImageBytes is the most of an image a download reads. const maxImageBytes = 64 << 20 @@ -1328,13 +1369,14 @@ var errImageStalled = errors.New("the download stalled") // FetchImage downloads the image at url with c: its bytes, and its type — // what the bytes are, over what the server says. It gives up when nothing -// comes for ImageStall or it has taken ImageLongest, and says which, and +// comes for ImageStall or it has taken imageLongest, and says which, and // how much had come. func FetchImage(ctx context.Context, c *http.Client, url string) ([]byte, string, error) { if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") { return nil, "", fmt.Errorf("%q isn't an http(s) URL", url) } - ctx, cancel := context.WithTimeout(ctx, ImageLongest) + longest := imageLongest() + ctx, cancel := context.WithTimeout(ctx, longest) defer cancel() ctx, stop := context.WithCancelCause(ctx) defer stop(nil) @@ -1349,7 +1391,7 @@ func FetchImage(ctx context.Context, c *http.Client, url string) ([]byte, string case errImageStalled: return fmt.Errorf("nothing came for %s, after %s", ImageStall, mb(got)) case context.DeadlineExceeded: - return fmt.Errorf("only %s came in %s", mb(got), ImageLongest) + return fmt.Errorf("only %s came in %s", mb(got), longest) } return err } diff --git a/internal/gateway/draw_fetch_test.go b/internal/gateway/draw_fetch_test.go index d71978a3b..5d300dfad 100644 --- a/internal/gateway/draw_fetch_test.go +++ b/internal/gateway/draw_fetch_test.go @@ -149,9 +149,9 @@ func TestImageByURLIsFetchedForB64Caller(t *testing.T) { // #1576's 502s at 300 s said only "context deadline exceeded". A vendor // that began answering but didn't finish in drawTimeout is said to have. func TestVendorThatStopsMidAnswerIsSaid(t *testing.T) { - was := drawTimeout - drawTimeout = 300 * time.Millisecond - t.Cleanup(func() { drawTimeout = was }) + was := drawUnit + drawUnit = 60 * time.Millisecond // the 5 minutes, 300ms + t.Cleanup(func() { drawUnit = was }) s, _ := relayed(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, `{"created":1,"data":[`) w.(http.Flusher).Flush() @@ -170,9 +170,9 @@ func TestVendorThatStopsMidAnswerIsSaid(t *testing.T) { // b64_json body that took 380 s, and on another with a 416 B url. Which of // the two stalled is said, with how much had come. func TestStalledAnswerSaysUrlOrB64(t *testing.T) { - was := drawTimeout - drawTimeout = 500 * time.Millisecond - t.Cleanup(func() { drawTimeout = was }) + was := drawUnit + drawUnit = 100 * time.Millisecond // the 5 minutes, 500ms + t.Cleanup(func() { drawUnit = was }) for _, c := range []struct { name, sent, want string }{ diff --git a/internal/gateway/draw_modelscope.go b/internal/gateway/draw_modelscope.go index 2fbf724cf..5c7287a71 100644 --- a/internal/gateway/draw_modelscope.go +++ b/internal/gateway/draw_modelscope.go @@ -82,7 +82,7 @@ func (s *Server) modelScopeTask(ctx context.Context, p provider.Provider, base s } select { case <-ctx.Done(): - return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, drawTimeout) + return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, givenTo(ctx, time.Now())) case <-time.After(modelScopeBusy[i]): } } @@ -107,7 +107,7 @@ func (s *Server) modelScopeTask(ctx context.Context, p provider.Provider, base s for { select { case <-ctx.Done(): - return nil, 504, fmt.Errorf("%s didn't finish drawing in %s", p.Name, drawTimeout) + return nil, 504, fmt.Errorf("%s didn't finish drawing in %s", p.Name, givenTo(ctx, time.Now())) case <-time.After(modelScopePoll): } b, code, err := s.sendWith(ctx, p, http.MethodGet, base+"/tasks/"+started.TaskID, "", nil, true, task) diff --git a/internal/gateway/draw_timeout_test.go b/internal/gateway/draw_timeout_test.go new file mode 100644 index 000000000..a57aa5c59 --- /dev/null +++ b/internal/gateway/draw_timeout_test.go @@ -0,0 +1,160 @@ +package gateway + +import ( + "encoding/base64" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// slowDrawer is a vendor whose images API answers after wait, as one does +// only once it has drawn, with Settings' Image generation timeout set to +// minutes (0 for the default). +func slowDrawer(t *testing.T, minutes int, wait time.Duration) *Server { + t.Helper() + fresh(t) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} { + t.Setenv(k, "") + } + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-r.Context().Done(): + return + case <-time.After(wait): + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"created":1,"data":[{"b64_json":"` + base64.StdEncoding.EncodeToString(pngBytes) + `"}]}`)) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "slow", Name: "Slow", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-image-1"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("slow", up.URL+"/v1", []catalog.Model{{ID: "gpt-image-1"}}); err != nil { + t.Fatal(err) + } + if minutes > 0 { + s := settings.Load() + s.ImageTimeout = minutes + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + } + return New() +} + +// deadlines records the deadline each request to a vendor goes out with, +// and whether it went as a drawing, on its way to the real transport. +type deadlines struct { + next http.RoundTripper + mu sync.Mutex + got []time.Duration + draw []bool +} + +func (d *deadlines) RoundTrip(r *http.Request) (*http.Response, error) { + dl, _ := r.Context().Deadline() + _, drawn := drawWaitOf(r.Context()) + d.mu.Lock() + d.got, d.draw = append(d.got, time.Until(dl)), append(d.draw, drawn) + d.mu.Unlock() + return d.next.RoundTrip(r) +} + +// neighbads on X: a slow image endpoint needed longer than the 5 minutes +// drawing was given. Settings' Image generation timeout of 30 minutes +// is what a drawing's request goes to the vendor with, through the +// gateway's own transport; with none set it is 5 minutes, as before. +func TestImageTimeoutSettingReachesTheVendor(t *testing.T) { + for _, c := range []struct { + minutes int + want time.Duration + }{{30, 30 * time.Minute}, {0, 5 * time.Minute}, {60, time.Hour}} { + s := slowDrawer(t, c.minutes, 0) + rec := &deadlines{next: s.client.Transport} + s.client = &http.Client{Transport: rec} + code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"slow/gpt-image-1","prompt":"a magpie"}`) + if code != 200 { + t.Fatalf("%d minutes: %d %s", c.minutes, code, raw) + } + if len(rec.got) != 1 || !rec.draw[0] || rec.got[0] > c.want || rec.got[0] < c.want-time.Minute { + t.Fatalf("%d minutes: the vendor was asked with %v left (as a drawing: %v), want %v", c.minutes, rec.got, rec.draw, c.want) + } + } +} + +// The same, with the minutes made short: a vendor that takes past the +// default 5 to begin answering, and past the wait any other request is +// given to begin (upstreamHeaderWait), draws when Settings gives it 30; +// with the default it is said not to have answered in 5. +func TestLongImageTimeoutLetsASlowVendorFinish(t *testing.T) { + wasUnit, wasHead := drawUnit, upstreamHeaderWait + drawUnit, upstreamHeaderWait = 20*time.Millisecond, 100*time.Millisecond // 5 minutes 100ms, 30 600ms, 10 minutes 100ms + t.Cleanup(func() { drawUnit, upstreamHeaderWait = wasUnit, wasHead }) + const slow = 300 * time.Millisecond + + s := slowDrawer(t, 30, slow) + code, a, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"slow/gpt-image-1","prompt":"a magpie"}`) + if code != 200 || len(a.Data) != 1 { + t.Fatalf("given 30: %d %s", code, raw) + } + if b, _ := base64.StdEncoding.DecodeString(a.Data[0].B64); string(b) != string(pngBytes) { + t.Fatalf("image %q", b) + } + + s = slowDrawer(t, 0, slow) + code, _, raw = postImages(t, s, "/v1/images/generations", "application/json", `{"model":"slow/gpt-image-1","prompt":"a magpie"}`) + if code != 504 || !strings.Contains(raw, "Slow didn't answer in 100ms") { + t.Fatalf("given the default: %d %s", code, raw) + } +} + +// An image a vendor answers with as a link is downloaded within the same +// minutes: a long setting isn't cut by the 5-minute download cap. +func TestImageDownloadGetsTheSetMinutes(t *testing.T) { + slowDrawer(t, 0, 0) + if got := imageLongest(); got != ImageLongest { + t.Fatalf("unset: %v", got) + } + slowDrawer(t, 45, 0) + if got := imageLongest(); got != 45*time.Minute { + t.Fatalf("given 45: %v", got) + } +} + +// A request that isn't a drawing still has upstreamHeaderWait to begin +// answering: only drawings wait longer. +func TestOnlyDrawingsWaitPastTheHeaderWait(t *testing.T) { + was := upstreamHeaderWait + upstreamHeaderWait = 100 * time.Millisecond + t.Cleanup(func() { upstreamHeaderWait = was }) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-r.Context().Done(): + case <-time.After(400 * time.Millisecond): + } + })) + t.Cleanup(up.Close) + c := &http.Client{Transport: upstreamTransport()} + req, _ := http.NewRequest(http.MethodGet, up.URL, nil) + if res, err := c.Do(req); err == nil || !strings.Contains(err.Error(), "timeout awaiting response headers") { + if res != nil { + res.Body.Close() + } + t.Fatalf("a chat's request waited past the header wait: %v", err) + } + ctx, cancel := drawWithin(t.Context(), 5*time.Second) + defer cancel() + req, _ = http.NewRequestWithContext(ctx, http.MethodGet, up.URL, nil) + res, err := c.Do(req) + if err != nil { + t.Fatalf("a drawing's request was cut: %v", err) + } + res.Body.Close() +} diff --git a/internal/gateway/effort_test.go b/internal/gateway/effort_test.go index 3799d112f..bf65d26a3 100644 --- a/internal/gateway/effort_test.go +++ b/internal/gateway/effort_test.go @@ -221,7 +221,7 @@ func TestTraceRecordsTheEffortSent(t *testing.T) { if strings.Join(got, ",") != "high,xhigh,high,max," { t.Errorf("usage efforts %q", got) } - vs := usage.Vias(time.Time{})[usage.AgentOf("")+"|sess-1"] + vs := usage.Vias(time.Time{}).Of(usage.AgentOf("") + "|sess-1") if len(vs) != 4 || vs[0].Model != "glm-5.3-flash" || vs[0].Effort != "high" || vs[0].Calls != 2 { t.Errorf("vias %+v", vs) } diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index c34871b28..2eef2d36d 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -1065,7 +1065,7 @@ func modelRefused(status int, body []byte) bool { } // the words are matched decoded, too (#1669) body = wordsOf(body) - return unservedWords.Match(body) && !quotaWords.Match(body) && !refusedWords.Match(body) + return unservedWords.Match(body) && !quotaWords.Match(body) && !refusedWords.Match(body) && !zdrRefused(status, body) } // codeAssistModelMissing says a Google account's Code Assist — the @@ -1209,6 +1209,48 @@ func protectionRefused(status int, body []byte) bool { return status >= 400 && protectionWords.Match(body) } +// zdrCoded is Command Code's error code for a model no Zero Data +// Retention upstream serves, as the error's code or type, asked with +// x-cmd-zdr: 1 (its plugin's switch, magpie-community/plugins#246): the +// Provider API's 422 {"error":{"message":"This model has no +// zero-data-retention upstream. Remove the x-cmd-zdr header or choose a +// different model.","type":"invalid_request_error","code": +// "cmd_zdr_no_providers"}}, and the 400 the plugin makes of Go's error +// line, {"error":{…,"type":"cmd_zdr_no_providers","code":400}}. Matched +// where the error names its code, not in its words: "…a different +// model.","type":"invalid_request_error" reads as a model unserved +// (unservedWords) otherwise. +var zdrCoded = regexp.MustCompile(`\\?"(type|code)\\?"\s*:\s*\\?"cmd_zdr_no_providers\\?"`) + +// zdrRefused says Command Code turned the request away for its Zero Data +// Retention setting: a choice the user made for every request to the +// provider, not the model or the account failing. Nothing rests for it, +// so the model answers again as soon as the switch is off; the same +// model at the same provider, sent the same header, isn't asked again; +// another member may be. +func zdrRefused(status int, body []byte) bool { + return (status == 400 || status == 422) && zdrCoded.Match(body) +} + +// zdrHeader carries, from keepRetry to the routing loop and restAfter, +// that a vendor's error was zdrRefused: the error the agent gets keeps +// Command Code's words but, in Anthropic's shape or for the 400 whose +// code is a number, not its code. +const zdrHeader = "X-Magpie-ZDR-Refused" + +// notMates is, of the candidates left, those not c's model at c's +// provider: its other accounts are sent the same Zero Data Retention +// header, and refuse the same. +func notMates(left []candidate, c candidate) []candidate { + var out []candidate + for _, x := range left { + if x.p.ID != c.p.ID || x.model != c.model { + out = append(out, x) + } + } + return out +} + // elsewhere is, of the candidates left, those not at c's provider, whose // every account and model the same request reaches the same backend // through. @@ -1283,7 +1325,7 @@ func tooLongUnsaid(p provider.Provider, model string, tokens, status int, body [ // the words are matched decoded, too (#1669) body = wordsOf(body) if overflowed(status, body) || failure(status, body) != failOther || quotaWords.Match(body) || - unservedWords.Match(body) || refusedWords.Match(body) || provider.EdgeBlocked(body) || regionRefused(status, body) { + unservedWords.Match(body) || refusedWords.Match(body) || provider.EdgeBlocked(body) || regionRefused(status, body) || zdrRefused(status, body) { return "", false } window := windowOf(p, model) @@ -1354,7 +1396,7 @@ func passing(status int, header http.Header, body []byte, again int) (time.Durat case wait > longestPause: return 0, false case status == 408, status == 500, status == 502, status == 503, status == 504, status == 529: - if strings.Contains(string(body), didNotStream) { + if bytes.Contains(body, []byte(didNotStream)) { return 0, false } return wait, again < lastRetries @@ -1717,7 +1759,7 @@ func (h *holdWriter) pass() { } dst := h.w.Header() for k, v := range h.header { - if k != resetsHeader && k != refusedHeader { // magpie's own notes, for restAfter and settle + if k != resetsHeader && k != refusedHeader && k != zdrHeader { // magpie's own notes, for restAfter and settle dst[k] = v } } @@ -2121,7 +2163,7 @@ func (h *holdWriter) keepAlive() { } dst := h.w.Header() for k, v := range src { - if k != resetsHeader && k != refusedHeader && k != "Content-Length" { + if k != resetsHeader && k != refusedHeader && k != zdrHeader && k != "Content-Length" { dst[k] = slices.Clone(v) } } diff --git a/internal/gateway/fastjson.go b/internal/gateway/fastjson.go index 9eda5f1f0..b9f4acf0a 100644 --- a/internal/gateway/fastjson.go +++ b/internal/gateway/fastjson.go @@ -6,9 +6,11 @@ import ( "encoding/binary" "encoding/json" "errors" + "hash/maphash" "reflect" "slices" "sync" + "sync/atomic" "unicode" "unicode/utf16" "unicode/utf8" @@ -36,7 +38,16 @@ import ( // of its own (a slice's old elements are decoded over, not replaced). func decodeJSON(data []byte, dst any) error { v := reflect.ValueOf(dst) - if v.Kind() != reflect.Pointer || v.IsNil() || !v.Elem().IsZero() || !jsonValid(data) { + if v.Kind() != reflect.Pointer || v.IsNil() || !v.Elem().IsZero() { + return json.Unmarshal(data, dst) + } + var members []memberSpan + if len(data) >= validMemoMin { + var valid bool + if valid, members = longBody(data); !valid { + return json.Unmarshal(data, dst) + } + } else if !jsonCheck(data) { return json.Unmarshal(data, dst) } start := skipJSONSpace(data, 0) @@ -47,7 +58,7 @@ func decodeJSON(data []byte, dst any) error { // of the value's opening and its close. return json.Unmarshal(append(data[:start+1:start+1], close), dst) } - if err := fillJSON(trimJSON(data), v.Elem()); err != nil { + if err := fillJSONIn(trimJSON(data), v.Elem(), members); err != nil { v.Elem().SetZero() return json.Unmarshal(data, dst) } @@ -168,7 +179,11 @@ func (f *fastFields) field(key []byte) int { // fillJSON decodes raw, a whole valid JSON value, into v; errSlowJSON or // another error leaves it to encoding/json. -func fillJSON(raw []byte, v reflect.Value) error { +func fillJSON(raw []byte, v reflect.Value) error { return fillJSONIn(raw, v, nil) } + +// fillJSONIn is fillJSON with where raw's members are, when known +// (longBody): a struct or map at raw's top is filled from them. +func fillJSONIn(raw []byte, v reflect.Value, members []memberSpan) error { t := v.Type() if t == rawMessageType { v.SetBytes(bytes.Clone(raw)) // a copy, as encoding/json makes @@ -191,7 +206,7 @@ func fillJSON(raw []byte, v reflect.Value) error { if v.IsNil() { v.Set(reflect.New(t.Elem())) } - return fillJSON(raw, v.Elem()) + return fillJSONIn(raw, v.Elem(), members) case reflect.String: if null { return nil @@ -229,7 +244,7 @@ func fillJSON(raw []byte, v reflect.Value) error { } var seen []bool var err error - eachMember(raw, func(key, val []byte) bool { + eachMemberIn(raw, members, func(key, val []byte) bool { name, ok := unquoteJSON(key) if !ok { err = errSlowJSON @@ -290,7 +305,7 @@ func fillJSON(raw []byte, v reflect.Value) error { v.Set(reflect.MakeMap(t)) } var err error - eachMember(raw, func(key, val []byte) bool { + eachMemberIn(raw, members, func(key, val []byte) bool { name, ok := unquoteJSON(key) if !ok { err = errSlowJSON @@ -351,6 +366,29 @@ func trimJSON(data []byte) []byte { // eachMember calls f with each member of obj, a valid JSON object, its key // still quoted, until f returns false. func eachMember(obj []byte, f func(key, val []byte) bool) { + eachMemberAt(obj, func(k0, k1, v0, v1 int) bool { return f(obj[k0:k1], obj[v0:v1:v1]) }) +} + +// eachMemberIn is eachMember, from where its members are when known +// (longBody), else by splitting obj. +func eachMemberIn(obj []byte, members []memberSpan, f func(key, val []byte) bool) { + if members == nil { + if h := topSplit.Load(); h != nil && len(obj) >= validMemoMin { + (*h)(obj) + } + eachMember(obj, f) + return + } + for _, m := range members { + if !f(obj[m.k0:m.k1], obj[m.v0:m.v1:m.v1]) { + return + } + } +} + +// eachMemberAt is eachMember by offsets: the key at [k0, k1), the value +// at [v0, v1). +func eachMemberAt(obj []byte, f func(k0, k1, v0, v1 int) bool) { i := skipJSONSpace(obj, 1) if obj[i] == '}' { return @@ -358,12 +396,12 @@ func eachMember(obj []byte, f func(key, val []byte) bool) { for { k := i i = skipJSONString(obj, i) - key := obj[k:i] + k1 := i i = skipJSONSpace(obj, i) i = skipJSONSpace(obj, i+1) // ':' s := i i = skipJSONValue(obj, i) - if !f(key, obj[s:i:i]) { + if !f(k, k1, s, i) { return } i = skipJSONSpace(obj, i) @@ -562,9 +600,122 @@ func hex4(s []byte) rune { // jsonMaxDepth is encoding/json's maxNestingDepth. const jsonMaxDepth = 10000 +// validMemoMin is the size from which jsonValid remembers what it found +// valid. A request body is decoded a dozen times or more on its way +// (modelOf, parse, the prompt, the conversation, the effort, the images…), +// and each decodeJSON checked all of it again: ~2.5ms a time at 2 MB, a +// fifth of the CPU of serving it. +const validMemoMin = 32 << 10 + +// validMemo is the last bodies found valid, by length and a hash under a +// seed of this process's own. +var validMemo struct { + sync.Mutex + sums [8]validEntry + next int +} + +type validSum struct { + n int + sum uint64 +} + +// validEntry is a body remembered valid, and where its top level's +// members are, once a decode has split it (nil before, and for a body not +// an object). +type validEntry struct { + validSum + members []memberSpan +} + +// memberSpan is a member of a body's top-level object: its key, quoted, +// at [k0, k1) and its value at [v0, v1), of the body trimmed (trimJSON). +type memberSpan struct{ k0, k1, v0, v1 int } + +// topSplit, when set (tests), is told of each object of validMemoMin or +// more that decodeJSON splits at its members. +var topSplit atomic.Pointer[func(data []byte)] + +// longBody is what decodeJSON knows of a body of validMemoMin or more: +// valid or not, and where its top level's members are. The members are +// remembered with the body, as its validity is: a request's body was split +// at its top level again by each of the dozen decodes it went through, +// each a walk over every byte of the conversation. +func longBody(data []byte) (valid bool, members []memberSpan) { + s := validSum{len(data), maphash.Bytes(validSeed, data)} + validMemo.Lock() + i := slices.IndexFunc(validMemo.sums[:], func(e validEntry) bool { return e.validSum == s }) + if i >= 0 && validMemo.sums[i].members != nil { + members = validMemo.sums[i].members + validMemo.Unlock() + return true, members + } + validMemo.Unlock() + if i < 0 { + if f := validScanned.Load(); f != nil { + (*f)(data) + } + if !jsonCheck(data) { + return false, nil + } + } + raw := trimJSON(data) + if raw[0] == '{' { + if f := topSplit.Load(); f != nil { + (*f)(data) + } + members = []memberSpan{} + eachMemberAt(raw, func(k0, k1, v0, v1 int) bool { + members = append(members, memberSpan{k0, k1, v0, v1}) + return true + }) + } + validMemo.Lock() + if i = slices.IndexFunc(validMemo.sums[:], func(e validEntry) bool { return e.validSum == s }); i >= 0 { + validMemo.sums[i].members = members + } else { + validMemo.sums[validMemo.next] = validEntry{s, members} + validMemo.next = (validMemo.next + 1) % len(validMemo.sums) + } + validMemo.Unlock() + return true, members +} + +var validSeed = maphash.MakeSeed() + +// validScanned, when set (tests), is told of each body of validMemoMin or +// more that jsonValid checks byte by byte. +var validScanned atomic.Pointer[func(data []byte)] + // jsonValid is json.Valid, without stepping through each byte by a call: // the grammar, and the depth past which encoding/json gives up, are its. +// A long body found valid is remembered, and not checked again. func jsonValid(data []byte) bool { + if len(data) < validMemoMin { + return jsonCheck(data) + } + s := validSum{len(data), maphash.Bytes(validSeed, data)} + validMemo.Lock() + known := slices.ContainsFunc(validMemo.sums[:], func(e validEntry) bool { return e.validSum == s }) + validMemo.Unlock() + if known { + return true + } + if f := validScanned.Load(); f != nil { + (*f)(data) + } + if !jsonCheck(data) { + return false + } + validMemo.Lock() + validMemo.sums[validMemo.next] = validEntry{validSum: s} + validMemo.next = (validMemo.next + 1) % len(validMemo.sums) + validMemo.Unlock() + return true +} + +// jsonCheck is jsonValid's check itself. +func jsonCheck(data []byte) bool { i := skipJSONSpace(data, 0) i, ok := validJSONValue(data, i, 0) return ok && skipJSONSpace(data, i) == len(data) diff --git a/internal/gateway/fastjson_memo_test.go b/internal/gateway/fastjson_memo_test.go new file mode 100644 index 000000000..4e1f8d70d --- /dev/null +++ b/internal/gateway/fastjson_memo_test.go @@ -0,0 +1,130 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "strings" + "sync/atomic" + "testing" +) + +// memoBody is a request body past validMemoMin, unique to the test. +func memoBody(tag string) []byte { + return []byte(`{"model":"` + tag + `","messages":[{"role":"user","content":"` + + strings.Repeat("a long prompt ", 6000) + `"}]}`) +} + +// countScans counts jsonValid's byte-by-byte checks of bodies equal to b. +func countScans(t *testing.T, b []byte) *atomic.Int32 { + var n atomic.Int32 + f := func(data []byte) { + if bytes.Equal(data, b) { + n.Add(1) + } + } + validScanned.Store(&f) + t.Cleanup(func() { validScanned.Store(nil) }) + return &n +} + +// A long body decoded by each reader of a request is checked for valid +// JSON once, not by every decodeJSON: at 2 MB each check cost ~2.5ms, and +// a request's body went through a dozen of them. +func TestDecodeJSONChecksALongBodyOnce(t *testing.T) { + body := memoBody(t.Name()) + scans := countScans(t, body) + for range 6 { + var v struct { + Model string `json:"model"` + } + if err := decodeJSON(body, &v); err != nil || v.Model != t.Name() { + t.Fatalf("decode: %v %q", err, v.Model) + } + } + if n := scans.Load(); n != 1 { + t.Fatalf("a %d-byte body was checked %d times over six decodes, want 1", len(body), n) + } +} + +// A long body's top level is split at its members once, not by each decode +// of it: each reader of a request (the model, the stream flag, the +// messages, the tools…) walked every byte of the conversation again to +// find its member. What each is given is what encoding/json gives it. +func TestDecodeJSONSplitsALongBodyOnce(t *testing.T) { + body := []byte(`{"model":"` + t.Name() + `","stream":true,"max_tokens":9,"messages":[{"role":"user","content":"` + + strings.Repeat("a long prompt ", 6000) + `"}],"metadata":{"user_id":"u"}}`) + var n atomic.Int32 + f := func(data []byte) { + if bytes.Equal(data, body) { + n.Add(1) + } + } + topSplit.Store(&f) + t.Cleanup(func() { topSplit.Store(nil) }) + type msgs struct { + Messages []struct { + Role string `json:"role"` + Content string `json:"content"` + } `json:"messages"` + } + for range 4 { + var a struct { + Model string `json:"model"` + Stream bool `json:"stream"` + } + var b msgs + var c *msgs + var d map[string]json.RawMessage + var e struct { + Metadata struct { + UserID string `json:"user_id"` + } `json:"metadata"` + Max int `json:"max_tokens"` + } + for _, dst := range []any{&a, &b, &c, &d, &e} { + if err := decodeJSON(body, dst); err != nil { + t.Fatal(err) + } + } + wa, wb, we := a, msgs{}, e + wa.Model, wa.Stream, we.Metadata.UserID, we.Max = "", false, "", 0 + var wd map[string]json.RawMessage + json.Unmarshal(body, &wa) + json.Unmarshal(body, &wb) + json.Unmarshal(body, &wd) + json.Unmarshal(body, &we) + if a != wa || len(b.Messages) != 1 || b.Messages[0] != wb.Messages[0] || c == nil || len(c.Messages) != 1 || + len(d) != len(wd) || string(d["messages"]) != string(wd["messages"]) || e != we { + t.Fatalf("decoded otherwise than encoding/json: %+v %+v %d %v", a, e, len(d), c == nil) + } + } + if got := n.Load(); got != 1 { + t.Fatalf("a %d-byte body's top level was split %d times over 20 decodes, want 1", len(body), got) + } +} + +// What is remembered is a valid body: an invalid one, or a valid one +// changed by a byte at the same length, is checked again and refused. +func TestDecodeJSONMemoKeepsRefusing(t *testing.T) { + body := memoBody(t.Name()) + var v map[string]any + if err := decodeJSON(body, &v); err != nil { + t.Fatal(err) + } + bad := bytes.Clone(body) + bad[len(bad)-1] = '!' + for range 3 { + var w map[string]any + if err := decodeJSON(bad, &w); err == nil { + t.Fatal("a body with a broken end decoded") + } + } + trunc := body[:len(body)-1] + var w map[string]any + if err := decodeJSON(trunc, &w); err == nil { + t.Fatal("a truncated body decoded") + } + if !jsonValid(body) || jsonValid(bad) { + t.Fatal("jsonValid's answer changed") + } +} diff --git a/internal/gateway/fastjson_split_bench_test.go b/internal/gateway/fastjson_split_bench_test.go new file mode 100644 index 000000000..9f3a5ed99 --- /dev/null +++ b/internal/gateway/fastjson_split_bench_test.go @@ -0,0 +1,35 @@ +package gateway + +import ( + "strings" + "testing" +) + +// BenchmarkDecodeReaders is a request's readers decoding one 200KB body, +// each into the few members it wants: the model and stream flag, the +// metadata, the max tokens. +func BenchmarkDecodeReaders(b *testing.B) { + body := []byte(`{"model":"claude-x","stream":true,"max_tokens":9,"messages":[{"role":"user","content":"` + + strings.Repeat("a long prompt with \\\"quotes\\\" and words ", 5000) + `"}],"metadata":{"user_id":"u"}}`) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + var a struct { + Model string `json:"model"` + Stream bool `json:"stream"` + } + var e struct { + Metadata struct { + UserID string `json:"user_id"` + } `json:"metadata"` + } + var m struct { + Max int `json:"max_tokens"` + } + for _, dst := range []any{&a, &e, &m} { + if err := decodeJSON(body, dst); err != nil { + b.Fatal(err) + } + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b389f5abe..b42a67796 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -190,7 +190,7 @@ func claudeTierStandIn(r *http.Request, agent, asked string) string { // session that started before it was switched off still asks for the model // its agent was then on, and the agent has been moved since (#200). func unserved(asked string) bool { - if asked == "" || strings.HasPrefix(asked, provider.GroupPrefix) { + if asked == "" || provider.IsGroupRef(asked) { return false } if _, ok := provider.GroupFor(asked); ok { @@ -242,6 +242,11 @@ func URL() string { // not magpie serve, which has none. Set by the gui. var Window bool +// Serves says how this process was started (app, tray, web, serve or tui): +// the Routing page of another magpie on this computer, which shows this +// one's routing, names it (#2606). Set by the cli. +var Serves = "app" + // Running reports whether a gateway answers at the address. func Running() bool { running, _ := Serving() @@ -262,6 +267,8 @@ type Served struct { Running bool // a magpie gateway answers Window bool // its routing can be watched in its window (#110) Version string // its version; "" from one that doesn't say + Pid int // its process id; 0 from one that doesn't say + Serves string // how it was started: app, tray, web, serve or tui; "" from one that doesn't say } // ServedBy asks the address which magpie answers there. Another magpie can @@ -282,11 +289,13 @@ func ServedBy() Served { Name string `json:"name"` Version string `json:"version"` Window bool `json:"window"` + Pid int `json:"pid"` + Serves string `json:"serves"` } if decodeJSON(b, &info) != nil || info.Name != "magpie" { return Served{Running: bytes.Contains(b, []byte(`"magpie"`)), Window: bytes.Contains(b, []byte(`"window":true`))} } - return Served{Running: true, Window: info.Window, Version: info.Version} + return Served{Running: true, Window: info.Window, Version: info.Version, Pid: info.Pid, Serves: info.Serves} } // Taken reports whether anything accepts connections at the gateway's @@ -591,6 +600,8 @@ func (s *Server) ListenAndServe(ctx context.Context) error { defer cancel() srv.Shutdown(c) s.subscription.abortAll() + provider.FlushServed() // what answered last, kept for the next start and the CLI + flushSticks() // who answered which conversation, for the next start or the magpie handed over to }() for { err := srv.Serve(ln) @@ -626,6 +637,11 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /api/hello", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version}) }) + // the Ollama API's model routes, for a client that takes a custom + // endpoint only as an Ollama server (ollama.go) + mux.HandleFunc("GET /api/version", s.ollamaVersion) + mux.HandleFunc("GET /api/tags", s.ollamaTags) + mux.HandleFunc("POST /api/show", s.ollamaShow) mux.HandleFunc("GET /v1/magpie/quotas", s.quotas) mux.HandleFunc("GET /v1/magpie/usage", s.usageSummary) mux.HandleFunc("GET /v1/magpie/usage/requests", s.usageRequests) @@ -634,6 +650,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET "+provider.RemoteCardsPath, s.quotaCards) mux.HandleFunc("POST "+provider.RemoteRefreshPath, s.quotaCardsRefresh) mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute) + mux.HandleFunc("GET /v1/magpie/trace", s.gatewayTrace) mux.HandleFunc("GET /v1/magpie/concurrency", s.concurrency) mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit) // a heap profile of this process, for magpie heap (loopback only) @@ -706,8 +723,14 @@ func responsesOverHTTP(w http.ResponseWriter, r *http.Request) { } func (s *Server) info(w http.ResponseWriter, r *http.Request) { - writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version, "models": len(provider.Catalog()), "window": Window, - "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", SearchMCPPath, VisionMCPPath, ToolsMCPPath}}) + out := map[string]any{"name": "magpie", "version": Version, "models": len(provider.Catalog()), "window": Window, + "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", SearchMCPPath, VisionMCPPath, ToolsMCPPath}} + // which process serves, for another magpie on this computer to name it + // on its Routing page (#2606); not told to another machine + if local(r) { + out["pid"], out["serves"] = os.Getpid(), Serves + } + writeJSON(w, 200, out) } // quotas is what is left of every subscription, plan and key magpie has, @@ -1118,7 +1141,7 @@ func (s *Server) model(w http.ResponseWriter, r *http.Request) { id := unprefixed(r.PathValue("id")) shown := keyAllowed(r, provider.Catalog()) for _, e := range shown { - if e.ID == id { + if e.ID == id || e.Group != "" && provider.SameRef(e.ID, id) { if agentOf(r) == ScienceID { // by the alias it asked by, which it keeps what it reads // under @@ -2245,9 +2268,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro repicked := 0 // times Copilot's Auto was asked again for a model the account is served floored := false // the reply's length raised to what the provider takes plainFor := "" // the account and model asked again without effort updates (#617) + // the account and model asked again for a reply that fits the window + // the prompt leaves, and how long that is (roomCap) + roomFor, roomCap := "", 0 // the key or subscription account the last try went to (#557) providerKeyID, providerKeyName, providerAccount := "", "", "" var other *Try // the first failure that wasn't an allowance run out + var forbade []forbidden // the plain 403s rested so far (forbiddenAlike) autoReset := resetFirst != nil // a Codex or Claude reset looked at, once a request // what the tries' held streams sent the agent ahead of a reply (#751) kept := &keptAlive{proto: from, told: start} @@ -2429,6 +2456,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } else if n := userOutput(c.p, c.model); n > 0 { attemptBody = withMaxOutput(from, attemptBody, n) } + if roomFor == c.who()+"|"+c.model { + if b, ok := withReplyCap(from, attemptBody, roomCap); ok { + attemptBody = b + } + } picked := false // the effort asked for in place of the agent's // a member fixed at an effort (#189), else the model asked for at // one (#536) @@ -2868,6 +2900,24 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro continue } } + if roomFor != c.who()+"|"+c.model && !hw.passing && (hw.code() == 400 || hw.code() == 422) { + // the window holds the prompt but not the reply asked for with + // it: DeepSeek counts max_tokens in its 1M window, and a client + // asking its full 384K for a 700K conversation (max_completion_ + // tokens, passed as max_tokens since #2355) was refused as too + // long, where every other member of its group answered + // (molvqingtai on Discord). The same one is asked again for what + // the window has left, as the vendor counted it + if left := replyLeft(wordsOf(hw.errBody())); left >= leastReplyLeft { + if _, ok := withReplyCap(from, attemptBody, left); ok { + roomFor, roomCap = c.who()+"|"+c.model, left + try.Fail = failRoom + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) + i-- + continue + } + } + } if hw.failed() && hw.refused { refusals++ if !refusalAsksAgain(refusals) { @@ -3066,12 +3116,22 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // had cost 616 tries, and the accounts their allowances. Another // vendor left in the group is asked, once protected := !hw.passing && !hw.refused && protectionRefused(hw.code(), hw.errBody()) - if protected { + // Command Code's Zero Data Retention setting refused the model + // (plugins #246): every account of the provider is sent the same + // header, so none of them is asked the model again, and nobody + // rests — it answers as soon as the switch is off. Another member, + // its other models among them, is asked + zdr := !hw.passing && !hw.refused && hw.code() >= 400 && hw.header.Get(zdrHeader) != "" + if protected || zdr { if other == nil { other = &Try{Status: call.Status, Error: call.Error} } try.Fail = failOther - if left := elsewhere(cands[i+1:], c); len(left) > 0 { + left := elsewhere(cands[i+1:], c) + if zdr { + left = notMates(cands[i+1:], c) + } + if len(left) > 0 { try.Fail = failShape s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) skipped = append(skipped, c.label()+": "+call.Error) @@ -3081,6 +3141,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro cands = cands[:i+1] last = true } + // nor is it asked again after a moment + protected = protected || zdr if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !last && hw.failed() && spentAfter(cands[i+1:]) { // the others left are out of their allowance (Discord, waroy: a // Codex account run out, Grok busy a moment): this one is the @@ -3141,13 +3203,47 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro matesLast(cands[i+1:], c) continue } + plain403 := hw.failed() && !hw.refused && plainForbidden(c, hw.code(), hw.errBody()) + if alike, others := forbiddenAlike(forbade, c); plain403 && len(alike) > 0 { + // a mate refused this request with a plain 403 too: the + // request is what is refused, not each account (plugins#243). + // Neither rests, the mate's rest taken back, and its other + // mates are asked last, as for a prompt turned away + for _, f := range alike { + unforbid(f) + } + forbade = others // each taken back once + try.Fail = failOther + s.trace.update(tr, func(t *Route) { + for _, f := range alike { + if f.try >= 0 && f.try < len(t.Tries) { + t.Tries[f.try].Rest = nil + } + } + if !last { + t.Tries[len(t.Tries)-1] = try + } + }) + if !last { + if other == nil { + other = &Try{Status: call.Status, Error: call.Error} + } + skipped = append(skipped, c.label()+": "+call.Error) + matesLast(cands[i+1:], c) + continue + } + } if !last && hw.failed() { if f := failure(hw.code(), hw.errBody()); other == nil && f != failQuota && f != failCredit { other = &Try{Status: call.Status, Error: call.Error} } rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool) try.Fail, try.Rest = rest.Why, &rest - s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) + at := -1 + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1], at = try, len(t.Tries)-1 }) + if plain403 { + forbade = append(forbade, forbidden{c: c, rest: rest, try: at}) + } skipped = append(skipped, c.label()+": "+call.Error) if waitsOf(c.patience, patienceFallback) > 0 && !hw.turnedAway && busy(hw.code(), hw.errBody()) { busyNow = noteBusy(busyNow, c, hw.header) @@ -3537,7 +3633,15 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P ownAPI := false // except a subagent's task its lead sealed (#1109): only the server // that sealed it reads it, and a translation would drop it - if relay && searchAsked(from, body) && (from == provider.Chat && !p.IsRemoteMagpie() || !searchesModel(p, from, model)) && !(from == provider.Responses && hasSealedAgentMessage(body)) { + if relay && searchedForIt(p, from, model, body) && !(from == provider.Responses && hasSealedAgentMessage(body)) { + relay, ownAPI = false, true + } + // Copilot seals an argument the tools mark "encrypted" (spawn_agent's + // message, MultiAgentV2) and then can't open what it sealed: the + // subagent's turn came back "Encrypted function output content could + // not be decrypted or decoded" (2026-10-17, a real account). Translated, + // the marks are left out and the call goes back to Codex unsealed. + if relay && from == provider.Responses && p.Account != nil && p.Account.Agent == "copilot" && asksSealing(body) { relay, ownAPI = false, true } // Zen's free models are asked as OpenCode asks them (zenfree.go) @@ -3744,6 +3848,7 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid body = deepseekTokenField(p, to, body) body = toolOneOfAsAnyOf(p, to, body) body = kimiToolEnumTypes(p, to, body) + body = kimiToolRefTypes(p, to, body) body = kimiLockedSampling(p, to, body) body = clinePin(p, to, body) body = codexImagesFit(p, to, body) @@ -4546,8 +4651,17 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if proto == provider.Responses { phases = &phaseTidy{sse: sse} } - // out is what a filter let through, through phases + // each item keeps the id it was added with (itemids.go): Copilot gives + // it another in every event + var ids *idTidy + if proto == provider.Responses && sse { + ids = &idTidy{} + } + // out is what a filter let through, through ids and phases out := func(b []byte) []byte { + if ids != nil { + b = ids.write(b) + } if phases != nil { return phases.write(b) } @@ -4602,6 +4716,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if sigs != nil { out = sigs.write(out) } + if ids != nil { + out = ids.write(out) + } if phases != nil { out = phases.write(out) } @@ -4664,6 +4781,13 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if sigs != nil { write(out(sigs.flush())) } + if ids != nil { + b := ids.flush() + if phases != nil { + b = phases.write(b) + } + write(b) + } if phases != nil { write(phases.flush()) } @@ -6060,7 +6184,9 @@ func validateModel(model string) (string, error) { // otherwise reads as Claude Opus 4 (provider.ClaudeSpelled) return real, nil } - return unflat(model), nil + // a found group's auto/ as group/auto-, the one id its + // key limits, routing, stats and usage rows know it by + return provider.CanonicalRef(unflat(model)), nil } // unflat is the catalog id a flat one stands for (provider.Unflat): MiniMax diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index a92e12fb6..1329a40c5 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -969,8 +969,8 @@ func TestModelsListReasoning(t *testing.T) { t.Fatal(err) } want := map[string]string{ - "a/sol": "low,medium,high,max", "b/sol": "medium,high", "group/auto-sol": "medium,high", - "a/mixed": "low,high", "b/mixed": "", "group/auto-mixed": "low,high", "a/plain": "", + "a/sol": "low,medium,high,max", "b/sol": "medium,high", "auto/sol": "medium,high", + "a/mixed": "low,high", "b/mixed": "", "auto/mixed": "low,high", "a/plain": "", } // a group reasons when any member does: b/mixed has no levels and a // list that says nothing of reasoning, but a/mixed does, so the group @@ -978,7 +978,7 @@ func TestModelsListReasoning(t *testing.T) { // at a/mixed's levels: b/mixed is sent no reasoning ask (quiet.go), so // it doesn't take them away (#2127: Codex showed no effort control for // a group with none, and ran it at medium) - reasoning := map[string]bool{"group/auto-mixed": true} + reasoning := map[string]bool{"auto/mixed": true} for _, m := range response.Data { expected, ok := want[m.ID] if !ok { diff --git a/internal/gateway/group_overhead_bench_test.go b/internal/gateway/group_overhead_bench_test.go new file mode 100644 index 000000000..9540b1127 --- /dev/null +++ b/internal/gateway/group_overhead_bench_test.go @@ -0,0 +1,196 @@ +package gateway + +import ( + "bytes" + "fmt" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// groupBenchUpstream answers an Anthropic request as it asked: streamed +// when its body says so. Refusing, it answers code with an overloaded +// error. +type groupBenchUpstream struct{ code int } + +const groupBenchReply = `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":7,"output_tokens":1}}` + +var groupBenchStream = sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"m1","usage":{"input_tokens":7}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`) + +func (u groupBenchUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + if u.code != 0 { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Retry-After", "3600") + w.WriteHeader(u.code) + io.WriteString(w, `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`) + return + } + if bytes.Contains(b, []byte(`"stream":true`)) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, groupBenchStream) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, groupBenchReply) +} + +// groupBenchCatalog is a catalog of providers serving models each, the +// same model ids at each (so magpie finds a group of each model), and +// groups of one, four and eight members, one whose first member fails +// every time, and one whose first member is resting. +func groupBenchCatalog(b *testing.B, providers, models int) { + b.Helper() + b.Setenv("XDG_CONFIG_HOME", b.TempDir()) + b.Setenv("XDG_CACHE_HOME", b.TempDir()) + good := httptest.NewServer(groupBenchUpstream{}) + b.Cleanup(good.Close) + failing := httptest.NewServer(groupBenchUpstream{code: 500}) + b.Cleanup(failing.Close) + resting := httptest.NewServer(groupBenchUpstream{code: 429}) + b.Cleanup(resting.Close) + var ids []string + for i := range models { + ids = append(ids, fmt.Sprintf("m%d", i)) + } + for i := range providers { + p := provider.Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: ids, Anthropic: good.URL} + if err := provider.Save(p); err != nil { + b.Fatal(err) + } + } + for _, p := range []provider.Provider{ + {ID: "bad", Name: "Bad", Key: "k", Models: ids, Anthropic: failing.URL}, + {ID: "rest", Name: "Rest", Key: "k", Models: ids, Anthropic: resting.URL}, + } { + if err := provider.Save(p); err != nil { + b.Fatal(err) + } + } + if err := settings.Save(settings.Settings{}); err != nil { + b.Fatal(err) + } + for _, g := range []provider.Group{ + {ID: "g1", Name: "G1", Members: []string{"p0/m1"}, Routing: provider.Ordered}, + {ID: "g4", Name: "G4", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1"}, Routing: provider.Ordered}, + {ID: "g8u", Name: "G8U", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1", "p4/m1", "p5/m1", "p6/m1", "p7/m1"}, Routing: provider.LeastUsed}, + {ID: "gfail", Name: "GFail", Members: []string{"bad/m1", "p0/m1", "p1/m1"}, Routing: provider.Ordered}, + {ID: "grest", Name: "GRest", Members: []string{"rest/m1", "p0/m1", "p1/m1"}, Routing: provider.Ordered}, + } { + if err := provider.SaveGroup(g); err != nil { + b.Fatal(err) + } + } + // as a user's files are: written a while ago, not just now (a file + // written in the last seconds is read again each time) + old := time.Now().Add(-time.Hour) + filepath.WalkDir(os.Getenv("XDG_CONFIG_HOME"), func(path string, _ fs.DirEntry, _ error) error { + return os.Chtimes(path, old, old) + }) + provider.Changed() +} + +// groupBenchCase is one benchmark's request. +type groupBenchCase struct { + providers, models, words int + stream bool + model string +} + +func (c groupBenchCase) name() string { + return fmt.Sprintf("catalog=%dx%d/%dKB/stream=%v/%s", c.providers, c.models, c.words*4/1000, c.stream, c.model) +} + +// groupBenchCases: a dozen providers of 20 models, with a ~200KB and a +// ~2MB conversation, and a large catalog (30 providers of 60 models, as +// a user of several relays has) with the ~200KB one. +func groupBenchCases() []groupBenchCase { + var out []groupBenchCase + for _, size := range []struct{ providers, models, words int }{{12, 20, 50_000}, {12, 20, 500_000}, {30, 60, 50_000}} { + for _, stream := range []bool{false, true} { + for _, model := range []string{"p0/m1", "group/g1", "group/g4", "group/g8u", "group/gfail", "group/grest"} { + out = append(out, groupBenchCase{size.providers, size.models, size.words, stream, model}) + } + } + } + return out +} + +// groupBenchServer is the gateway with c's catalog, and a request of the +// body c sends that fails the benchmark unless it is answered. +func groupBenchServer(b *testing.B, c groupBenchCase) func() { + noRests() + b.Cleanup(noRests) + groupBenchCatalog(b, c.providers, c.models) + body := largeConversation(provider.Anthropic, c.model, c.words) + if c.stream { + body = bytes.Replace(body, []byte(`"stream":false`), []byte(`"stream":true`), 1) + } + b.SetBytes(int64(len(body))) + h := New().Handler() + do := func() { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", bytes.NewReader(body))) + if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte("ok")) { + b.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + } + do() // the resting member rests + return do +} + +// BenchmarkGroupOverhead is a request to a provider's model and the same +// request to routing groups, streamed and not, with a long conversation: +// what magpie adds for a group is the difference. cpu-ms/op is the CPU +// the process spent, which a busy machine doesn't change as it does the +// wall time. +func BenchmarkGroupOverhead(b *testing.B) { + for _, c := range groupBenchCases() { + b.Run(c.name(), func(b *testing.B) { + do := groupBenchServer(b, c) + b.ResetTimer() + cpu, _ := processCPU() + for range b.N { + do() + } + after, _ := processCPU() + b.ReportMetric(float64(after-cpu)/float64(b.N)/1e6, "cpu-ms/op") + }) + } +} + +// BenchmarkGroupOverheadParallel is BenchmarkGroupOverhead's requests sent +// at once, as several agents send them. +func BenchmarkGroupOverheadParallel(b *testing.B) { + for _, c := range groupBenchCases() { + if c.stream || c.words > 50_000 { + continue + } + b.Run(c.name(), func(b *testing.B) { + do := groupBenchServer(b, c) + b.ResetTimer() + cpu, _ := processCPU() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + do() + } + }) + after, _ := processCPU() + b.ReportMetric(float64(after-cpu)/float64(b.N)/1e6, "cpu-ms/op") + }) + } +} diff --git a/internal/gateway/group_test.go b/internal/gateway/group_test.go index 27e790b00..7432a31b5 100644 --- a/internal/gateway/group_test.go +++ b/internal/gateway/group_test.go @@ -240,7 +240,7 @@ func TestRoutingGroups(t *testing.T) { ids = append(ids, e.ID) } } - if got := strings.Join(ids, " "); got != "group/auto-m a/m a/only-a b/vendor/m" { + if got := strings.Join(ids, " "); got != "auto/m a/m a/only-a b/vendor/m" { t.Fatalf("catalog: %s", got) } if err := provider.SaveGroup(provider.Group{Name: "Mine", Members: []string{"b/vendor/m", "a/only-a"}, Routing: provider.Ordered}); err != nil { diff --git a/internal/gateway/groups_off_test.go b/internal/gateway/groups_off_test.go index bac197919..f31597103 100644 --- a/internal/gateway/groups_off_test.go +++ b/internal/gateway/groups_off_test.go @@ -26,7 +26,7 @@ func TestGroupsOnAndOff(t *testing.T) { rec := httptest.NewRecorder() s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil)) list := rec.Body.String() - if strings.Contains(list, `"group/mine"`) != mine || !strings.Contains(list, `"group/auto-m"`) { + if strings.Contains(list, `"group/mine"`) != mine || !strings.Contains(list, `"auto/m"`) { t.Fatalf("%s: models %s", when, list) } code, body := postAs(t, s, "", `{"model":"group/mine","messages":[{"role":"user","content":"hi"}]}`) diff --git a/internal/gateway/image_input_test.go b/internal/gateway/image_input_test.go index e4ce8783a..89585a312 100644 --- a/internal/gateway/image_input_test.go +++ b/internal/gateway/image_input_test.go @@ -357,7 +357,7 @@ func TestGroupWithUnknownImageCapabilityReachesUpstream(t *testing.T) { } } for _, e := range provider.Catalog() { - if e.ID == "group/auto-claude-sonnet-4-5" { + if e.ID == "auto/claude-sonnet-4-5" { if !e.Images || e.ImageInput == nil || !*e.ImageInput { t.Fatalf("group image capability: %+v", e) } diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index ff2dfd78e..348523f1d 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -460,6 +460,11 @@ type Result struct { type collector struct { res Result args strings.Builder // arguments of the open tool call + // text is what the part at textAt-1 has had added to its text since, + // written into the part by flush: adding each delta to the part's + // string copied the whole reply so far every time + text strings.Builder + textAt int // fresh: a KThinkStart said the next reasoning is a block of its own fresh bool err string @@ -488,6 +493,25 @@ func (c *collector) open() *Part { return nil } +// grow adds s to the text of the part at i, the last one. +func (c *collector) grow(i int, s string) { + if c.textAt != i+1 { + c.flush() + c.text.WriteString(c.res.Parts[i].Text) + c.textAt = i + 1 + } + c.text.WriteString(s) +} + +// flush writes the text grow gathered into its part. +func (c *collector) flush() { + if c.textAt > 0 { + c.res.Parts[c.textAt-1].Text = c.text.String() + c.text = strings.Builder{} + c.textAt = 0 + } +} + func (c *collector) closeTool() { if p := c.last(ToolCall); p != nil && p.Args == nil { s := strings.TrimSpace(c.args.String()) @@ -512,7 +536,7 @@ func (c *collector) add(ev Event) { c.res.Usage.add(ev.Usage) case KText: if p := c.last(Text); p != nil { - p.Text += ev.Text + c.grow(len(c.res.Parts)-1, ev.Text) } else { c.closeTool() c.res.Parts = append(c.res.Parts, Part{Kind: Text, Text: ev.Text}) @@ -522,7 +546,7 @@ func (c *collector) add(ev Event) { return case KThink: if p := c.open(); p != nil { - p.Text += ev.Text + c.grow(len(c.res.Parts)-1, ev.Text) } else { c.closeTool() c.res.Parts = append(c.res.Parts, Part{Kind: Thinking, Text: ev.Text}) @@ -581,6 +605,7 @@ func (c *collector) add(ev Event) { } func (c *collector) finish() Result { + c.flush() c.closeTool() // a reply of tool calls ended "stop" (a relay's end_turn beside its // tool_use blocks, 蓝猫 on Discord) is the client's to run the calls diff --git a/internal/gateway/itemids.go b/internal/gateway/itemids.go new file mode 100644 index 000000000..126a1bba8 --- /dev/null +++ b/internal/gateway/itemids.go @@ -0,0 +1,123 @@ +package gateway + +import ( + "github.com/tidwall/gjson" +) + +// idTidy keeps each output item of a relayed Responses stream under the +// one id its output_item.added gave it. GitHub Copilot's /responses gives +// an item a new id in every event: the added, each delta, the done and +// response.completed's output each carry another (2026-10-19, a real +// account, gpt-5.5 with web_search). Codex starts an item by the added's +// id and finishes one by the done's, so with two ids a message was shown +// twice, once as it streamed and once finished, and a web search stayed +// started (echo_ts on Discord, once ec7f47432 relayed Codex on Copilot +// instead of translating it). An upstream whose ids already agree goes +// through as it came. +type idTidy struct { + buf []byte + ids map[int64]idOf // output_index → the item's id and type, as added +} + +type idOf struct{ id, typ string } + +func (t *idTidy) write(b []byte) []byte { + t.buf = append(t.buf, b...) + var out []byte + for { + n := eventEnd(t.buf) + if n < 0 { + return out + } + out = append(out, t.event(t.buf[:n])...) + t.buf = t.buf[n:] + } +} + +func (t *idTidy) flush() []byte { + b := t.buf + t.buf = nil + return b +} + +func (t *idTidy) event(ev []byte) []byte { + data := eventData(ev) + if len(data) == 0 || !gjson.ValidBytes(data) { + return append([]byte(nil), ev...) + } + e := gjson.ParseBytes(data) + at := e.Get("output_index") + switch typ := e.Get("type").String(); { + case typ == "response.output_item.added": + if id := e.Get("item.id").String(); id != "" && at.Exists() { + if t.ids == nil { + t.ids = map[int64]idOf{} + } + t.ids[at.Int()] = idOf{id, e.Get("item.type").String()} + } + return append([]byte(nil), ev...) + case typ == "response.completed" || typ == "response.incomplete" || typ == "response.failed": + return t.ended(ev, data, e) + case !at.Exists(): + return append([]byte(nil), ev...) + } + was, ok := t.ids[at.Int()] + if !ok { + return append([]byte(nil), ev...) + } + itemID, itemIn := e.Get("item_id"), e.Get("item.id") + if (!itemID.Exists() || itemID.String() == was.id) && (!itemIn.Exists() || itemIn.String() == was.id) { + return append([]byte(nil), ev...) + } + var m map[string]any + if decodeNumbers(data, &m) != nil { + return append([]byte(nil), ev...) + } + if itemID.Exists() { + m["item_id"] = was.id + } + if it, _ := m["item"].(map[string]any); it != nil && itemIn.Exists() && (was.typ == "" || it["type"] == was.typ) { + it["id"] = was.id + } + nb, err := marshalPlain(m) + if err != nil { + return append([]byte(nil), ev...) + } + return withData(ev, nb) +} + +// ended is the reply's last event, each item of its output under the id +// it was added with. +func (t *idTidy) ended(ev, data []byte, e gjson.Result) []byte { + differs := false + for i, it := range e.Get("response.output").Array() { + if was, ok := t.ids[int64(i)]; ok && it.Get("id").Exists() && it.Get("id").String() != was.id && (was.typ == "" || it.Get("type").String() == was.typ) { + differs = true + break + } + } + if !differs { + return append([]byte(nil), ev...) + } + var m map[string]any + if decodeNumbers(data, &m) != nil { + return append([]byte(nil), ev...) + } + res, _ := m["response"].(map[string]any) + out, _ := res["output"].([]any) + for i, v := range out { + it, _ := v.(map[string]any) + was, ok := t.ids[int64(i)] + if it == nil || !ok { + continue + } + if _, has := it["id"]; has && (was.typ == "" || it["type"] == was.typ) { + it["id"] = was.id + } + } + nb, err := marshalPlain(m) + if err != nil { + return append([]byte(nil), ev...) + } + return withData(ev, nb) +} diff --git a/internal/gateway/itemids_test.go b/internal/gateway/itemids_test.go new file mode 100644 index 000000000..1ffba1fb3 --- /dev/null +++ b/internal/gateway/itemids_test.go @@ -0,0 +1,104 @@ +package gateway + +import ( + "os" + "strings" + "testing" + + "github.com/tidwall/gjson" +) + +// Copilot's /responses gives an item a new id in every event (the fixture +// is a real reply, gpt-5.5 offered web_search and a function, its +// encrypted parts cut short). Relayed to Codex, each item keeps the one +// id it was added with, in its events, its done and response.completed, +// so Codex shows the commentary once and ends the search it started +// (echo_ts on Discord). +func TestCopilotItemKeepsItsID(t *testing.T) { + reply, err := os.ReadFile("testdata/copilot_rotating_ids.sse") + if err != nil { + t.Fatal(err) + } + c := copilotSol(t) + c.mu.Lock() + c.reply = string(reply) + c.mu.Unlock() + code, out := postTo(t, New(), "/v1/responses", `{"model":"copilot/gpt-6-luna","stream":true,"probe":"as sent", + "input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Search for the latest Go release, then run go version."}]}], + "tools":[{"type":"function","name":"exec_command","description":"Runs a command","strict":false,"parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}},{"type":"web_search"}]}`) + if code != 200 { + t.Fatalf("%d %s", code, out) + } + if c.last(t)["probe"] != "as sent" { + t.Fatal("not relayed: the reply under test is Copilot's own") + } + ids := map[int64]map[string]bool{} // output_index → every id it was given + note := func(at int64, id string) { + if ids[at] == nil { + ids[at] = map[string]bool{} + } + ids[at][id] = true + } + texts := map[string]int{} + completed := false + for _, line := range strings.Split(out, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok { + continue + } + e := gjson.Parse(data) + switch e.Get("type").String() { + case "response.completed": + completed = true + for i, it := range e.Get("response.output").Array() { + note(int64(i), it.Get("id").String()) + } + continue + case "response.output_item.done": + if it := e.Get("item"); it.Get("type").String() == "message" { + texts[it.Get("content.0.text").String()]++ + } + } + at := e.Get("output_index") + if !at.Exists() { + continue + } + if id := e.Get("item.id"); id.Exists() { + note(at.Int(), id.String()) + } + if id := e.Get("item_id"); id.Exists() { + note(at.Int(), id.String()) + } + } + if !completed || len(ids) != 4 { + t.Fatalf("completed %v, items %d: %s", completed, len(ids), out) + } + for at, seen := range ids { + if len(seen) != 1 { + t.Errorf("item %d went by %d ids", at, len(seen)) + } + } + if len(texts) != 1 { + t.Errorf("messages done: %v", texts) + } +} + +// An upstream whose ids agree, as OpenAI's do, goes through byte for byte. +func TestItemIDsThatAgreeGoAsTheyCame(t *testing.T) { + stream := sse( + `data: {"type":"response.created","response":{"id":"r1"}}`, + `data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`, + `data: {"type":"response.output_text.delta","output_index":0,"item_id":"msg_1","content_index":0,"delta":"a & c"}`, + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"a & c"}]}}`, + `data: {"type":"response.completed","response":{"id":"r1","output":[{"type":"message","id":"msg_1"}],"usage":{"input_tokens":1.0}}}`, + ) + var got []byte + tidy := &idTidy{} + for i := 0; i < len(stream); i += 7 { + got = append(got, tidy.write([]byte(stream[i:min(i+7, len(stream))]))...) + } + got = append(got, tidy.flush()...) + if string(got) != stream { + t.Errorf("changed:\n%s\nwant:\n%s", got, stream) + } +} diff --git a/internal/gateway/key_models.go b/internal/gateway/key_models.go index a1fa5d990..c22509800 100644 --- a/internal/gateway/key_models.go +++ b/internal/gateway/key_models.go @@ -16,9 +16,10 @@ import ( // is refused before any provider is asked. A model is held to by its // provider's id and its own, "/", whatever the agent // called it. A routing group passes when the key names it, "group/" -// (or "group/*", every group), and then every member of it does, through -// it; else only when every model in it does. A group the key names inside -// one it doesn't counts for its own members. +// (or "group/*", every group), a group magpie found by its auto/ +// too, either id passing for the other (allows), and then every member of +// it does, through it; else only when every model in it does. A group the +// key names inside one it doesn't counts for its own members. // magpieChoseKey marks, in a request's context, a call magpie makes for a // model the user picked in its settings rather than the caller (a web @@ -52,20 +53,46 @@ func accountHolds(r *http.Request) (access.Identity, bool) { return who, len(who.Accounts) > 0 } +// allows is who.Allows, a found group named by either of its ids: a key +// held to auto/ (as the model lists give it, any spelling of the +// model) may use group/auto-, the id the gateway routes it by, and +// one held to group/auto- or group/* the auto/ an agent asks +// for, which the gateway takes back to that id (validateModel). A pattern +// of auto/ ids ("auto/*") holds to the groups' auto/. +func allows(who access.Identity, ids ...string) bool { + if who.Allows(ids...) { + return true + } + for _, id := range ids { + if !strings.HasPrefix(id, provider.GroupPrefix+"auto-") { + continue + } + if pub := provider.PublicRef(id); pub != id && who.Allows(pub) { + return true + } + for _, p := range who.Models { + if !strings.Contains(p, "*") && strings.HasPrefix(p, provider.AutoPrefix) && strings.EqualFold(provider.CanonicalRef(p), id) { + return true + } + } + } + return false +} + // modelAllowed says the key may use provider p's model. func modelAllowed(who access.Identity, p provider.Provider, model string) bool { - return who.Allows(p.ID + "/" + model) + return allows(who, p.ID+"/"+model) } // memberAllowed says the key may use a routing group's member: the model, // or a group it is reached through that the key names. func memberAllowed(who access.Identity, m provider.Member) bool { - return who.Allows(append([]string{m.Provider.ID + "/" + m.Model}, m.Path...)...) + return allows(who, append([]string{m.Provider.ID + "/" + m.Model}, m.Path...)...) } // groupNamed says the key names the routing group g itself. func groupNamed(who access.Identity, g provider.Group) bool { - return g.ID != "" && who.Allows(provider.GroupPrefix+g.ID) + return g.ID != "" && (allows(who, provider.GroupPrefix+g.ID) || who.Allows(g.Ref())) } // groupAllowed says the key may use the routing group g: it names it, or diff --git a/internal/gateway/kimi_schema.go b/internal/gateway/kimi_schema.go index 28880dd36..8d698c323 100644 --- a/internal/gateway/kimi_schema.go +++ b/internal/gateway/kimi_schema.go @@ -2,6 +2,8 @@ package gateway import ( "bytes" + "net/url" + "sort" "strconv" "strings" @@ -16,9 +18,10 @@ import ( // defined" (#886, cua-driver's parse_visual_regions, whose kinds' items are // {"enum":["text","icon"]}), and the whole request fails though the tool is // never called. The type is the one every value has — string, integer, -// number or boolean; values of mixed types, or a null among them, are left -// as they were. It is written in place, after the schema's brace, so the -// rest of the body and a cache's prefix stay as they were. +// number or boolean, or that type and "null" when a null is among them, the +// one type array Kimi takes beside an enum; values of other mixed types are +// left as they were. It is written in place, after the schema's brace, so +// the rest of the body and a cache's prefix stay as they were. func kimiToolEnumTypes(p provider.Provider, to provider.Protocol, body []byte) []byte { if !isKimi(p, to) { return body @@ -32,19 +35,29 @@ func kimiToolEnumTypes(p provider.Provider, to provider.Protocol, body []byte) [ } var ins []typeInsert collectUntypedEnums(body, tools, false, &ins) + return withTypes(body, ins) +} + +// withTypes is body with each insert's type written after its schema's +// opening brace; a brace named twice gets it once. +func withTypes(body []byte, ins []typeInsert) []byte { if len(ins) == 0 { return body } - // the walk goes through the body in order, so the inserts ascend + sort.SliceStable(ins, func(i, j int) bool { return ins[i].at < ins[j].at }) var out bytes.Buffer - out.Grow(len(body) + len(ins)*20) - last := 0 + out.Grow(len(body) + len(ins)*24) + last := -1 for _, in := range ins { - out.Write(body[last : in.at+1]) - out.WriteString(`"type":"` + in.typ + `",`) - last = in.at + 1 + if in.at == last { + continue + } + start := last + 1 + out.Write(body[start : in.at+1]) + out.WriteString(`"type":` + in.typ + `,`) + last = in.at } - out.Write(body[last:]) + out.Write(body[last+1:]) return out.Bytes() } @@ -59,8 +72,8 @@ func isKimi(p provider.Provider, to provider.Protocol) bool { } type typeInsert struct { - at int // the schema's opening brace - typ string + at int // the schema's opening brace + typ string // the type as JSON: "string", or ["string","null"] } // collectUntypedEnums adds, for each schema under node with an enum or a @@ -80,7 +93,7 @@ func collectUntypedEnums(body []byte, node gjson.Result, inSchema bool, ins *[]t } else if c := node.Get("const"); c.Exists() { vals = []gjson.Result{c} } - if t := valuesType(vals); t != "" { + if t := enumType(vals); t != "" { *ins = append(*ins, typeInsert{node.Index, t}) } } @@ -109,6 +122,29 @@ func collectUntypedEnums(body []byte, node gjson.Result, inSchema bool, ins *[]t } } +// enumType is the type, as JSON, an enum or const of vals is written with +// for Kimi: the one all of them have, or it and "null" when a null is among +// them; "" when there are none or other types are mixed. +func enumType(vals []gjson.Result) string { + var rest []gjson.Result + null := false + for _, v := range vals { + if v.Type == gjson.Null { + null = true + continue + } + rest = append(rest, v) + } + t := valuesType(rest) + switch { + case t == "": + return "" + case null: + return `["` + t + `","null"]` + } + return `"` + t + `"` +} + // valuesType is the JSON Schema type all of vals have, "" when there are // none or they differ; whole numbers among fractions make them number. func valuesType(vals []gjson.Result) string { @@ -210,3 +246,256 @@ func leadingInt(s string) (int, string) { } return n, s[i:] } + +// kimiToolRefTypes is body with a type written into each schema its tools' +// $refs reach that has none, for Kimi and Moonshot. Their validator expands +// a $ref and refuses a target with no type — 400 "not a valid moonshot +// flavored json schema … At path 'properties.b': detected infinite +// recursion without termination condition" — and the whole request fails, +// though the same schema written inline passes. Codex sends such targets: +// its MCP and Codex App tools come as zod's $defs (__schema0, __schema1 …), +// and it types a def with properties or an enum but leaves a oneOf or an +// allOf one as it was (chaosy on Discord, Codex on k3). The type is the +// one the target's keywords or branches say, a type array when they differ, +// and every type when nothing does, which Kimi takes as "any". A target +// that is {}, an anyOf (Kimi refuses a type beside one: "type should be +// defined in anyOf items instead of the parent schema") or only another +// $ref is left as Kimi takes it, as is an enum whose values no one type +// array can hold. Written in place, like kimiToolEnumTypes', after which it +// runs. +func kimiToolRefTypes(p provider.Provider, to provider.Protocol, body []byte) []byte { + if !isKimi(p, to) || !bytes.Contains(body, []byte(`"$ref"`)) { + return body + } + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() || tools.Index <= 0 { + return body + } + var ins []typeInsert + tools.ForEach(func(_, tool gjson.Result) bool { + for _, at := range []string{"function.parameters", "parameters", "input_schema"} { + if root := tool.Get(at); root.IsObject() { + collectRefTargets(body, root, root, &ins) + } + } + return true + }) + return withTypes(body, ins) +} + +// collectRefTargets adds, for each local $ref under node (a schema of the +// tool schema root) whose target Kimi would refuse untyped, where the +// target opens and the type it is given. +func collectRefTargets(body []byte, root, node gjson.Result, ins *[]typeInsert) { + walkSchema(node, func(s gjson.Result) { + ref := s.Get(`\$ref`) + if ref.Type != gjson.String { + return + } + t, ok := refTarget(root, ref.String()) + if !ok || !t.IsObject() || t.Index <= 0 || t.Index >= len(body) || body[t.Index] != '{' || !untypedForKimi(t) { + return + } + if typ := kimiSchemaType(root, t); typ != "" { + *ins = append(*ins, typeInsert{t.Index, typ}) + } + }) +} + +// walkSchema calls f with node and every schema under it, through the +// keywords that hold schemas. +func walkSchema(node gjson.Result, f func(gjson.Result)) { + switch { + case node.IsArray(): + node.ForEach(func(_, v gjson.Result) bool { + walkSchema(v, f) + return true + }) + case node.IsObject(): + f(node) + node.ForEach(func(key, v gjson.Result) bool { + switch key.String() { + case "properties", "$defs", "definitions", "dependentSchemas", "patternProperties": + v.ForEach(func(_, s gjson.Result) bool { + walkSchema(s, f) + return true + }) + case "items", "additionalProperties", "contains", "propertyNames", "not", "if", "then", "else", "allOf", "anyOf", "oneOf", "prefixItems", "unevaluatedProperties", "unevaluatedItems", "contentSchema": + walkSchema(v, f) + } + return true + }) + } +} + +// refTarget is the schema a local $ref ("#", "#/$defs/x") names in root. +func refTarget(root gjson.Result, ref string) (gjson.Result, bool) { + if ref != "#" && !strings.HasPrefix(ref, "#/") { + return gjson.Result{}, false + } + cur := root + for _, tok := range strings.Split(ref, "/")[1:] { + tok = strings.ReplaceAll(strings.ReplaceAll(tok, "~1", "/"), "~0", "~") + if u, err := url.PathUnescape(tok); err == nil { + tok = u + } + if !cur.IsObject() && !cur.IsArray() { + return gjson.Result{}, false + } + cur = cur.Get(gjson.Escape(tok)) + if !cur.Exists() { + return gjson.Result{}, false + } + } + return cur, true +} + +// untypedForKimi is whether Kimi refuses s as a $ref's target: it has no +// type, isn't {}, an anyOf, or a $ref with nothing but notes beside it. +func untypedForKimi(s gjson.Result) bool { + if s.Get("type").Exists() || s.Get("anyOf").Exists() { + return false + } + only := true + n := 0 + s.ForEach(func(k, _ gjson.Result) bool { + n++ + switch k.String() { + case "$ref", "description", "title", "default", "examples", "$comment": + default: + only = false + } + return true + }) + if n == 0 { + return false + } + return !(only && s.Get(`\$ref`).Exists()) +} + +// allKimiTypes is every JSON Schema type, which Kimi takes for a schema +// that may be anything. +const allKimiTypes = `["string","number","integer","boolean","object","array","null"]` + +// kimiSchemaType is the type, as JSON, an untyped schema s is given: the +// one (or the ones) its keywords and branches say, every type when they +// say nothing, and "" for an enum no type Kimi takes beside one can hold. +func kimiSchemaType(root, s gjson.Result) string { + if e := s.Get("enum"); e.IsArray() { + return enumType(e.Array()) + } + if c := s.Get("const"); c.Exists() { + return enumType([]gjson.Result{c}) + } + ts := schemaTypes(root, s, 0) + if len(ts) == 0 { + return allKimiTypes + } + if ts["integer"] && ts["number"] { + delete(ts, "integer") + } + var names []string + for _, t := range []string{"string", "number", "integer", "boolean", "object", "array", "null"} { + if ts[t] { + names = append(names, `"`+t+`"`) + } + } + if len(names) == 1 { + return names[0] + } + return "[" + strings.Join(names, ",") + "]" +} + +// schemaTypes is the set of types s can have, as its type, its keywords, +// its values or its branches (through their $refs) say; nil when they +// don't say. +func schemaTypes(root, s gjson.Result, depth int) map[string]bool { + if depth > 16 || !s.IsObject() { + return nil + } + ts := map[string]bool{} + if t := s.Get("type"); t.Exists() { + for _, v := range t.Array() { + ts[v.String()] = true + } + return ts + } + if ref := s.Get(`\$ref`); ref.Type == gjson.String { + if t, ok := refTarget(root, ref.String()); ok { + return schemaTypes(root, t, depth+1) + } + return nil + } + if e := s.Get("enum"); e.IsArray() || s.Get("const").Exists() { + vals := e.Array() + if c := s.Get("const"); c.Exists() { + vals = []gjson.Result{c} + } + for _, v := range vals { + switch v.Type { + case gjson.String: + ts["string"] = true + case gjson.True, gjson.False: + ts["boolean"] = true + case gjson.Null: + ts["null"] = true + case gjson.Number: + if strings.ContainsAny(v.Raw, ".eE") { + ts["number"] = true + } else { + ts["integer"] = true + } + default: + if v.IsArray() { + ts["array"] = true + } else { + ts["object"] = true + } + } + } + return ts + } + // a branch that says nothing makes oneOf and anyOf anything; allOf + // is what its branches that do say + for _, k := range []string{"oneOf", "anyOf", "allOf"} { + bs := s.Get(k) + if !bs.IsArray() { + continue + } + known := false + for _, b := range bs.Array() { + bt := schemaTypes(root, b, depth+1) + if len(bt) == 0 && k != "allOf" { + return nil + } + for t := range bt { + ts[t] = true + known = true + } + } + if known { + return ts + } + } + has := func(keys ...string) bool { + for _, k := range keys { + if s.Get(k).Exists() { + return true + } + } + return false + } + switch { + case has("properties", "required", "additionalProperties", "patternProperties", "minProperties", "maxProperties", "propertyNames", "dependentRequired", "dependentSchemas", "unevaluatedProperties"): + ts["object"] = true + case has("items", "prefixItems", "minItems", "maxItems", "uniqueItems", "contains", "unevaluatedItems"): + ts["array"] = true + case has("minLength", "maxLength", "pattern", "format", "contentEncoding", "contentMediaType"): + ts["string"] = true + case has("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"): + ts["number"] = true + default: + return nil + } + return ts +} diff --git a/internal/gateway/kimi_schema_test.go b/internal/gateway/kimi_schema_test.go index 0eda23d58..56cb91864 100644 --- a/internal/gateway/kimi_schema_test.go +++ b/internal/gateway/kimi_schema_test.go @@ -18,7 +18,9 @@ import ( // 'properties.options.properties.kinds.anyOf.items': type is not defined" // (#886), and the whole request failed. Values of mixed types, a schema // with a type, a property called enum and the rest of the body are left as -// they were; anyone else is sent the tools unchanged. +// they were; a null among one type's values gives that type and "null", +// the type array Kimi takes beside an enum. Anyone else is sent the tools +// unchanged. func TestKimiToolEnumTypes(t *testing.T) { t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("XDG_CACHE_HOME", t.TempDir()) @@ -61,6 +63,7 @@ func TestKimiToolEnumTypes(t *testing.T) { `"scale":{"enum"`, `"scale":{"type":"number","enum"`, `"on":{"const"`, `"on":{"type":"boolean","const"`, `"mode":{ "enum"`, `"mode":{"type":"string", "enum"`, + `"maybe":{"enum"`, `"maybe":{"type":["string","null"],"enum"`, ).Replace(tools) b := got["api.kimi.com"] if !strings.Contains(b, want) { @@ -74,6 +77,96 @@ func TestKimiToolEnumTypes(t *testing.T) { } } +// A schema a tool's $ref reaches goes to Kimi with a type: Kimi expands +// the $ref and refuses a target with none, 400 "At path 'properties.b': +// detected infinite recursion without termination condition", and Codex on +// k3 failed outright (chaosy on Discord). Codex sends zod's $defs with a +// oneOf or allOf def untyped, as captured from Codex 0.162.1 (b, c); raw +// clients send defs typed by nothing but their keywords, or by nothing at +// all. Each goes on the chat route, the Anthropic route and from Codex's +// Responses; a {} def, an anyOf (Kimi refuses a type beside one), a typed +// def, an unreferenced one and the rest of the body are left as they were, +// and anyone else is sent the tools unchanged. +func TestKimiToolRefTypes(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + kimi, err := provider.FromPreset("kimi-code-cn") + if err != nil { + t.Fatal(err) + } + kimi.ID, kimi.Key, kimi.Models = "kimi", "k", []string{"m"} + for _, p := range []provider.Provider{kimi, + {ID: "other", Name: "Other", Key: "k", Chat: "https://other.test/v1", Anthropic: "https://other.test", Models: []string{"m"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + got := map[string]string{} + s := New() + s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) { + b, _ := io.ReadAll(r.Body) + got[r.URL.Host+r.URL.Path] = string(b) + return &http.Response{StatusCode: 400, Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"no","type":"invalid_request_error"}}`))}, nil + })} + schema := `{"type":"object","properties":{"a":{"$ref":"#/$defs/__schema0"},"b":{"$ref":"#/$defs/__schema1"},` + + `"c":{"items":{"$ref":"#/$defs/__schema2"},"type":"array"},"d":{"anyOf":[{"$ref":"#/$defs/P"},{"type":"null"}]},` + + `"e":{"$ref":"#/$defs/M"},"f":{"$ref":"#/definitions/D"},"g":{"$ref":"#/$defs/R"},"h":{"$ref":"#/$defs/U"},"i":{"$ref":"#/$defs/S"}},` + + `"$defs":{"__schema0":{},"__schema1":{"oneOf":[{"type":"string"},{"type":"number"}]},"__schema2":{"allOf":[{"type":"string"}]},` + + `"P":{"properties":{"x":{"type":"string"}}},"M":{"minLength":1},"R":{"oneOf":[{"$ref":"#/$defs/P"},{"$ref":"#/definitions/D"}]},` + + `"U":{"anyOf":[{"type":"string"},{"$ref":"#/$defs/U"}]},"S":{"type":"string","enum":["x"]},"V":{"oneOf":[{"type":"string"}]}},` + + `"definitions":{"D":{"description":"anything"}}}` + anything := `["string","number","integer","boolean","object","array","null"]` + want := strings.NewReplacer( + `"__schema1":{`, `"__schema1":{"type":["string","number"],`, + `"__schema2":{`, `"__schema2":{"type":"string",`, + `"P":{`, `"P":{"type":"object",`, + `"M":{`, `"M":{"type":"string",`, + `"R":{`, `"R":{"type":`+anything+`,`, + `"D":{`, `"D":{"type":`+anything+`,`, + ).Replace(schema) + routes := []struct{ path, tools, upstream, otherUp string }{ + {"/v1/chat/completions", `"tools":[{"type":"function","function":{"name":"automation_update","parameters":%s}}]`, "api.kimi.com/coding/v1/chat/completions", "other.test/v1/chat/completions"}, + {"/v1/messages", `"tools":[{"name":"automation_update","input_schema":%s}]`, "api.kimi.com/coding/v1/messages", "other.test/v1/messages"}, + {"/v1/responses", `"tools":[{"type":"function","name":"automation_update","parameters":%s}]`, "api.kimi.com/coding/v1/chat/completions", "other.test/v1/chat/completions"}, + } + for _, r := range routes { + for _, id := range []string{"kimi", "other"} { + clear(got) + msgs := `"messages":[{"role":"user","content":"hi"}],"max_tokens":16,` + if r.path == "/v1/responses" { + msgs = `"input":"hi",` + } + body := `{"model":"` + id + `/m",` + msgs + strings.Replace(r.tools, "%s", schema, 1) + `}` + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", r.path, strings.NewReader(body))) + up := r.upstream + if id == "other" { + up = r.otherUp + } + b, ok := got[up] + if !ok { + t.Fatalf("%s %s: nothing sent to %s, only %v (%d %s)", r.path, id, up, got, rec.Code, rec.Body) + } + if !json.Valid([]byte(b)) { + t.Fatalf("%s %s: invalid JSON sent:\n%s", r.path, id, b) + } + sent := gjson.Get(b, "tools.0.function.parameters") + if !sent.Exists() { + sent = gjson.Get(b, "tools.0.input_schema") + } + w := schema + if id == "kimi" { + w = want + } + if sent.Raw != w { + t.Errorf("%s %s was sent:\n%s\nwant:\n%s", r.path, id, sent.Raw, w) + } + } + } +} + // A request to a model whose server locks temperature and top_p — Kimi // Code's kimi-for-coding and k3*, kimi-k2.5 and later on either Kimi // platform — goes without them: the whitelist refuses the ones clients diff --git a/internal/gateway/lan_test.go b/internal/gateway/lan_test.go index 84caeb9dc..3d381613f 100644 --- a/internal/gateway/lan_test.go +++ b/internal/gateway/lan_test.go @@ -332,6 +332,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) { routes := [][2]string{ {"GET", "/"}, {"GET", "/v1"}, {"GET", "/v1/models"}, {"GET", "/models"}, {"GET", "/v1/models/x"}, {"GET", "/muse-code/models"}, {"GET", "/api/hello"}, + {"GET", "/api/version"}, {"GET", "/api/tags"}, {"POST", "/api/show"}, {"GET", "/v1/magpie/quotas"}, {"GET", "/v1/magpie/quotas/history"}, {"GET", provider.RemoteCardsPath}, {"POST", provider.RemoteRefreshPath}, {"GET", "/v1/magpie/route?session=s"}, {"GET", "/v1/magpie/concurrency"}, {"GET", "/v1/magpie/limit"}, diff --git a/internal/gateway/maxoutput.go b/internal/gateway/maxoutput.go index ee7f92359..67421c341 100644 --- a/internal/gateway/maxoutput.go +++ b/internal/gateway/maxoutput.go @@ -1,7 +1,12 @@ package gateway import ( + "bytes" "encoding/json" + "regexp" + "strconv" + + "github.com/tidwall/gjson" "github.com/yetone/magpie/internal/provider" ) @@ -109,3 +114,74 @@ func withMaxOutput(proto provider.Protocol, body []byte, limit int) []byte { } return withFields(body, fields) } + +// replyLeft reads, from a refusal that counts the reply asked for in the +// window (DeepSeek's and vLLM's "This model's maximum context length is +// 1000000 tokens. However, you requested 1100000 tokens (706784 in the +// messages, 393216 in the completion)"), the tokens the window has left +// for a reply after the prompt; 0 when the error isn't one of those, or +// the prompt alone fills the window. +func replyLeft(msg []byte) int { + window, prompt := 0, 0 + if m := windowAndPrompt.FindSubmatch(msg); m != nil { + window, _ = strconv.Atoi(string(m[1])) + prompt, _ = strconv.Atoi(string(m[2])) + if m[2] == nil { + prompt, _ = strconv.Atoi(string(m[3])) + } + } else if m := inputPlusReply.FindSubmatch(msg); m != nil { + prompt, _ = strconv.Atoi(string(m[1])) + window, _ = strconv.Atoi(string(m[2])) + } + if window <= 0 || prompt <= 0 || prompt >= window { + return 0 + } + return window - prompt +} + +// windowAndPrompt matches the window and the prompt's part of a refusal +// that adds the reply's allowance to the prompt: "(N in the messages, M in +// the completion)", or vLLM's newer "your prompt contains at least N input +// tokens". +var windowAndPrompt = regexp.MustCompile(`(?is)maximum context length is (\d+) tokens.{0,200}?(?:\((\d+) in the messages, \d+ in the completion\)|your prompt contains at least (\d+) input tokens)`) + +// inputPlusReply is Anthropic's words for the same, which an endpoint +// speaking its API may answer with: "input length and `max_tokens` exceed +// context limit: 197202 + 21333 > 200000". +var inputPlusReply = regexp.MustCompile(`(?i)input length and .{0,3}max_tokens.{0,3} exceed context limit:\s*(\d+)\s*\+\s*\d+\s*>\s*(\d+)`) + +// leastReplyLeft is the least room left for a reply that is worth asking +// for: less, and the conversation needs compacting, which the refusal +// tells the agent as it is (DeepSeek's own default reply is 8K). +const leastReplyLeft = 8192 + +// withReplyCap is body asking for a reply of at most limit tokens, in +// proto's words, whether or not it named a limit before: a request that +// named none was given the vendor's own, which was too large. false when +// it asked for no more already, or proto keeps no such field magpie sets. +func withReplyCap(proto provider.Protocol, body []byte, limit int) ([]byte, bool) { + if limit <= 0 { + return nil, false + } + out := withMaxOutput(proto, body, limit) + if !bytes.Equal(out, body) { + return out, true + } + var key string + switch proto { + case provider.Chat: + if gjson.GetBytes(body, "max_tokens").Exists() || gjson.GetBytes(body, "max_completion_tokens").Exists() { + return nil, false + } + key = "max_tokens" + case provider.Responses: + if gjson.GetBytes(body, "max_output_tokens").Exists() { + return nil, false + } + key = "max_output_tokens" + default: + // Anthropic's always names one; Gemini's is lowered above + return nil, false + } + return withFields(body, map[string]any{key: limit}), true +} diff --git a/internal/gateway/off_test.go b/internal/gateway/off_test.go index 4c84d71ab..76d1316ad 100644 --- a/internal/gateway/off_test.go +++ b/internal/gateway/off_test.go @@ -34,7 +34,7 @@ func TestProviderOff(t *testing.T) { } return strings.Join(ids, " ") } - const all = "group/mine group/auto-m a/m a/only-a b/vendor/m b/only-b" + const all = "group/mine auto/m a/m a/only-a b/vendor/m b/only-b" if got := catalog(); got != all { t.Fatalf("catalog: %s", got) } @@ -46,7 +46,7 @@ func TestProviderOff(t *testing.T) { if err != nil || !pb.Off || pb.Key != "kb" { t.Fatalf("switched off, b is kept with its key: %+v %v", pb, err) } - if got := catalog(); got != "group/mine group/auto-m a/m a/only-a" { + if got := catalog(); got != "group/mine auto/m a/m a/only-a" { t.Fatalf("catalog with b off: %s", got) } if _, _, ok := provider.Resolve("b/vendor/m"); ok { diff --git a/internal/gateway/ollama.go b/internal/gateway/ollama.go new file mode 100644 index 000000000..56fb98a0f --- /dev/null +++ b/internal/gateway/ollama.go @@ -0,0 +1,159 @@ +package gateway + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "strings" + + "github.com/yetone/magpie/internal/provider" +) + +// The Ollama API's model routes, for a client that takes a custom endpoint +// only as an Ollama server (Visual Studio's Copilot BYOK, wani on Discord; +// VS Code's Copilot "Ollama" provider): the user enters the gateway's own +// address (http://127.0.0.1:3425) as the Ollama endpoint. VS Code's +// Copilot (vscode-copilot-chat, ollamaProvider.ts) asks /api/version and +// refuses a server older than 0.6.4, lists /api/tags and takes each +// model's "model", asks /api/show of each (a model whose show fails or +// has no capabilities is left out), and chats on the server's +// OpenAI-compatible /v1/chat/completions, which magpie serves already. +// These routes sit on Handler's mux, so lanGuard, corsGuard and the key +// limits judge them as every route. + +// ollamaVersion is the Ollama release magpie answers /api/version as: one +// past every client's minimum (VS Code's Copilot asks 0.6.4). +const ollamaVersion = "0.12.6" + +func (s *Server) ollamaVersion(w http.ResponseWriter, r *http.Request) { + writeJSON(w, 200, map[string]any{"version": ollamaVersion}) +} + +// ollamaTags lists the models the agent asking is shown, as Ollama's +// /api/tags lists the pulled ones: name and model are magpie's id, which +// the client sends back as the model to chat with. +func (s *Server) ollamaTags(w http.ResponseWriter, r *http.Request) { + models := []map[string]any{} + for _, e := range catalogFor(r) { + models = append(models, map[string]any{ + "name": e.ID, "model": e.ID, "modified_at": ollamaModified, "size": 0, + "digest": ollamaDigest(e.ID), "details": ollamaDetails(e), "capabilities": ollamaCapabilities(e), + }) + } + writeJSON(w, 200, map[string]any{"models": models}) +} + +// ollamaShow is one model as Ollama's /api/show tells it. A client reads +// what it takes from capabilities, its window from model_info's +// ".context_length" (VS Code's Copilot takes 32768 +// without it) and its name from "general.basename". +func (s *Server) ollamaShow(w http.ResponseWriter, r *http.Request) { + body, ok := s.requestBody(w, r, provider.Chat) + if !ok { + return + } + var req struct { + Model string `json:"model"` + Name string `json:"name"` // what clients before Ollama 0.5 send + } + if err := json.Unmarshal(body, &req); err != nil { + ollamaError(w, http.StatusBadRequest, "invalid request: "+err.Error()) + return + } + id := strings.TrimSpace(req.Model) + if id == "" { + id = strings.TrimSpace(req.Name) + } + if id == "" { + ollamaError(w, http.StatusBadRequest, "model is required") + return + } + e, ok := ollamaEntry(r, id) + if !ok { + ollamaError(w, http.StatusNotFound, "model '"+id+"' not found") + return + } + // every key here is sent: the ollama CLI before 0.7 reads + // parameter_count, context_length and embedding_length without + // checking them and panics on one missing ("ollama show", 0.6.8) + window := e.Context + if window <= 0 { + // what VS Code's Copilot assumes without one; a 0 it would take + // as the window + window = ollamaDefaultContext + } + info := map[string]any{ + "general.architecture": ollamaArch, "general.basename": provider.Labels([]provider.Entry{e})[0], + "general.parameter_count": 0, ollamaArch + ".context_length": window, ollamaArch + ".embedding_length": 0, + } + writeJSON(w, 200, map[string]any{ + "modelfile": "", "parameters": "", "template": "", + "details": ollamaDetails(e), "model_info": info, "capabilities": ollamaCapabilities(e), + "modified_at": ollamaModified, + }) +} + +// ollamaCapabilities are what the model does, in Ollama's words: it +// completes and calls tools (every model magpie serves is asked with +// tools), sees when it takes images, and thinks when it reasons. +func ollamaCapabilities(e provider.Entry) []string { + caps := []string{"completion", "tools"} + if e.Images { + caps = append(caps, "vision") + } + if e.Thinks() { + caps = append(caps, "thinking") + } + return caps +} + +// ollamaArch is the architecture every model is told as: model_info's +// keys are named after it. +const ollamaArch = "magpie" + +// ollamaDefaultContext is the window told for a model whose own magpie +// doesn't know: the one VS Code's Copilot takes when none is told. +const ollamaDefaultContext = 32768 + +// ollamaModified stands in for when a model was pulled, which no model +// here was. +const ollamaModified = "2025-01-01T00:00:00Z" + +// ollamaEntry is the model id names among those the caller is shown (a +// gateway key held to some models is shown those alone): by its catalog +// id, or its bare id when the user lists bare ids. +func ollamaEntry(r *http.Request, id string) (provider.Entry, bool) { + shown := catalogFor(r) + id = unprefixed(id) + for _, e := range shown { + if e.ID == id { + return e, true + } + } + if provider.BareModelIDs() { + return provider.BareEntry(shown, id) + } + return provider.Entry{}, false +} + +func ollamaDetails(e provider.Entry) map[string]any { + d := map[string]any{"parent_model": "", "format": "", "family": ollamaArch, "families": []string{ollamaArch}, + "parameter_size": "", "quantization_level": ""} + if e.Context > 0 { + d["context_length"] = e.Context + } + return d +} + +// ollamaDigest stands in for a model file's digest: the same id always +// gives the same one. +func ollamaDigest(id string) string { + sum := sha256.Sum256([]byte(id)) + return hex.EncodeToString(sum[:]) +} + +// ollamaError is an error as Ollama's API says one. +func ollamaError(w http.ResponseWriter, status int, msg string) { + writeJSON(w, status, map[string]any{"error": msg}) +} diff --git a/internal/gateway/ollama_test.go b/internal/gateway/ollama_test.go new file mode 100644 index 000000000..45ded2244 --- /dev/null +++ b/internal/gateway/ollama_test.go @@ -0,0 +1,277 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// ollamaPlan is a provider with a model that sees, thinks and has a +// window, and one that does none of these, for the Ollama routes to tell +// of. +func ollamaPlan(t *testing.T, chat string) { + t.Helper() + yes, no := true, false + if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: chat, + Models: []string{"seer", "plain"}, Contexts: map[string]int{"seer": 400000}}); err != nil { + t.Fatal(err) + } + for _, err := range []error{ + provider.SetModelImage("plan/seer", &yes), provider.SetModelImage("plan/plain", &no), + provider.SetModelEfforts("plan/seer", []string{"low", "high"}), + } { + if err != nil { + t.Fatal(err) + } + } +} + +// A client that takes a custom endpoint only as an Ollama server (Visual +// Studio's Copilot BYOK, wani on Discord; VS Code's Copilot Ollama +// provider) asks /api/version, lists /api/tags and reads each model's +// capabilities and window from /api/show, then chats on +// /v1/chat/completions. The list is magpie's catalog by its ids, and a +// model's window and what it takes are its catalog entry's. +func TestOllamaModelRoutes(t *testing.T) { + fresh(t) + ollamaPlan(t, "http://127.0.0.1:1/v1") + h := New().Handler() + do := func(method, path, body string) *httptest.ResponseRecorder { + t.Helper() + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.RemoteAddr = "127.0.0.1:50123" + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + if w := do("GET", "/api/version", ""); w.Code != 200 || !strings.Contains(w.Body.String(), `"version":"`+ollamaVersion+`"`) { + t.Fatalf("version: %d %s", w.Code, w.Body) + } + var tags struct { + Models []struct { + Name, Model, Digest string + Details struct{ Family string } + } + } + w := do("GET", "/api/tags", "") + if err := json.Unmarshal(w.Body.Bytes(), &tags); err != nil || w.Code != 200 { + t.Fatalf("tags: %d %s", w.Code, w.Body) + } + var names []string + for _, m := range tags.Models { + if m.Name != m.Model || len(m.Digest) != 64 { + t.Fatalf("tag %+v", m) + } + names = append(names, m.Name) + } + if !slices.Contains(names, "plan/seer") || !slices.Contains(names, "plan/plain") { + t.Fatalf("tags list %v", names) + } + type shown struct { + Capabilities []string + ModelInfo map[string]any `json:"model_info"` + } + show := func(body string) (int, shown) { + t.Helper() + w := do("POST", "/api/show", body) + var s shown + if w.Code == 200 { + if err := json.Unmarshal(w.Body.Bytes(), &s); err != nil { + t.Fatal(w.Body.String()) + } + } + return w.Code, s + } + c, s := show(`{"model":"plan/seer"}`) + arch, _ := s.ModelInfo["general.architecture"].(string) + if c != 200 || !slices.Equal(s.Capabilities, []string{"completion", "tools", "vision", "thinking"}) || s.ModelInfo[arch+".context_length"] != float64(400000) || + !strings.Contains(fmt.Sprint(s.ModelInfo["general.basename"]), "seer") { + t.Fatalf("show seer: %d %+v", c, s) + } + // a client from before Ollama 0.5 names it "name"; a window magpie + // doesn't know is told as the one VS Code's Copilot assumes, never 0 + c, s = show(`{"name":"plan/plain"}`) + if c != 200 || !slices.Equal(s.Capabilities, []string{"completion", "tools"}) || s.ModelInfo[arch+".context_length"] != float64(32768) { + t.Fatalf("show plain: %d %+v", c, s) + } + // the ollama CLI before 0.7 reads these as numbers unchecked, and + // panics on one missing ("ollama show" with 0.6.8) + for _, k := range []string{"general.parameter_count", arch + ".context_length", arch + ".embedding_length"} { + if _, ok := s.ModelInfo[k].(float64); !ok { + t.Fatalf("model_info %s: %v", k, s.ModelInfo[k]) + } + } + if c, _ := show(`{"model":"plan/nothing"}`); c != 404 { + t.Fatal("an unknown model:", c) + } + if c, _ := show(`{}`); c != 400 { + t.Fatal("no model:", c) + } +} + +// A gateway key held to some models is listed and shown those alone on the +// Ollama routes, as on /v1/models. +func TestOllamaRoutesHoldAKey(t *testing.T) { + fresh(t) + ollamaPlan(t, "http://127.0.0.1:1/v1") + keys, secrets := newCaller(t, "Held") + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/plain"}}); err != nil { + t.Fatal(err) + } + h := New().Handler() + do := func(method, path, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+secrets[0]) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + if w := do("GET", "/api/tags", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "plan/plain") || strings.Contains(w.Body.String(), "plan/seer") { + t.Fatalf("held key's tags: %d %s", w.Code, w.Body) + } + if w := do("POST", "/api/show", `{"model":"plan/seer"}`); w.Code != 404 { + t.Fatalf("held key shown a model it may not use: %d %s", w.Code, w.Body) + } + if w := do("POST", "/api/show", `{"model":"plan/plain"}`); w.Code != 200 { + t.Fatalf("held key's own model: %d %s", w.Code, w.Body) + } +} + +// The Ollama routes are guarded as every gateway route is, through the +// real server stack: with no key, a page elsewhere, a sandboxed frame +// (Origin null), a page at a localhost subdomain, a page rebound to +// loopback under its own name, and another machine while magpie isn't +// shared or sends none are all refused, and none is told a model. An +// agent on this computer, and a keyed call, are answered. +func TestOllamaRoutesGuarded(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + t.Setenv("MAGPIE_PUBLIC_URL", "") + t.Setenv("MAGPIE_TRUST_PROXY", "") + ollamaPlan(t, "http://127.0.0.1:1/v1") + srv := lanGuard(New().Handler()) + routes := []struct{ method, path, body string }{ + {"GET", "/api/version", ""}, + {"GET", "/api/tags", ""}, + {"POST", "/api/show", `{"model":"plan/seer"}`}, + } + const gw = "127.0.0.1:3425" + browser := []string{"User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15", + "Sec-Fetch-Mode", "no-cors", "Content-Type", "text/plain;charset=UTF-8"} + do := func(method, path, body, from, host string, hdr ...string) *httptest.ResponseRecorder { + t.Helper() + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.RemoteAddr, r.Host = from, host + for i := 0; i+1 < len(hdr); i += 2 { + r.Header.Set(hdr[i], hdr[i+1]) + } + w := httptest.NewRecorder() + srv.ServeHTTP(w, r) + return w + } + refused := func(what string, w *httptest.ResponseRecorder, codes ...int) { + t.Helper() + if !slices.Contains(codes, w.Code) || strings.Contains(w.Body.String(), "plan/") || w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("%s: %d %s", what, w.Code, w.Body) + } + } + for _, rt := range routes { + at := rt.method + " " + rt.path + // pages on this computer's browser, with no key + refused(at+" from a page elsewhere", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, append([]string{"Origin", "https://evil.example", "Sec-Fetch-Site", "cross-site"}, browser...)...), http.StatusForbidden) + refused(at+" from Origin null", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, append([]string{"Origin", "null", "Sec-Fetch-Site", "cross-site"}, browser...)...), http.StatusForbidden) + refused(at+" from a localhost subdomain", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, append([]string{"Origin", "http://evil.localhost", "Sec-Fetch-Site", "cross-site"}, browser...)...), http.StatusForbidden) + // rebound: no Origin on a GET, the page's own on a POST + hdr := append([]string{"Sec-Fetch-Site", "same-origin"}, browser...) + if rt.method == "POST" { + hdr = append(hdr, "Origin", "http://rebind.attacker.example:3425") + } + refused(at+" rebound", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", "rebind.attacker.example:3425", hdr...), http.StatusForbidden) + refused(at+" rebound at a localhost subdomain", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", "evil.localhost:3425", hdr...), http.StatusForbidden) + // another machine, no Origin at all: magpie not shared + refused(at+" from the LAN, not shared", do(rt.method, rt.path, rt.body, "192.168.1.9:5000", "192.168.1.2:3425"), http.StatusForbidden) + // a tunnel on loopback + refused(at+" through a tunnel, not shared", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, "X-Forwarded-For", "203.0.113.9"), http.StatusForbidden) + // an agent here, as VS Code's Copilot calls it: answered + if w := do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, "User-Agent", "node-fetch"); w.Code != 200 { + t.Errorf("%s from an agent here: %d %s", at, w.Code, w.Body) + } + } + // shared: another machine needs an enabled key + _, secrets := newCaller(t, "Visual Studio") + for _, rt := range routes { + at := rt.method + " " + rt.path + for _, hdr := range [][]string{nil, {"Authorization", "Bearer magpie"}, {"Authorization", "Bearer sk-magpie-wrong"}} { + resetAuthThrottle() + refused(at+" from the LAN with "+strings.Join(hdr, " "), do(rt.method, rt.path, rt.body, "192.168.1.9:5000", "192.168.1.2:3425", hdr...), http.StatusUnauthorized) + } + if w := do(rt.method, rt.path, rt.body, "192.168.1.9:5000", "192.168.1.2:3425", "Authorization", "Bearer "+secrets[0]); w.Code != 200 { + t.Errorf("%s from the LAN with its key: %d %s", at, w.Code, w.Body) + } + // a sandboxed frame or a rebound page with an enabled key is + // answered, as on /v1 + if w := do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, append([]string{"Origin", "null", "Authorization", "Bearer " + secrets[0]}, browser...)...); w.Code != 200 { + t.Errorf("%s from Origin null with a key: %d %s", at, w.Code, w.Body) + } + } + settings.Save(settings.Settings{LAN: false}) +} + +// VS Code's Copilot chats with a model it listed from /api/tags on +// /v1/chat/completions, streamed, with an empty bearer (its +// Ollama provider has no key field) and stream_options it adds itself +// (openAIEndpoint.ts interceptBody): the request reaches the model's +// provider by the id the list gave, and the stream comes back. +func TestOllamaClientChats(t *testing.T) { + fresh(t) + var got []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var req struct{ Model string } + json.Unmarshal(b, &req) + got = append(got, r.URL.Path+" "+req.Model+" "+r.Header.Get("Authorization")) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"hello from seer\"},\"finish_reason\":null}]}\n\n"+ + "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":3}}\n\ndata: [DONE]\n\n") + })) + defer up.Close() + ollamaPlan(t, up.URL+"/v1") + srv := lanGuard(New().Handler()) + var tags struct{ Models []struct{ Model string } } + r := httptest.NewRequest("GET", "/api/tags", nil) + r.RemoteAddr, r.Host = "127.0.0.1:50123", "127.0.0.1:3425" + w := httptest.NewRecorder() + srv.ServeHTTP(w, r) + if err := json.Unmarshal(w.Body.Bytes(), &tags); err != nil || len(tags.Models) == 0 { + t.Fatalf("tags: %d %s", w.Code, w.Body) + } + model := "" + for _, m := range tags.Models { + if strings.HasSuffix(m.Model, "/seer") { + model = m.Model + } + } + body := `{"messages":[{"role":"system","content":"You are an AI programming assistant."},{"role":"user","content":"hi"}],"model":"` + model + + `","temperature":0.1,"top_p":1,"n":1,"stream":true,"tools":[{"type":"function","function":{"name":"read_file","description":"Read a file","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}}],"stream_options":{"include_usage":true}}` + r = httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body)) + r.RemoteAddr, r.Host = "127.0.0.1:50123", "127.0.0.1:3425" + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Authorization", "Bearer ") + w = httptest.NewRecorder() + srv.ServeHTTP(w, r) + if w.Code != 200 || !strings.Contains(w.Body.String(), "hello from seer") { + t.Fatalf("chat: %d %s", w.Code, w.Body) + } + if len(got) != 1 || got[0] != "/v1/chat/completions seer Bearer upstream-secret" { + t.Fatalf("upstream got %q", got) + } +} diff --git a/internal/gateway/patience.go b/internal/gateway/patience.go index b66c71281..8c5fe4394 100644 --- a/internal/gateway/patience.go +++ b/internal/gateway/patience.go @@ -1,10 +1,10 @@ package gateway import ( + "bytes" "context" "net/http" "slices" - "strings" "time" "github.com/yetone/magpie/internal/provider" @@ -59,7 +59,7 @@ func busy(status int, body []byte) bool { switch status { case 408, 500, 502, 503, 504, 529: return failure(status, body) == failOther && !protectionRefused(status, body) && - !strings.Contains(string(body), didNotStream) + !bytes.Contains(body, []byte(didNotStream)) case 429: return failure(status, body) == failRate && !creditWords.Match(wordsOf(body)) } diff --git a/internal/gateway/plain403_rest_test.go b/internal/gateway/plain403_rest_test.go new file mode 100644 index 000000000..301dcc369 --- /dev/null +++ b/internal/gateway/plain403_rest_test.go @@ -0,0 +1,124 @@ +package gateway + +import ( + "io" + "net/http" + "slices" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// A plain 403 (or 401) that names no quota is about the key or the +// request, not the window: an account whose cached usage read 98% rests +// on the backoff ladder, not until its window resets. Before, it sat out +// the whole week on the reading alone (plugins#243, zygs1083-dotcom: one +// Factory 403 benched a working account into its reset). A 403 that does +// say the quota is spent still rests until the window, and so does any +// other failure at 98%, as before. +func TestPlain403DoesNotRestUntilTheWindow(t *testing.T) { + forgetRouting() + old := allowances + defer func() { allowances = old }() + now := time.Now() + week := now.Add(39 * time.Hour) + allowances = func(string) map[string]provider.Allowance { + return map[string]provider.Allowance{ + "me@x.com": {{Used: 98, Resets: week, Span: 7 * 24 * time.Hour}}, + } + } + acct := candidate{p: provider.Provider{ID: "factory", Account: &provider.Account{Agent: "factory", User: "me@x.com"}}, model: "claude-opus-4-7", rest: "factory#me@x.com"} + if !acct.full(now).Equal(week) { + t.Fatal("the account at 98% doesn't read as full; the test proves nothing") + } + s := &Server{} + near := func(d, want time.Duration) bool { return d > want-time.Minute && d <= want } + + for _, status := range []int{http.StatusForbidden, http.StatusUnauthorized} { + forgetRouting() + r := s.restAfter(acct, status, http.Header{}, []byte(`{"error":{"message":"Forbidden"}}`)) + if r.By == "window" || r.By != "backoff" || time.Until(r.Until) > longestRetry { + t.Fatalf("a plain %d at 98%% rests %v by %s (%s)", status, time.Until(r.Until).Round(time.Minute), r.By, r.Why) + } + } + + // a 403 that says the quota is spent is out until the window + forgetRouting() + r := s.restAfter(acct, http.StatusForbidden, http.Header{}, []byte(`{"error":{"message":"You've hit your usage limit"}}`)) + if r.Why != failQuota || r.By != "window" || !near(time.Until(r.Until), 39*time.Hour) { + t.Fatalf("a 403 saying used up rests %v by %s (%s)", time.Until(r.Until).Round(time.Minute), r.By, r.Why) + } + // and another failure at 98% still trusts the reading, as before + forgetRouting() + r = s.restAfter(acct, http.StatusBadGateway, http.Header{}, []byte("bad gateway")) + if r.By != "window" || !near(time.Until(r.Until), 39*time.Hour) { + t.Fatalf("a 502 at 98%% rests %v by %s", time.Until(r.Until).Round(time.Minute), r.By) + } +} + +// One request refused with a plain 403 by two accounts of a provider is +// the request refused, not each account (plugins#243, zygs1083-dotcom: +// Factory's 403 for a Claude Code wrapper it refused walked every account +// into backoff, so the next requests found them all resting). Neither +// rests, and an account after them answers. One account's plain 403 +// alone still rests it, as a key refused does. +func TestPlain403OnTwoMatesRestsNeither(t *testing.T) { + forbid := func(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + io.WriteString(w, `{"error":{"message":"Forbidden"}}`) + } + for _, x := range []struct { + name string + spares []string + also []string // accounts after acct-1 that refuse too + resting []string // who rests after + code int + }{ + {"alone", []string{"b@example.com"}, nil, []string{"codex@me@example.com"}, 200}, + {"two alike, a third answers", []string{"b@example.com", "c@example.com"}, []string{"acct-2"}, nil, 200}, + {"two alike, nobody left", []string{"b@example.com"}, []string{"acct-2"}, nil, 403}, + } { + t.Run(x.name, func(t *testing.T) { + codexSignedIn(t, x.spares...) + if err := provider.SetRouting("codex", provider.Ordered); err != nil { + t.Fatal(err) + } + var tried []string + chatgptRefusing(t, &tried, forbid, x.also...) + s := New() + code, body := codexAskOn(s, `{"model":"gpt-5.5","stream":true,"input":"ping"}`) + if code != x.code { + t.Fatalf("status %d: %s; tried %v", code, body, tried) + } + r := lastRoute(s) + for _, who := range append([]string{"codex@me@example.com"}, func() (w []string) { + for _, s := range x.spares { + w = append(w, "codex@"+s) + } + return + }()...) { + _, ok := restOf(who) + if want := slices.Contains(x.resting, who); ok != want { + t.Fatalf("%s resting %v, want %v; tried %v; tries %+v", who, ok, want, tried, r.Tries) + } + if !slices.Contains(x.resting, who) { + routed.Lock() + n := routed.failures[who] + routed.Unlock() + if n != 0 { + t.Fatalf("%s still counts %d failures", who, n) + } + } + } + if want := map[int]string{200: "acct-1,acct-2", 403: "acct-1,acct-2"}[code]; x.also != nil && !strings.HasPrefix(strings.Join(tried, ","), want) { + t.Fatalf("tried %v", tried) + } + if x.also != nil && (r.Tries[0].Rest != nil || r.Tries[1].Rest != nil) { + t.Fatalf("tries still say they rest: %+v", r.Tries) + } + }) + } +} diff --git a/internal/gateway/plugin_cline_pin_test.go b/internal/gateway/plugin_cline_pin_test.go index e3ebaae35..90c351d27 100644 --- a/internal/gateway/plugin_cline_pin_test.go +++ b/internal/gateway/plugin_cline_pin_test.go @@ -12,10 +12,12 @@ import ( // The Cline plugin's provider has ClinePass's Upstream tick too (ARNO on // Discord): saved on it, a DeepSeek model's request reaches the plugin -// pinned to DeepSeek's own API, on Chat and Anthropic Messages alike, and -// its other models' requests go as sent. -func TestClinePluginPinsDeepSeek(t *testing.T) { +// pinned to DeepSeek's own API and a GLM model's to Z.ai's (sdytman on +// Discord), on Chat and Anthropic Messages alike, and its other models' +// requests go as sent. +func TestClinePluginPinsDeepSeekAndGLM(t *testing.T) { t.Setenv("FAKE_DEEPSEEK", "1") + t.Setenv("FAKE_GLM", "1") var mu sync.Mutex var sent []map[string]any pid := besideFake(t, "cline", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -37,8 +39,8 @@ func TestClinePluginPinsDeepSeek(t *testing.T) { if err != nil { t.Fatal(err) } - if !p.ClinePinnable() || p.ClinePin("deepseek-v4-pro") != "" { - t.Fatalf("the Cline plugin's provider: pinnable %v, pinned unasked %q", p.ClinePinnable(), p.ClinePin("deepseek-v4-pro")) + if !p.ClinePinnable() || p.ClinePin("deepseek-v4-pro") != "" || p.ClinePin("glm-5.3") != "" { + t.Fatalf("the Cline plugin's provider: pinnable %v, pinned unasked %q %q", p.ClinePinnable(), p.ClinePin("deepseek-v4-pro"), p.ClinePin("glm-5.3")) } ask := func() []map[string]any { mu.Lock() @@ -47,13 +49,15 @@ func TestClinePluginPinsDeepSeek(t *testing.T) { for _, req := range []struct{ path, body string }{ {"/v1/chat/completions", `{"model":"` + pid + `/deepseek-v4-pro","messages":[{"role":"user","content":"hi"}]}`}, {"/v1/messages", `{"model":"` + pid + `/deepseek-v4-pro","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`}, + {"/v1/chat/completions", `{"model":"` + pid + `/glm-5.3","messages":[{"role":"user","content":"hi"}]}`}, + {"/v1/messages", `{"model":"` + pid + `/glm-5.3","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`}, {"/v1/chat/completions", `{"model":"` + pid + `/fake-1","messages":[{"role":"user","content":"hi"}]}`}, } { postProto(t, New(), req.path, req.body) } mu.Lock() defer mu.Unlock() - if len(sent) != 3 { + if len(sent) != 5 { t.Fatalf("the plugin sent %d requests", len(sent)) } return append([]map[string]any(nil), sent...) @@ -73,13 +77,17 @@ func TestClinePluginPinsDeepSeek(t *testing.T) { t.Fatalf("the tick wasn't kept: %+v, %v", p, err) } got := ask() - for i, q := range got[:2] { + for i, q := range got[:4] { + want := `{"gateway":{"only":["deepseek"]}}` + if i >= 2 { + want = `{"gateway":{"only":["zai"]}}` + } po, _ := json.Marshal(q["providerOptions"]) - if string(po) != `{"gateway":{"only":["deepseek"]}}` { - t.Fatalf("request %d (DeepSeek) reached the plugin with providerOptions %s", i, po) + if string(po) != want { + t.Fatalf("request %d reached the plugin with providerOptions %s, want %s", i, po, want) } } - if got[2]["providerOptions"] != nil { - t.Fatalf("fake-1 pinned: %v", got[2]["providerOptions"]) + if got[4]["providerOptions"] != nil { + t.Fatalf("fake-1 pinned: %v", got[4]["providerOptions"]) } } diff --git a/internal/gateway/plugin_zdr_test.go b/internal/gateway/plugin_zdr_test.go new file mode 100644 index 000000000..6d48b53c0 --- /dev/null +++ b/internal/gateway/plugin_zdr_test.go @@ -0,0 +1,225 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" +) + +// Command Code's own answers to x-cmd-zdr: 1 for a model no Zero Data +// Retention upstream serves, as they came on 2026-10-19 for +// poolside/laguna-s-2.1-free (magpie-community/plugins#246, its +// zdr.test.mjs): the Provider API's 422, and the 400 the plugin makes of +// Go's /alpha/generate error line. +const ( + zdrProvider422 = `{"error":{"message":"This model has no zero-data-retention upstream. Remove the x-cmd-zdr header or choose a different model.","type":"invalid_request_error","code":"cmd_zdr_no_providers"}}` + zdrGo400 = `{"error":{"message":"This model has no zero-data-retention upstream. Disable CMD_ZDR or pick a different model.","type":"cmd_zdr_no_providers","code":400}}` +) + +// noneRested says nothing of the provider id rests or has a failure +// counted against it. +func noneRested(t *testing.T, id string) { + t.Helper() + restingUntil.Lock() + for k, until := range restingUntil.m { + if strings.HasPrefix(k, id) && time.Now().Before(until) { + t.Errorf("%s rests until %s", k, until) + } + } + restingUntil.Unlock() + routed.Lock() + for k, n := range routed.failures { + if strings.HasPrefix(k, id) && n > 0 { + t.Errorf("%s has %d failures counted", k, n) + } + } + routed.Unlock() +} + +// A Zero Data Retention refusal from Command Code (plugin 0.1.14's switch) +// is about that request's setting, not the model or the account: nothing +// rests, so the model answers again as soon as the switch is off; in a +// group the next member, at another vendor, is asked; the account's mates +// at the same model, sent the same header, aren't; and alone, the agent +// has Command Code's own words. Before, the 422's "…a different +// model.","type":"invalid_request_error" read as the model unserved +// (unservedWords) and rested it on the account. +func TestCommandCodeZDRRefusalRestsNothing(t *testing.T) { + for _, x := range []struct { + name, body string + status int + }{ + {"provider api", zdrProvider422, 422}, + {"go", zdrGo400, 400}, + } { + t.Run(x.name, func(t *testing.T) { + var mu sync.Mutex + zdr := true + var asked []string + movedFake(t, "commandcode-plan", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + mu.Lock() + on := zdr + asked = append(asked, r.Header.Get("Authorization")) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if on { + w.WriteHeader(x.status) + io.WriteString(w, x.body) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"from commandcode"},"finish_reason":null}]}`+"\n\n") + io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n") + })) + // a second Command Code account: the switch is the provider's, + // so it is sent the same header + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + if _, err := plugin.APIKey(ctx, "commandcode-plan", 0, nil, "k2", plugin.NewAccount); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + if p, err := provider.Find("commandcode-plan"); err != nil || len(p.AlsoOn()) != 1 { + t.Fatalf("Find = %+v, %v", p, err) + } + b := &scripted{replies: []reply{{200, "", chatOK}, {200, "text/event-stream", chatStreamOK}}} + scriptedOn(t, "b", provider.Chat, b) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"commandcode-plan/fake-1", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + reset := func() { + mu.Lock() + asked = nil + mu.Unlock() + } + n := func() int { + mu.Lock() + defer mu.Unlock() + return len(asked) + } + + // alone: one account asked, the agent has Command Code's words + code, body := postAs(t, s, "", `{"model":"commandcode-plan/fake-1","messages":[{"role":"user","content":"hi"}]}`) + if code != x.status || !strings.Contains(body, "no zero-data-retention upstream") || n() != 1 { + t.Fatalf("alone: %d %s (asked %d)", code, body, n()) + } + noneRested(t, "commandcode-plan") + + // in a group: the next member answers, and nothing rests + reset() + code, body = postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "hello") || n() != 1 || b.n != 1 { + t.Fatalf("group: %d %s (commandcode %d, b %d)", code, body, n(), b.n) + } + r := s.trace.routes[len(s.trace.routes)-1] + if len(r.Tries) != 2 || r.Tries[0].Status != x.status || r.Tries[0].Rest != nil { + t.Fatalf("tries %+v", r.Tries) + } + noneRested(t, "commandcode-plan") + + // and for an agent speaking Anthropic's Messages, whose error + // shape keeps no code + reset() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", + strings.NewReader(`{"model":"group/g","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`))) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from b") || n() != 1 || b.n != 2 { + t.Fatalf("messages: %d %s (commandcode %d, b %d)", rec.Code, rec.Body, n(), b.n) + } + rec = httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", + strings.NewReader(`{"model":"commandcode-plan/fake-1","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`))) + if rec.Code != x.status || !strings.Contains(rec.Body.String(), "no zero-data-retention upstream") || n() != 2 { + t.Fatalf("messages alone: %d %s (commandcode %d)", rec.Code, rec.Body, n()) + } + noneRested(t, "commandcode-plan") + + // the switch off: Command Code is asked first again, and answers + mu.Lock() + zdr = false + mu.Unlock() + reset() + code, body = postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "from commandcode") || n() != 1 || b.n != 2 { + t.Fatalf("switch off: %d %s (commandcode %d, b %d)", code, body, n(), b.n) + } + }) + } +} + +// Only Command Code's own error code makes a refusal a setting's: another +// vendor's model refusal in the same words, or one in the same OpenAI +// error shape, still rests the model as before. +func TestZDRRefusalIsCommandCodesCodeOnly(t *testing.T) { + for _, x := range []struct { + status int + body string + zdr, rest bool // zdrRefused, modelRefused + }{ + {422, zdrProvider422, true, false}, + {400, zdrGo400, true, false}, + {400, `Command Code: ` + zdrGo400, true, false}, + // the same words with no such code are another vendor's + {422, `{"error":{"message":"This model has no zero-data-retention upstream. Remove the x-cmd-zdr header or choose a different model.","type":"invalid_request_error"}}`, false, true}, + {404, `{"error":{"message":"The model 'gpt-9' does not exist","type":"invalid_request_error","code":"model_not_found"}}`, false, true}, + {400, `{"error":{"message":"model \"gpt-6-sol\" is not accessible via the /chat/completions endpoint","code":"unsupported_api_for_model"}}`, false, true}, + // the code named in a message, not as the error's type or code + {400, `{"error":{"message":"unknown model; see cmd_zdr_no_providers","type":"invalid_request_error"}}`, false, true}, + // not a refusal + {200, zdrProvider422, false, false}, + } { + if got := zdrRefused(x.status, []byte(x.body)); got != x.zdr { + t.Errorf("zdrRefused(%d, %s) = %v", x.status, x.body, got) + } + if got := modelRefused(x.status, []byte(x.body)); got != x.rest { + t.Errorf("modelRefused(%d, %s) = %v", x.status, x.body, got) + } + } +} + +// Wherever a try's failure is rested — a strict conversation's own +// account, a System One decision, a count — a Zero Data Retention refusal +// rests nothing: read from the vendor's own body, or from magpie's note +// beside the error the agent was given in Anthropic's shape, which keeps +// no code. Another vendor's model refusal in the same words still rests +// the model. +func TestZDRRefusalNeverRests(t *testing.T) { + fresh(t) + s := New() + c := candidate{p: provider.Provider{ID: "commandcode-plan", Name: "Command Code Plan", Key: "k"}, model: "m", rest: "commandcode-plan"} + noted := http.Header{} + keepRetry(noted, http.Header{}, []byte(zdrGo400)) + anthropicShaped := []byte(`{"error":{"message":"Command Code Plan: This model has no zero-data-retention upstream. Disable CMD_ZDR or pick a different model.","type":"invalid_request_error"},"type":"error"}`) + for _, x := range []struct { + status int + header http.Header + body []byte + }{ + {422, http.Header{}, []byte(zdrProvider422)}, + {400, http.Header{}, []byte(zdrGo400)}, + {400, noted, anthropicShaped}, + } { + s.restAfter(c, x.status, x.header, x.body) + if r, ok := restingOf(c); ok { + t.Fatalf("%d %s rests: %+v", x.status, x.body, r) + } + } + noneRested(t, "commandcode-plan") + // without the note, the same words rest the model, as any vendor's do + s.restAfter(c, 400, http.Header{}, anthropicShaped) + if _, ok := restingOf(c); !ok { + t.Fatal("a model refusal without Command Code's code rests nothing") + } +} diff --git a/internal/gateway/quotas_held_key_test.go b/internal/gateway/quotas_held_key_test.go index d09cd734b..82ea7923f 100644 --- a/internal/gateway/quotas_held_key_test.go +++ b/internal/gateway/quotas_held_key_test.go @@ -110,6 +110,14 @@ func TestHeldKeyToldNoAccounts(t *testing.T) { if r := route(from, s, other); (i == 0) != (r != nil) { t.Errorf("%s from %s: another key's session %s: %v", name, from, other, r) } + // the whole trace (#2606), every key's routes: this computer + // alone, and never a held key, even from here + c, b := do("GET", "/v1/magpie/trace", from, s) + if want := i == 0 && from == "127.0.0.1:5000"; want != (c == 200) { + t.Errorf("%s from %s: the trace: %d %s", name, from, c, b) + } else if i > 0 && from == "127.0.0.1:5000" && !strings.Contains(b, provider.KeyHeldCode) { + t.Errorf("%s from %s: the trace refused without saying the key is held: %d %s", name, from, c, b) + } } } } diff --git a/internal/gateway/reply_room_test.go b/internal/gateway/reply_room_test.go new file mode 100644 index 000000000..51f50d09c --- /dev/null +++ b/internal/gateway/reply_room_test.go @@ -0,0 +1,203 @@ +package gateway + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// deepseekWindow is a fake of DeepSeek's chat API that counts the reply +// asked for (max_tokens) in its window with the prompt, as DeepSeek does, +// and refuses in its words a request whose two together pass it. +type deepseekWindow struct { + mu sync.Mutex + window int + prompt int + asked []int64 // each request's max_tokens, -1 when it named none +} + +func (d *deepseekWindow) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + n := int64(-1) + if v := gjson.GetBytes(b, "max_tokens"); v.Exists() { + n = v.Int() + } + d.mu.Lock() + d.asked = append(d.asked, n) + d.mu.Unlock() + if n < 0 || d.prompt+int(n) > d.window { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + fmt.Fprintf(w, `{"error":{"message":"This model's maximum context length is %d tokens. However, you requested %d tokens (%d in the messages, %d in the completion). Please reduce the length of the messages or completion.","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}`, + d.window, d.prompt+int(n), d.prompt, n) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"id":"test","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"ok"}}]}`, + `data: {"id":"test","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + `data: [DONE]`, + )) +} + +func (d *deepseekWindow) took() []int64 { + d.mu.Lock() + defer d.mu.Unlock() + out := append([]int64(nil), d.asked...) + d.asked = nil + return out +} + +// A client asking DeepSeek for its whole 384K reply on a conversation of +// 706,784 tokens is refused by DeepSeek as too long, since its 1M window +// counts the reply asked for: since #2355 passed max_completion_tokens on +// as max_tokens, every such turn at the official DeepSeek member of a +// group failed as "too long for its model" (molvqingtai on Discord). It +// is asked again for the reply the window has left, and answers. Room +// too small to be worth a reply still reaches the agent as the overflow. +func TestDeepSeekReplyFitsTheWindowLeft(t *testing.T) { + fresh(t) + d := &deepseekWindow{window: 1000000, prompt: 706784} + up := httptest.NewServer(d) + defer up.Close() + p, err := provider.FromPreset("deepseek") + if err != nil { + t.Fatal(err) + } + p.Key = "fixture-key" + p.Chat = up.URL + "/v1" + // its chat API alone, the fake: no request reaches DeepSeek + p.Responses, p.Anthropic = "", "" + p.Models = []string{"deepseek-flash"} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + msgs := `"messages":[{"role":"user","content":"hi"}]` + for _, c := range []struct { + path, body string + want []int64 + }{ + // DSH's pi-ai, OpenAI's field (#2355) + {"/v1/chat/completions", `{"model":"deepseek/deepseek-flash","stream":true,"max_completion_tokens":393216,` + msgs + `}`, []int64{393216, 293216}}, + {"/v1/chat/completions", `{"model":"deepseek/deepseek-flash","stream":true,"max_tokens":393216,` + msgs + `}`, []int64{393216, 293216}}, + // a Responses client, translated to DeepSeek's chat API + {"/v1/responses", `{"model":"deepseek/deepseek-flash","stream":true,"max_output_tokens":393216,"input":"hi"}`, []int64{393216, 293216}}, + // one that fits is asked once + {"/v1/chat/completions", `{"model":"deepseek/deepseek-flash","stream":true,"max_tokens":32000,` + msgs + `}`, []int64{32000}}, + } { + code, reply := post(t, c.path, c.body) + if code != 200 { + t.Fatalf("%s: HTTP %d: %s", c.body, code, reply) + } + if got := d.took(); fmt.Sprint(got) != fmt.Sprint(c.want) { + t.Fatalf("%s: DeepSeek was asked max_tokens %v, want %v", c.body, got, c.want) + } + } + + // the prompt leaves under leastReplyLeft: the conversation needs + // compacting, and the agent is told it overflowed, asked once + d.prompt = 1000000 - 4000 + code, reply := post(t, "/v1/chat/completions", `{"model":"deepseek/deepseek-flash","stream":true,"max_tokens":393216,`+msgs+`}`) + if code != 400 || !strings.Contains(reply, "maximum context length") { + t.Fatalf("no room: HTTP %d: %s", code, reply) + } + if got := d.took(); fmt.Sprint(got) != "[393216]" { + t.Fatalf("no room: DeepSeek was asked %v, want once", got) + } +} + +func TestReplyLeft(t *testing.T) { + for _, c := range []struct { + msg string + want int + }{ + {"This model's maximum context length is 1000000 tokens. However, you requested 1100000 tokens (706784 in the messages, 393216 in the completion). Please reduce the length of the messages or completion.", 293216}, + {"This model's maximum context length is 32768 tokens. However, you requested 32000 output tokens and your prompt contains at least 769 input tokens, for a total of at least 32769 tokens.", 31999}, + // Anthropic's, from an endpoint speaking its API + {"input length and `max_tokens` exceed context limit: 970000 + 64000 > 1000000, decrease input length or `max_tokens` and try again", 30000}, + // the prompt alone is too long: nothing is left + {"This model's maximum context length is 131072 tokens. However, you requested 140000 tokens (140000 in the messages, 0 in the completion).", 0}, + // says no parts + {"This model's maximum context length is 131072 tokens. However, you requested 140000 tokens", 0}, + {"Invalid max_tokens value, the valid range of max_tokens is [1, 8192]", 0}, + } { + if got := replyLeft([]byte(c.msg)); got != c.want { + t.Errorf("replyLeft(%q) = %d, want %d", c.msg, got, c.want) + } + } +} + +// Claude Code and Codex reach an endpoint speaking Anthropic's API (as +// DeepSeek's /anthropic does) with a reply limit of their own (Claude +// Code's 64000) or the model's whole (Codex names none, so magpie asks +// the model's, #1792). Told a 1M window, they compact only near it, and +// a turn whose prompt and reply together pass it was refused, so Codex +// stopped with "ran out of room in the model's context window" (da34, +// Jeremy.Zhou on Discord). Each is asked again for what the window left. +func TestAnthropicReplyFitsTheWindowLeft(t *testing.T) { + fresh(t) + const window, prompt = 1000000, 970000 + var mu sync.Mutex + var asked []int64 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + n := gjson.GetBytes(b, "max_tokens").Int() + mu.Lock() + asked = append(asked, n) + mu.Unlock() + if prompt+int(n) > window { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + fmt.Fprintf(w, `{"type":"error","error":{"type":"invalid_request_error","message":"input length and `+"`max_tokens`"+` exceed context limit: %d + %d > %d, decrease input length or `+"`max_tokens`"+` and try again"}}`, prompt, n, window) + return + } + if gjson.GetBytes(b, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"m\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n"+ + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n"+ + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\n"+ + "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n"+ + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n"+ + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"m","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, Anthropic: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := provider.SetModelOutput("a/m", 393216); err != nil { + t.Fatal(err) + } + s := New() + for _, c := range []struct { + name, path, body string + want string + }{ + {"Claude Code", "/v1/messages", `{"model":"a/m","max_tokens":64000,"messages":[{"role":"user","content":"hi"}]}`, "[64000 30000]"}, + {"Codex", "/v1/responses", `{"model":"a/m","input":"hi"}`, "[393216 30000]"}, + } { + mu.Lock() + asked = nil + mu.Unlock() + if code, raw := postJSON(t, s, c.path, c.body); code != 200 { + t.Fatalf("%s: %d %s", c.name, code, raw) + } + mu.Lock() + got := fmt.Sprint(asked) + mu.Unlock() + if got != c.want { + t.Fatalf("%s: the endpoint was asked max_tokens %s, want %s", c.name, got, c.want) + } + } +} diff --git a/internal/gateway/request_builds_once_test.go b/internal/gateway/request_builds_once_test.go index 290cd75d1..63ed12f7e 100644 --- a/internal/gateway/request_builds_once_test.go +++ b/internal/gateway/request_builds_once_test.go @@ -2,6 +2,7 @@ package gateway import ( "testing" + "time" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/provider" @@ -11,18 +12,32 @@ import ( // model up on its way: each build reads every agent's sign-in, every // plugin's and the settings, and three builds a request kept magpie at // 100–350% CPU under seven agents at once (#2502). The next request, -// nothing held between them, builds afresh. +// within a second and nothing written, builds none: one request after +// another built the providers again each time. After a write it builds +// once more. func TestRequestBuildsProvidersOnce(t *testing.T) { plugin.UseCached(nil) setup(t, provider.Chat, &fake{t: t, reply: sse(`{"choices":[{"delta":{"content":"hi"}}]}`, "[DONE]")}) - for i := range 2 { - n := provider.AllBuilt.Load() + var first time.Time + for i, want := range []int64{1, 0, 1} { + if i == 2 { + provider.Changed() // a provider saved + } + n, start := provider.AllBuilt.Load(), time.Now() + if i == 1 && start.Sub(first) > 900*time.Millisecond { + // what was built is held for a second: a request this late + // (a loaded machine) builds again, rightly + want = 1 + } + if i == 0 { + first = start + } code, body := post(t, "/v1/chat/completions", `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`) if code != 200 { t.Fatalf("%d %s", code, body) } - if got := provider.AllBuilt.Load() - n; got != 1 { - t.Fatalf("request %d built the providers %d times, want 1", i+1, got) + if got := provider.AllBuilt.Load() - n; got != want { + t.Fatalf("request %d built the providers %d times, want %d", i+1, got, want) } } } diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 7419263f2..fe494c915 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -196,6 +196,62 @@ func unsealed(schema json.RawMessage) json.RawMessage { return out } +// asksSealing is a Responses request whose tools mark a parameter +// "encrypted" (MultiAgentV2's spawn_agent message): an upstream that +// honours the mark answers the call with that argument sealed. +func asksSealing(body []byte) bool { + if !bytes.Contains(body, []byte(`"encrypted"`)) { + return false + } + var q struct { + Tools []struct { + Parameters json.RawMessage `json:"parameters"` + Tools []struct { + Parameters json.RawMessage `json:"parameters"` + } `json:"tools"` + } `json:"tools"` + } + if decodeJSON(body, &q) != nil { + return false + } + var mark func(any) bool + mark = func(v any) bool { + switch x := v.(type) { + case map[string]any: + if b, ok := x["encrypted"].(bool); ok && b { + return true + } + for _, c := range x { + if mark(c) { + return true + } + } + case []any: + for _, c := range x { + if mark(c) { + return true + } + } + } + return false + } + marked := func(schema json.RawMessage) bool { + var v any + return bytes.Contains(schema, []byte(`"encrypted"`)) && decodeJSON(schema, &v) == nil && mark(v) + } + for _, t := range q.Tools { + if marked(t.Parameters) { + return true + } + for _, nt := range t.Tools { + if marked(nt.Parameters) { + return true + } + } + } + return false +} + func flatName(namespace, name string) string { return provider.FlatName(namespace, name) } @@ -1270,32 +1326,95 @@ func (u Usage) responses() map[string]any { // responsesDecoder turns a Responses stream into events. // -// A function call's arguments are given once the call is done, not as -// their deltas come: the deltas can leave out what the finished call holds -// (#613: Codex's spawn_agent came back with arguments {} where the request -// was translated, though the upstream's finished call had them), and what -// was sent of a call's arguments can't be taken back. +// A function call's arguments are given as their deltas come: a model +// writing a patch or a command for minutes is seen writing it (echo_ts on +// Discord: Codex on Copilot, translated for its web_search, saw nothing +// until the call was done). The deltas can leave out what the finished +// call holds (#613: Codex's spawn_agent came back with arguments {} where +// the request was translated, though the upstream's finished call had +// them), and what was sent of a call's arguments can't be taken back. So +// the deltas that would make the arguments whole JSON wait for the call's +// done events (jsonWhole), and the call is given what they add to it. type responsesDecoder struct { started bool called bool // a function call was streamed calling bool // a function call is open - args strings.Builder // the open call's argument deltas + sent strings.Builder // the open call's argument deltas given so far + held string // its deltas since they made whole JSON, not given yet + whole jsonWhole // where its deltas stand in their JSON full string // the open call's arguments as its done events give them } -// endCall gives the open call's arguments: the deltas, or what its done -// events give where that holds more. +// argsDelta gives an open call's argument delta, or holds it when with +// it the deltas are whole JSON, which the done events may yet replace. +func (d *responsesDecoder) argsDelta(delta string, emit func(Event)) { + if d.whole.feed(delta) { + d.held += delta + return + } + text := d.held + delta + d.held = "" + d.sent.WriteString(text) + if text != "" { + emit(Event{Kind: KToolArgs, Text: text}) + } +} + +// endCall gives the rest of the open call's arguments: what was held, or +// what its done events give past what was sent where they hold more. func (d *responsesDecoder) endCall(emit func(Event)) { if !d.calling { return } d.calling = false - args := pickArgs(d.args.String(), d.full) - d.args.Reset() - d.full = "" - if args != "" { - emit(Event{Kind: KToolArgs, Text: args}) + sent := d.sent.String() + rest := d.held + if args := pickArgs(sent+d.held, d.full); strings.HasPrefix(args, sent) { + rest = args[len(sent):] } + d.sent.Reset() + d.held, d.full, d.whole = "", "", jsonWhole{} + if rest != "" { + emit(Event{Kind: KToolArgs, Text: rest}) + } +} + +// jsonWhole follows a stream of JSON text, a piece at a time, for whether +// what came so far is a whole object or array. +type jsonWhole struct { + depth int + str, esc bool + began bool +} + +// feed reads the next piece and says whether the text is whole after it. +func (j *jsonWhole) feed(s string) bool { + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case j.esc: + j.esc = false + case j.str: + if c == '\\' { + j.esc = true + } else if c == '"' { + j.str = false + } + case c == '"': + j.str = true + if j.depth == 0 { + j.began = false + } + case c == '{' || c == '[': + j.depth++ + j.began = true + case c == '}' || c == ']': + j.depth-- + case c != ' ' && c != '\t' && c != '\n' && c != '\r' && j.depth == 0: + j.began = false // a value that isn't one, or after one + } + } + return j.began && j.depth == 0 && !j.str } // pickArgs is the fuller of a call's arguments as streamed and as its done @@ -1369,7 +1488,7 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error { emit(Event{Kind: KThink, Text: ev.Delta}) case "response.function_call_arguments.delta": if d.calling { - d.args.WriteString(ev.Delta) + d.argsDelta(ev.Delta, emit) } else { emit(Event{Kind: KToolArgs, Text: ev.Delta}) } @@ -1502,6 +1621,9 @@ type responsesEncoder struct { // collector's last part isn't it once a hidden thinking block (signed // with no text, or redacted) has come after the call (#1786) call Part + // input reads a custom tool's input out of its call's arguments as + // they come + input customStream // a message's output_item.done, and the events after it, wait here // until its phase is known (phase.go, #2437) heldMsg map[string]any @@ -1661,10 +1783,15 @@ func (e *responsesEncoder) closeAs(sealed json.RawMessage) { args = "{}" } p := e.call - if q := e.named[p.Name]; !q.Search && !q.Custom { + item = callTo(map[string]any{"id": e.itemID, "type": "function_call", "status": "completed", "call_id": p.ID, "arguments": args}, p.Name, e.named) + switch q := e.named[p.Name]; { + case q.Custom: + // as OpenAI ends a custom tool's input deltas + input, _ := item.(map[string]any)["input"].(string) + e.send("response.custom_tool_call_input.done", map[string]any{"item_id": e.itemID, "output_index": e.item, "input": input}) + case !q.Search: e.send("response.function_call_arguments.done", callTo(map[string]any{"item_id": e.itemID, "output_index": e.item, "call_id": p.ID, "arguments": args}, p.Name, e.named)) } - item = callTo(map[string]any{"id": e.itemID, "type": "function_call", "status": "completed", "call_id": p.ID, "arguments": args}, p.Name, e.named) } e.send("response.output_item.done", map[string]any{"output_index": e.item, "item": item}) e.output = append(e.output, item) @@ -1759,14 +1886,21 @@ func (e *responsesEncoder) event(ev Event) { item := callTo(map[string]any{"type": "function_call", "call_id": ev.ID, "arguments": ""}, ev.Name, e.named) e.openItem(ToolCall, itemPrefix(item), item) e.call = Part{Kind: ToolCall, ID: ev.ID, Name: ev.Name} + e.input = customStream{} e.col.add(ev) return case KToolArgs: if e.open == ToolCall && ev.Text != "" { e.text.WriteString(ev.Text) - // a custom tool's input is whole only once its arguments are: - // it goes in the item when that is done - if !e.named[e.call.Name].Custom { + switch q := e.named[e.call.Name]; { + case q.Custom: + // a custom tool's input, as it is read out of the + // arguments: what the model writes of a patch is seen as + // it writes it, as from OpenAI + if in := e.input.feed(ev.Text); in != "" { + e.send("response.custom_tool_call_input.delta", map[string]any{"item_id": e.itemID, "output_index": e.item, "delta": in}) + } + default: e.send("response.function_call_arguments.delta", map[string]any{"item_id": e.itemID, "output_index": e.item, "delta": ev.Text}) } } diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 1d81d5708..6929fdd83 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -79,6 +79,68 @@ func servedCandidate(c candidate, tokens int) { } } +// forbidden is a plain 403 one request was given, and the rest it took: +// what forbiddenAlike and unforbid read. +type forbidden struct { + c candidate + rest Rest + try int // its index in the route's Tries, -1 untraced +} + +// plainForbidden says a reply is a 403 that says nothing of why: no +// quota, credit, rate, verification, restriction, a model not served. +// Such a 403 may be the key's or the request's. +func plainForbidden(c candidate, status int, body []byte) bool { + return status == http.StatusForbidden && failureOf(c, status, body) == failOther && + !modelRefused(status, body) && !codeAssistModelMissing(c.p, status, body) +} + +// forbiddenAlike is the plain 403s of c's mates earlier in the request: +// another key or account of its provider, asked the same model at the +// same reasoning. Two of them refusing one request alike, it is the +// request that is refused, not each account (plugins#243, +// zygs1083-dotcom: Factory's 403 for a Claude Code wrapper it refused +// rested every account in turn, and the next requests found them all in +// backoff). +// The rest of seen is returned beside them, for the request to keep. +func forbiddenAlike(seen []forbidden, c candidate) (alike, others []forbidden) { + for _, f := range seen { + if f.c.p.ID == c.p.ID && f.c.model == c.model && f.c.effort == c.effort && f.c.who() != c.who() { + alike = append(alike, f) + } else { + others = append(others, f) + } + } + return alike, others +} + +// unforbid takes back the rest a plain 403 took and the failures it +// counted, when a mate's alike 403 said the request was what was refused. +// A rest taken since, which isn't this one, stays. +func unforbid(f forbidden) { + if f.rest.By == "off" || f.rest.Key == "" { + return // it neither rested nor counted + } + routed.Lock() + for _, k := range []string{f.c.restKey(), f.c.restID()} { + if n := routed.failures[k]; n > 1 { + routed.failures[k] = n - 1 + } else { + delete(routed.failures, k) + } + if f.c.model == "" { + break // restID is restKey: counted once + } + } + routed.Unlock() + restingUntil.Lock() + if until, ok := restingUntil.m[f.rest.Key]; ok && until.Equal(f.rest.Until) { + delete(restingUntil.m, f.rest.Key) + delete(restingUntil.note, f.rest.Key) + } + restingUntil.Unlock() +} + // clearRest wakes a candidate that just answered, whether it was tried after // a provider rest or after a model-specific rest. func clearRest(key string) { @@ -221,6 +283,10 @@ const ( // failOverflow: the conversation is too long for the member's model // (#700) — another member, with room for it, is asked, and nobody rests failOverflow = "overflow" + // failRoom: the window held the prompt but not the reply asked for + // with it — the same one is asked again for the reply the window has + // left, and nobody rests + failRoom = "room" // failSlow: the member hadn't begun its reply when its group's // FirstToken ran out, nothing of it sent — the next is asked, and // nobody rests, as a long prompt is slow anywhere @@ -297,14 +363,14 @@ func failure(status int, body []byte) string { // Kimi's "exceeded model token limit" is the conversation's // length, not the plan's return failOther - case status == 402 && usedUpWords.Match(body) && !creditWords.Match(body) && !strings.Contains(string(body), "insufficient_quota"): + case status == 402 && usedUpWords.Match(body) && !creditWords.Match(body) && !bytes.Contains(body, []byte("insufficient_quota")): // a 402 that says a usage limit and nothing of money is out of // quota, not of credit: Factory's "You've reached your weekly // standard usage limit (resets in …). Switch to Droid Core …" is // Standard's pool, which counts some models only, and read as the // account out of credit it rested Droid Core with it (#1979) return failQuota - case status == 402, creditWords.Match(body) && (status != 429 || brokeWords.Match(body)) || strings.Contains(string(body), "insufficient_quota"): + case status == 402, creditWords.Match(body) && (status != 429 || brokeWords.Match(body)) || bytes.Contains(body, []byte("insufficient_quota")): return failCredit case status == 429 && resetsWhen.Match(body): // out until the time it names, in whichever language it said so: @@ -598,8 +664,11 @@ var zhipuResets = regexp.MustCompile(`(?:\bYour limit will reset at|您的限额 // offset goes with it: "20:12 UTC+8" today, else "Oct 16 09:00 UTC+8". // Without it a magpie on UTC+8 said "not asked again before 17:12" to a // user who couldn't tell whose 17:12 it was (Player on Discord). -func heldClock(t, now time.Time) string { - t, now = t.Local(), now.Local() +func heldClock(t, now time.Time) string { return heldClockIn(t, now, time.Local) } + +// heldClockIn is heldClock on the clock of loc. +func heldClockIn(t, now time.Time, loc *time.Location) string { + t, now = t.In(loc), now.In(loc) s := t.Format("Jan 2 15:04") if y, m, d := t.Date(); now.Year() == y && now.Month() == m && now.Day() == d { s = t.Format("15:04") @@ -745,6 +814,12 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo now := time.Now() d := fallbackCooldown why := failureOf(c, status, body) + if header.Get(zdrHeader) != "" || zdrRefused(status, body) { + // Command Code's Zero Data Retention setting refused the request: + // the model and the account are as good as they were, and answer + // as soon as the switch is off + return Rest{Why: why, Status: status, By: "off", Until: now} + } // read before the allowance is asked again below: out of a pool that // counts some models only, the account's others are still in theirs // (Cursor's Auto with Other Models used up) @@ -858,8 +933,12 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo // everyone (sub2api's 503) says nothing of the key's own windows. // Held to the longest an account out of quota sits out: the window // is the vendor's reading, and one read a year off (a /usage date - // with no year) would bench the account until someone noticed - if t := c.full(now); !t.IsZero() && c.p.Account != nil && !unserved { + // with no year) would bench the account until someone noticed. + // Not a refusal (401, 403) that names no quota: one that did is + // failQuota already, and a plain 403 is about the key or the + // request, so a cached reading of 98% benched a working account + // until its window reset (plugins#243, zygs1083-dotcom) + if t := c.full(now); !t.IsZero() && c.p.Account != nil && !unserved && status != http.StatusUnauthorized && status != http.StatusForbidden { d, r.By, modelBackoff = min(t.Sub(now), longestQuota), "window", false } } @@ -1039,6 +1118,11 @@ func keepRetry(dst, src http.Header, body []byte) { // it, for settle to try the next account (#248) dst.Set(refusedHeader, note) } + if zdrCoded.Match(body) { + // the error the agent gets may lose Command Code's code: that it + // was its Zero Data Retention setting goes on beside it + dst.Set(zdrHeader, "1") + } } // refusedHeader carries, from keepRetry to settle, that an error status diff --git a/internal/gateway/rpm.go b/internal/gateway/rpm.go index dd414ba48..4bf0eb43a 100644 --- a/internal/gateway/rpm.go +++ b/internal/gateway/rpm.go @@ -58,6 +58,17 @@ func rpmSpan() time.Duration { return rpmWindow + rpmSlack } // the provider's QueueWait isn't shorter; tests shorten it. var rpmLongest = 2 * time.Minute +// rpmNow is the clock the minute is read on, and rpmTimer the timer a +// request waits for room on; tests hold both, so what they check doesn't +// rest on how fast a loaded machine gets to it (#1791). +var ( + rpmNow = time.Now + rpmTimer = func(d time.Duration) (<-chan time.Time, func() bool) { + t := time.NewTimer(d) + return t.C, t.Stop + } +) + // rpms are the times of the requests of each key or account with a MaxRPM. type rpms struct { mu sync.Mutex @@ -150,7 +161,7 @@ func (l *rpms) wait(ctx context.Context, who string, limit int, longest time.Dur if limit <= 0 { return 0, nil } - now := time.Now() + now := rpmNow() at, err := l.reserve(who, limit, longest, now) if err != nil { return 0, err @@ -160,14 +171,14 @@ func (l *rpms) wait(ctx context.Context, who string, limit int, longest time.Dur return 0, nil } defer notePhase(ctx, "rpm")() - t := time.NewTimer(d) - defer t.Stop() + c, stop := rpmTimer(d) + defer stop() select { - case <-t.C: + case <-c: return d, nil case <-ctx.Done(): l.giveBack(who, at) - return time.Since(now), ctx.Err() + return rpmNow().Sub(now), ctx.Err() } } @@ -182,7 +193,7 @@ func (l *rpms) free(who string, limit int) bool { if l.m == nil { return true } - return len(l.prune(who, time.Now())) < limit + return len(l.prune(who, rpmNow())) < limit } // used is how many requests of who's are counted in its minute now, to go @@ -193,7 +204,7 @@ func (l *rpms) used(who string) int { if l.m == nil { return 0 } - return len(l.prune(who, time.Now())) + return len(l.prune(who, rpmNow())) } // rpmTicket, on a request's context, counts each request made with it diff --git a/internal/gateway/rpm_test.go b/internal/gateway/rpm_test.go index ee4134d06..8310b76f6 100644 --- a/internal/gateway/rpm_test.go +++ b/internal/gateway/rpm_test.go @@ -3,9 +3,11 @@ package gateway import ( "context" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" + "slices" "strings" "sync" "testing" @@ -26,7 +28,11 @@ type minuteVendor struct { // when its connection has to be dialed (and, to a real vendor, its TLS // handshake made) while the later ones reuse it late time.Duration - n int + // clock, when set, is MaxRPM's held clock (holdMinute): the vendor + // notes each request's time on it, and a late first moves it on by + // late rather than sleeping + clock *minuteClock + n int } func (v *minuteVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -34,11 +40,19 @@ func (v *minuteVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { v.mu.Lock() v.n++ if v.n == 1 && v.late > 0 { - v.mu.Unlock() - time.Sleep(v.late) - v.mu.Lock() + if v.clock != nil { + v.clock.advance(v.late) + } else { + v.mu.Unlock() + time.Sleep(v.late) + v.mu.Lock() + } + } + if v.clock != nil { + v.at = append(v.at, v.clock.Now()) + } else { + v.at = append(v.at, time.Now()) } - v.at = append(v.at, time.Now()) v.path = append(v.path, r.URL.Path) failing := v.fail > 0 && strings.HasSuffix(r.URL.Path, "/chat/completions") if failing { @@ -82,6 +96,187 @@ func slackMinute(t *testing.T, w, longest time.Duration) { rpmSlack = w / 6 } +// minuteClock is MaxRPM's clock and timer held still: it moves only when the +// test moves it. A test of the minute on the wall clock went red on a busy +// machine whenever the machine was slower than the checks allowed: a second +// request that came late in a 1.5s window was told Retry-After 1, or found +// the window passed (#1791). On the held clock, what the limiter decides +// rests on the minute's arithmetic alone, and a wait for room is a state +// the test sees (waiting) rather than a time it measures. +type minuteClock struct { + mu sync.Mutex + now time.Time + waits []*minuteWait +} + +type minuteWait struct { + at time.Time + c chan time.Time +} + +// holdMinute holds MaxRPM's clock for the test, before its gateway starts. +// A minuteVendor given the clock lets every wait go before the gateway +// closes (rpmGateway), so a request a failed test left waiting ends. +func holdMinute(t *testing.T) *minuteClock { + t.Helper() + c := &minuteClock{now: time.Now()} + on, ot := rpmNow, rpmTimer + rpmNow, rpmTimer = c.Now, c.timer + t.Cleanup(func() { rpmNow, rpmTimer = on, ot }) + return c +} + +func (c *minuteClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *minuteClock) timer(d time.Duration) (<-chan time.Time, func() bool) { + c.mu.Lock() + defer c.mu.Unlock() + w := &minuteWait{at: c.now.Add(d), c: make(chan time.Time, 1)} + if !w.at.After(c.now) { + w.c <- c.now + return w.c, func() bool { return false } + } + c.waits = append(c.waits, w) + return w.c, func() bool { + c.mu.Lock() + defer c.mu.Unlock() + i := slices.Index(c.waits, w) + if i < 0 { + return false + } + c.waits = slices.Delete(c.waits, i, i+1) + return true + } +} + +// advance moves the clock on by d, letting go the waits it reaches. +func (c *minuteClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = c.now.Add(d) + c.waits = slices.DeleteFunc(c.waits, func(w *minuteWait) bool { + if w.at.After(c.now) { + return false + } + w.c <- c.now + return true + }) +} + +// waiting is when each request waiting for room in the minute goes. +func (c *minuteClock) waiting() []time.Time { + c.mu.Lock() + defer c.mu.Unlock() + var at []time.Time + for _, w := range c.waits { + at = append(at, w.at) + } + return at +} + +// release lets every wait go. +func (c *minuteClock) release() { + c.mu.Lock() + defer c.mu.Unlock() + for _, w := range c.waits { + w.c <- w.at + } + c.waits = nil +} + +// rpmReply is a request's answer, or the error that ended it. +type rpmReply struct { + code int + header http.Header + body string + err error +} + +// askRPM sends body to the gateway's path and answers on the channel once +// the request ends. +func askRPM(ctx context.Context, gw, path, body string) <-chan rpmReply { + out := make(chan rpmReply, 1) + go func() { + req, _ := http.NewRequestWithContext(ctx, "POST", gw+path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + res, err := http.DefaultClient.Do(req) + if err != nil { + out <- rpmReply{err: err} + return + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + out <- rpmReply{code: res.StatusCode, header: res.Header, body: string(b)} + }() + return out +} + +const rlPath, rlBody = "/v1/chat/completions", `{"model":"rl/m","messages":[{"role":"user","content":"hi"}]}` + +// rpmBound bounds how long a test waits for a request on a busy machine to +// get where it is going: never a check of how fast it was, only so a test +// gone wrong ends. +const rpmBound = 2 * time.Minute + +// atOnce is r's answer, failing the test if its request starts a wait for +// room in the minute instead: on the held clock such a wait never ends on +// its own, so the request either answers without one or is seen waiting. +func (c *minuteClock) atOnce(t *testing.T, what string, r <-chan rpmReply) rpmReply { + t.Helper() + for end := time.Now().Add(rpmBound); time.Now().Before(end); { + select { + case got := <-r: + return got + case <-time.After(5 * time.Millisecond): + } + if w := c.waiting(); len(w) > 0 { + c.release() + t.Fatalf("%s waited for room in the minute, to go %s after now", what, w[0].Sub(c.Now())) + } + } + t.Fatalf("%s didn't end in %s", what, rpmBound) + return rpmReply{} +} + +// waitsUntil is when the one request waiting for room in the minute goes, +// once it is waiting. +func (c *minuteClock) waitsUntil(t *testing.T, what string) time.Time { + t.Helper() + var w []time.Time + rpmEventually(t, what+" waiting for room in the minute", func() bool { w = c.waiting(); return len(w) > 0 }) + if len(w) != 1 { + t.Fatalf("%d waiting for room in the minute, want %s alone", len(w), what) + } + return w[0] +} + +// rpmAnswered is r's answer, once its request ends. +func rpmAnswered(t *testing.T, what string, r <-chan rpmReply) rpmReply { + t.Helper() + select { + case got := <-r: + return got + case <-time.After(rpmBound): + t.Fatalf("%s didn't end in %s", what, rpmBound) + } + return rpmReply{} +} + +// rpmEventually waits for cond, as within does, with room for a busy machine. +func rpmEventually(t *testing.T, what string, cond func() bool) { + t.Helper() + for end := time.Now().Add(rpmBound); time.Now().Before(end); time.Sleep(5 * time.Millisecond) { + if cond() { + return + } + } + t.Fatalf("timed out waiting for %s", what) +} + // rpmGateway is a gateway as the real server serves it (lanGuard in // front), with a provider "rl" of one key whose MaxRPM is limit. func rpmGateway(t *testing.T, v *minuteVendor, limit int) (*Server, string) { @@ -95,45 +290,49 @@ func rpmGateway(t *testing.T, v *minuteVendor, limit int) (*Server, string) { s := New() gw := httptest.NewServer(lanGuard(s.Handler())) t.Cleanup(gw.Close) - return s, gw.URL -} - -func chatOnce(ctx context.Context, gw string) (*http.Response, string, error) { - req, _ := http.NewRequestWithContext(ctx, "POST", gw+"/v1/chat/completions", strings.NewReader(`{"model":"rl/m","messages":[{"role":"user","content":"hi"}]}`)) - req.Header.Set("Content-Type", "application/json") - res, err := http.DefaultClient.Do(req) - if err != nil { - return nil, "", err + if v.clock != nil { + // before the gateway closes, which waits for its requests + t.Cleanup(v.clock.release) } - b, _ := io.ReadAll(res.Body) - res.Body.Close() - return res, string(b), nil + return s, gw.URL } // coeo91 on Discord: OpenRouter's free models take 20 requests a minute, // which a limit at once of 1 didn't keep to. With a MaxRPM of 2, through // the real server, two requests go at once and the third waits until the -// first is a minute old, then is answered. +// first is a minute (and the slack) old, then is answered; the vendor, +// whose first request came late by its dial, still sees the third a whole +// window after the first. func TestMaxRPMWaitsForRoomInTheMinute(t *testing.T) { window := 1500 * time.Millisecond slackMinute(t, window, time.Minute) // the first dials the connection the others reuse - v := &minuteVendor{late: 150 * time.Millisecond} + v := &minuteVendor{late: 150 * time.Millisecond, clock: holdMinute(t)} _, gw := rpmGateway(t, v, 2) - start := time.Now() - for i := range 3 { - res, body, err := chatOnce(context.Background(), gw) - if err != nil || res.StatusCode != 200 || !strings.Contains(body, `"ok"`) { - t.Fatalf("request %d: %v %v %s", i+1, err, res, body) + clk := v.clock + t0 := clk.Now() + for i := range 2 { + what := fmt.Sprintf("request %d, with room in the minute,", i+1) + if r := clk.atOnce(t, what, askRPM(context.Background(), gw, rlPath, rlBody)); r.err != nil || r.code != 200 || !strings.Contains(r.body, `"ok"`) { + t.Fatalf("request %d: %v %d %s", i+1, r.err, r.code, r.body) } } + third := askRPM(context.Background(), gw, rlPath, rlBody) + until := clk.waitsUntil(t, "the third") + if want := t0.Add(window + rpmSlack); !until.Equal(want) { + t.Fatalf("the third waits to go %s after the first, want the window and slack, %s", until.Sub(t0), want.Sub(t0)) + } + if n := len(v.times()); n != 2 { + t.Fatalf("the vendor saw %d while the third waits, want 2", n) + } + clk.advance(until.Sub(clk.Now())) + if r := rpmAnswered(t, "the third", third); r.err != nil || r.code != 200 || !strings.Contains(r.body, `"ok"`) { + t.Fatalf("request 3: %v %d %s", r.err, r.code, r.body) + } at := v.times() if len(at) != 3 { t.Fatalf("the vendor saw %d requests, want 3", len(at)) } - if d := at[1].Sub(start); d > window/2 { - t.Fatalf("the second waited %s with room in the minute", d) - } if d := at[2].Sub(at[0]); d < window { t.Fatalf("the vendor saw the third %s after the first, inside the %s window", d, window) } @@ -146,21 +345,20 @@ func TestMaxRPMWaitsForRoomInTheMinute(t *testing.T) { func TestMaxRPMTooLongIs429WithRetryAfter(t *testing.T) { window := 1500 * time.Millisecond shortMinute(t, window, 200*time.Millisecond) - v := &minuteVendor{} + v := &minuteVendor{clock: holdMinute(t)} _, gw := rpmGateway(t, v, 1) - if res, body, err := chatOnce(context.Background(), gw); err != nil || res.StatusCode != 200 { - t.Fatalf("first: %v %v %s", err, res, body) + clk := v.clock + if r := clk.atOnce(t, "the first", askRPM(context.Background(), gw, rlPath, rlBody)); r.err != nil || r.code != 200 { + t.Fatalf("first: %v %d %s", r.err, r.code, r.body) } - began := time.Now() - res, body, err := chatOnce(context.Background(), gw) - if err != nil { - t.Fatal(err) + // the clock held where the first went, the minute has room again in + // the whole window, 1.5s: Retry-After 2 + r := clk.atOnce(t, "the second, to be turned away,", askRPM(context.Background(), gw, rlPath, rlBody)) + if r.err != nil { + t.Fatal(r.err) } - if res.StatusCode != 429 || res.Header.Get("Retry-After") != "2" || !strings.Contains(body, "1 requests a minute is its limit") { - t.Fatalf("second = %d Retry-After %q %s, want a 429 saying the limit, Retry-After 2", res.StatusCode, res.Header.Get("Retry-After"), body) - } - if d := time.Since(began); d > window/2 { - t.Fatalf("turned away after %s, not at once", d) + if r.code != 429 || r.header.Get("Retry-After") != "2" || !strings.Contains(r.body, "1 requests a minute is its limit") { + t.Fatalf("second = %d Retry-After %q %s, want a 429 saying the limit, Retry-After 2", r.code, r.header.Get("Retry-After"), r.body) } if n := len(v.times()); n != 1 { t.Fatalf("the vendor saw %d, want 1", n) @@ -168,9 +366,9 @@ func TestMaxRPMTooLongIs429WithRetryAfter(t *testing.T) { if r := restingNow(t); len(r) != 0 { t.Fatalf("%v rest for a limit of the user's", r) } - time.Sleep(window) - if res, body, err := chatOnce(context.Background(), gw); err != nil || res.StatusCode != 200 { - t.Fatalf("after the minute: %v %v %s", err, res, body) + clk.advance(window) + if r := clk.atOnce(t, "the next, after the minute,", askRPM(context.Background(), gw, rlPath, rlBody)); r.err != nil || r.code != 200 { + t.Fatalf("after the minute: %v %d %s", r.err, r.code, r.body) } } @@ -178,25 +376,29 @@ func TestMaxRPMTooLongIs429WithRetryAfter(t *testing.T) { // nothing is sent, and its place in the minute is given back. func TestMaxRPMAgentGoneWhileWaiting(t *testing.T) { shortMinute(t, 3*time.Second, time.Minute) - v := &minuteVendor{} + v := &minuteVendor{clock: holdMinute(t)} s, gw := rpmGateway(t, v, 1) - if res, _, err := chatOnce(context.Background(), gw); err != nil || res.StatusCode != 200 { - t.Fatalf("first: %v %v", err, res) + clk := v.clock + if r := clk.atOnce(t, "the first", askRPM(context.Background(), gw, rlPath, rlBody)); r.err != nil || r.code != 200 { + t.Fatalf("first: %v %d", r.err, r.code) } who := meterWho(provider.Provider{ID: "rl", Key: "k"}) ctx, cancel := context.WithCancel(context.Background()) - done := make(chan error, 1) - go func() { - _, _, err := chatOnce(ctx, gw) - done <- err - }() - within(t, "the second waiting", func() bool { return s.rpms.used(who) == 2 }) + second := askRPM(ctx, gw, rlPath, rlBody) + clk.waitsUntil(t, "the second") + if n := s.rpms.used(who); n != 2 { + t.Fatalf("%d counted with the second waiting, want 2", n) + } cancel() - if err := <-done; err == nil { + if r := rpmAnswered(t, "the canceled request", second); r.err == nil { t.Fatal("the canceled request answered") } - within(t, "its place given back", func() bool { return s.rpms.used(who) == 1 }) - time.Sleep(100 * time.Millisecond) + rpmEventually(t, "its place given back", func() bool { return s.rpms.used(who) == 1 }) + // its wait ended with its place given back, so nothing is left to send + // it once the minute has room + if w := clk.waiting(); len(w) != 0 { + t.Fatalf("%d still waiting for room after the agent went", len(w)) + } if n := len(v.times()); n != 1 { t.Fatalf("the vendor saw %d, want 1", n) } @@ -209,47 +411,41 @@ func TestMaxRPMAgentGoneWhileWaiting(t *testing.T) { func TestMaxRPMCountsRetriesAndCounts(t *testing.T) { window := 1500 * time.Millisecond slackMinute(t, window, time.Minute) - v := &minuteVendor{fail: 1, late: 150 * time.Millisecond} + v := &minuteVendor{fail: 1, late: 150 * time.Millisecond, clock: holdMinute(t)} _, gw := rpmGateway(t, v, 3) - if res, body, err := chatOnce(context.Background(), gw); err != nil || res.StatusCode != 200 { - t.Fatalf("first: %v %v %s", err, res, body) + clk := v.clock + t0 := clk.Now() + if r := clk.atOnce(t, "the first", askRPM(context.Background(), gw, rlPath, rlBody)); r.err != nil || r.code != 200 { + t.Fatalf("first: %v %d %s", r.err, r.code, r.body) } if n := len(v.times()); n != 2 { t.Fatalf("the vendor saw %d, want the 503 and its retry", n) } - req, _ := http.NewRequest("POST", gw+"/v1/messages/count_tokens", strings.NewReader(`{"model":"rl/m","messages":[{"role":"user","content":"hi"}]}`)) - req.Header.Set("Content-Type", "application/json") - res, err := http.DefaultClient.Do(req) - if err != nil { - t.Fatal(err) - } + r := clk.atOnce(t, "the count, with room in the minute,", askRPM(context.Background(), gw, "/v1/messages/count_tokens", rlBody)) var count struct { InputTokens int `json:"input_tokens"` } - json.NewDecoder(res.Body).Decode(&count) - res.Body.Close() - if count.InputTokens != 7 { - t.Fatalf("count = %d, want the vendor's 7", count.InputTokens) + json.Unmarshal([]byte(r.body), &count) + if r.err != nil || count.InputTokens != 7 { + t.Fatalf("count = %d (%v %s), want the vendor's 7", count.InputTokens, r.err, r.body) } // with no room in the minute, a count doesn't wait: the estimate // answers, and the vendor isn't asked - req, _ = http.NewRequest("POST", gw+"/v1/messages/count_tokens", strings.NewReader(`{"model":"rl/m","messages":[{"role":"user","content":"hi"}]}`)) - req.Header.Set("Content-Type", "application/json") - began := time.Now() - res, err = http.DefaultClient.Do(req) - if err != nil { - t.Fatal(err) - } - io.Copy(io.Discard, res.Body) - res.Body.Close() - if res.StatusCode != 200 || time.Since(began) > window/2 { - t.Fatalf("a count with no room: %d after %s", res.StatusCode, time.Since(began)) + r = clk.atOnce(t, "a count with no room", askRPM(context.Background(), gw, "/v1/messages/count_tokens", rlBody)) + if r.err != nil || r.code != 200 { + t.Fatalf("a count with no room: %v %d %s", r.err, r.code, r.body) } if n := len(v.times()); n != 3 { t.Fatalf("the vendor saw %d, want the count estimated", n) } - if res, body, err := chatOnce(context.Background(), gw); err != nil || res.StatusCode != 200 { - t.Fatalf("last: %v %v %s", err, res, body) + last := askRPM(context.Background(), gw, rlPath, rlBody) + until := clk.waitsUntil(t, "the last") + if want := t0.Add(window + rpmSlack); !until.Equal(want) { + t.Fatalf("the last waits to go %s after the first, want the window and slack, %s: the retry or the count wasn't counted", until.Sub(t0), want.Sub(t0)) + } + clk.advance(until.Sub(clk.Now())) + if r := rpmAnswered(t, "the last", last); r.err != nil || r.code != 200 { + t.Fatalf("last: %v %d %s", r.err, r.code, r.body) } at := v.times() if len(at) != 4 { diff --git a/internal/gateway/search.go b/internal/gateway/search.go index 666646aa5..80b3bc440 100644 --- a/internal/gateway/search.go +++ b/internal/gateway/search.go @@ -1,6 +1,7 @@ package gateway import ( + "bytes" "cmp" "context" "encoding/json" @@ -105,8 +106,14 @@ func searchesItself(p provider.Provider, proto provider.Protocol) bool { saidTo := p.Searches && (proto == provider.Anthropic || proto == provider.Responses) && p.Base(proto) != "" if p.Account != nil { // Grok by its id: moved to its plugin, its account is the plugin's; - // its plugin beside the built-in (grok-plugin) by the plugin's id - return (p.Account.Agent == "codex" || p.ID == "grok" || p.PluginProvider() == "grok") && proto == provider.Responses || + // its plugin beside the built-in (grok-plugin) by the plugin's id. + // Copilot's /responses runs web_search itself for every model it + // serves there: gpt-5.3-codex, gpt-5.4-mini, gpt-6-luna, grok-4.7 + // and mai-code-1.1-flash each answered a request offering it with + // web_search_call items and cited pages (2026-10-17, a real + // account). Translated for magpie's search instead, Codex's every + // turn on Copilot lost the relay (echo_ts on Discord). + return (p.Account.Agent == "codex" || p.Account.Agent == "copilot" || p.ID == "grok" || p.PluginProvider() == "grok") && proto == provider.Responses || p.IsPlugin() && saidTo } if saidTo { @@ -209,13 +216,24 @@ var searchHosts = map[provider.Protocol][]string{ // searchAsked is whether a body offers the model web search, looked for // cheaply before it is parsed. func searchAsked(proto provider.Protocol, body []byte) bool { - if !strings.Contains(string(body), "web_search") && !strings.Contains(string(body), "oogle_search") && !strings.Contains(string(body), "googleSearch") { + // bytes, not string(body): each conversion copied the whole body, three + // times a request (a 200KB body: 640KB and 3ms) + if !bytes.Contains(body, []byte("web_search")) && !bytes.Contains(body, []byte("oogle_search")) && !bytes.Contains(body, []byte("googleSearch")) { return false } req, err := parse(proto, body) return err == nil && req.WebSearch } +// searchedForIt is whether a relayed request's web search is done by magpie +// for the provider, which can't be relayed: a body offering it to a model +// that doesn't search by itself. What is known of the provider is asked +// first: Codex offers web_search on every turn, and each relayed turn was +// parsed whole to learn it, for a provider that searches by itself. +func searchedForIt(p provider.Provider, from provider.Protocol, model string, body []byte) bool { + return (from == provider.Chat && !p.IsRemoteMagpie() || !searchesModel(p, from, model)) && searchAsked(from, body) +} + // searcher is the model magpie searches with: the one Settings names, while // it can (chosenSearcher), else the first of the providers that search by // themselves, with a small model of theirs, as searching needs no more. @@ -242,6 +260,10 @@ func searchRank(p provider.Provider) int { return 0 case p.Account != nil && p.Account.Agent == "codex": return 1 + case p.Account != nil && p.Account.Agent == "copilot": + // it searches for its own models only: another's searches would + // spend its premium requests, which no one asked for + return -1 case searchesItself(p, provider.Anthropic): return 2 case searchesItself(p, provider.Responses): @@ -370,7 +392,7 @@ func Searchers() []SearcherChoice { } var ms []catalog.Model for _, m := range p.Available() { - if !strings.HasPrefix(m.ID, provider.GroupPrefix) && searchableModel(p, m.ID) { + if !provider.IsGroupRef(m.ID) && searchableModel(p, m.ID) { ms = append(ms, m) } } @@ -436,7 +458,7 @@ func smallReady(p provider.Provider, keep func(catalog.Model) bool, from provide } l := strings.ToLower(m.ID) // a subscription's list can have what magpie wrote into its agent - if strings.HasPrefix(m.ID, provider.GroupPrefix) || (p.Account != nil && strings.Contains(m.ID, "/")) || + if strings.HasPrefix(m.ID, provider.GroupPrefix) || strings.HasPrefix(m.ID, provider.AutoPrefix) || (p.Account != nil && strings.Contains(m.ID, "/")) || strings.ContainsAny(l, ":~") || slices.ContainsFunc([]string{"nano", "lite", "image", "audio", "tts", "embed", "free"}, func(w string) bool { return strings.Contains(l, w) }) { continue } diff --git a/internal/gateway/search_test.go b/internal/gateway/search_test.go index 9057f5412..84bf1da2d 100644 --- a/internal/gateway/search_test.go +++ b/internal/gateway/search_test.go @@ -656,3 +656,49 @@ func TestPluginSaidToSearch(t *testing.T) { }) } } + +// A request's body is looked at for web search without a copy of it, and +// not parsed at all for a provider that searches by itself: Codex offers +// web_search on every turn, and each relayed turn was parsed whole. +func TestSearchAskedLooksCheaply(t *testing.T) { + long := strings.Repeat("a long prompt with words in it ", 7000) + plain := []byte(`{"model":"m","input":"` + long + `"}`) + if n := testing.AllocsPerRun(20, func() { searchAsked(provider.Responses, plain) }); n != 0 { + t.Errorf("a %dKB body with no search in it: %v allocations, want 0", len(plain)/1024, n) + } + asks := []byte(`{"model":"gpt-5","input":"` + long + `","tools":[{"type":"web_search"}]}`) + codex := provider.Provider{ID: "codex", Responses: provider.CodexBase, Account: &provider.Account{Agent: "codex"}} + if searchedForIt(codex, provider.Responses, "gpt-5", asks) { + t.Error("Codex searches by itself, and magpie searched for it") + } + if n := testing.AllocsPerRun(20, func() { searchedForIt(codex, provider.Responses, "gpt-5", asks) }); n > 20 { + t.Errorf("a provider that searches by itself: %v allocations, the body parsed", n) + } + other := provider.Provider{ID: "x", Responses: "https://example.test/v1"} + if !searchedForIt(other, provider.Responses, "gpt-5", asks) { + t.Error("a provider that doesn't search: magpie didn't search for it") + } + if searchedForIt(other, provider.Responses, "gpt-5", plain) { + t.Error("a body offering no search: magpie searched for it") + } +} + +func BenchmarkSearchedForIt(b *testing.B) { + long := strings.Repeat("a long prompt with words in it ", 7000) + asks := []byte(`{"model":"gpt-5","input":"` + long + `","tools":[{"type":"web_search"}]}`) + plain := []byte(`{"model":"gpt-5","input":"` + long + `"}`) + codex := provider.Provider{ID: "codex", Responses: provider.CodexBase, Account: &provider.Account{Agent: "codex"}} + other := provider.Provider{ID: "x", Responses: "https://example.test/v1"} + b.Run("codex-asks", func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + searchedForIt(codex, provider.Responses, "gpt-5", asks) + } + }) + b.Run("other-plain", func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + searchedForIt(other, provider.Responses, "gpt-5", plain) + } + }) +} diff --git a/internal/gateway/testdata/clinepass_stream.sse b/internal/gateway/testdata/clinepass_stream.sse new file mode 100644 index 000000000..9fc780758 --- /dev/null +++ b/internal/gateway/testdata/clinepass_stream.sse @@ -0,0 +1,3 @@ +data: {"id":"gen_01M3YFPP549JB6EP8D4RCXD6EH","object":"chat.completion.chunk","created":1790950726,"model":"deepseek/deepseek-v4.1-flash","choices":[{"index":0,"delta":{"role":"assistant"},"logprobs":null,"finish_reason":null}],"system_fingerprint":"fp_jgawxng80g"} +data: {"choices":[{"delta":{"provider_metadata":{"deepseek":{"choiceIndex":0,"messageRole":"assistant","promptCacheHitTokens":0,"promptCacheMissTokens":37,"responseObject":"chat.completion.chunk","systemFingerprint":"aeb56401ca74e127821c4f9126dcb669"},"gateway":{"cost":"0.00001515","gatewayCost":"0.00001515","generationId":"gen_01M3YFPP549JB6EP8D4RCXD6EH","inferenceCost":"0.00001515","inputInferenceCost":"0.00000555","marketCost":"0.00001515","outputInferenceCost":"0.0000096","routing":{"affinity":{"outcome":"confirmed","pinnedProvider":"deepseek"},"canonicalSlug":"deepseek/deepseek-v4.1-flash","clientSessionId":"sess-ed01ce273d78b615f19287b8325e4aee","clientSessionIdSource":"explicit","fallbacksAvailable":[],"finalProvider":"deepseek","modelAttemptCount":1,"modelAttempts":[{"canonicalSlug":"deepseek/deepseek-v4.1-flash","providerAttemptCount":1,"providerAttempts":[{"credentialType":"system","endTime":1790950726481,"provider":"deepseek","providerRequestId":"4ae0eeb4ebc6bcc03390f31ec70cc26a","providerResponseId":"00b1015b-004f-4132-9223-649fed188560","startTime":1790950725813,"statusCode":200,"success":true}],"success":true}],"originalModelId":"deepseek/deepseek-v4.1-flash","planningReasoning":"Provider set restricted to: deepseek. System credentials planned for: deepseek. Total execution order: deepseek(system)","resolvedProvider":"deepseek","totalProviderAttemptCount":1},"surchargeCost":"0"}}},"finish_reason":"length","index":0,"logprobs":null}],"created":1790950726,"generationId":"gen_01M3YFPP549JB6EP8D4RCXD6EH","id":"gen_01M3YFPP549JB6EP8D4RCXD6EH","model":"deepseek/deepseek-v4.1-flash","object":"chat.completion.chunk","system_fingerprint":"fp_jgawxng80g","usage":{"cache_creation_input_tokens":0,"completion_tokens":16,"completion_tokens_details":{"image_tokens":0,"reasoning_tokens":16},"cost":0.00001515,"cost_details":null,"gateway_cost":0.00001515,"is_byok":false,"market_cost":0.00001515,"prompt_tokens":37,"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0,"video_tokens":0},"total_tokens":53}} +data: [DONE] diff --git a/internal/gateway/testdata/copilot_rotating_ids.sse b/internal/gateway/testdata/copilot_rotating_ids.sse new file mode 100644 index 000000000..5be726cd5 --- /dev/null +++ b/internal/gateway/testdata/copilot_rotating_ids.sse @@ -0,0 +1,63 @@ +event: response.created +data: {"copilot_info_messages":[{"code":"model_pending_deprecation","message":"GPT-5.5 has a planned deprecation date of 2026-10-19."}],"copilot_warning_messages":[{"code":"model_degraded_provider","message":"GPT-5.5 is currently experiencing degraded performance due to issues with the model upstream provider. We are actively working to resolve the issue. In the meantime, you might want to use Auto or a different model."}],"response":{"access_programs":null,"background":false,"completed_at":null,"created_at":1792422687,"error":null,"frequency_penalty":0,"id":"rJzvYM1P5MQ9LajMAiVpPIlUk8AFZNJdiXRdRXIVg1L51uO6KRRSD4MSODLrruc9DPf2sHqJ9D83/bBdLOYDhqxVg4Qw7moEASYqCwk4rmGUKZRyRpSYG/xBEPBspnaMlz7R7LiPOohnzvF2DnRXf5aoppRd/d+mtFOmqnS0tyjA7x8fQ4WH3HKoOK+ppSp5m9CvJnMaMHpbcb8dC7MhrAyZaiNX5LG4eDjn8iIsdEBamnyjSK3eoNqszUPcycxEk7LQ1pFPWrcUBziy/nwu/oN4nfNmO4LMAPH/wBLtOPh4AUzRYrBrFTpy3k2YDHzOlhEd0DuL3sv0EGvGXyYtb1gJhn7ekbybkWRZlMeTumqrFRIWpxYFriGCxK2ssl2ic7bgum6sp09ELXHAeQPSXhs1VrC4D/Pi","incomplete_details":null,"instructions":"You are a coding agent. Before running a command, tell the u","max_output_tokens":null,"max_tool_calls":null,"metadata":{},"model":"gpt-5.5-2026-04-23","moderation":null,"object":"response","output":[],"parallel_tool_calls":false,"presence_penalty":0,"previous_response_id":null,"prompt_cache_retention":"24h","reasoning":{"context":"current_turn","effort":"low","mode":"standard","summary":"detailed"},"safety_identifier":"71052818b1f5a274739a8ded0a543a6fcbeafe9c192fd4b2d8fb1857a3c29560","service_tier":"default","status":"in_progress","store":false,"temperature":1,"text":{"format":{"type":"text"},"verbosity":"medium"},"tool_choice":"auto","tool_usage":{"image_gen":{"cached_tokens":0,"cached_tokens_details":{"cached_image_tokens":0,"cached_text_tokens":0},"input_tokens":0,"input_tokens_details":{"image_tokens":0,"text_tokens":0},"output_tokens":0,"output_tokens_details":{"image_tokens":0,"text_tokens":0},"total_tokens":0},"web_search":{"num_requests":0}},"tools":[{"type":"function","name":"exec_command"},{"type":"web_search","name":null}],"top_logprobs":0,"top_p":0.98,"truncation":"disabled","usage":null,"user":null},"sequence_number":0,"type":"response.created"} + +event: response.in_progress +data: {"response":{"access_programs":null,"background":false,"completed_at":null,"created_at":1792422687,"error":null,"frequency_penalty":0,"id":"sKkohqPwbwigrYAyIjhfj9nfxy9cDSkq68mo7lmLpno9tSj+biND707A2wUdRX6sRcEr0twck032l9J9efLImevN5AAJtjXtV1cscG/GbDOeIhApynSZaoHSg7R5TbG7YOevaTdX03FARaubGddFT7UdQ/WSWmQ+t6KBFSuaxhFRozVZlvRQpRJhCRjsisNVJ56yn7d28Oo9CgeVQ9JBvmT2sdUQJX4k1LrOJMwQvZZUb1QMoXXdSssCZ/lEWvf+Kega1KRY5A5qkWbT5vr4Zg5Cf97DCes60fN/wgo86bYvPZdZA0bN11wDcCqBPhyoUxmjGtexFFp5fxFQFUw4X/8MmFCYQKtVI3SUIU4hWY5cZQMjcX3KsLrWvFPLPijvT4px2ffr7bzfR/h82ME2c+t7D6THxw0W","incomplete_details":null,"instructions":"You are a coding agent. Before running a command, tell the u","max_output_tokens":null,"max_tool_calls":null,"metadata":{},"model":"gpt-5.5-2026-04-23","moderation":null,"object":"response","output":[],"parallel_tool_calls":false,"presence_penalty":0,"previous_response_id":null,"prompt_cache_retention":"24h","reasoning":{"context":"current_turn","effort":"low","mode":"standard","summary":"detailed"},"safety_identifier":"71052818b1f5a274739a8ded0a543a6fcbeafe9c192fd4b2d8fb1857a3c29560","service_tier":"default","status":"in_progress","store":false,"temperature":1,"text":{"format":{"type":"text"},"verbosity":"medium"},"tool_choice":"auto","tool_usage":{"image_gen":{"cached_tokens":0,"cached_tokens_details":{"cached_image_tokens":0,"cached_text_tokens":0},"input_tokens":0,"input_tokens_details":{"image_tokens":0,"text_tokens":0},"output_tokens":0,"output_tokens_details":{"image_tokens":0,"text_tokens":0},"total_tokens":0},"web_search":{"num_requests":0}},"tools":[{"type":"function","name":"exec_command"},{"type":"web_search","name":null}],"top_logprobs":0,"top_p":0.98,"truncation":"disabled","usage":null,"user":null},"sequence_number":1,"type":"response.in_progress"} + +event: response.output_item.added +data: {"item":{"content":[],"encrypted_content":"O8/dTdGe1ng61iI0UZYUBQenAlg2QODffh7kHHwxTCz4zlkw","id":"xcF0hsDZV6oP70yaHs2KzRI5Wg5V3RLmjjygZkPHgZVEpkcpjhoVozg6NeFxWBCVU9uCgq073IDPKpnq6tyojuZG/qSWxdD3XGYRHDZBbSlz5CLZ5pOvE6CR1c/SCbqT9L2NFox5TTLn7THIZ90kpZUvWiQoXHLGZEo+jdX+qnTf5Qm2cHB4t24wLSNSt9Rl3FanSKUb04uxIXt12ZhSTwbnlgMFQu5mKdlRWxzJQtkeDBw1saB1SnpKT8fzGF2deteY9plsEx2MeNymOu07nYir3wlV3zvKhtJjOQzY1dLYh4kaF5ZScmKVjF75cqov8kzexZk6k5PB8efu9at2R/cbImXSUA/j8N/QSkrdGfJOHYXwAkPbOSj7VplKuaJ1OqYrt7zqbE1AtDGwGuuGZYpn5CZaNQ==","summary":[],"type":"reasoning"},"output_index":0,"sequence_number":2,"type":"response.output_item.added"} + +event: response.output_item.done +data: {"item":{"content":[],"encrypted_content":"uhHG640BbKtaOCB7u3tV14F/viVzOE3/C173bfmf63N2HZ88","id":"frdh/GMtTAfTfHwU2T6gYnh+jP77XMYxdUV+8qLsfzmHm4tOXeNudPxxtHb0mp/SJARq8Y8pFw86ODidlfr9X11sEW5CF4qwpUHyWJ2DDLWNcGPh4P4LBcKVvBTWesGknxsUjyCJ3861p4nd67hc/rV1c3uXgGl2TNxDcdf5QFuSYJknQtRyh9Qlhe8FO6TXNxuGSYLNcD5EeUlEjizo4+Hga1jlGYDxQd9xVxv35svh1PwbwA5qAAATsNxres8wrrD7xdHolORgF3SNZHqz13H7x7Ev2uIm63Yv/QNPsxWjpz3xP+PsEVsIsaHvB739VFVPwN2QOPjTgdiU4gWqnF7CXW4J/Yu3hTqKWHPwT+reS1xhO6O3uQa46WvNHvW5DNth/mVInCJuokcDePf5qmj6R1FbRQ==","summary":[],"type":"reasoning"},"output_index":0,"sequence_number":3,"type":"response.output_item.done"} + +event: response.output_item.added +data: {"item":{"id":"bNa9KmE+lBrGs9DRYL/5MIAYER+PPdMcS0UlTQZPSDWQQZWj/ONsjTGOhKNR/d29fT7gk8jpn9UxqMM8qkI2c5zTYcsmqIxH/TWjzI4E+yDIup/ZGiT2CRxkosr6AUxphd+DTRRXUWKc+858fFSVs4ft8UY9rkTYncg8q0kyT5F4SYqcRESpihCWjZntyUqFbSsC7FqcoKBcf96w2hK9vnuqXOEQJifwUPwgi58RYPVHlkHRJ1l2xdEvH7aEWyvntLdZDG7oAaASif7PatPkVF/izfov30kp6OF/dqM/iwL/yeyHeYP+k+gBjcJzBjIoYtvwmIMHdnjYNax+kgWiuVtdTnxTNHK8/KdsJ+5kXSKODxNLW+qhYCAZM+a7WBZaC6diWkv/wuj3PEhpbExVW1CoVD/kcQ==","status":"in_progress","type":"web_search_call"},"output_index":1,"sequence_number":4,"type":"response.output_item.added"} + +event: response.web_search_call.in_progress +data: {"item_id":"NxtpMElSWxKJJ09S0CaMoxAgfhHVr689lZEqDYG8COFPJRuM1FUp1XQCi0I1AVaiCs6Unw+4OmmRnx/tXAzz1XW9PLc87gsqyDUHx2LpdpvV3LvZEr3YiJDBstqaYN24dgCUvpLQeJv16cGTZekHFLLBbnL+BSBM+z6c/Q4F5zeatntfaJSqRmoIMYMBVj2EnvwzwwCZfkdZmY6Gr0mAuJTqtb3+2N3LuWtBDQ30A0v1mapiLjcRrL2xpqjC7mEawr5ImZwY2INP91DGkmbCZKEAqiisvLA9sBr192pDzzlfsjKXtzsd53j+3P4pvvpaMhwBBXRxrYYHns9OaBU6Md2aIFfphm8cxA5UpanHDH74CXWkbpi86k7fR0JCwgD6ae0ODA294Ff44Qx32s/VspbnWsQkBw==","output_index":1,"sequence_number":5,"type":"response.web_search_call.in_progress"} + +event: response.web_search_call.searching +data: {"item_id":"oCpJBBs+h46UjVwS0tuggwYvExOh3ws9EhRuIBH/7ls3f8Dp4Ql3KT9vMwA7BBDIbBc4xTdPYhPx6QT0lcNJ941EMBgLRELGKsEKLwzucHcEsUxPPHhvgTIc8islaPH49/q7B3LVNEPODcDMaHZzSM1bt50u41AxK+x92MspqJKC9nkRhmHHUgBioIVqN1LCwmPPPlkcQ6GsEWh5ufoDzq6tQ0uaRMMC5e9X97TOmj6tYjhPuC13ldjQhFID8bcy6GyHt1Q8yeCgWozn3cfzHrSgxfsZIIFNAB+hoGPxWQsJiwv/PJYYmcAD00OD4iRQ2wmT79W6a6SVYCb0IanzMwv10UO1QnF4RcI/8t/HHG55K7LOShWIUvnC3g38h65BFnJ15FxSzIOCg3lfvCsB2WVSQPdTCw==","output_index":1,"sequence_number":6,"type":"response.web_search_call.searching"} + +event: response.web_search_call.completed +data: {"item_id":"wzFFknhudC9dXrtEWNPiarm4n/mW09xRgFELN4WU8JpWOfkQmwipzfMuWEMV1xT8vBrlbyqlOca96NIi53iIFDf168mAluulwlIlNdCvZX/LqS+hbxWjE/erM3VCh+ZPfvwBC1G+rg9u9Pidf+NLNupA7EURhhOxFJclwv53b0RBY9PWcLh7Ulw5uY4xVWoJcbtHJITkglyqPD02ol639PgmWXWs7GhaNE2x0S/XhKGmRIGSxcbqMfw/vi2tpf64IHSyQrhX77ZF8q+RrWJIx46rXXUAyXxDv01v0YhsJPVWlhb5sORohNSG71hihUzHrgG1IWUzn4PcGoEQoAloCbTpGOpG9JJ+cUgDDaik2yuVa6YYN7qcS1g9Anlwni7mtSeuFv5hK/Gn+mSFwA1hM4xaa7fcWg==","output_index":1,"sequence_number":7,"type":"response.web_search_call.completed"} + +event: response.output_item.done +data: {"item":{"action":{"queries":["latest Go release version official Go downloads"],"query":"latest Go release version official Go downloads","type":"search"},"id":"+h06EBf5mFA99e2BR78Ph7PPDoLYd1UdVUsJcvppHjt9l/DrAhCp+sgTipHMwqkjrn7xhwkzmLXAPk/iFNRnevc7wVk8gHMTyk67nQ4OXzCpOd6iRQO3kHN1ZVrnK277fe/O5mFXT3csR3uL1SYJAnZ9EGhdpXZo+Gt5Uk2H1g9lup4R9zfkU2Ep1dJHsgxCRU6BIz7kb8RR7HZ6OgCqSCUIbmyya+2KsDdHJXsbjzHX9dbTXS3vIm2QLcYjXdKRKqxGnxERu84nzFSW2EnPwD5R6Pdrih/6tOgr0uuQkJ0S344jO0XvmL13KjrSBw+Mrd8AhgsbPRgNtRuEQGAfzuTPEx3JXy2yhtNaBwrAoHXKEry/1zoWF6UK64knwAktCIwoIaYQm7MF6CyBQ1IgZ7rAKV9d6g==","status":"completed","type":"web_search_call"},"output_index":1,"sequence_number":8,"type":"response.output_item.done"} + +event: response.output_item.added +data: {"item":{"content":[],"id":"FrZ4LgXpt210jCb4ZGM+muXzFpYSGTkxthPMAW8BwXcX3qLgJQgwYqDzo0zKaKlJBqtAxYUzQgowyO1mFLgXnNgMnDDvHbUG3wtHvullGAK0PNg5k42PEHWNQTkYBEANL0Cc8AAvCXn0G21Tvuyf53ks1JIXGNictf0t0+3DQ/5KHwH1fNx8rEgnJpz15hI2ucPusv/8SSZDiUJ8FbrzCNnK3k+6JUK512K1GWr4Wk6B/iP9iWxTCzXMtDakkoAqWyuEaZKV1yv8RrOk+wGCLDztE8XLNDgCsDGyKDCSL1n5LoFwaqcRiP6Fb8UdS7oJnWLp+4XWkuhyIFBrfvntjb7prRtjCETIUxcTo9YzLJbrJ3ftP2qBW9UyNki80Lr4KMuKTsQy651C2lXllS4RnzgafbzheNo=","phase":"commentary","role":"assistant","status":"in_progress","type":"message"},"output_index":2,"sequence_number":9,"type":"response.output_item.added"} + +event: response.content_part.added +data: {"content_index":0,"item_id":"B/BMkJnP/YpUL4K5HWtN0F7ut9cYyQuVnOcqMDF60Xtw/e327CtGZ6EqYOkC3AuK6C6R9nQFu1LHvQDsD7XXXBa/phKE/znWMAd2WSG9ZQhaNUzkGcuUHYdUuCJmu71V7LkErdOr2esBpZdauNRUo3Pv21A01gsTryNNpvaHMEB6kEi1YMQTDaJVoVYCDLJugsxv+OgaAunqaxIxpd2/6EUjO++BXYWXvioHnIKMWoHToUvTOJzCVqYspp2gnddO5UvlMUsE/viCF76fwrEqsSJ4JPOt1kQq4J7xa8V3oZSUSARhvYPL1UmV9I1ilB1FOWbLI4PqqoDeirDnI1zSupSa5tTaVH7SWZq8aDuMOzcsN2dA8WVlfexFrPzPlbqMCdVw0y9A/8/hSbW3xkT1GJP4LXonwKg=","output_index":2,"part":{"annotations":[],"logprobs":[],"text":"","type":"output_text"},"sequence_number":10,"type":"response.content_part.added"} + +event: response.output_text.delta +data: {"content_index":0,"delta":"I found the official Go release history listing **go1.27.0**","item_id":"R16+6sqfOHARF7OZLeZ26YPHEwKWZ6504nV8xYc1l7NwgAUm9XG7mTMEBvouoKssI3jm/mQ8oObvbh9NfRI1AtwUdkuK/SwPKEXXa9Iej5b33GqtznnJ6p5a/AXdrJMU2tPGtgaXmmbjbn2DP8Cst7em6k5bvDUu5gAqtVH38iRPNFQ2uMD/wx0I+c3biSEpHSKuxDr2QQaj+HPpoTZwrBOc1E62nWi3RcedQvYKpTgdiAToe7bP2mQGfdg/ZeblIfACvuRPzeDgXRQhBbT+t9As41yR0ezU/hs4p5gGrNTusmum7EBSPdZUkx+M8hpBvu4pibUilyUsrPI4hvYU4Z6NBWC8Y976ERTtFNwjP0Huuh9oBvgoDSvSoZng13sCTgBvRNYV1n8NzEPn+6EWzcLtLthsZco=","logprobs":[],"obfuscation":"Y15l","output_index":2,"sequence_number":11,"type":"response.output_text.delta"} + +event: response.output_text.delta +data: {"content_index":0,"delta":" as the latest stable release, so I’ll now run the local `go version` command to compare it against that.","item_id":"a7eLb1R3NgS0gifzfmTqEpJx+xsmghaNojh4MIyGZCZAFUjH3k2QwkjeN8u/f7GGb+/WHficNa0ciCM8WT/mukJtI8WnW9uOkjgT5X8pIpJMx2/AjktJ4tkutPrtZJccaEFwFLE4GNDK34xJbffJ6rvNFDQfNbI9N+9ZzRXNxQPVY2fLTgIO9vLejauZryfFWTrsCZvUi4j6yyJNTOxT20ZIPvrMQic49/Sccy6uUKQFEh8ah76jC3UJknKwqGlqpiD/4yFe+jiPvr4VXLJzLe9d2WqS7NEqj6bzXY1x8qvYX+jLibSHm7RUthV3CYyJCOMOKVO4gj10c+kmTE2hLrXczvTdQ4C/EINez9kHZo0zwaIC0mycBp5MeMimdI9GBpFNwgO3iniWdtmU67H+J4QokjRapeI=","logprobs":[],"obfuscation":"bBT5EBu","output_index":2,"sequence_number":12,"type":"response.output_text.delta"} + +event: response.output_text.done +data: {"content_index":0,"item_id":"iFhic3CXyVBrUPfB+hFUBFlqcHWitwCcMiYggc/WARnkPFGHo/YpUjqoCg6Eh599MOEBiy/Oev15GIMvVNO01MNFKpFFpAeazBRvRB3kzG0/tDvlJgkHdJpFEEoWqeqoYtDo2O7jh+w9eFIgGwMLh2sbBz6vzltCt7gtglNjfiipNnGxOh5kaXCnmgPXfTlabMyT469zd1HHAjERzfWHaZIbLRohIE3K6gTixagAEWFX8sDyCCSeVKLrdE8nYDStP1RShWYk97aNbhZ3FmyjikGfonzK2W0k9CbHwo6mFUu09FNvHFajQKQ/4KN+qziu3rY4Rbj5ZrgMTHv+cKunMfJxm8ObNFst90RhOZ3xmtFpcJiJKdiGGp3z6ySzvJggYWHEnLzfvOpQBLKEVJ7z/7AmOiHo3Z0=","logprobs":[],"output_index":2,"sequence_number":13,"text":"I found the official Go release history listing **go1.27.0** as the latest stable release, so I’ll now run the local `go version` command to compare it against that.","type":"response.output_text.done"} + +event: response.content_part.done +data: {"content_index":0,"item_id":"OByhhiIO3J0VDvkP9r0qtJM78rYoblBCTVDjAGXl6wZkkSbIzbtz00bUrLzjyIkSGih3dtXjdH8CCf6hKM3+0ZSxwdTy2IFu38b7Ws3wZWnqUDsy4HaTOI2TfUus6bhMsuTEPBWc8BazQLHya8vQXGdrXPbDHQlWtnPt1zLEamx+sXgU+cdv5UdfQlz0oXl8qYtmJtiSP1KzOegIp2170OYLri/EGpPY56IzQSfdsjUm478PFF3qJ9v0Xar6jbFmycqEB7yp2TrfO6cj3z+6bvcVUgletOp+mTg73HgZjPLGU7nik6PJDMxiqcVUo4x2MpELKBqvOp+b20uuH+7Bgbr0o4cEVjU6VZQLI1DgdHDjR3hsLDPdLo2IhVVo2/sOnX86d83BNz1dkcr2ddvh3Ln1X7po45c=","output_index":2,"part":{"annotations":[],"logprobs":[],"text":"I found the official Go release history listing **go1.27.0** as the latest stable release, so I’ll now run the local `go version` command to compare it against that.","type":"output_text"},"sequence_number":14,"type":"response.content_part.done"} + +event: response.output_item.done +data: {"item":{"content":[{"annotations":[],"logprobs":[],"text":"I found the official Go release history listing **go1.27.0** as the latest stable release, so I’ll now run the local `go version` command to compare it against that.","type":"output_text"}],"id":"AFvekZkeBHTQW+eGOgeI5cdC5xvtiP5tKJvm7+inOpfltRVnQupzOxVs+m6kFaVQtLzqDLcF4hvSeEExfd8DFTSES7kum6psEokznEN2jiZK/kfWPzlVA75usca6siPnTYE0QpsmVgcgmJY7Y6pnuhfK/UsIMxzkeRMnT3N+Ffi3NgZU6RaSRO0/sYK51GuLVgUDsQLmTtKGZ/HiAHcjKZqEdswBKMa/2eaiqsynUqySMaruR4waVeW45Ta2tljnzCGHqkGBFvsKtC16gjA3zUsaGP11ukLKHESPSjYScAXr+adQere23jE/uoKfqT85M3V2ZBsly1YI7YmvBvQGAzLmpjvJba7qx03rga/9JunSRisHst6OgN/dLEPc0tCGT6B3MUMg4q/F/r61rhvenq0paH3sb2A=","phase":"commentary","role":"assistant","status":"completed","type":"message"},"output_index":2,"sequence_number":15,"type":"response.output_item.done"} + +event: response.output_item.added +data: {"item":{"arguments":"","call_id":"call_HbUGN0YBQvw0Bs2basus3wDn","id":"LW6G3L5gLDw7BOGJuE31bUQbDNk70jwG+0/jpSgO5sGvaAUCnPkoCqK1EOEEj+T/SoaZVIldigRAP5HuoqnKflDPebhlIF6ApKwlU6p96voAbmzWKq7mk9/icwZFU7EvoFxp06EtoSyD4zMJlP4sQSCt3zp1AyGFhcxRdV7RE4uhCZxHLiU+s9ndmrKQT4QKMoKzIWB4ENQ5E1yzGniDYXyu4mPJJqK95wUVnmZjMq3TNMuMyctCF8KFDzw+ISTVw+BtLgWlAspTQrQj450juJYBQYT85L2T6ifTMkzAfh19swFyWv+cV8iCw2IRPHl5zzoeSNBqneKgYOTSEZpzfg9Xy5jcg2573oEzSUsoLdQZX00WKCRBaHNZA3j/WqV6/np3SIkhPiunRGPVvTvjVct3+tkOEg==","name":"exec_command","status":"in_progress","type":"function_call"},"output_index":3,"sequence_number":16,"type":"response.output_item.added"} + +event: response.function_call_arguments.delta +data: {"delta":"{\"cmd\":\"go version\"}","item_id":"/DgrFYL/PF8whvyahkWMnhPv7Pk6wgAdZstfjbZQ2fnDA22dV5z2cSkUirpNFdDHkuAjjCy2wOB+wqXs4Kp7L03FLqGlRSL06yds4CD5AdqYR68YA0lRkFZRmoWSNggOLGlqSvXlGO/7noZriCFvpoB9X1QTgZZQL5a6eI/3kKCj2eoLM7KjIsoebyaug1O1iDbuXtdC45K5RtLCJ7XJKi1nVHeYxj/7FNJOAU4KMyOOSg9f1XOqAa3IxbkIgcnLO3po7U7INKlABQ5Y4vvl9YMMc1jYwLwmfGGYc4QEQVpOkWurrZZnaekG9hnef9gH8fBw7bilDJtUcinRbhFEX8d5+NjDX/xRePqIGNX7lNMeuRyZ0//Zxc2/4frxOCNy+5ZhIxA+FriTgEil6AWWC9nyU2OMAw==","obfuscation":"0H1A0Egt36dj","output_index":3,"sequence_number":17,"type":"response.function_call_arguments.delta"} + +event: response.function_call_arguments.done +data: {"arguments":"{\"cmd\":\"go version\"}","item_id":"P22tsYsjCI+SYKG4RPJ+GVjt0Wcj6whoZSyOxw+QSQN37EWxqXJfYp7L6OkuHGQAetaOrjWTIz0T1tWmP8zqrWU1qZV+G6XDZ2uEm/pJYddHjhj100NSudTvGmPIjsFqT3O4gXEAupSXOGt2nhnolSJ/NIosNG07gkAvqAnYvbPRVydgrCkBcaOxH+c7t11VAh2KFJ52e4okVQ6ZRRhBDOYq9eD3ALwsVHk9Kg+ft+WnpYqUUz4Ql1/2RA+5BNUbMn9pkHlGLCQVBWcTEpHHgIThjZV/LNEZPlU2Q3Ku1jskmaZKfHVSdzeCjAhYhm+XZ2QCVu0dbgcEUZyhrfFh1cT09bUjiluLhw0nGmHAAGgeT1z8ju2oXn5F969A6S5B7q2MybvJA/APoCJnmIscpJ4hZxpMFw==","output_index":3,"sequence_number":18,"type":"response.function_call_arguments.done"} + +event: response.output_item.done +data: {"item":{"arguments":"{\"cmd\":\"go version\"}","call_id":"call_HbUGN0YBQvw0Bs2basus3wDn","id":"GpWGgz/HFG4wpQCzc7TWT5U/aKb8zp9Zrf6s+Xm4KofRvqfMjQQGVHVpOZ8OdVARsheSzmZHJn4cZvhiOwYk1V4F0y5VbsnJCxbDd/hFF426nddmYpGE2iCDWofEuXST6JpcBr3XQ3G9eKC5ws4wjCeJK93wmd9UPrt4sKrFHsruCyyZ8h8Dg5P/fLPgmL0FAsWzBgrAn520NoQHYLfjIJhTneDZtMzzTHWrAGOAyMi5okd3h9fQ/5dlJCNkTBHDGSGDVW5WOgIZOR5ARBQW/WrHnfqASx0AfG1VVrNVsfs0TlHNzfLk0ukaq1syxwzsdctrETNAKcs4BDzYGCO3SSGiKUgXr8p8AUMOMhkY8JfXUzNAvYgkOUKdzW2pekhXRKka3dqFXHU3QEgUaGxhnNpQfVhDqg==","name":"exec_command","status":"completed","type":"function_call"},"output_index":3,"sequence_number":19,"type":"response.output_item.done"} + +event: response.completed +data: {"copilot_info_messages":[{"code":"model_pending_deprecation","message":"GPT-5.5 has a planned deprecation date of 2026-10-19."}],"copilot_usage":{"token_details":[{"batch_size":1000000,"cost_per_batch":500000000000,"model":"gpt-5.5","token_count":5285,"token_type":"input"},{"batch_size":1000000,"cost_per_batch":50000000000,"model":"gpt-5.5","token_count":3712,"token_type":"cache_read"},{"batch_size":1000000,"cost_per_batch":0,"model":"gpt-5.5","token_count":0,"token_type":"cache_write"},{"batch_size":1000000,"cost_per_batch":3000000000000,"model":"gpt-5.5","token_count":107,"token_type":"output"}],"total_nano_aiu":3149100000},"copilot_warning_messages":[{"code":"model_degraded_provider","message":"GPT-5.5 is currently experiencing degraded performance due to issues with the model upstream provider. We are actively working to resolve the issue. In the meantime, you might want to use Auto or a different model."}],"response":{"access_programs":null,"background":false,"completed_at":1792422693,"created_at":1792422687,"error":null,"frequency_penalty":0,"id":"6BDiYBNSndttMS/yq11iqapvJ2oMsDwuwx/la6eBNjcM77HohB7XL6BFmeTnbWbFFUPaFHBnhX3vGjT/z+XZ1CWhOh81Sn39XEsDjQe4oGHjQlTEjlSTtHCuKyb58jwiK7iM/Q3vSopd9TBPF4O61RWwn/RE1E408R5cjslrehfNz9NI80kCAxDJ9DNXzQeuXaRHvsGI/HIa3ZUd1lJBHb8TkSYnfIbknJpD+Q0rsP2/kGAigG9DuW2oxYtw0T0d0+c6Zr044ZvZFCgkndl1fTbTFUdudIdA7eeTd/ccVS3HukFUH3bgae0jpOol5aHhcjGDvRHlEYGfQQvIQfjChsDBHAw3BaRopGaP8N/O5BaHgHhxwexteO32J9ArrR2P0B/RaRuviaBNjEy/zAgrb5CcesIUl9l0","incomplete_details":null,"instructions":"You are a coding agent. Before running a command, tell the u","max_output_tokens":null,"max_tool_calls":null,"metadata":{},"model":"gpt-5.5-2026-04-23","moderation":null,"object":"response","output":[{"content":[],"encrypted_content":"Dn1tSnQgikz7Z8WTT0YqHHaIJEo9OUm2vCtuWjhEbh7mS3R3","id":"Dx5OmEZEHZbFcsa7K9DTNwkWcpt4TBep4OgloIaOszS1AlD212QcoPxyrrLNlKI0GbKTMATkjNu4P2r6CfyttvOk7oun5Osb9d49uoyCsvW/XGswwIRv8fwYxJJ9YIhP4n5F6s2N2TOm0XVnUPoUtiPJOlTQ/UvNYyPMIkOr2PmKeEtb8/nvzm3BRNf3VnJaYUyCKFxdTUJYx4e5xkCzGShPF1PAauKwaOWXjdNCsWfObiej0Xap021mMAKqwgWcYrA+nMYtFOyl7222lEkFJEZSN4xr6Em6ZRO/132yZTTXAP2lzBaO1h1Sqt8Yffiz8R4H5c3/E+O/VjwaZGhEuSUUnImxj6dd2l0obUrAt5S41RAKsh+nqteugBJr96x9rgPeERFhDPStG9JfiOL8mJVd0p3haw==","summary":[],"type":"reasoning"},{"action":{"queries":["latest Go release version official Go downloads"],"query":"latest Go release version official Go downloads","type":"search"},"id":"NtGc0beGsHHFvBQjcbTEGRoB6BHUGG4TCuEwDhhUKxsj4nvGYdoOXBJBIY3r8thTBbiw4dYJ74TtpAfKfV2iARRRs0AwjFTKLdn6+q8bHGuB4ukAlxUfsXm/KmgWnRvszizv2COva/hh7H5fG21n2e0coW53PTL8J7jOARDCpwRa4fYii/aHsny+x8TO56ajvmvs/vyfmuosXU6LZPVL+jNnqDmOVZdDNd8Kc98vzac+sHn7kmXQLz7N4MebEyYgA6LiQ+Do3cSGTDx+oA6C4WWhqcIZgATWO7OAR7MQt2779wBcijThMI/uRakag/oqCZ4wcu84Pe1op+8gEWskCBIMhxlQaSd4Fl8QNKFnWKEKLCvxC9yOkzof3yp3I+sEVdvCjZxHjRBwqBeg7aUyMnImLzuPtw==","status":"completed","type":"web_search_call"},{"content":[{"annotations":[],"logprobs":[],"text":"I found the official Go release history listing **go1.27.0** as the latest stable release, so I’ll now run the local `go version` command to compare it against that.","type":"output_text"}],"id":"oZ0DVMrEEzH24StMag/wpzW1WyKrKH17UIUnJB7ER/duHreFn8K5lCBz+TsOuUBpXu3og4pWQJESrkRdkjh7x3BlCwFl57Yh+ZGXC5fgvvGeAPOYoothtjBEi8oBbDuYS4lY3k5PjLwwKA+HRxaAJSvqsYryR1xPyh69Y4S3eZN/eRO0duhTYGOHiNAGlacpPg6QYE1WPbQxc24lycCv0R/Lnm85vXbfh3qm7j44QpE4AOxAVtHlUeQ0ATSiPFNE5E2nc3Of3EtUaVhaA9GZwxx2ckCl1DrNkMQOmqZ+nlhCpm/88jxpG0BxC+U0MUqMb3QcTZuQCsVACO8Wwa46qXqNYpFP6l5XxP0ugHhtQL97suC1qzkYQR5atsOFF9pod3Zp/IoeUiLuULv4Y1nu3MWng3270tQ=","phase":"commentary","role":"assistant","status":"completed","type":"message"},{"arguments":"{\"cmd\":\"go version\"}","call_id":"call_HbUGN0YBQvw0Bs2basus3wDn","id":"sQvKMNJ34ZavzIa0GhteNSWe/tooaQTblz0Cajm78CIabrjFGdJWykMWs8zHdpVPeTz80cTcT5A0qQfjBoWauNxFGYOVBZcDC8csErwuZqiXrHr+YnlOGROrz3X46HYE17jl+cENdh7ZRL2NOCETJWsLi7ZxS9lxvK67G9IM24oFjcTF7WpiALkBTHJBEhdsovX4//Hk9LzqNJn5dDdYS0h6JoFCSWzeGNydkgitVzjxn6q1N2ruh8OrwlkCGw142Q05amOSX/6EfiG7lozs/7O0MeHkH21rmBPuVhPrebjj63xaOEgPSv6GJYo3L1t7NVoA6bpVEeVdtALEFgmdzL+El9oQciuNUk9M5cpiyaleYcV5QM3vC/Bfd356AHAR83wfso/McU5ynITPqV8+rI+usMlBgg==","name":"exec_command","status":"completed","type":"function_call"}],"parallel_tool_calls":false,"presence_penalty":0,"previous_response_id":null,"prompt_cache_retention":"24h","reasoning":{"context":"current_turn","effort":"low","mode":"standard","summary":"detailed"},"safety_identifier":"71052818b1f5a274739a8ded0a543a6fcbeafe9c192fd4b2d8fb1857a3c29560","service_tier":"default","status":"completed","store":false,"temperature":1,"text":{"format":{"type":"text"},"verbosity":"medium"},"tool_choice":"auto","tool_usage":{"image_gen":{"cached_tokens":0,"cached_tokens_details":{"cached_image_tokens":0,"cached_text_tokens":0},"input_tokens":0,"input_tokens_details":{"image_tokens":0,"text_tokens":0},"output_tokens":0,"output_tokens_details":{"image_tokens":0,"text_tokens":0},"total_tokens":0},"web_search":{"num_requests":1}},"tools":[{"type":"function","name":"exec_command"},{"type":"web_search","name":null}],"top_logprobs":0,"top_p":0.98,"truncation":"disabled","usage":{"input_tokens":8997,"input_tokens_details":{"cache_write_tokens":0,"cached_tokens":3712},"output_tokens":107,"output_tokens_details":{"reasoning_tokens":41},"total_tokens":9104},"user":null},"sequence_number":20,"type":"response.completed"} + diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index cee51083e..b3d695d6f 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -10,8 +10,13 @@ package gateway import ( "context" + "io" + "net" "net/http" + "net/url" + "os" "slices" + "strconv" "strings" "sync" "time" @@ -480,6 +485,16 @@ type TraceState struct { Seq int64 `json:"seq"` Routes []Route `json:"routes"` Totals Totals `json:"totals"` + // By is the magpie whose routing this is, when it is another magpie's + // (OwnerTrace): the console names it from here, so the name follows the + // trace when another magpie takes the gateway over (#2606) + By *TraceBy `json:"by,omitempty"` +} + +// TraceBy names the magpie a trace was read from. +type TraceBy struct { + Pid int `json:"pid"` + Serves string `json:"serves"` } func (t *trace) changed() { @@ -637,6 +652,131 @@ func (t *trace) update(r *Route, f func(r *Route)) { r.Seq = t.seq } +// gatewayTrace tells this gateway's routing to another magpie on the same +// computer, which does not serve the gateway and so has no trace of its own +// (#2606, fatcutegg: the trace is the serving process's, and a second magpie +// showed none of it). Its console reads this to show the same Routing page. +// This computer alone, and never to a held key: the trace names accounts, +// what they served, folders and why accounts rest. A request through a proxy +// or tunnel on this computer isn't local, nor is a LAN one while shared. +func (s *Server) gatewayTrace(w http.ResponseWriter, r *http.Request) { + if !local(r) { + writeError(w, provider.Chat, http.StatusForbidden, "magpie's routing is told to this computer alone") + return + } + if refuseHeld(w, r, heldRefused) { + return + } + after, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64) + var wait time.Duration + if r.URL.Query().Get("wait") != "" { + wait = 25 * time.Second + } + st := s.Trace(r.Context(), after, wait) + writeJSON(w, 200, map[string]any{"object": "trace", "now": time.Now(), "seq": st.Seq, "routes": st.Routes, "totals": st.Totals, "pid": os.Getpid(), "serves": Serves}) +} + +// ownerURL is the gateway's address on loopback, where the magpie serving +// it is read by another magpie on this computer (OwnerTrace, OwnerLanes). +// An address on another interface, or another host, gives "": the trace is +// read from this computer alone, never from wherever MAGPIE_ADDR points. +func ownerURL() string { + h, p, err := net.SplitHostPort(Addr()) + if err != nil { + return "" + } + ip := net.ParseIP(strings.Trim(h, "[]")) + switch { + case h == "", strings.EqualFold(h, "localhost"), ip != nil && ip.IsUnspecified(): + return "http://" + net.JoinHostPort("127.0.0.1", p) + case ip != nil && ip.IsLoopback(): + return "http://" + net.JoinHostPort(ip.String(), p) + } + return "" +} + +// OwnerTrace reads the routing the magpie serving the gateway's address has +// decided, for a magpie on this computer that doesn't serve it: its console +// reads this and shows the same Routing page (#2606: the trace is the +// serving process's alone, so a second magpie showed none of it). ok is +// false when nothing answers there, or a magpie too old to tell its trace, +// or one that refuses: unknown, never an empty trace. +func OwnerTrace(ctx context.Context, after int64, wait time.Duration) (TraceState, bool) { + base := ownerURL() + if base == "" { + return TraceState{}, false + } + q := url.Values{} + if after > 0 { + q.Set("after", strconv.FormatInt(after, 10)) + } + if wait > 0 { + q.Set("wait", "1") + } + // the serving magpie holds a long poll up to 25s; a hung one is let go + // a few seconds past that, and at once when the page stops asking + c := &http.Client{Timeout: wait + 5*time.Second} + req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/v1/magpie/trace?"+q.Encode(), nil) + if err != nil { + return TraceState{}, false + } + res, err := c.Do(req) + if err != nil { + return TraceState{}, false + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return TraceState{}, false + } + b, err := io.ReadAll(io.LimitReader(res.Body, 8<<20)) + if err != nil { + return TraceState{}, false + } + var out struct { + Object string `json:"object"` + Seq int64 `json:"seq"` + Routes []Route `json:"routes"` + Totals Totals `json:"totals"` + Pid int `json:"pid"` + Serves string `json:"serves"` + } + if decodeJSON(b, &out) != nil || out.Object != "trace" || out.Routes == nil { + return TraceState{}, false + } + return TraceState{Seq: out.Seq, Routes: out.Routes, Totals: out.Totals, By: &TraceBy{Pid: out.Pid, Serves: out.Serves}}, true +} + +// OwnerLanes reads the lanes of the magpie serving the gateway's address, for +// a console that doesn't serve it (the providers' rows show the same pills +// wherever the gateway runs). ok is false when nothing answers there. It is +// asked on every state read, so it waits no longer than ServedBy does. +func OwnerLanes() (map[string]Lane, bool) { + base := ownerURL() + if base == "" { + return nil, false + } + c := &http.Client{Timeout: 700 * time.Millisecond} + res, err := c.Get(base + "/v1/magpie/concurrency") + if err != nil { + return nil, false + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return nil, false + } + b, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if err != nil { + return nil, false + } + var out struct { + Data map[string]Lane `json:"data"` + } + if decodeJSON(b, &out) != nil || out.Data == nil { + return nil, false + } + return out.Data, true +} + // Trace is the routes changed after seq, oldest first. With none, it waits // up to wait for one. func (s *Server) Trace(ctx context.Context, after int64, wait time.Duration) TraceState { diff --git a/internal/gateway/trace_peer_test.go b/internal/gateway/trace_peer_test.go new file mode 100644 index 000000000..4b9a71df6 --- /dev/null +++ b/internal/gateway/trace_peer_test.go @@ -0,0 +1,99 @@ +package gateway + +import ( + "encoding/json" + "net/http/httptest" + "os" + "testing" +) + +// The routing is this process's own, so a magpie on this computer that does +// not serve the gateway reads it here to show the same Routing page (#2606). +// It answers this computer alone: the trace names accounts and what they +// served, and the magpie that reads it is on the same machine. +func TestGatewayTraceIsLoopbackOnly(t *testing.T) { + h := New().Handler() + + t.Run("this computer", func(t *testing.T) { + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/v1/magpie/trace", nil) + r.RemoteAddr = "127.0.0.1:50123" + h.ServeHTTP(w, r) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + var got struct { + Object string `json:"object"` + Seq int64 `json:"seq"` + Routes []json.RawMessage `json:"routes"` + Pid int `json:"pid"` + Serves string `json:"serves"` + } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.Object != "trace" || got.Routes == nil { + t.Fatalf("object %q routes %v", got.Object, got.Routes) + } + // the console names the magpie routing from the trace it plays + if got.Pid != os.Getpid() || got.Serves != Serves { + t.Errorf("the trace doesn't name its magpie: pid %d serves %q", got.Pid, got.Serves) + } + }) + + // a proxy or tunnel on this computer (cloudflared, Tailscale serve) + // hands on someone else's request from loopback + t.Run("through a proxy here", func(t *testing.T) { + for _, hdr := range []string{"X-Forwarded-For", "Cf-Connecting-IP", "Tailscale-User-Login"} { + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/v1/magpie/trace", nil) + r.RemoteAddr = "127.0.0.1:50123" + r.Header.Set(hdr, "203.0.113.7") + h.ServeHTTP(w, r) + if w.Code != 403 { + t.Fatalf("a request a proxy handed on (%s) reached the trace: %d %s", hdr, w.Code, w.Body) + } + } + }) + + t.Run("another machine", func(t *testing.T) { + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/v1/magpie/trace", nil) + r.RemoteAddr = "192.168.0.9:50123" + h.ServeHTTP(w, r) + if w.Code != 403 { + t.Fatalf("another machine reached the trace: %d %s", w.Code, w.Body) + } + }) +} + +// Another magpie's trace is read from this computer alone (#2606): an +// address on another interface or host is never asked, whatever +// MAGPIE_ADDR says, and one listening everywhere is read on loopback. +func TestOwnerReadOnLoopbackAlone(t *testing.T) { + for addr, want := range map[string]string{ + "127.0.0.1:3561": "http://127.0.0.1:3561", + "0.0.0.0:3561": "http://127.0.0.1:3561", + ":3561": "http://127.0.0.1:3561", + "[::]:3561": "http://127.0.0.1:3561", + "localhost:3561": "http://127.0.0.1:3561", + "[::1]:3561": "http://[::1]:3561", + "127.0.0.2:3561": "http://127.0.0.2:3561", + "192.168.1.9:3561": "", + "10.0.0.5:3561": "", + "example.com:3561": "", + "magpie.tail:3561": "", + } { + t.Setenv("MAGPIE_ADDR", addr) + if got := ownerURL(); got != want { + t.Errorf("MAGPIE_ADDR %s: read at %q, want %q", addr, got, want) + } + } + t.Setenv("MAGPIE_ADDR", "192.0.2.1:3561") + if _, ok := OwnerTrace(t.Context(), 0, 0); ok { + t.Error("a trace read from another host") + } + if _, ok := OwnerLanes(); ok { + t.Error("lanes read from another host") + } +} diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 4b21415ca..90b5c25cc 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -13,11 +13,25 @@ import ( // OpenRouter names it in a top-level "provider" — a Chat body and every // chunk of its stream, an Anthropic Messages body — and in a Messages // stream's message_start, as message.provider (seen 2026-10-05: DeepInfra, -// StreamLake). Its Responses replies name none. +// StreamLake). Its Responses replies name none. ClinePass (api.cline.bot) +// names it in a Chat choice's provider_metadata, as +// gateway.routing.finalProvider: under delta in a stream's chunk, under +// message in one body (#2847, smart-lty). Only those places count: a +// choice's content is the model's, and providerAttempts inside routing +// lists every provider tried, not the one that answered. func upstreamOf(b []byte) string { - if !bytes.Contains(b, []byte(`"provider"`)) { + if !bytes.Contains(b, []byte(`"provider"`)) && !bytes.Contains(b, []byte(`"finalProvider"`)) { return "" } + type routed struct { + ProviderMetadata struct { + Gateway struct { + Routing struct { + FinalProvider json.RawMessage `json:"finalProvider"` + } `json:"routing"` + } `json:"gateway"` + } `json:"provider_metadata"` + } var v struct { Provider json.RawMessage `json:"provider"` Message struct { @@ -26,11 +40,19 @@ func upstreamOf(b []byte) string { Response struct { Provider json.RawMessage `json:"provider"` } `json:"response"` + Choices []struct { + Delta routed `json:"delta"` + Message routed `json:"message"` + } `json:"choices"` } if json.Unmarshal(b, &v) != nil { return "" } - for _, raw := range []json.RawMessage{v.Provider, v.Message.Provider, v.Response.Provider} { + raws := []json.RawMessage{v.Provider, v.Message.Provider, v.Response.Provider} + for _, c := range v.Choices { + raws = append(raws, c.Delta.ProviderMetadata.Gateway.Routing.FinalProvider, c.Message.ProviderMetadata.Gateway.Routing.FinalProvider) + } + for _, raw := range raws { var s string // a request's provider options echoed back are an object if json.Unmarshal(raw, &s) == nil { if s = strings.TrimSpace(s); s != "" && len(s) <= 64 { diff --git a/internal/gateway/upstream_h2_silent_test.go b/internal/gateway/upstream_h2_silent_test.go new file mode 100644 index 000000000..4796d9a18 --- /dev/null +++ b/internal/gateway/upstream_h2_silent_test.go @@ -0,0 +1,233 @@ +package gateway + +import ( + "context" + "crypto/tls" + "crypto/x509" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/provider" +) + +// silentPath sits between the gateway and a vendor and can go silent on +// the connections open through it: it goes on taking what the gateway +// writes, so every write succeeds, and passes nothing either way, as a +// local proxy whose own way out died, or a NAT that forgot the flow, does. +// A connection opened after it went silent passes as before. +type silentPath struct { + ln net.Listener + to string + mu sync.Mutex + open []*silentConn + wg sync.WaitGroup +} + +type silentConn struct { + a, b net.Conn + silent atomic.Bool +} + +func newSilentPath(t *testing.T, to string) *silentPath { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + p := &silentPath{ln: ln, to: to} + p.wg.Add(1) + go func() { + defer p.wg.Done() + for { + a, err := ln.Accept() + if err != nil { + return + } + b, err := net.Dial("tcp", to) + if err != nil { + a.Close() + continue + } + c := &silentConn{a: a, b: b} + p.mu.Lock() + p.open = append(p.open, c) + p.mu.Unlock() + pipe := func(dst, src net.Conn) { + defer p.wg.Done() + buf := make([]byte, 32<<10) + for { + n, err := src.Read(buf) + if n > 0 && !c.silent.Load() { + if _, werr := dst.Write(buf[:n]); werr != nil { + return + } + } + if err != nil { + return + } + } + } + p.wg.Add(2) + go pipe(b, a) + go pipe(a, b) + } + }() + t.Cleanup(func() { + p.ln.Close() + p.mu.Lock() + for _, c := range p.open { + c.a.Close() + c.b.Close() + } + p.mu.Unlock() + p.wg.Wait() + }) + return p +} + +// hush silences every connection open now. +func (p *silentPath) hush() int { + p.mu.Lock() + defer p.mu.Unlock() + for _, c := range p.open { + c.silent.Store(true) + } + return len(p.open) +} + +func (p *silentPath) conns() int { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.open) +} + +// quickPings has the gateway's transports, made after it, ping a quiet +// HTTP/2 connection after 200ms and drop it 300ms later, and trust +// vendor's certificate. +func quickPings(t *testing.T, vendor *httptest.Server) { + pool := x509.NewCertPool() + pool.AddCert(vendor.Certificate()) + wasTLS, wasAfter, wasWait := upstreamTLS, netproxy.PingAfter, netproxy.PingWait + upstreamTLS = &tls.Config{RootCAs: pool, ServerName: "127.0.0.1"} + netproxy.PingAfter, netproxy.PingWait = 200*time.Millisecond, 300*time.Millisecond + t.Cleanup(func() { upstreamTLS, netproxy.PingAfter, netproxy.PingWait = wasTLS, wasAfter, wasWait }) +} + +func h2Vendor(t *testing.T, h http.HandlerFunc) *httptest.Server { + vendor := httptest.NewUnstartedServer(h) + vendor.EnableHTTP2 = true + vendor.StartTLS() + t.Cleanup(vendor.Close) + return vendor +} + +// #2843 (pinewhite): every request of a group to ClinePass hung with no +// first byte for half an hour, and a restart answered the same request in +// 1.6s. Over HTTP/2 every request to a vendor shares one connection, and +// one gone silent without closing (a proxy's way out died, a NAT dropped +// the flow) was kept and given every new request, each waiting up to the +// 10-minute ResponseHeaderTimeout, while the kernel took the writes. The +// gateway's transport now pings a connection quiet for a while and drops +// it when the ping goes unanswered: the request on it fails (so the group +// moves on) and the next one dials a new connection. +func TestSilentHTTP2ConnectionIsDropped(t *testing.T) { + fresh(t) + vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + io.WriteString(w, r.Proto) + }) + path := newSilentPath(t, vendor.Listener.Addr().String()) + quickPings(t, vendor) + s := New() + t.Cleanup(s.client.CloseIdleConnections) + u := "https://" + path.ln.Addr().String() + "/v1/chat/completions" + ask := func(within time.Duration) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), within) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, u, nil) + res, err := s.client.Do(req) + if err != nil { + return "", err + } + defer res.Body.Close() + b, err := io.ReadAll(res.Body) + return string(b), err + } + if got, err := ask(10 * time.Second); err != nil || got != "HTTP/2.0" { + t.Fatalf("first request: %q, %v; want HTTP/2.0", got, err) + } + if n := path.hush(); n != 1 { + t.Fatalf("%d connections open before the path went silent, want 1", n) + } + // the stalled request ends well before a client gives up (curl -m 55 + // in the report), here 10s against a ping bound of 0.5s + began := time.Now() + _, err := ask(10 * time.Second) + if err == nil { + t.Fatal("a request on the silent connection was answered") + } + if d := time.Since(began); d >= 10*time.Second { + t.Fatalf("a request on the silent connection hung %v, until the client gave up: %v", d, err) + } + // and the one after it goes out on a new connection, without a restart + if got, err := ask(10 * time.Second); err != nil || got != "HTTP/2.0" { + t.Fatalf("request after the silent connection: %q, %v; want HTTP/2.0 on a new connection", got, err) + } + if n := path.conns(); n != 2 { + t.Errorf("%d connections dialled, want 2: the silent one and a new one", n) + } +} + +// The same through a routing group, as in the report: a group's first +// member on a connection gone silent is given up on and the next member +// answers, where before the request hung until its agent gave up and the +// next one hung the same way. +func TestGroupMovesOnFromSilentHTTP2Connection(t *testing.T) { + fresh(t) + vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"a","choices":[{"message":{"role":"assistant","content":"from a"}}]}`) + }) + path := newSilentPath(t, vendor.Listener.Addr().String()) + quickPings(t, vendor) + if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, + Chat: "https://" + path.ln.Addr().String() + "/v1"}); err != nil { + t.Fatal(err) + } + serveOn(t, "b", "k", []string{"m"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"b","choices":[{"message":{"role":"assistant","content":"from b"}}]}`) + })) + if err := provider.SaveGroup(provider.Group{Name: "Auto", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + t.Cleanup(s.client.CloseIdleConnections) + ask := func() (int, string, time.Duration) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/chat/completions", + strings.NewReader(`{"model":"group/auto","messages":[{"role":"user","content":"hi"}]}`)).WithContext(ctx) + began := time.Now() + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String(), time.Since(began) + } + if code, body, _ := ask(); code != http.StatusOK || !strings.Contains(body, "from a") { + t.Fatalf("first group request: %d %s; want a's reply", code, body) + } + path.hush() + code, body, took := ask() + if code != http.StatusOK || !strings.Contains(body, "from b") { + t.Fatalf("group request with a's connection silent: %d %s after %v; want b's reply", code, body, took) + } +} diff --git a/internal/gateway/upstream_test.go b/internal/gateway/upstream_test.go index 79c7a9491..181277d24 100644 --- a/internal/gateway/upstream_test.go +++ b/internal/gateway/upstream_test.go @@ -1,9 +1,12 @@ package gateway import ( + "bufio" + "bytes" "io" "net/http" "net/http/httptest" + "os" "strings" "testing" "time" @@ -137,3 +140,96 @@ func TestUpstreamOf(t *testing.T) { } } } + +// clinePassStream is a real ClinePass stream (api.cline.bot, DeepSeek V4.1 +// Flash, 2026-10-02), as captured in wkeking/clinepass-channel-monitor's +// testdata/plain_success.log (MIT): its last chunk names the provider that +// answered only in choices[].delta.provider_metadata.gateway.routing. +func clinePassStream(t *testing.T) []string { + t.Helper() + b, err := os.ReadFile("testdata/clinepass_stream.sse") + if err != nil { + t.Fatal(err) + } + var lines []string + sc := bufio.NewScanner(bytes.NewReader(b)) + sc.Buffer(nil, 1<<20) + for sc.Scan() { + if l := sc.Text(); l != "" { + lines = append(lines, l) + } + } + return lines +} + +// ClinePass says the provider behind it as finalProvider in a choice's +// provider_metadata (#2847, smart-lty): under delta in a stream, under +// message in one body. Only there: the model's own text naming it, or the +// list of providers tried, says none. +func TestUpstreamOfClinePass(t *testing.T) { + var last string + for _, l := range clinePassStream(t) { + if d := strings.TrimPrefix(l, "data: "); strings.Contains(d, "finalProvider") { + last = d + } + } + if got := upstreamOf([]byte(last)); got != "deepseek" { + t.Errorf("real ClinePass chunk: upstreamOf = %q; want deepseek", got) + } + whole := strings.Replace(last, `"delta":{"provider_metadata"`, `"message":{"role":"assistant","content":"hi","provider_metadata"`, 1) + if got := upstreamOf([]byte(whole)); got != "deepseek" { + t.Errorf("one body: upstreamOf = %q; want deepseek", got) + } + for in, want := range map[string]string{ + `{"choices":[{"delta":{"provider_metadata":{"gateway":{"routing":{"finalProvider":"novita"}}}}}]}`: "novita", + `{"choices":[{"delta":{"content":"provider_metadata gateway routing \"finalProvider\":\"deepseek\""}}]}`: "", + `{"choices":[{"delta":{"provider_metadata":{"gateway":{"routing":{"modelAttempts":[{"providerAttempts":[{"provider":"deepseek"}]}]}}}}}]}`: "", + `{"choices":[{"delta":{"provider_metadata":{"gateway":{"routing":{"finalProvider":{"id":"x"}}}}}}]}`: "", + `{"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"{\"finalProvider\":\"x\"}"}}]}}]}`: "", + `{"provider":"Novita","choices":[{"delta":{"provider_metadata":{"gateway":{"routing":{"finalProvider":"deepseek"}}}}}]}`: "Novita", + } { + if got := upstreamOf([]byte(in)); got != want { + t.Errorf("upstreamOf(%s) = %q; want %q", in, got, want) + } + } +} + +// The real ClinePass stream's provider reaches the route, its try, the +// request log and the usage ledger, relayed to a Chat client or translated +// to a Messages one (#2847). +func TestClinePassUpstreamRecorded(t *testing.T) { + stream := clinePassStream(t) + for _, path := range []string{"/v1/chat/completions", "/v1/messages"} { + t.Run(path, func(t *testing.T) { + fresh(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + for _, l := range stream { + io.WriteString(w, l+"\n\n") + } + })) + t.Cleanup(up.Close) + p := provider.Provider{ID: "fake", Name: "Fake", Key: "k", Chat: up.URL + "/v1", Models: []string{"sol"}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + body := `{"model":"fake/sol","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hi"}]}` + s := New() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + r := lastRoute(s) + if r.Upstream != "deepseek" || len(r.Tries) != 1 || r.Tries[0].Upstream != "deepseek" { + t.Errorf("route upstream %q, tries %+v", r.Upstream, r.Tries) + } + if calls := s.Recent(); len(calls) == 0 || calls[0].Usage.Upstream != "deepseek" { + t.Errorf("request log: %+v", calls) + } + if u := usage.Load(time.Time{}); len(u) != 1 || u[0].Upstream != "deepseek" { + t.Errorf("usage %+v", u) + } + }) + } +} diff --git a/internal/gateway/upstream_transport.go b/internal/gateway/upstream_transport.go index bce715a1f..8bacd8337 100644 --- a/internal/gateway/upstream_transport.go +++ b/internal/gateway/upstream_transport.go @@ -17,16 +17,45 @@ var upstreamTLS *tls.Config // (#237), and the ChatGPT backend over HTTP/1.1 (netproxy.HTTP1). Every // other vendor is spoken HTTP/2 to wherever it offers it. A request that // finds its kept-alive connection dropped is sent again on a new one -// (replayable). +// (replayable). A vendor is given upstreamHeaderWait to begin answering, +// but for a drawing, which an images API answers only once it has drawn: +// it goes through a transport of its own that waits as long as Settings' +// Image generation timeout gives it (drawWithin), up to 60 minutes. func upstreamTransport() http.RoundTripper { - return replayable{netproxy.Dispatch(&http.Transport{ + return drawsApart{ + any: replayable{netproxy.Dispatch(vendorTransport(upstreamHeaderWait))}, + draws: replayable{netproxy.Dispatch(vendorTransport(0))}, + } +} + +// upstreamHeaderWait is how long a vendor is given to begin answering a +// request that isn't a drawing. +var upstreamHeaderWait = 10 * time.Minute + +// vendorTransport is a transport to the vendors that gives one wait to +// begin answering, none for 0: the request's context then bounds it. +func vendorTransport(wait time.Duration) *http.Transport { + return &http.Transport{ Proxy: netproxy.Func, - ResponseHeaderTimeout: 10 * time.Minute, + ResponseHeaderTimeout: wait, MaxIdleConnsPerHost: 8, IdleConnTimeout: 90 * time.Second, ForceAttemptHTTP2: true, TLSClientConfig: upstreamTLS, - })} + // a silent HTTP/2 connection is pinged and dropped (#2843) + HTTP2: netproxy.HTTP2Health(), + } +} + +// drawsApart sends a drawing's request (drawWaitOf) through draws, every +// other through any. +type drawsApart struct{ any, draws http.RoundTripper } + +func (t drawsApart) RoundTrip(r *http.Request) (*http.Response, error) { + if _, ok := drawWaitOf(r.Context()); ok { + return t.draws.RoundTrip(r) + } + return t.any.RoundTrip(r) } // replayable lets Go's transport send a request again, at once and on a new diff --git a/internal/gateway/video.go b/internal/gateway/video.go index 7766b9969..d5ba3f332 100644 --- a/internal/gateway/video.go +++ b/internal/gateway/video.go @@ -58,6 +58,11 @@ var grokVideoAspects = []string{"1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3 // maxVideoBytes is the most of a video the gateway passes on. const maxVideoBytes = 512 << 20 +// videoTimeout is how long a video's vendor is given to answer each of its +// calls: to take the video on, say how it goes, and send it. A video is +// made between them, so Settings' Image generation timeout isn't it. +const videoTimeout = 5 * time.Minute + // Videomakers are the models a provider can make videos with: a Grok // subscription's, another magpie's, a preset plan's models when magpie // implements that vendor's video API, and those a provider's own model list @@ -743,7 +748,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) { w, done = restoring(w) defer done() } - ctx, cancel := context.WithTimeout(r.Context(), drawTimeout) + ctx, cancel := drawWithin(r.Context(), videoTimeout) defer cancel() var ( v videoStart @@ -957,7 +962,7 @@ func (s *Server) videosGet(w http.ResponseWriter, r *http.Request) { writeError(w, provider.Chat, 403, held) return } - ctx, cancel := context.WithTimeout(r.Context(), drawTimeout) + ctx, cancel := drawWithin(r.Context(), videoTimeout) defer cancel() if filmsOpenAI(p) { obj, model, code, err := s.openAIVideo(ctx, p, vendorID, id) @@ -1001,7 +1006,7 @@ func (s *Server) videosContent(w http.ResponseWriter, r *http.Request) { writeError(w, provider.Chat, 403, held) return } - ctx, cancel := context.WithTimeout(r.Context(), drawTimeout) + ctx, cancel := drawWithin(r.Context(), videoTimeout) defer cancel() if filmsOpenAI(p) { if _, models := keyHolds(r); models { diff --git a/internal/gateway/vision.go b/internal/gateway/vision.go index c3a4b8b53..cefc225d7 100644 --- a/internal/gateway/vision.go +++ b/internal/gateway/vision.go @@ -9,6 +9,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "slices" "strings" "sync" "time" @@ -46,9 +47,11 @@ var visionTimeout, visionWaitMost = 3 * time.Minute, 10 * time.Minute // visionParallel is how many images of a request are described at once. const visionParallel = 4 -// sightsKept is how many descriptions are kept: an agent sends a -// conversation's images again every turn. -const sightsKept = 256 +// sightsKept is how many descriptions are kept, the least recently used +// dropped first: an agent sends a conversation's images again every turn, +// and a long Computer Use one holds hundreds of screenshots (fflake33). +// A description is a few kilobytes. +const sightsKept = 2048 const visionSystem = `You describe images for an AI model that cannot see them. It will answer the user from your description alone, so leave nothing out that it may need. - Transcribe all text exactly as written, keeping its layout: code, terminal output, error messages, logs, UI labels, menus, file names, numbers. @@ -292,6 +295,12 @@ func (s *Server) describe(ctx context.Context, model, src string) (string, error key := hex.EncodeToString(sum[:]) s.sightMu.Lock() if e, ok := s.sights[key]; ok { + // used again, so the last to go: a long conversation's first + // images, still sent every turn, outlast those of conversations + // that have ended + if i := slices.Index(s.sightOrder, key); i >= 0 { + s.sightOrder = append(append(s.sightOrder[:i:i], s.sightOrder[i+1:]...), key) + } s.sightMu.Unlock() select { case <-e.done: diff --git a/internal/gateway/vision_test.go b/internal/gateway/vision_test.go index 0f2a55490..427244f99 100644 --- a/internal/gateway/vision_test.go +++ b/internal/gateway/vision_test.go @@ -1,6 +1,8 @@ package gateway import ( + "encoding/base64" + "fmt" "io" "net/http" "net/http/httptest" @@ -211,3 +213,27 @@ func TestSeerPicksAModelThatSees(t *testing.T) { t.Fatal("seer with vision off") } } + +// A long conversation sends every past screenshot again on each turn +// (fflake33, Discord: hundreds of them). Each is described once, not again +// on the next turn once there are more than 256. +func TestManyImagesDescribedOnce(t *testing.T) { + s, u := eyed(t) + const n = 300 + var parts []string + for i := range n { + img := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("screenshot %d", i))) + parts = append(parts, `{"type":"input_image","image_url":"data:image/png;base64,`+img+`"}`) + } + body := `{"model":"probe/text","input":[{"role":"user","content":[{"type":"input_text","text":"read"},` + strings.Join(parts, ",") + `]}]}` + for turn := 1; turn <= 2; turn++ { + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("turn %d: %d %.300s", turn, rec.Code, rec.Body.String()) + } + } + if got := len(u.sent("eye")); got != n { + t.Fatalf("%d images described %d times over two turns, want each once", n, got) + } +} diff --git a/internal/gateway/zhipu_resets_test.go b/internal/gateway/zhipu_resets_test.go index 85cb1126c..f8bf736f6 100644 --- a/internal/gateway/zhipu_resets_test.go +++ b/internal/gateway/zhipu_resets_test.go @@ -74,7 +74,9 @@ func TestResetsZhipu(t *testing.T) { } // heldClock gives the time with its offset, so a reader on another clock -// can tell whose it is. +// can tell whose it is. Each zone is passed in, never set on time.Local: +// time.Now reads time.Local, and a goroutine an earlier test left running +// read it while this test wrote it, a race on ubuntu CI (run 39242954115). func TestHeldClock(t *testing.T) { cst := time.FixedZone("CST", 8*3600) now := time.Date(2026, 10, 15, 16, 25, 0, 0, cst) @@ -88,10 +90,7 @@ func TestHeldClock(t *testing.T) { {time.UTC, time.Date(2026, 10, 15, 20, 12, 13, 0, cst), "12:12 UTC+0"}, {time.FixedZone("", -(3*3600 + 30*60)), time.Date(2026, 10, 15, 20, 12, 13, 0, cst), "08:42 UTC-3:30"}, } { - was := time.Local - time.Local = c.zone - got := heldClock(c.at, now) - time.Local = was + got := heldClockIn(c.at, now, c.zone) if got != c.want { t.Errorf("%v in %v: %q, want %q", c.at, c.zone, got, c.want) } diff --git a/internal/gui/api.go b/internal/gui/api.go index dfcf408eb..f9edf4612 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1172,6 +1172,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { if _, sent := fields["noAutoDownload"]; !sent { in.NoAutoDownload = cur.NoAutoDownload } + // nor how long an image is given to be drawn + if _, sent := fields["imageTimeout"]; !sent { + in.ImageTimeout = cur.ImageTimeout + } in.AgentOrder, in.AgentsHidden, in.AgentsShown = cur.AgentOrder, cur.AgentsHidden, cur.AgentsShown in.Window, in.WindowMaximised = cur.Window, cur.WindowMaximised // the window's own, as it was last resized // and what other pages keep here: which models an agent is shown, and @@ -1623,7 +1627,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { // Resolve intentionally accepts arbitrary names under a known // provider. An approval reviewer must be a model or group magpie // actually lists, including providers kept unlisted for routing. - if !slices.ContainsFunc(provider.Served(), func(e provider.Entry) bool { return e.ID == v }) { + if !slices.ContainsFunc(provider.Served(), func(e provider.Entry) bool { return e.ID == v || e.Group != "" && provider.SameRef(e.ID, v) }) { fail(rw, fmt.Errorf("no model %s for Codex's auto-review", v)) return } diff --git a/internal/gui/api_settings_test.go b/internal/gui/api_settings_test.go index 1883c72a7..e7dfd1351 100644 --- a/internal/gui/api_settings_test.go +++ b/internal/gui/api_settings_test.go @@ -201,6 +201,36 @@ func TestSettingsRefusalRetries(t *testing.T) { } } +// How long an image is given to be drawn (neighbads on X) is set by the +// Settings page, 0 for the default 5 minutes, kept by a save from a page +// that doesn't send it, and refused past 60 with the saved value kept. +func TestSettingsImageTimeout(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + handler := Handler(nil, nil) + for _, x := range []struct { + body string + code int + want int + }{ + {`{"theme":"dark","imageTimeout":30}`, http.StatusOK, 30}, + {`{"theme":"light"}`, http.StatusOK, 30}, + {`{"theme":"light","imageTimeout":61}`, http.StatusBadRequest, 30}, + {`{"theme":"light","imageTimeout":0}`, http.StatusOK, 0}, + } { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(x.body))) + if rec.Code != x.code { + t.Fatalf("%s: %d %s", x.body, rec.Code, rec.Body) + } + if got := settings.Load().ImageTimeout; got != x.want { + t.Fatalf("%s: imageTimeout %d", x.body, got) + } + } +} + func TestSettingsColorblindMode(t *testing.T) { h := t.TempDir() t.Setenv("HOME", h) diff --git a/internal/gui/app.go b/internal/gui/app.go index ffad83a8e..9fd474b3e 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -29,6 +29,7 @@ import ( "github.com/yetone/magpie/internal/shortcut" "github.com/yetone/magpie/internal/stats" "github.com/yetone/magpie/internal/update" + "github.com/yetone/magpie/internal/webview2env" ) //go:embed tray.png @@ -281,11 +282,17 @@ func (h *host) zoomWindows() { // windowsOptions are the app's Windows options. Portable, WebView2 keeps // its profile in data\webview2: left to Wails it is %APPDATA%\magpie.exe, // a folder a portable magpie must not leave behind (#508). Installed, it -// stays there, so what the pages kept isn't lost. +// stays there, so what the pages kept isn't lost. The browser arguments +// the user set in WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS, which Wails' loader +// blanks before WebView2 can read them, are merged into Wails' own (#2753). func windowsOptions() application.WindowsOptions { + disabled, enabled, other := webView2Args(webview2env.Args) return application.WindowsOptions{ DisableQuitOnLastWindowClosed: true, WebviewUserDataPath: appdir.WebView(), + DisabledFeatures: disabled, + EnabledFeatures: enabled, + AdditionalBrowserArgs: other, } } diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 22db3bdee..eaec35c30 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2062,6 +2062,7 @@ body.window .foot { padding-left: 18px; } .pop li .option-words { display: flex; align-items: center; min-width: 0; flex: 1 1 auto; gap: 9px; } .pop li .v { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; } .pop li .badge.free, .pop li .badge.ctx, .pop li .badge.rate, .pop li .badge.path { flex: none; margin-left: -4px; padding: 0 4px; font-size: 9px; line-height: 14px; align-self: center; } +.pop li .mtell { flex: none; margin-left: -4px; font-size: 11px; color: var(--muted); } .pop li .n { flex: 1 1 0; min-width: 0; font-size: 11.5px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; } .pop li .favorite { display: none; align-items: center; justify-content: center; color: var(--faint); width: 24px; height: 24px; border-radius: 6px; flex: none; } .pop li:hover .favorite, .pop li .favorite.on { display: inline-flex; } @@ -2680,8 +2681,10 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } /* the sign-in link, one line, selected whole with a click */ .signing .signlink { display: flex; align-items: center; gap: 4px; margin: 5px 0 1px; min-width: 0; } .signing .signlink code { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--code-style, normal) var(--code-weight, 400) 11px/1.3 var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); color: var(--fg-2); padding: 4px 7px; border: 1px solid var(--line); border-radius: 6px; background: var(--card); user-select: all; -webkit-user-select: all; cursor: text; } -.signing .callback-form { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-top: 6px; } -.signing .callback-form input { flex: 1; min-width: 120px; width: 100%; padding: 6px 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); color: var(--fg); font-size: 12px; } +.signing .callback-form { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 6px; } +.signing .callback-form input { flex: 1; min-width: 120px; width: 100%; height: 28px; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); color: var(--fg); font-size: 12px; } +/* the field's button: as tall as the field, with the same corners */ +.signing .callback-form > button { height: 28px; padding: 0 12px; border-radius: 7px; } .signing .why { color: var(--red); } /* a plugin's ways to sign in: the question keeps the row, the choices wrap beneath it at whatever length the plugin names them */ @@ -3035,7 +3038,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .mbulk { display: flex; align-items: center; gap: 6px; } .mbulk > input { max-width: 260px; flex: 1; } /* a long list scrolls on its own, not the editor with it past its ends */ -.mchips { display: flex; flex-wrap: wrap; gap: 4px; max-height: min(132px, 28vh); overflow-y: auto; overscroll-behavior: contain; padding: 1px; } +.mchips { display: flex; flex-wrap: wrap; gap: 4px; max-height: min(240px, 40vh); overflow-y: auto; overscroll-behavior: contain; padding: 1px; } .mchips::-webkit-scrollbar { width: 0; } /* let out to its full height (#833): the editor's body scrolls instead */ .mchips.open { max-height: none; overflow-y: visible; } @@ -3061,6 +3064,18 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .mchip:hover { color: var(--fg); border-color: var(--muted); } .mchip.on { color: var(--accent); background: var(--accent-soft); border-color: color-mix(in srgb, var(--accent) 45%, transparent); font-weight: 500; } .mchip.on::before { content: "✓"; font-size: 10px; } +/* a chip a click picks and unpicks keeps its size either way (frankdeng on + Discord: the tick, and the bolder name, widened a chip as it was picked, + and every chip after it moved under the pointer). Its tick has a place + of its own, as a menu's check column has, held empty while unpicked, and + a pick is said by the tick and the colour, the weight left as it is. */ +.mchip.pick { padding-left: 7px; } +.mchip.pick::before { content: "✓"; font-size: 10px; margin-right: -1px; visibility: hidden; } +.mchip.pick.on { font-weight: inherit; } +.mchip.pick.on::before { visibility: visible; } +/* what tells a model from others of the same name (modelTells): quiet, + after the name, never in the accent of a pick */ +.mchip .mtell { color: var(--muted); font-weight: 400; font-size: 10.5px; } .mchip.own.on::before { content: "+"; } /* served with none picked: the vendor's list stands in for the picks. Drawn apart from a pick (no tick, no accent): a click picks it alone (#681) */ @@ -4129,7 +4144,8 @@ input[type="checkbox"]:disabled { opacity: .45; } .ag-manager .ag-manage-search { width: 100%; box-sizing: border-box; } .ag-manage-actions { display: flex; flex-wrap: wrap; gap: 6px; margin: 12px 0; } .ag-manage-count, .ag-manage-state { color: var(--fg-2); font-size: 12px; } -.ag-manage-row { display: flex; align-items: center; gap: 10px; padding: 10px 0; } +/* a row is a
, which hands the + // address to a helper program (ext:: runs a command) + remoteHelper = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.-]*::`) + // scpLike is git's user@host:path for SSH + scpLike = regexp.MustCompile(`^(?:([\w.-]+)@)?([\w.-]+):(.+)$`) + gitRef = regexp.MustCompile(`^[\w./+@-]+$`) + hexRef = regexp.MustCompile(`^[0-9a-fA-F]{7,40}$`) +) + +// gitSchemes are the URL schemes a git source may have. file:// is a +// repository on this machine or a mounted share, which the user named. +var gitSchemes = map[string]bool{"https": true, "http": true, "ssh": true, "git": true, "git+ssh": true, "ssh+git": true, "file": true} + +// gitSource reads a git repository out of what the user typed: a URL +// (https://host/group/sub/repo(.git), ssh://, git://, file://), SSH's +// git@host:group/repo.git, or host/group/repo. A GitLab page's +// /-/tree// (or /-/blob/…/SKILL.md), and Gitea's +// /src/branch//, name a branch and a folder in it; the ref is +// the first part after them, so a branch with a / in its name is read +// as a ref and a folder. ok is false for what isn't meant as one; an +// error is one that is, refused. +func gitSource(s string) (src Source, ok bool, err error) { + s = strings.TrimSpace(s) + if s == "" { + return Source{}, false, nil + } + if strings.HasPrefix(s, "-") { + return Source{}, true, fmt.Errorf("a repository's address can't start with -") + } + if remoteHelper.MatchString(s) { + return Source{}, true, fmt.Errorf("magpie doesn't install from a git address with a transport (%s): give the repository's https or SSH address", s[:strings.Index(s, "::")+2]) + } + if strings.IndexFunc(s, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0 { + return Source{}, false, nil + } + repo, rest := s, "" + for _, sep := range []string{"/-/tree/", "/-/blob/", "/src/branch/", "/src/tag/", "/src/commit/"} { + if i := strings.Index(s, sep); i > 0 { + repo, rest = s[:i], s[i+len(sep):] + break + } + } + repo = strings.TrimSuffix(repo, "/") + if strings.HasSuffix(repo, "/-") { // https://host/group/repo/-/ alone + repo = strings.TrimSuffix(repo, "/-") + } + if !strings.Contains(repo, "://") { + // user@host:path, or host.name:path; a Windows drive (C:) is a + // folder, never a host + if m := scpLike.FindStringSubmatch(repo); m != nil && len(m[2]) > 1 && (m[1] != "" || strings.Contains(m[2], ".")) { + if strings.HasPrefix(m[3], "-") || strings.HasPrefix(m[2], "-") { + return Source{}, true, fmt.Errorf("a repository's address can't start with -") + } + } else if first, _, _ := strings.Cut(repo, "/"); strings.Contains(first, ".") && strings.Count(repo, "/") >= 2 { + repo = "https://" + repo // gitlab.example.com/group/repo + } else { + return Source{}, false, nil + } + } + if strings.Contains(repo, "://") { + u, err := url.Parse(repo) + if err != nil || u.Scheme == "" { + return Source{}, false, nil + } + if !gitSchemes[strings.ToLower(u.Scheme)] { + return Source{}, true, fmt.Errorf("magpie doesn't install from a %s:// address: give the repository's https or SSH address", u.Scheme) + } + if _, set := u.User.Password(); set { + // it would be kept in library.json, shown on the page and + // carried to a backup + return Source{}, true, fmt.Errorf("leave the password or token out of the address: magpie runs your own git, which signs in with its credential helper or your SSH key") + } + if strings.ToLower(u.Scheme) != "file" && (u.Host == "" || strings.HasPrefix(u.Host, "-")) { + return Source{}, true, fmt.Errorf("%s names no host", repo) + } + if strings.Trim(u.Path, "/") == "" { + return Source{}, true, fmt.Errorf("%s names no repository", repo) + } + } + src = Source{Kind: "git", Repo: repo} + if rest != "" { + ref, path, _ := strings.Cut(strings.Trim(rest, "/"), "/") + if ref != "HEAD" { + src.Ref = ref + } + if q := strings.IndexAny(path, "?#"); q >= 0 { + path = path[:q] + } + src.Path = strings.Trim(strings.TrimSuffix(strings.TrimSuffix(path, "SKILL.md"), "/"), "/") + if src.Ref != "" && (!gitRef.MatchString(src.Ref) || strings.HasPrefix(src.Ref, "-") || strings.Contains(src.Ref, "..")) { + return Source{}, true, fmt.Errorf("%q isn't a branch or tag git can fetch", src.Ref) + } + if strings.Contains("/"+src.Path+"/", "/../") { + return Source{}, true, fmt.Errorf("%q isn't a folder in the repository", src.Path) + } + } + return src, true, nil +} + +// gitURL is a git source as the user can type it again: the repository, +// and its ref and folder as a GitLab page names them. An https address +// loses its .git there, so it opens the repository's page; GitLab and +// Gitea fetch it without one too. +func gitURL(s *Source) string { + if s.Ref == "" && s.Path == "" { + return s.Repo + } + ref := s.Ref + if ref == "" { + ref = "HEAD" + } + u := s.Repo + if strings.HasPrefix(u, "https://") || strings.HasPrefix(u, "http://") { + u = strings.TrimSuffix(u, ".git") // the page, not the clone + } + u += "/-/tree/" + ref + if s.Path != "" { + u += "/" + s.Path + } + return u +} + +// sameGitRepo is whether two addresses are one repository: by host and +// path, however it is reached (https, SSH, with .git or without). +func sameGitRepo(a, b string) bool { + if strings.EqualFold(strings.TrimSuffix(a, ".git"), strings.TrimSuffix(b, ".git")) { + return true + } + ra, rb := remoteRepo(a), remoteRepo(b) + return ra != "" && strings.EqualFold(ra, rb) +} + +// gitHeads is the commit each git download is at, by its folder. +var gitHeads = struct { + sync.Mutex + m map[string]string +}{m: map[string]string{}} + +func gitHeadOf(dir string) string { + gitHeads.Lock() + defer gitHeads.Unlock() + return gitHeads.m[dir] +} + +func noteGitHead(dir, sha string) { + gitHeads.Lock() + defer gitHeads.Unlock() + for d := range gitHeads.m { + if _, err := os.Stat(d); err != nil { + delete(gitHeads.m, d) // a download removed since + } + } + gitHeads.m[dir] = sha +} + +// errNoGit is git missing from this computer. +func errNoGit() error { + return errors.New("installing from a git repository runs git, and git isn't installed here (or isn't on PATH): install git and try again") +} + +// gitEnv is the environment git runs in: the user's, so their credential +// helper, SSH agent and config work, with every question asked on a +// terminal turned off (no one sees it, and it would wait for ever), and +// git's messages in English, as magpie reads them. +func gitEnv(git string) []string { + env := append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "LC_ALL=C", "LANGUAGE=C") + if os.Getenv("GIT_SSH_COMMAND") == "" && os.Getenv("GIT_SSH") == "" { + // ssh asks for a passphrase or a new host's key on the terminal: + // BatchMode refuses instead. A core.sshCommand of the user's own + // (a key for the intranet) is kept, which GIT_SSH_COMMAND would + // override. + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := proc.CommandContext(ctx, git, "config", "--global", "--get", "core.sshCommand") + cmd.Env = env + if out, _ := cmd.Output(); strings.TrimSpace(string(out)) == "" { + env = append(env, "GIT_SSH_COMMAND=ssh -o BatchMode=yes") + } + } + return env +} + +// runGit runs git with args in dir, and gives back its output, or an +// error saying plainly what went wrong for src. +func runGit(ctx context.Context, git string, env []string, dir string, src Source, args ...string) ([]byte, error) { + cmd := proc.CommandContext(ctx, git, append([]string{"-c", "protocol.ext.allow=never", "-c", "core.symlinks=false"}, args...)...) + cmd.Dir, cmd.Env = dir, env + var stderr strings.Builder + cmd.Stderr = &stderr + out, err := cmd.Output() + if err == nil { + return out, nil + } + if ctx.Err() == context.DeadlineExceeded { + return nil, fmt.Errorf("git took over %s to fetch %s and was stopped", gitTimeout, src.Repo) + } + var ee *exec.ExitError + if !errors.As(err, &ee) { + return nil, fmt.Errorf("couldn't run git: %w", err) + } + return nil, gitError(src, stderr.String()) +} + +// gitError says what git's message means for the user. +func gitError(src Source, msg string) error { + low := strings.ToLower(msg) + said := gitSaid(msg) + host := gitHost(src.Repo) + switch { + case strings.Contains(low, "xcrun: error") || strings.Contains(low, "invalid active developer path") || strings.Contains(low, "no developer tools were found"): + return errors.New("installing from a git repository runs git, and git isn't installed here: install Apple's command line tools (xcode-select --install) and try again") + case strings.Contains(low, "host key verification failed"): + return fmt.Errorf("SSH doesn't know %s's host key yet: connect to it once with ssh or git in a terminal to accept it, then try again (git said: %s)", host, said) + case strings.Contains(low, "could not read username") || strings.Contains(low, "could not read password") || + strings.Contains(low, "terminal prompts disabled") || strings.Contains(low, "authentication failed") || + strings.Contains(low, "permission denied") || strings.Contains(low, "access denied") || + strings.Contains(low, "the requested url returned error: 401") || strings.Contains(low, "the requested url returned error: 403"): + return fmt.Errorf("git couldn't sign in to %s. magpie runs your own git, so sign in the way git does there (a credential helper or an SSH key that can read the repository), check `git clone %s` works in a terminal, and try again (git said: %s)", host, src.Repo, said) + case strings.Contains(low, "couldn't find remote ref") || strings.Contains(low, "unknown revision"): + return fmt.Errorf("%s has no branch or tag %s", src.Repo, src.Ref) + case strings.Contains(low, "repository not found") || strings.Contains(low, "does not appear to be a git repository") || + strings.Contains(low, "not found") && strings.Contains(low, "repository") || strings.Contains(low, "returned error: 404"): + return fmt.Errorf("there's no git repository at %s, or it can't be read without signing in (git said: %s)", src.Repo, said) + case strings.Contains(low, "could not resolve host") || strings.Contains(low, "connection refused") || + strings.Contains(low, "connection timed out") || strings.Contains(low, "network is unreachable") || strings.Contains(low, "couldn't connect"): + return fmt.Errorf("git couldn't reach %s (git said: %s)", host, said) + } + return fmt.Errorf("git couldn't fetch %s: %s", src.Repo, said) +} + +// gitSaid is git's message, its last few lines, for an error. +func gitSaid(s string) string { + var keep []string + for _, l := range strings.Split(strings.TrimSpace(s), "\n") { + if l = strings.TrimSpace(l); l != "" && !strings.HasPrefix(l, "hint:") { + keep = append(keep, l) + } + } + if len(keep) > 3 { + keep = keep[len(keep)-3:] + } + out := strings.Join(keep, " / ") + if r := []rune(out); len(r) > 400 { + out = string(r[:399]) + "…" + } + if out == "" { + out = "nothing" + } + return out +} + +// gitHost is the host of a repository's address, for a message. +func gitHost(repo string) string { + if u, err := url.Parse(repo); err == nil && u.Scheme != "" { + if u.Host == "" { + return repo + } + return u.Hostname() + } + if m := scpLike.FindStringSubmatch(repo); m != nil { + return m[2] + } + return repo +} + +// fetchGit fetches the repository's ref (its default branch when "") +// with the user's git, one commit deep, into a new folder, and gives it +// back without its .git: what GitHub's tarball would have. Links are +// checked out as small files holding where they point, as a tarball's +// are left out: never followed out of the folder. +func fetchGit(src Source) (string, error) { + git := gitPath() + if git == "" { + return "", errNoGit() + } + ctx, cancel := context.WithTimeout(context.Background(), gitTimeout) + defer cancel() + env := gitEnv(git) + tmp, err := os.MkdirTemp("", skillTemp) + if err != nil { + return "", err + } + fail := func(err error) (string, error) { + os.RemoveAll(tmp) + return "", err + } + if _, err := runGit(ctx, git, env, tmp, src, "init", "-q"); err != nil { + return fail(err) + } + ref := src.Ref + if ref == "" { + ref = "HEAD" + } + if _, err := runGit(ctx, git, env, tmp, src, "fetch", "-q", "--depth", "1", "--no-tags", "--", src.Repo, ref); err != nil { + // a host that serves git over plain ("dumb") HTTP can't fetch one + // commit deep: the whole history then + if !strings.Contains(strings.ToLower(err.Error()), "shallow") { + return fail(err) + } + if _, err := runGit(ctx, git, env, tmp, src, "fetch", "-q", "--no-tags", "--", src.Repo, ref); err != nil { + return fail(err) + } + } + if _, err := runGit(ctx, git, env, tmp, src, "-c", "advice.detachedHead=false", "checkout", "-q", "FETCH_HEAD"); err != nil { + return fail(err) + } + out, err := runGit(ctx, git, env, tmp, src, "rev-parse", "FETCH_HEAD") + if err != nil { + return fail(err) + } + if err := os.RemoveAll(filepath.Join(tmp, ".git")); err != nil { + return fail(err) + } + if size := dirSize(tmp); size > maxFetch { + return fail(fmt.Errorf("%s is %s, over the %s magpie fetches", src.Repo, mb(size), mb(maxFetch))) + } + noteGitHead(tmp, strings.TrimSpace(string(out))) + return tmp, nil +} + +func dirSize(dir string) int64 { + var n int64 + filepath.Walk(dir, func(_ string, fi os.FileInfo, err error) error { + if err == nil && fi.Mode().IsRegular() { + n += fi.Size() + } + return nil + }) + return n +} + +// gitRemoteHead asks the repository, with git ls-remote, which commit its +// ref (its default branch when "") is at now. A ref that is a commit is +// that commit. +func gitRemoteHead(src Source) (string, error) { + if hexRef.MatchString(src.Ref) { + return strings.ToLower(src.Ref), nil + } + git := gitPath() + if git == "" { + return "", errNoGit() + } + ctx, cancel := context.WithTimeout(context.Background(), gitTimeout) + defer cancel() + args := []string{"ls-remote", "--", src.Repo} + if src.Ref == "" { + args = append(args, "HEAD") + } else { + args = append(args, "refs/heads/"+src.Ref, "refs/tags/"+src.Ref, "refs/tags/"+src.Ref+"^{}") + } + out, err := runGit(ctx, git, gitEnv(git), os.TempDir(), src, args...) + if err != nil { + return "", err + } + refs := map[string]string{} + for _, l := range strings.Split(string(out), "\n") { + if sha, name, ok := strings.Cut(strings.TrimSpace(l), "\t"); ok { + refs[name] = sha + } + } + for _, k := range []string{"HEAD", "refs/tags/" + src.Ref + "^{}", "refs/heads/" + src.Ref, "refs/tags/" + src.Ref} { + if sha := refs[k]; hexRef.MatchString(sha) { + return sha, nil + } + } + if src.Ref == "" { + return "", fmt.Errorf("%s names no default branch", src.Repo) + } + return "", fmt.Errorf("%s has no branch or tag %s any more", src.Repo, src.Ref) +} + +// checkGitSkill checks a skill from a git repository: git ls-remote says +// which commit its ref is at; one the skill was fetched at is current, +// and for another the repository is fetched and the skill's folder +// compared with the library's, since a commit elsewhere in the repository +// doesn't change it. When its files are the repository's, it gives back +// the commit they're at and their hash, for the library to keep. +func checkGitSkill(s *Skill, f *fetcher, asked map[string]string) (SkillCheck, string, string) { + src := *s.Source + c := SkillCheck{Name: s.Name, Status: "unknown"} + head, ok := asked[src.Ref] + if !ok { + var err error + if head, err = gitRemoteHead(src); err != nil { + c.Error = err.Error() + return c, "", "" + } + asked[src.Ref] = head + } + c.Commit = head + if s.Commit != "" && strings.EqualFold(s.Commit, head) { + c.Status = "current" + return c, "", "" + } + tmp, err := f.fetch(src) + if err != nil { + c.Error = err.Error() + return c, "", "" + } + from := filepath.Join(tmp, filepath.FromSlash(src.Path)) + if _, ok := readMeta(from); !ok { + c.Error = fmt.Sprintf("%s has no SKILL.md at %s any more", src.Repo, src.Path) + return c, "", "" + } + have := s.Hash + if have == "" { + have = hashDir(skillDir(s.Name)) + } + if theirs := hashDir(from); theirs == "" || theirs != have { + c.Status = "update" + return c, "", "" + } + c.Status = "current" + if h := gitHeadOf(tmp); h != "" { + c.Commit = h + } + return c, c.Commit, have +} + +// isGit is whether what the user typed is a git repository's address +// magpie fetches from. +func isGit(s string) bool { + _, ok, err := gitSource(s) + return ok && err == nil +} diff --git a/internal/library/skillgit_test.go b/internal/library/skillgit_test.go new file mode 100644 index 000000000..1ccb22cc4 --- /dev/null +++ b/internal/library/skillgit_test.go @@ -0,0 +1,274 @@ +package library + +import ( + "errors" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// sunset on Discord: skills from GitLab, and from a company's own GitLab +// on its intranet. What the user types is read as a git repository, with +// a GitLab page's ref and folder; what git would take as an option, or a +// transport that runs a command, is refused. +func TestGitSourceReads(t *testing.T) { + for _, c := range []struct{ in, repo, ref, path string }{ + {"https://gitlab.com/group/skills", "https://gitlab.com/group/skills", "", ""}, + {"https://gitlab.com/group/skills.git", "https://gitlab.com/group/skills.git", "", ""}, + {"https://git.corp.example/team/sub/deep/skills/", "https://git.corp.example/team/sub/deep/skills", "", ""}, + {"https://git.corp.example/team/sub/skills/-/tree/main/skills/pdf", "https://git.corp.example/team/sub/skills", "main", "skills/pdf"}, + {"https://gitlab.com/g/r/-/tree/HEAD", "https://gitlab.com/g/r", "", ""}, + {"https://gitlab.com/g/r/-/blob/v1.2/skills/pdf/SKILL.md", "https://gitlab.com/g/r", "v1.2", "skills/pdf"}, + {"https://gitea.corp/g/r/src/branch/dev/skills", "https://gitea.corp/g/r", "dev", "skills"}, + {"http://10.0.0.5/g/r.git", "http://10.0.0.5/g/r.git", "", ""}, + {"git@gitlab.corp.example:team/sub/skills.git", "git@gitlab.corp.example:team/sub/skills.git", "", ""}, + {"git@gitlab:team/skills.git", "git@gitlab:team/skills.git", "", ""}, + {"ssh://git@gitlab.corp:2222/team/skills.git", "ssh://git@gitlab.corp:2222/team/skills.git", "", ""}, + {"file:///srv/git/skills.git", "file:///srv/git/skills.git", "", ""}, + {"gitlab.com/group/skills", "https://gitlab.com/group/skills", "", ""}, + } { + src, ok, err := gitSource(c.in) + if !ok || err != nil { + t.Errorf("%s: ok %v, %v", c.in, ok, err) + continue + } + if src.Kind != "git" || src.Repo != c.repo || src.Ref != c.ref || src.Path != c.path { + t.Errorf("%s: read as %+v", c.in, src) + } + // what the page shows is read back as the same source + if back, _, err := gitSource(src.String()); err != nil || !sameGitRepo(back.Repo, src.Repo) || back.Ref != src.Ref || back.Path != src.Path { + t.Errorf("%s: shown as %s, read back as %+v (%v)", c.in, src.String(), back, err) + } + } + for _, in := range []string{"owner/repo", "C:/Users/me/skills", "hello", "", "skills folder"} { + if _, ok, _ := gitSource(in); ok { + t.Errorf("%q read as a git repository", in) + } + } + for _, in := range []string{ + "-uhack", "--upload-pack=touch /tmp/x", "ext::sh -c touch% /tmp/x", "file::/tmp/x", "fd::3", + "https://me:glpat-secret@gitlab.com/g/r.git", "ftp://host/g/r", "https://gitlab.com/", + "https://gitlab.com/g/r/-/tree/--upload-pack=x/skills", "https://gitlab.com/g/r/-/tree/main/../../x", + "git@-oProxyCommand=x:g/r", + } { + if _, ok, err := gitSource(in); ok && err == nil { + t.Errorf("%q isn't refused", in) + } + } +} + +// gitRepo makes a bare repository with skills in it, and gives its +// file:// address and a function to commit files to it. git runs with no +// system or user config of the machine's (no credential helper, no +// Keychain). +func gitRepo(t *testing.T, files map[string]string) (string, func(map[string]string)) { + t.Helper() + git, err := exec.LookPath("git") + if err != nil { + t.Skip("git isn't installed") + } + old := gitPath + gitPath = func() string { return git } + t.Cleanup(func() { gitPath = old }) + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), "gitconfig")) + root := t.TempDir() + bare, work := filepath.Join(root, "skills.git"), filepath.Join(root, "work") + run := func(dir string, args ...string) { + t.Helper() + cmd := exec.Command(git, append([]string{"-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "init.defaultBranch=main", "-c", "commit.gpgsign=false"}, args...)...) + cmd.Dir = dir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + run(root, "init", "-q", "--bare", bare) + run(root, "init", "-q", work) + commit := func(files map[string]string) { + for p, body := range files { + write(t, filepath.Join(work, filepath.FromSlash(p)), body) + } + run(work, "add", "-A") + run(work, "commit", "-q", "-m", "skills") + run(work, "push", "-q", bare, "HEAD:refs/heads/main") + } + commit(files) + p := filepath.ToSlash(bare) + if !strings.HasPrefix(p, "/") { + p = "/" + p // C:/… on Windows + } + return "file://" + p, commit +} + +func TestInstallFromGitRepo(t *testing.T) { + sandbox(t) + addr, commit := gitRepo(t, map[string]string{ + "skills/pdf/SKILL.md": "---\nname: pdf\ndescription: PDFs\n---\nv1\n", + "skills/pdf/notes.md": "one", + "skills/review/SKILL.md": "---\nname: review\ndescription: Reviews\n---\n", + "README.md": "hi", + }) + p, err := ProbeSkills(addr) + if err != nil { + t.Fatal(err) + } + if p.Kind != "git" || len(p.Candidates) != 2 || p.Candidates[0].Path != "skills/pdf" { + t.Fatalf("probe %+v", p) + } + if _, err := InstallSkills(addr, []string{"skills/pdf"}, []string{"claude"}); err != nil { + t.Fatal(err) + } + l, _ := load() + s := l.skill("pdf") + if s == nil || s.Source.Kind != "git" || s.Source.Repo != addr || s.Source.Path != "skills/pdf" || s.Hash == "" || len(s.Commit) != 40 { + t.Fatalf("installed as %+v %+v", s, s.Source) + } + if b, err := os.ReadFile(filepath.Join(skillDir("pdf"), "notes.md")); err != nil || string(b) != "one" { + t.Fatalf("notes.md: %q %v", b, err) + } + if _, err := os.Stat(filepath.Join(skillDir("pdf"), ".git")); err == nil { + t.Fatal("the skill has git's folder") + } + installedAt := s.Commit + + // the repository changes the skill: a check says so, an update takes it + commit(map[string]string{"skills/pdf/notes.md": "two"}) + checks, err := CheckSkills() + if err != nil { + t.Fatal(err) + } + if len(checks) != 1 || checks[0].Status != "update" { + t.Fatalf("check %+v", checks) + } + if _, err := UpdateSkill("pdf", false); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(filepath.Join(skillDir("pdf"), "notes.md")); string(b) != "two" { + t.Fatalf("not updated: %q", b) + } + l, _ = load() + updatedAt := l.skill("pdf").Commit + if len(updatedAt) != 40 || updatedAt == installedAt { + t.Fatalf("commit after the update %q (was %q)", updatedAt, installedAt) + } + if checks, _ := CheckSkills(); len(checks) != 1 || checks[0].Status != "current" { + t.Fatalf("after the update %+v", checks) + } + + // a commit elsewhere in the repository leaves the skill current, at it + commit(map[string]string{"README.md": "changed"}) + if checks, _ := CheckSkills(); len(checks) != 1 || checks[0].Status != "current" || checks[0].Error != "" { + t.Fatalf("after a commit elsewhere %+v", checks) + } + l, _ = load() + if c := l.skill("pdf").Commit; c == updatedAt || len(c) != 40 { + t.Fatalf("the commit found the same isn't kept: %q", c) + } + + // installing it again is had already + res, err := InstallSkills(addr, []string{"skills/pdf"}, nil) + if err != nil || len(res.Had) != 1 { + t.Fatalf("again: %+v %v", res, err) + } + + // changed here, an update is refused, naming the repository + write(t, filepath.Join(skillDir("pdf"), "notes.md"), "mine") + commit(map[string]string{"skills/pdf/notes.md": "three"}) + _, err = UpdateSkill("pdf", false) + var edited *EditedError + if !errors.As(err, &edited) || !strings.Contains(err.Error(), "fetched from "+addr) { + t.Fatalf("an update over a change here: %v", err) + } +} + +// A GitLab page's address of a folder on a branch installs that folder +// from that branch. +func TestGitTreeURLInstallsFolder(t *testing.T) { + sandbox(t) + addr, commit := gitRepo(t, map[string]string{"skills/a/SKILL.md": "---\nname: a\ndescription: on main\n---\n"}) + _ = commit + p, err := ProbeSkills(addr + "/-/tree/main/skills/a") + if err != nil { + t.Fatal(err) + } + if len(p.Candidates) != 1 || p.Candidates[0].Name != "a" || p.Candidates[0].Path != "skills/a" { + t.Fatalf("candidates %+v", p.Candidates) + } + if _, err := ProbeSkills(addr + "/-/tree/nope/skills/a"); err == nil || !strings.Contains(err.Error(), "no branch or tag nope") { + t.Fatalf("a missing branch: %v", err) + } + if _, err := ProbeSkills(addr + "/-/tree/main/skills/zz"); err == nil || !strings.Contains(err.Error(), "has no folder skills/zz") { + t.Fatalf("a missing folder: %v", err) + } +} + +// Without git, the probe says git is needed; nothing else is tried. +func TestGitMissingSaysSo(t *testing.T) { + sandbox(t) + old := gitPath + gitPath = func() string { return "" } + t.Cleanup(func() { gitPath = old }) + _, err := ProbeSkills("https://gitlab.example.com/team/skills.git") + if err == nil || !strings.Contains(err.Error(), "git isn't installed") { + t.Fatalf("got %v", err) + } +} + +// A host that wants a sign-in git can't give it: the error says git +// couldn't sign in, and how the user's own git signs in, never waits for +// a password. +func TestGitSignInRefusedSaysSo(t *testing.T) { + sandbox(t) + gitRepo(t, map[string]string{"a/SKILL.md": "---\nname: a\n---\n"}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("WWW-Authenticate", `Basic realm="GitLab"`) + w.WriteHeader(401) + })) + t.Cleanup(srv.Close) + _, err := ProbeSkills(srv.URL + "/team/private-skills.git") + if err == nil || !strings.Contains(err.Error(), "git couldn't sign in to 127.0.0.1") { + t.Fatalf("got %v", err) + } +} + +// What git would read as an option, or a transport that runs a command, +// never reaches git. +func TestGitRefusesOptionsAndTransports(t *testing.T) { + sandbox(t) + old := gitPath + gitPath = func() string { t.Error("git ran"); return "" } + t.Cleanup(func() { gitPath = old }) + for in, want := range map[string]string{ + "-uhack": "can't start with -", + "--upload-pack=touch x": "can't start with -", + "ext::sh -c touch% x": "transport (ext::)", + "file::/tmp/x": "transport (file::)", + "https://u:tok@gitlab.com/g": "leave the password or token out", + } { + if _, err := ProbeSkills(in); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: %v", in, err) + } + } +} + +// git's own words, as it prints them, read as what they mean. +func TestGitErrorsSaid(t *testing.T) { + src := Source{Kind: "git", Repo: "https://git.corp.example/team/skills.git", Ref: "dev"} + for msg, want := range map[string]string{ + "fatal: could not read Username for 'https://git.corp.example': terminal prompts disabled\n": "git couldn't sign in to git.corp.example", + "remote: HTTP Basic: Access denied\nfatal: Authentication failed for 'https://git.corp.example/team/skills.git/'\n": "git couldn't sign in", + "git@git.corp.example: Permission denied (publickey).\nfatal: Could not read from remote repository.\n": "git couldn't sign in", + "Host key verification failed.\nfatal: Could not read from remote repository.\n": "host key", + "fatal: couldn't find remote ref dev\n": "has no branch or tag dev", + "fatal: unable to access 'https://git.corp.example/team/skills.git/': Could not resolve host: git.corp.example\n": "couldn't reach git.corp.example", + "xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun\n": "git isn't installed", + } { + if err := gitError(src, msg); !strings.Contains(err.Error(), want) { + t.Errorf("%q said as %q", msg, err) + } + } +} diff --git a/internal/library/skills.go b/internal/library/skills.go index c5a42def5..2a6adc257 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -34,7 +34,8 @@ type Skill struct { // Hash is of the skill's files as last fetched from GitHub, and Commit // the last commit to have touched its folder there, once a check has // found the two to agree: together they tell whether GitHub has - // changed the skill since. + // changed the skill since. For one from another git repository, + // Commit is the commit of the repository it was fetched at. Hash string `json:"hash,omitempty"` Commit string `json:"commit,omitempty"` // From is the repository one not installed from GitHub was found to @@ -43,11 +44,12 @@ type Skill struct { } // Source is where a skill came from: a GitHub repository it can be updated -// from, or a folder on this machine the library links to, so that editing -// the folder is editing the skill. +// from, another git repository (fetched with the user's own git), or a +// folder on this machine the library links to, so that editing the folder +// is editing the skill. type Source struct { - Kind string `json:"kind"` // github | folder - Repo string `json:"repo,omitempty"` + Kind string `json:"kind"` // github | git | folder + Repo string `json:"repo,omitempty"` // owner/repo for github, the address git fetches for git Ref string `json:"ref,omitempty"` Path string `json:"path,omitempty"` // in the repository Dir string `json:"dir,omitempty"` // the folder, for kind folder @@ -60,6 +62,9 @@ func (s *Source) String() string { if s.Kind == "folder" { return s.Dir } + if s.Kind == "git" { + return gitURL(s) + } u := "https://github.com/" + s.Repo if s.Ref != "" || s.Path != "" { ref := s.Ref @@ -747,12 +752,20 @@ var tarballURL = func(repo, ref string) string { return "https://codeload.github.com/" + repo + "/tar.gz/" + url.PathEscape(ref) } -// fetch downloads the repository into a new folder and gives it back. A +// remote is whether a skill's source is a repository it is fetched from +// again to update: GitHub, or another git repository. +func (s *Source) remote() bool { return s != nil && (s.Kind == "github" || s.Kind == "git") } + +// fetch downloads the repository into a new folder and gives it back; one +// not on GitHub is fetched with the user's git (fetchGit). A // repository codeload doesn't hand out without a token, a private one, is // asked of GitHub's API with the user's GitHub token (37FlowAI on X): the // API redirects to codeload, and the token, sent to the API's host alone, // isn't carried over to it. func fetch(src Source) (string, error) { + if src.Kind == "git" { + return fetchGit(src) + } c := &http.Client{Timeout: 2 * time.Minute} get := func(u string) (*http.Response, bool, error) { req, _ := http.NewRequest("GET", u, nil) @@ -994,12 +1007,16 @@ func skillsCommand(input string) string { } // ProbeSkills looks for skills at what the user typed: a GitHub repository -// (or a folder in one), a folder on this machine, or a skills CLI command -// for either. +// (or a folder in one), any other git repository (GitLab, one on a +// company's own server; fetched with the user's git), a folder on this +// machine, or a skills CLI command for one of them. func ProbeSkills(input string) (*Probe, error) { input = strings.TrimSpace(skillsCommand(input)) if input == "" { - return nil, fmt.Errorf("paste a GitHub link or a folder's path") + return nil, fmt.Errorf("paste a GitHub or git repository's link or a folder's path") + } + if strings.HasPrefix(input, "-") { + return nil, fmt.Errorf("a repository's address can't start with -") } sweepStaleDownloads() @@ -1011,12 +1028,15 @@ func ProbeSkills(input string) (*Probe, error) { } p.Kind, p.root, p.src = "folder", dir, Source{Kind: "folder", Dir: dir} p.Candidates = candidates(dir, "") - } else if src, ok := githubSource(input); ok { + } else if src, ok := githubSource(input); ok || isGit(input) { + if !ok { + src, _, _ = gitSource(input) + } tmp, err := fetch(src) if err != nil { return nil, err } - p.Kind, p.root, p.src = "github", tmp, src + p.Kind, p.root, p.src = src.Kind, tmp, src if _, err := os.Stat(filepath.Join(tmp, filepath.FromSlash(src.Path))); src.Path != "" && err != nil { os.RemoveAll(tmp) return nil, fmt.Errorf("%s has no folder %s", src.Repo, src.Path) @@ -1024,8 +1044,10 @@ func ProbeSkills(input string) (*Probe, error) { p.Candidates = candidates(tmp, src.Path) p.Left = tookLeftOut(tmp, src.Path) keepProbe(input, p, tmp) + } else if _, ok, err := gitSource(input); ok && err != nil { + return nil, err } else { - return nil, fmt.Errorf("that's neither a GitHub repository nor a folder's full path") + return nil, fmt.Errorf("that's neither a git repository's link (GitHub, GitLab or another host) nor a folder's full path") } if p.Candidates == nil { p.Candidates = []Candidate{} @@ -1104,6 +1126,8 @@ func fromSameSource(s *Skill, src Source, path, from string) bool { switch src.Kind { case "github": return strings.EqualFold(s.Source.Repo, src.Repo) && s.Source.Path == path + case "git": + return sameGitRepo(s.Source.Repo, src.Repo) && s.Source.Path == path case "folder": return realDir(s.Source.Dir) == realDir(from) } @@ -1152,7 +1176,7 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *i switch { case src.Kind == "folder" && linked(dir) && realDir(dir) == realDir(from): src.Dir = from - case src.Kind == "github" && !linked(dir) && sameTree(dir, from): + case src.remote() && !linked(dir) && sameTree(dir, from): src.Path = c.Path case src.Kind == "folder" && realDir(from) == realDir(dir): // a folder already in the library's own (#595): linked to @@ -1193,6 +1217,9 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *i in.added = append(in.added, c.Name) } sk := &Skill{Name: c.Name, Source: &src, Agents: slices.Clone(agents)} + if src.Kind == "git" { + sk.Hash, sk.Commit = hashDir(dir), gitHeadOf(p.root) + } if src.Kind == "github" { sk.Hash = hashDir(dir) // every skill the picker showed was offered: a check @@ -1228,7 +1255,7 @@ func UpdateSkill(name string, replace bool) (*Result, error) { f := &fetcher{} defer f.clean() if edited, _ := l.editState(s, Targets()); edited && !replace { - return nil, &EditedError{Name: name} + return nil, editedError(s) } up, err := f.prepare(s) if err != nil { @@ -1239,7 +1266,7 @@ func UpdateSkill(name string, replace bool) (*Result, error) { if s := l.skill(name); s != nil && !replace { // changed while it was fetched if edited, _ := l.editState(s, targets); edited { - return &EditedError{Name: name} + return editedError(s) } } return up.apply(l, targets) @@ -1303,7 +1330,7 @@ func updateSkills(names []string) (*Result, error) { for _, up := range ups { if s := l.skill(up.name); s != nil { if edited, _ := l.editState(s, targets); edited { - failed = append(failed, Problem{What: "skill:" + up.name, Error: (&EditedError{Name: up.name}).Error()}) + failed = append(failed, Problem{What: "skill:" + up.name, Error: editedError(s).Error()}) continue } } @@ -1327,10 +1354,10 @@ func updateSkills(names []string) (*Result, error) { return res, nil } -// updatable is whether a skill can be fetched again: one from GitHub, or -// one CC Switch installed from there. +// updatable is whether a skill can be fetched again: one from GitHub or +// another git repository, or one CC Switch installed from GitHub. func updatable(s *Skill) bool { - if s.Source != nil && s.Source.Kind == "github" { + if s.Source.remote() { return true } _, ok := ccSwitchOrigin(s) @@ -1382,21 +1409,22 @@ func (f *fetcher) clean() { // skillUpdate is a skill fetched again, ready to take the old one's place. type skillUpdate struct { - name string - src *Source - adopt bool - from string + name string + src *Source + adopt bool + from string + commit string // the commit a git repository was fetched at } func (f *fetcher) prepare(s *Skill) (*skillUpdate, error) { name := s.Name src, adopt := s.Source, false - if src == nil || src.Kind != "github" { + if !src.remote() { // one CC Switch installed from GitHub becomes the library's own, // fetched from there, leaving CC Switch's folder as it is o, ok := ccSwitchOrigin(s) if !ok { - return nil, fmt.Errorf("%s isn't from GitHub; it's kept as it is", name) + return nil, fmt.Errorf("%s isn't from GitHub or a git repository; it's kept as it is", name) } src, adopt = &o, true } else { @@ -1422,7 +1450,11 @@ func (f *fetcher) prepare(s *Skill) (*skillUpdate, error) { if _, ok := readMeta(from); !ok { return nil, fmt.Errorf("%s has no SKILL.md at %s any more", src.Repo, src.Path) } - return &skillUpdate{name: name, src: src, adopt: adopt, from: from}, nil + up := &skillUpdate{name: name, src: src, adopt: adopt, from: from} + if src.Kind == "git" { + up.commit = gitHeadOf(tmp) + } + return up, nil } // apply puts the fetched skill in the old one's place; the agents' links @@ -1465,8 +1497,8 @@ func (up *skillUpdate) apply(l *Library, targets []*Target) error { s.Source = up.src } // the commit it's at is known again once a check finds the files - // GitHub has to be these - s.Hash, s.Commit = hash, "" + // GitHub has to be these; a git repository's is the one fetched + s.Hash, s.Commit = hash, up.commit } forgetCheck(name) if old == "" { diff --git a/internal/library/sync.go b/internal/library/sync.go index 4c185d29c..41fd4289c 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -326,7 +326,7 @@ type SkillView struct { Name string `json:"name"` Description string `json:"description"` Source string `json:"source,omitempty"` - Kind string `json:"kind"` // github, folder, or "" for one kept in the library + Kind string `json:"kind"` // github, git, folder, or "" for one kept in the library Origin string `json:"origin,omitempty"` // on GitHub, as CC Switch installed it: it can be updated from there Repo string `json:"repo,omitempty"` // the repository it came from, however it came in, for the page to group by Icon string `json:"icon,omitempty"` diff --git a/internal/netproxy/http2_health_test.go b/internal/netproxy/http2_health_test.go new file mode 100644 index 000000000..2282ddbde --- /dev/null +++ b/internal/netproxy/http2_health_test.go @@ -0,0 +1,23 @@ +package netproxy + +import ( + "net/http" + "testing" +) + +// http.DefaultClient's HTTP/2 connections (usage cards, catalogs, +// sign-ins) are checked as the gateway's are: one gone silent is pinged +// and dropped rather than given every request after it (#2843). +func TestInstallChecksHTTP2Connections(t *testing.T) { + d, ok := http.DefaultTransport.(*http.Transport) + if !ok { + t.Skip("http.DefaultTransport is not an *http.Transport") + } + was, wasClient, wasProxy := d.HTTP2, http.DefaultClient.Transport, d.Proxy + t.Cleanup(func() { d.HTTP2, http.DefaultClient.Transport, d.Proxy = was, wasClient, wasProxy }) + d.HTTP2 = nil + Install() + if d.HTTP2 == nil || d.HTTP2.SendPingTimeout != PingAfter || d.HTTP2.PingTimeout != PingWait { + t.Fatalf("http.DefaultTransport's HTTP/2 after Install: %+v; want pings after %v, dropped after %v", d.HTTP2, PingAfter, PingWait) + } +} diff --git a/internal/netproxy/netproxy.go b/internal/netproxy/netproxy.go index abedcb0ad..5c9989cb5 100644 --- a/internal/netproxy/netproxy.go +++ b/internal/netproxy/netproxy.go @@ -25,14 +25,35 @@ import ( // Install routes http.DefaultTransport (and so http.DefaultClient) through // Func, and http.DefaultClient's requests made on a provider's behalf -// (With) through a transport of that provider's proxy (Dispatch). +// (With) through a transport of that provider's proxy (Dispatch). Its +// HTTP/2 connections are checked as the gateway's are (HTTP2Health). func Install() { if t, ok := http.DefaultTransport.(*http.Transport); ok { t.Proxy = Func + if t.HTTP2 == nil { + t.HTTP2 = HTTP2Health() + } http.DefaultClient.Transport = Dispatch(t) } } +// PingAfter and PingWait: an HTTP/2 connection that has had no frame for +// PingAfter is pinged, and dropped when no answer comes within PingWait. +var PingAfter, PingWait = 20 * time.Second, 10 * time.Second + +// HTTP2Health is the HTTP/2 setting of a transport to the vendors. Every +// request to one host shares one HTTP/2 connection, and one gone silent +// without closing (a proxy's way out died, a NAT forgot the flow) was +// given every new request, each waiting for its transport's +// ResponseHeaderTimeout while the kernel took the writes, until a restart +// (#2843). A ping finds it, and the requests on it fail, so a group moves +// on and the next request dials anew. A live vendor answers a ping +// whatever its streams are doing, so a long wait for a first byte is +// never cut by it. +func HTTP2Health() *http.HTTP2Config { + return &http.HTTP2Config{SendPingTimeout: PingAfter, PingTimeout: PingWait} +} + // Func is an http.Transport Proxy function: the proxy the request's // context names (With), or else the global one, which a host on the // user's own network goes around (onLAN). diff --git a/internal/plugin/auth_read_once_test.go b/internal/plugin/auth_read_once_test.go new file mode 100644 index 000000000..da08ab1cd --- /dev/null +++ b/internal/plugin/auth_read_once_test.go @@ -0,0 +1,81 @@ +package plugin + +import ( + "bytes" + "context" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// TestAuthReadOncePerVersion: host.js reads and parses plugin-auth.json +// once per version of the file, not on every request (its account, its +// renewal and the plugin's getAuth each read it). A file rewritten with +// the same size inside one tick of the file system's clock, which leaves +// the same time, is still read again, and a plugin's copy is its own. +func TestAuthReadOncePerVersion(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("no node on PATH") + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, node, "-e", authReadOnceJS, filepath.Join(t.TempDir(), "plugin-auth.json")) + cmd.Stdin = bytes.NewReader(hostJS) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%v\n%s", err, out) + } +} + +const authReadOnceJS = ` +const assert = require('node:assert/strict') +const realFs = require('node:fs') +const vm = require('node:vm') +const source = realFs.readFileSync(0, 'utf8') +const section = (from, to) => { + const start = source.indexOf(from) + const end = source.indexOf(to, start) + assert.ok(start >= 0 && end > start, 'production section exists') + return source.slice(start, end) +} +const authPath = process.argv[1] +let reads = 0 +const fs = { ...realFs, readFileSync: (p, ...rest) => { + if (p === authPath) reads++ + return realFs.readFileSync(p, ...rest) +} } +const context = vm.createContext({ fs, authPath, Buffer, structuredClone, Date, toErr: () => {}, send: () => {}, pause: () => {} }) +const run = code => vm.runInContext(code, context) +run(section('function parseAuth(', '// writeDurable')) +const past = new Date(Date.now() - 60e3) +const write = (v, at) => { + realFs.writeFileSync(authPath, JSON.stringify(v)) + if (at) realFs.utimesSync(authPath, at, at) +} + +write({ a: { type: 'api', key: 'k1' } }, past) +for (let i = 0; i < 100; i++) assert.equal(run('readAuth()').a.key, 'k1') +assert.equal(reads, 1, 'a settled file is read once for 100 reads, read ' + reads + ' times') + +// written again: read again +write({ a: { type: 'api', key: 'k2' }, b: { type: 'api', key: 'k3' } }, new Date(past.getTime() + 1000)) +assert.equal(run('readAuth()').a.key, 'k2') + +// a file written just now, rewritten with the same size and time (two +// writes inside one tick of the clock): its bytes tell them apart +const now = new Date() +write({ a: { type: 'api', key: 'x1' } }, now) +assert.equal(run('readAuth()').a.key, 'x1') +write({ a: { type: 'api', key: 'x2' } }, now) +assert.equal(run('readAuth()').a.key, 'x2', 'a same-size rewrite in one tick is read') + +// what a plugin is handed is its own to change +const copy = run('authCopy("a")') +copy.key = 'changed' +assert.equal(run('readAuth()').a.key, 'x2') +const all = run('authCopy()') +all.a.key = 'changed' +assert.equal(run('readAuth()').a.key, 'x2') +console.log('ok') +` diff --git a/internal/plugin/chunk_frame_test.go b/internal/plugin/chunk_frame_test.go new file mode 100644 index 000000000..e73e50e0b --- /dev/null +++ b/internal/plugin/chunk_frame_test.go @@ -0,0 +1,66 @@ +package plugin + +import ( + "encoding/base64" + "encoding/json" + "strings" + "testing" +) + +// TestChunkFrameReadsWithoutJSON: a chunk frame as host.js writes it +// (JSON.stringify({id, event: "chunk", data}), which chunkLine joins by +// hand) is read without encoding/json, and reads the same as through it. +// Any line of another shape goes through encoding/json as before. +func TestChunkFrameReadsWithoutJSON(t *testing.T) { + raw := make([]byte, 70<<10) + for i := range raw { + raw[i] = byte(i * 31) + } + for _, tc := range []struct { + id int64 + data string + }{ + {1, base64.StdEncoding.EncodeToString(raw)}, + {987654321, base64.StdEncoding.EncodeToString([]byte("data: {}\n\n"))}, + {42, "AA=="}, + } { + b, err := json.Marshal(struct { + ID int64 `json:"id"` + Event string `json:"event"` + Data string `json:"data"` + }{tc.id, "chunk", tc.data}) + if err != nil { + t.Fatal(err) + } + for _, line := range []string{string(b) + "\n", string(b), string(b) + "\r\n"} { + got, ok := chunkFrame([]byte(line)) + if !ok { + t.Fatalf("a chunk frame as host.js writes it (%.60q…) went through encoding/json", line) + } + var want message + if err := json.Unmarshal([]byte(line), &want); err != nil { + t.Fatal(err) + } + if got.ID != want.ID || got.Event != want.Event || got.Data != want.Data { + t.Fatalf("read as id %d %q %d bytes, encoding/json reads id %d %q %d bytes", got.ID, got.Event, len(got.Data), want.ID, want.Event, len(want.Data)) + } + } + } + for _, line := range []string{ + `{"id":1,"event":"head","status":200,"headers":{}}`, + `{"id":1,"result":null}`, + `{"id":1,"event":"chunk","data":"QU` + "\\" + `/A"}`, // an escape: JSON reads it otherwise + `{"id":1,"event":"chunk","data":"QUFB\"}`, + `{"id":-1,"event":"chunk","data":"QUFB"}`, + `{"id":1e3,"event":"chunk","data":"QUFB"}`, + `{"id":1,"event":"chunk","data":"QUFB","x":"y"}`, + `{"id":1,"event":"chunk","data":"QUFB"} `, + `{"id":1,"event":"chunk","data":"` + strings.Repeat("A", 8) + `"}x`, + `{"id":12345678901234567890,"event":"chunk","data":"QUFB"}`, + `{"event":"chunk","id":1,"data":"QUFB"}`, + } { + if m, ok := chunkFrame([]byte(line)); ok { + t.Fatalf("%s read as a chunk frame %+v, want it left to encoding/json", line, m) + } + } +} diff --git a/internal/plugin/host.go b/internal/plugin/host.go index b1843548f..e037d29d5 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -2,6 +2,7 @@ package plugin import ( "bufio" + "bytes" "context" "crypto/sha256" _ "embed" @@ -1033,8 +1034,9 @@ func (h *host) read(out io.Reader) { for { line, err := readLine(r, h.lineLimit()) if len(line) > 0 { - var m message - if json.Unmarshal(line, &m) == nil { + if m, ok := chunkFrame(line); ok { + h.dispatch(m) + } else if json.Unmarshal(line, &m) == nil { h.dispatch(m) } } @@ -1057,6 +1059,45 @@ func (h *host) read(out io.Reader) { h.fail(fmt.Errorf("the plugin host quit: %v", err)) } +var ( + chunkHead = []byte(`{"id":`) + chunkMid = []byte(`,"event":"chunk","data":"`) +) + +// chunkFrame is the chunk frame in line when it has exactly the shape +// host.js's chunkLine writes, {"id":N,"event":"chunk","data":"…"}, with +// nothing in the data JSON would escape: the reply's bytes come in these, +// and encoding/json scanned every base64 byte of each, several times what +// decoding them costs. Any other line is not one, and is unmarshalled; push +// checks the data is base64 of a frame's size either way. +func chunkFrame(line []byte) (message, bool) { + line = bytes.TrimSuffix(bytes.TrimSuffix(line, []byte("\n")), []byte("\r")) + rest, ok := bytes.CutPrefix(line, chunkHead) + if !ok { + return message{}, false + } + i := bytes.IndexByte(rest, ',') + if i <= 0 || i > 18 { + return message{}, false + } + var id int64 + for _, c := range rest[:i] { + if c < '0' || c > '9' { + return message{}, false + } + id = id*10 + int64(c-'0') + } + data, ok := bytes.CutPrefix(rest[i:], chunkMid) + if !ok { + return message{}, false + } + data, ok = bytes.CutSuffix(data, []byte(`"}`)) + if !ok || bytes.IndexByte(data, '"') >= 0 || bytes.IndexByte(data, '\\') >= 0 { + return message{}, false + } + return message{ID: id, Event: "chunk", Data: string(data)}, true +} + // readLine reads one '\n'-terminated line, at most max bytes, so a child that // never ends a line cannot make the host allocate without bound. It is // errLineTooLong once max is passed. diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 353fc2e39..36376492b 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -112,8 +112,14 @@ function queueLine(line) { // send queues one message, ignoring whether it was written. const send = (msg) => queueLine(JSON.stringify(msg) + "\n").promise -// sendCancelable is send, with a way to give the wait up. -const sendCancelable = (msg) => queueLine(JSON.stringify(msg) + "\n") +// sendCancelable is send, with a way to give the wait up. A string is a +// line made already (chunkLine). +const sendCancelable = (msg) => queueLine(typeof msg === "string" ? msg : JSON.stringify(msg) + "\n") + +// chunkLine is JSON.stringify({id, event: "chunk", data}) + "\n", made by +// joining: base64 has nothing JSON escapes, and stringify scanning every +// byte of it for something to escape cost more than the base64 itself. +const chunkLine = (id, data) => '{"id":' + JSON.stringify(id) + ',"event":"chunk","data":"' + data + '"}\n' // A host cancellation suppresses the answer; a local abort still owes Go // its error. The record, rather than the signal, owns pending wire output. @@ -285,6 +291,22 @@ const hooks = [] // {spec, hooks} const gatewayHooks = [] // {spec, options, onRequest} const loaded = [] // {spec, id, error} const loaders = new Map() // account → options the auth loader returned +// infos are info's answers a request is given, by account: built once, not +// for every fetch, which asked the plugin's models hook (its vendor, once +// its own list's time was up) before each request went. One goes with its +// account's sign-in (forgetAccount), and all with the options the user set +// (setProviderOptions) or a new models.dev catalog; a listing (providers) +// puts its own in. +const infos = new Map() // account → {gen, md, info} +let infoGen = 0 + +// forgetAccount drops what was made of the sign-in at key: its loader's +// options and its info, which the next request makes again. +function forgetAccount(key) { + loaders.delete(key) + infos.delete(key) + infoGen++ +} const sessions = new Map() // oauth sign-in in progress → its authorize result const inflight = new Map() // fetch id → its lifecycle and owned resources const renewing = new Map() // account → its sign-in's renewal under way @@ -700,11 +722,10 @@ let authUnread = false // readAuthState is the sign-ins and whether they are known: a file not // there is none, known; one that doesn't read is its .bak's, known, or // none, unknown. -function readAuthState() { - const buf = readFileSteady(authPath) +function readAuthState(buf = readFileSteady(authPath)) { if (buf === null) return { all: {}, known: true } const v = parseAuth(buf.toString("utf8")) - if (v) return { all: v, known: true } + if (v) return { all: v, known: true, own: true } const why = describeBad(buf) let bak = null try { @@ -725,8 +746,41 @@ function readAuthState() { return { all: {}, known: false } } +// authSeen is plugin-auth.json as last parsed, kept while the file has the +// same time, size and inode: every request read and parsed it two or three +// times (its account, its renewal, the plugin's getAuth), ~0.6 ms each for +// a dozen sign-ins. While the file's time is too recent for a second write +// to stamp a later one (Linux's clock is a tick coarse), its bytes are kept +// and compared too, as Go's filememo does. +let authSeen = null // {mtimeMs, size, ino, raw, all} +const AUTH_SETTLED = 2000 + +// readAuth is the sign-ins, shared: the caller must not change them, and +// hands a plugin a copy (authCopy). function readAuth() { - return readAuthState().all + let st = null + try { + st = fs.statSync(authPath) + } catch {} + const e = authSeen + const same = st && e && e.mtimeMs === st.mtimeMs && e.size === st.size && e.ino === st.ino + if (same && !e.raw) return e.all + const buf = readFileSteady(authPath) + if (same && buf && buf.equals(e.raw)) { + if (Date.now() - e.mtimeMs > AUTH_SETTLED) e.raw = null + return e.all + } + const s = readAuthState(buf) + authSeen = st && s.own ? { mtimeMs: st.mtimeMs, size: st.size, ino: st.ino, raw: Date.now() - st.mtimeMs > AUTH_SETTLED ? null : buf, all: s.all } : null + return s.all +} + +// authCopy is readAuth's sign-ins, or the one at key, the plugin's own to +// change. +function authCopy(key) { + const all = readAuth() + const v = key === undefined ? all : all[key] + return v === undefined ? undefined : structuredClone(v) } // writeDurable replaces p with data through a temp file flushed to the @@ -886,7 +940,7 @@ function setAuth(key, info) { changeAuth((all) => { all[key] = info }) - loaders.delete(key) + forgetAccount(key) send({ event: "auth", provider: providerOf(key), account: key }) } @@ -894,7 +948,7 @@ function removeAuth(key) { changeAuth((all) => { delete all[key] }) - loaders.delete(key) + forgetAccount(key) send({ event: "auth", provider: providerOf(key), account: key }) } @@ -984,8 +1038,8 @@ function settle(provider, key) { return false }) if (k) { - loaders.delete(k) - loaders.delete(key) + forgetAccount(k) + forgetAccount(key) send({ event: "auth", provider, account: k }) return k } @@ -1023,7 +1077,7 @@ function makeClient() { all[key] = body }) if (kept !== false) { - loaders.delete(key) + forgetAccount(key) send({ event: "auth", provider: providerOf(key), account: key }) } } @@ -1156,7 +1210,7 @@ async function loadPlugins(list) { } const pis = pi ? list.filter((p) => pi.isPi(p.target)) : [] if (pis.length) { - const h = { readAuth, changeAuth, keyFor, send, directory } + const h = { readAuth: authCopy, changeAuth, keyFor, send, directory } const got = await pi.load(h, pis).catch((e) => pis.map((p) => ({ spec: p.spec, error: String(e?.stack ?? e) }))) for (const r of got) { for (const x of r.hooks ?? []) hooks.push(x) @@ -1676,7 +1730,7 @@ async function info(id, key, strict) { try { const given = JSON.parse(JSON.stringify(out)) const l = { tried: false, lastOk: false } - const next = await listing.run(l, () => inScope(id, k, () => ph.models(given, { auth: all[k] }))) + const next = await listing.run(l, () => inScope(id, k, () => ph.models(given, { auth: authCopy(k) }))) // a hook that asked its vendor, got no list and gave back the one it // was given fell back: magpie keeps the list it had, as a built-in // whose fetch failed keeps the one it fetched last; so does one that @@ -1709,6 +1763,26 @@ async function info(id, key, strict) { return out } +// infoOf is info(id, key) as a request has it: the one built for the +// account, until its sign-in or the options change. What it gives is +// shared: the caller must not change it. +async function infoOf(id, key) { + const md = mdev() + const had = infos.get(key) + if (had && had.gen === infoGen && had.md === md) return had.info + const gen = infoGen + const p = await info(id, key) + // a sign-in changed while it was built: the next request builds it again + if (gen === infoGen) infos.set(key, { gen, md, info: p }) + return p +} + +// keepInfo keeps p, info(id, key) just built by a listing, for the +// account's requests. +function keepInfo(key, p, gen) { + if (gen === infoGen && !p.failed) infos.set(key, { gen, md: mdev(), info: p }) +} + // shown is a plugin's string as magpie shows it: trimmed and at most n // characters, "" for anything else. const shown = (v, n) => (typeof v === "string" ? v.trim().slice(0, n) : "") @@ -1827,12 +1901,14 @@ async function providers({ proxies } = {}) { for (const [id, a] of auths()) { const keys = accountsOf(stored, id) const through = (k) => proxies?.[id]?.[k ?? keys[0] ?? ""] ?? proxies?.[id]?.[""] ?? "" + const gen = infoGen const p = await via.run(through(), () => info(id)) + keepInfo(keys[0] ?? id, p, gen) // each account's own models, as the built-ins read each account's: a // plan may serve fewer, or others, than the first account's. One that // can't be read is taken to have them all, or the ones it was last // told to have, as a built-in account whose fetch failed keeps its own. - const own = await Promise.all(keys.slice(1).map((k) => via.run(through(k), () => info(id, k, true)).catch((e) => ({ failed: true, listError: e?.message ?? String(e) })))) + const own = await Promise.all(keys.slice(1).map((k) => via.run(through(k), () => info(id, k, true)).then((q) => (keepInfo(k, q, gen), q)).catch((e) => ({ failed: true, listError: e?.message ?? String(e) })))) const models = { ...p.models } for (const q of own) for (const [k, m] of Object.entries(q?.models ?? {})) models[k] ??= m const ids = (q) => Object.values(q.models).filter((m) => m.status !== "deprecated").map((m) => m.id) @@ -1985,7 +2061,10 @@ async function authorize({ provider, method, inputs, account, proxy }) { const a = await via.run(proxy ?? "", () => inScope(provider, key, () => m.authorize(m.prompts?.length ? inputs ?? {} : undefined))) const session = String(nextSession++) sessions.set(session, { provider, key, a, inputs, proxy: proxy ?? "" }) - return { session, url: a.url ?? "", instructions: a.instructions ?? "", method: a.method } + // opened (not OpenCode's) is a page the plugin's own CLI opened already: + // Grok Build's `grok login` opens it on macOS and Windows, and magpie's + // opening it too showed it twice (andyfmyth on X) + return { session, url: a.url ?? "", instructions: a.instructions ?? "", method: a.method, opened: a.opened === true } } // failed is a sign-in's failure, with why, where the plugin tells it @@ -2106,7 +2185,7 @@ async function renew(provider, key, a) { }) if (kept === false) return unrenewed.delete(key) - loaders.delete(key) + forgetAccount(key) send({ event: "auth", provider, account: key }) send({ event: "signIn", provider, account: key, said: "renewed" }) } @@ -2123,8 +2202,8 @@ async function options(provider, key) { const stored = readAuth()[key] let opts = {} if (a?.loader && stored) { - const p = await info(provider, key) - opts = (await inScope(provider, key, () => a.loader(async () => readAuth()[key], JSON.parse(JSON.stringify(p))))) ?? {} + const p = await infoOf(provider, key) + opts = (await inScope(provider, key, () => a.loader(async () => authCopy(key), JSON.parse(JSON.stringify(p))))) ?? {} } if (!opts.apiKey && stored?.type === "api") opts = { ...opts, apiKey: stored.key } loaders.set(key, opts) @@ -2180,8 +2259,8 @@ async function usageOf(provider, account) { const key = accountKey(provider, account) if (!readAuth()[key]) throw new Error("not signed in") await fresh(provider, key) - const p = await info(provider, key) - const u = (await inScope(provider, key, () => a.usage(async () => readAuth()[key], JSON.parse(JSON.stringify(p))))) ?? {} + const p = await infoOf(provider, key) + const u = (await inScope(provider, key, () => a.usage(async () => authCopy(key), JSON.parse(JSON.stringify(p))))) ?? {} const when = (v) => { if (v === undefined || v === null || v === "") return "" const d = new Date(typeof v === "number" && v < 1e11 ? v * 1000 : v) @@ -2255,8 +2334,8 @@ async function checkinOf(provider, account) { const key = accountKey(provider, account) if (!readAuth()[key]) throw new Error("not signed in") await fresh(provider, key) - const p = await info(provider, key) - const r = (await inScope(provider, key, () => a.checkin(async () => readAuth()[key], JSON.parse(JSON.stringify(p))))) ?? {} + const p = await infoOf(provider, key) + const r = (await inScope(provider, key, () => a.checkin(async () => authCopy(key), JSON.parse(JSON.stringify(p))))) ?? {} const num = (v) => (typeof v === "number" && isFinite(v) ? Math.max(0, v) : 0) const message = typeof r.message === "string" ? r.message : "" if (!checkinOutcomes.includes(r.outcome)) { @@ -2301,13 +2380,19 @@ async function fetchAs(id, record, key, params) { for (const [k, v] of Object.entries(sdkHeaders(npm, o.apiKey))) h.set(k, v) for (const [k, v] of Object.entries(o.headers ?? {})) h.set(k, String(v)) for (const [k, v] of Object.entries(headers ?? {})) h.set(k, v) - // chat.headers: what the plugins add to the request, theirs winning - const p = await info(provider, key) - checkFetch(record) - const m = p.models[model] ?? { id: model, providerID: provider, api: { id: model, npm } } - for (const x of hooks) { + // chat.headers: what the plugins add to the request, theirs winning. + // They are told the provider as info builds it once for the account + // (infoOf), the one object every request is told, as OpenCode tells + // them the provider it keeps + const said = hooks.filter((x) => typeof x.hooks["chat.headers"] === "function") + let p, m + if (said.length) { + p = await infoOf(provider, key) + checkFetch(record) + m = p.models[model] ?? { id: model, providerID: provider, api: { id: model, npm } } + } + for (const x of said) { const fn = x.hooks["chat.headers"] - if (typeof fn !== "function") continue const out = { headers: {} } try { await fn( @@ -2355,7 +2440,8 @@ async function fetchAs(id, record, key, params) { // the loop leaves rather than parking on a stream that never drains for await (const chunk of res.body) { checkFetch(record) - const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + // a chunk the stream handed over is this reader's: viewed, not copied + const bytes = Buffer.isBuffer(chunk) ? chunk : ArrayBuffer.isView(chunk) ? Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) : Buffer.from(chunk) for (let off = 0; off < bytes.length; ) { // one frame at a time, no more than the reader has credited: a // reader that stopped leaves the upstream paused here @@ -2364,7 +2450,7 @@ async function fetchAs(id, record, key, params) { if (n <= 0) break const data = bytes.subarray(off, off + n).toString("base64") gate.spend(n + FRAME_OVERHEAD) - await sendForFetch(record, { id, event: "chunk", data }) + await sendForFetch(record, chunkLine(id, data)) checkFetch(record) off += n } @@ -2419,6 +2505,9 @@ const handlers = { // plugin reads them when it next asks (#2038) setProviderOptions(p) { chosen = p?.options ?? {} + // a models hook may list by them + infos.clear() + infoGen++ return null }, // check tries one account as a request would: its loader, then its @@ -2464,7 +2553,7 @@ const handlers = { if (!Object.keys(out).length) return false }) for (const k of Object.keys(out)) { - loaders.delete(k) + forgetAccount(k) send({ event: "auth", provider: providerOf(k), account: k }) } return { auths: out } @@ -2476,7 +2565,7 @@ const handlers = { return null }, reload(p) { - for (const k of p.account ? [p.account] : accountsOf(readAuth(), p.provider)) loaders.delete(k) + for (const k of p.account ? [p.account] : accountsOf(readAuth(), p.provider)) forgetAccount(k) return null }, } diff --git a/internal/plugin/host_flow_test.go b/internal/plugin/host_flow_test.go index 54d8eaedc..4c0a52632 100644 --- a/internal/plugin/host_flow_test.go +++ b/internal/plugin/host_flow_test.go @@ -84,7 +84,7 @@ const context = vm.createContext({ process: { stdout, stdin: {}, exit: () => { throw Error('unexpected exit') } }, readline: { createInterface: () => rl }, options: async () => ({ fetch: async () => context.reply }), - info: async () => ({ models: {} }), + infoOf: async () => ({ models: {} }), sdkHeaders: () => ({}), bodyOf: () => undefined, accountKey: () => '', via: { run: (_, fn) => fn() }, inScope: (_, key, fn) => fn(), @@ -121,6 +121,34 @@ async function main() { assert.equal(await run('gate.take(64)'), 64) run('gate.stop(); gate.add(1)') assert.equal(await run('gate.take(64)'), -1, 'stopped gate refuses remaining credit') + } else if (name === 'chunk-frames') { + const parts = [new Uint8Array([0, 1, 2, 250, 251, 252]), Buffer.from('data: {"a":"\\u00e9 \\"q\\""}\n\n'), new Uint8Array(70 << 10).fill(65)] + context.reply.body = (async function* () { for (const p of parts) yield p })() + let copies = 0 + let stringified = 0 + const realJSON = run('JSON') + context.Buffer = new Proxy(Buffer, { get(target, key) { + if (key !== 'from') return Reflect.get(target, key) + return (...args) => { + if (args.length === 1 && ArrayBuffer.isView(args[0])) copies++ + return target.from(...args) + } + } }) + context.JSON = { parse: realJSON.parse, stringify: (v, ...rest) => { + if (v && v.event === 'chunk') stringified++ + return realJSON.stringify(v, ...rest) + } } + fetchOne() + await until(idle, 'streamed fetch settles') + context.Buffer = Buffer + delete context.JSON + const chunks = lines.filter(msg => msg.event === 'chunk') + assert.ok(chunks.every(msg => msg.id === 1), 'every frame is the fetch\'s') + assert.equal(chunks.length, 4, 'a chunk over 64 KB goes in two frames') + assert.deepEqual(Buffer.concat(chunks.map(msg => Buffer.from(msg.data, 'base64'))), Buffer.concat(parts)) + assert.deepEqual(lines.map(msg => msg.event || 'result'), ['head', 'chunk', 'chunk', 'chunk', 'chunk', 'result']) + assert.equal(stringified, 0, 'chunk frames are joined, not stringified') + assert.equal(copies, 0, 'chunks are viewed, not copied') } else if (name === 'split-chunk') { blockOn = 'chunk' context.reply.body = (async function* () { yield Buffer.alloc(3 * (64 << 10)) })() @@ -225,10 +253,13 @@ async function main() { if (stage === 'options') { entered = true; await barrier } return { fetch: async () => { vendorCalls++; return context.reply } } } - context.info = async () => { + context.infoOf = async () => { if (stage === 'info') { entered = true; await barrier } return { models: {} } } + // a request is told the provider only for a chat.headers hook + run('hooks.length = 0') + if (stage === 'info') run('hooks.push({ spec: "t", hooks: { "chat.headers": async () => {} } })') fetchOne() await until(() => entered, 'plugin setup entered its deferred await') assert.equal(run('inflight.get(1).state'), 'setup') @@ -239,7 +270,7 @@ async function main() { await until(idle, 'cancelled setup finishes') assert.equal(vendorCalls, 0, 'cancelled setup never starts vendor') context.options = async () => ({ fetch: async () => { vendorCalls++; return context.reply } }) - context.info = async () => ({ models: {} }) + context.infoOf = async () => ({ models: {} }) fetchOne() await until(idle, 'healthy fetch after cancelled setup') assert.equal(vendorCalls, 1) @@ -648,6 +679,20 @@ func TestFlowBigReplyProd(t *testing.T) { // vendor's head — leave the host able to answer a later request. It is the Go // side of the lifecycle: the host's slots come back, and the JS side's own // finally (covered by construction) lets each request's controller and gate go. +// TestHostFramesChunksCheaply: the body's chunks go out as the same frames, +// but without copying each chunk or stringifying each frame: stringify +// scanned every base64 byte for something to escape, which cost more than +// the base64. +func TestHostFramesChunksCheaply(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("no node on PATH") + } + if out, err := runHostJSCase(t, node, "chunk-frames"); err != nil { + t.Fatalf("chunk frames: %v\n%s", err, out) + } +} + func TestFlowAbortDuringSetupStaysHealthy(t *testing.T) { node, err := exec.LookPath("node") if err != nil { diff --git a/internal/plugin/info_once_test.go b/internal/plugin/info_once_test.go new file mode 100644 index 000000000..e3ceb50b2 --- /dev/null +++ b/internal/plugin/info_once_test.go @@ -0,0 +1,101 @@ +package plugin + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// A request is told the provider as info builds it once for its account, +// not built again for every fetch: each build asked the plugin's models +// hook, and with it the vendor once the plugin's own list was due, before +// the request went. A new sign-in or new options build it again, once. +func TestFetchBuildsInfoOnce(t *testing.T) { + sandbox(t) + var mu sync.Mutex + var told []string // x-plugin-model, as chat.headers set it, and x-models, as the loader was told them + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + told = append(told, r.Header.Get("x-plugin-model")+" "+r.Header.Get("x-models")) + mu.Unlock() + io.WriteString(w, "ok") + })) + defer srv.Close() + t.Setenv("FAKE_BASE", srv.URL+"/v1") + log := filepath.Join(t.TempDir(), "models.log") + t.Setenv("FAKE_MODELS_LOG", log) + asked := func() int { + b, _ := os.ReadFile(log) + return strings.Count(string(b), "asked") + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := Providers(ctx); err != nil { + t.Fatal(err) + } + if _, err := APIKey(ctx, "fakeco", 0, nil, "k1", NewAccount); err != nil { + t.Fatal(err) + } + fetch := func() { + t.Helper() + res, err := Fetch(ctx, FetchRequest{Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible", + URL: srv.URL + "/v1/chat/completions", Method: "POST", Body: []byte(`{}`)}) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + if string(b) != "ok" { + t.Fatalf("answered %q", b) + } + } + fetch() + n := asked() + for range 20 { + fetch() + } + if got := asked() - n; got != 0 { + t.Fatalf("20 requests asked the models hook %d more times, want 0", got) + } + mu.Lock() + for _, m := range told { + if m != "fake-1 fake-1,fake-claude,fake-gemini" { + t.Fatalf("chat.headers and the loader were told %q, want fake-1 and every model", m) + } + } + mu.Unlock() + + // a new sign-in for the account: built again, once + if err := Restore(ctx, "fakeco", "fakeco", map[string]any{"type": "api", "key": "k2"}); err != nil { + t.Fatal(err) + } + n = asked() + for range 5 { + fetch() + } + if got := asked() - n; got != 1 { + t.Fatalf("after a new sign-in 5 requests asked the models hook %d times, want 1", got) + } + // new options: built again, once + if err := SetProviderOptions(ctx); err != nil { + t.Fatal(err) + } + n = asked() + for range 5 { + fetch() + } + if got := asked() - n; got != 1 { + t.Fatalf("after new options 5 requests asked the models hook %d times, want 1", got) + } +} diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 56b603a91..72bfe1f83 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -810,6 +810,9 @@ type Authorization struct { URL string `json:"url"` Instructions string `json:"instructions"` Method string `json:"method"` + // Opened is a page the plugin (its vendor's CLI) opened already, not + // to be opened again + Opened bool `json:"opened"` } // NewAccount is the account a sign-in goes to when it is a new one: the diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index 9981f08a0..8f7154d09 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -87,6 +87,8 @@ export const FakePlugin = async ({ client }) => ({ if (process.env.FAKE_GROK) cfg.provider[ID].models["grok-4.7"] = { name: "Grok 4.7", provider: { npm: "@ai-sdk/openai" }, limit: { context: 4000, output: 400 } } // $FAKE_DEEPSEEK: a DeepSeek model, as Cline's cline-pass/deepseek-v4-pro if (process.env.FAKE_DEEPSEEK) cfg.provider[ID].models["deepseek-v4-pro"] = { name: "DeepSeek V4 Pro", limit: { context: 1000, output: 100 } } + // $FAKE_GLM: a GLM model, as Cline's cline-pass/glm-5.3 + if (process.env.FAKE_GLM) cfg.provider[ID].models["glm-5.3"] = { name: "GLM 5.3", limit: { context: 1000, output: 100 } } // $FAKE_SEARCHES: the provider's upstream searches by itself (#2027), // as a plugin in front of Claude's API says if (process.env.FAKE_SEARCHES) cfg.provider[ID].searches = true @@ -132,6 +134,9 @@ export const FakePlugin = async ({ client }) => ({ url: "https://fake.invalid/auth?where=" + inputs.where, instructions: "Paste the code", method: "code", + // team "cli-opened": the page is open already, as Grok Build's + // `grok login` opens its own on macOS and Windows + opened: inputs.team === "cli-opened", callback: async (code) => (process.env.FAKE_SIGNIN && (await fetch(process.env.FAKE_SIGNIN + "/token").catch(() => {})), code === "good") ? { type: "success", refresh: "r-" + (inputs.team ?? "none"), access: "stale", expires: 0, ...fakeWho(inputs.team) } @@ -240,6 +245,8 @@ export const FakePlugin = async ({ client }) => ({ provider: { id: ID, models: async (p, { auth }) => { + // $FAKE_MODELS_LOG: each time the hook is asked is a line there + if (process.env.FAKE_MODELS_LOG) (await import("node:fs")).appendFileSync(process.env.FAKE_MODELS_LOG, "asked\n") if (auth?.refresh === "r-dead" || auth?.key === "dead") throw new Error("the vendor refused the sign-in") if (auth?.refresh === "r-models-gone") throw Object.assign(new Error("the vendor refused the sign-in"), { signIn: "expired" }) // a sign-in past its time, said in words only, as Grok's plugin says it diff --git a/internal/provider/account_test.go b/internal/provider/account_test.go index 3230a4d2c..af677c910 100644 --- a/internal/provider/account_test.go +++ b/internal/provider/account_test.go @@ -68,7 +68,7 @@ func signIn(t *testing.T) string { // isolate keeps tests off the machine's own Claude Code Keychain // logins and forgets anything a previous test cached. -func isolate(t *testing.T) { +func isolate(t testing.TB) { t.Helper() oldKeychain, oldBase, oldExe := claudeKeychain, claudeBase, claudeExecutable oldDevin := DevinExecutable diff --git a/internal/provider/autoref.go b/internal/provider/autoref.go new file mode 100644 index 000000000..dda4f185a --- /dev/null +++ b/internal/provider/autoref.go @@ -0,0 +1,218 @@ +package provider + +// The id agents are given for a group magpie found (ZeroClover on X): "auto/", +// the model's own id as a vendor spells it (auto/claude-opus-5.5), so that a +// client reading the part after the slash as a model id — as models.dev keys +// its models — knows the model. It was "group/auto-" (Slug's, dots +// dashed), which nothing outside magpie could read, and that id is still +// served as it was, forever: agents' configs, gateway keys, saved groups and +// rules hold it. +// +// Inside magpie a found group stays "group/auto-": providers.json's +// members, rules and classifiers, the gateway's routing, a key's limits and +// the usage log keep that one id, so a group is counted under one name +// whichever an agent sent (CanonicalRef, taken back in the gateway before +// anything reads the request). The catalog lists the group by its public id +// (Group.Ref), so every list and config that is built from the catalog — +// /v1/models, the model lists written into agents, the pickers — names it so. +// +// "auto" is not a provider's id: Save and Rename refuse it, and a plugin +// that calls its provider auto is auto-plugin (PluginID). One of the user's +// own saved as "auto" before keeps its models: while it is there, auto/ +// is its model x, and found groups are listed as group/auto- as before +// (autoRefsOn). + +import ( + "errors" + "slices" + "strings" + "unicode" + + "github.com/yetone/magpie/internal/catalog" +) + +// AutoPrefix starts the id agents are given for a group magpie found: +// "auto/". +const AutoPrefix = "auto/" + +// autoID is the provider id that would take auto/ for its own. +const autoID = "auto" + +// errAutoID refuses "auto" as a new provider's id: auto/ names the +// groups magpie finds. +var errAutoID = errors.New(`"auto" starts the ids of the groups magpie finds (auto/); pick another id`) + +// autoRefsOn reports whether auto/ names found groups: unless the +// user has a provider of their own with the id "auto", saved before the +// id was kept for found groups, whose models it stays. +func autoRefsOn() bool { return !customIDs()[autoID] } + +// AutoRefsOn is autoRefsOn, for the packages that spell a group's id. +func AutoRefsOn() bool { return autoRefsOn() } + +// autoGroupOfRef is the group id auto/ names, model as any vendor +// spells it: the id magpie gives the group it finds for the model +// (AutoGroupID). +func autoGroupOfRef(model string) string { return AutoGroupID(model) } + +// IsGroupRef reports whether ref names a routing group: group/, or a +// found group's auto/. +func IsGroupRef(ref string) bool { + _, ok := GroupIDOf(ref) + return ok +} + +// CanonicalRef is ref as magpie keeps it: a found group's auto/ as +// group/auto-, an effort after it (":high") and Claude Code's [1m] +// mark kept; any other ref as it is. The gateway takes a request's model +// back to it before key limits, routing and the usage log see it, so the +// two ids of one group are one. +func CanonicalRef(ref string) string { + s := strings.TrimSpace(ref) + s, marked := strings.CutSuffix(s, "[1m]") + m, ok := strings.CutPrefix(s, AutoPrefix) + if !ok || strings.TrimSpace(m) == "" || !autoRefsOn() { + return ref + } + level := "" + if i := strings.LastIndex(m, ":"); i > 0 && slices.Contains(MemberEfforts, strings.ToLower(m[i+1:])) { + m, level = m[:i], ":"+strings.ToLower(m[i+1:]) + } + gid := autoGroupOfRef(m) + if gid == "auto-" { + return ref + } + out := GroupPrefix + gid + level + if marked { + out += "[1m]" + } + return out +} + +// canonicalRefs spells every model or group g names as magpie keeps it +// (CanonicalRef): a found group a picker listed as auto/ is stored +// as group/auto-, so its members, off and fast lists, weights, rules +// and classifier name it by one id. g's lists are its own (Group.own). +func (g *Group) canonicalRefs() { + for _, l := range [][]string{g.Members, g.Off, g.Fast} { + for i, v := range l { + l[i] = CanonicalRef(v) + } + } + for k, v := range g.Weights { + if c := CanonicalRef(k); c != k { + delete(g.Weights, k) + g.Weights[c] = v + } + } + for i := range g.Rules { + g.Rules[i].Use = CanonicalRef(g.Rules[i].Use) + } + g.Classifier = CanonicalRef(g.Classifier) +} + +// SameRef reports whether a and b name the same model or group, a found +// group by either of its ids. +func SameRef(a, b string) bool { + return a == b || CanonicalRef(a) == CanonicalRef(b) +} + +// Ref is the id agents pick the group by: auto/ for a group magpie +// found (one with an auto-… id whose members are that model), its model +// spelt as a vendor spells it; group/ for any other, and for every +// group while a provider of the user's is called auto. +func (g Group) Ref() string { + if g.Spelled != "" && autoRefsOn() { + return AutoPrefix + g.Spelled + } + return GroupPrefix + g.ID +} + +// PublicRef is the id agents are given for ref: a found group's +// group/auto- as its auto/ (Group.Ref), its effort and [1m] +// mark kept; any other ref as it is, a found group magpie has none of now +// too. +func PublicRef(ref string) string { + s := strings.TrimSpace(ref) + s, marked := strings.CutSuffix(s, "[1m]") + gid, ok := strings.CutPrefix(s, GroupPrefix) + if !ok || !strings.HasPrefix(gid, "auto-") || !autoRefsOn() { + return ref + } + level := "" + if i := strings.LastIndex(gid, ":"); i > 0 { + gid, level = gid[:i], gid[i:] + } + g, ok := groupOf(Groups(), gid) + if !ok || g.Spelled == "" { + return ref + } + out := g.Ref() + level + if marked { + out += "[1m]" + } + return out +} + +// spelledIn is how the model of a found group's id is spelt by a vendor +// (Group.Spelled): of the members whose model merges into the group by its +// own id (mergeKey), the first models.dev lists by that very spelling, else +// the first; failing those, the model the user said a member is the same +// as (settings' ModelSameAs). Without a vendor's prefix ("anthropic/"). +// "" for a group whose id is not auto-…, or none of whose members is its +// model: one the user made, whatever it is called, stays group/. +func spelledIn(g Group, same map[string]string) string { + if !strings.HasPrefix(g.ID, "auto-") { + return "" + } + var own, alike []string + for _, id := range g.Members { + if strings.HasPrefix(id, GroupPrefix) || IsPattern(id) { + continue + } + model, _ := MemberEffort(id) + pid, m, ok := strings.Cut(model, "/") + if !ok || m == "" { + continue + } + if v := same[pid+"/"+m]; v != "" { + if "auto-"+Slug(sameModel(v)) == g.ID { + alike = append(alike, lastPart(v)) + } + continue + } + if "auto-"+Slug(sameModel(m)) == g.ID { + own = append(own, lastPart(m)) + } + } + // an id a relay lists as its display name ("GPT-6 Sol") is no id to + // put in an agent's config: the one vendors agree on is, below + spaced := func(s string) bool { return strings.ContainsFunc(s, unicode.IsSpace) } + spacedOnly := len(own)+len(alike) > 0 + own, alike = slices.DeleteFunc(own, spaced), slices.DeleteFunc(alike, spaced) + for _, s := range own { + if catalog.Lists(s) { + return s + } + } + if len(own) > 0 { + return own[0] + } + if len(alike) > 0 { + return alike[0] + } + if spacedOnly { + return strings.TrimPrefix(g.ID, "auto-") + } + return "" +} + +// lastPart is a model's id without a vendor's prefix: what follows its +// last slash, trimmed. +func lastPart(m string) string { + m = strings.TrimSpace(m) + if i := strings.LastIndex(m, "/"); i >= 0 { + m = m[i+1:] + } + return m +} diff --git a/internal/provider/autoref_test.go b/internal/provider/autoref_test.go new file mode 100644 index 000000000..29daa0576 --- /dev/null +++ b/internal/provider/autoref_test.go @@ -0,0 +1,207 @@ +package provider + +import ( + "errors" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +// autoRefHome is a sandbox HOME with two providers serving Claude Opus 5.5, +// each spelling it its own way, and a models.dev catalog listing it as +// Anthropic spells it, with its window and reply limit. +func autoRefHome(t *testing.T) { + t.Helper() + isolate(t) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(catalog.CachePath(), []byte(`{"anthropic": {"models": { + "claude-opus-5.5": {"id":"claude-opus-5.5","name":"Claude Opus 5.5","limit":{"context":400000,"output":96000}}}}}`), 0o644); err != nil { + t.Fatal(err) + } + catalog.Reset() + t.Cleanup(catalog.Reset) + for id, m := range map[string]string{"a": "claude-opus-5-5", "b": "claude-opus-5.5"} { + if err := Save(Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{m, "x"}}); err != nil { + t.Fatal(err) + } + } +} + +// A group magpie found is listed as auto/, the model's id as a +// vendor spells it (ZeroClover on X), so a client looking the part after +// the slash up on models.dev finds the model; its old group/auto- is +// the same group, and a group the user made stays group/. +func TestFoundGroupListedByItsModelsID(t *testing.T) { + autoRefHome(t) + if err := SaveGroup(Group{Name: "Mine", Members: []string{"a/x", "b/x"}}); err != nil { + t.Fatal(err) + } + refs := map[string]string{} + for _, g := range Groups() { + refs[g.ID] = g.Ref() + } + if refs["auto-claude-opus-5-5"] != "auto/claude-opus-5.5" { + t.Errorf("the found group's id: %q", refs["auto-claude-opus-5-5"]) + } + if refs["mine"] != "group/mine" { + t.Errorf("the user's group's id: %q", refs["mine"]) + } + var e Entry + for _, c := range Catalog() { + if c.Group == "auto-claude-opus-5-5" { + e = c + } + } + if e.ID != "auto/claude-opus-5.5" { + t.Fatalf("the catalog lists the group as %q", e.ID) + } + // what a client does with it: the model's id after auto/, on models.dev + model := strings.TrimPrefix(e.ID, AutoPrefix) + if catalog.ContextOf(model) != 400000 || catalog.OutputOf(model) != 96000 { + t.Errorf("models.dev has %s at %d/%d", model, catalog.ContextOf(model), catalog.OutputOf(model)) + } + if e.Context != 400000 || e.Output != 96000 { + t.Errorf("the group's own limits: %d/%d", e.Context, e.Output) + } + + for in, want := range map[string]string{ + "auto/claude-opus-5.5": "group/auto-claude-opus-5-5", + "auto/anthropic/Claude-Opus-5.5": "group/auto-claude-opus-5-5", + "auto/claude-opus-5-5": "group/auto-claude-opus-5-5", + "auto/claude-opus-5.5:high[1m]": "group/auto-claude-opus-5-5:high[1m]", + "group/auto-claude-opus-5-5": "group/auto-claude-opus-5-5", + "a/claude-opus-5-5": "a/claude-opus-5-5", + "auto/": "auto/", + "openrouter/auto": "openrouter/auto", + } { + if got := CanonicalRef(in); got != want { + t.Errorf("CanonicalRef(%q) = %q, want %q", in, got, want) + } + } + for in, want := range map[string]string{ + "group/auto-claude-opus-5-5": "auto/claude-opus-5.5", + "group/auto-claude-opus-5-5:high[1m]": "auto/claude-opus-5.5:high[1m]", + "group/mine": "group/mine", + "group/auto-gone": "group/auto-gone", + } { + if got := PublicRef(in); got != want { + t.Errorf("PublicRef(%q) = %q, want %q", in, got, want) + } + } + + // both ids are served, as the one group + for _, id := range []string{"auto/claude-opus-5.5", "group/auto-claude-opus-5-5", "auto/claude-opus-5.5[1m]"} { + p, m, ok := Resolve(id) + if !ok || p.ID != e.Provider.ID || m != e.Model { + t.Errorf("Resolve(%q) = %q %q %v, want %q %q", id, p.ID, m, ok, e.Provider.ID, e.Model) + } + if gid, ok := GroupIDOf(id); !ok || gid != "auto-claude-opus-5-5" { + t.Errorf("GroupIDOf(%q) = %q %v", id, gid, ok) + } + } + + // a group picked as a member by its new id is kept by its old one + if err := SaveGroup(Group{ID: "mine", Name: "Mine", Members: []string{"a/x", "auto/claude-opus-5.5"}}); err != nil { + t.Fatal(err) + } + for _, g := range Groups() { + if g.ID == "mine" && !slices.Equal(g.Members, []string{"a/x", "group/auto-claude-opus-5-5"}) { + t.Errorf("stored members: %v", g.Members) + } + } +} + +// "auto" is no new provider's id: auto/ names found groups. One +// the user saved before keeps its models: while it is there, auto/ is +// its model x, and found groups are listed by their old ids. +func TestProviderNamedAuto(t *testing.T) { + autoRefHome(t) + if err := Save(Provider{ID: "auto", Name: "Auto", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"y"}}); !errors.Is(err, errAutoID) { + t.Fatalf("a new provider named auto: %v", err) + } + if err := Rename("a", "auto"); !errors.Is(err, errAutoID) { + t.Fatalf("renaming a provider to auto: %v", err) + } + if PluginID("auto") != "auto-plugin" || PluginID("group") != "group-plugin" { + t.Errorf("plugin ids: %q %q", PluginID("auto"), PluginID("group")) + } + + // one in providers.json from before + raw, err := os.ReadFile(Path()) + if err != nil { + t.Fatal(err) + } + s := strings.Replace(string(raw), `"providers": [`, `"providers": [{"id": "auto", "name": "Auto", "key": "k", "chat": "http://127.0.0.1:1/v1", "models": ["claude-opus-5.5", "y"]},`, 1) + if s == string(raw) { + t.Fatalf("providers.json: %s", raw) + } + if err := os.WriteFile(Path(), []byte(s), 0o600); err != nil { + t.Fatal(err) + } + if _, err := Find("auto"); err != nil { + t.Fatal(err) + } + if AutoRefsOn() { + t.Fatal("auto/ still names found groups beside a provider called auto") + } + for _, id := range []string{"auto/y", "auto/claude-opus-5.5"} { + p, m, ok := Resolve(id) + if !ok || p.ID != "auto" || m != strings.TrimPrefix(id, "auto/") { + t.Errorf("Resolve(%q) = %q %q %v: not the auto provider's model", id, p.ID, m, ok) + } + if CanonicalRef(id) != id { + t.Errorf("CanonicalRef(%q) = %q", id, CanonicalRef(id)) + } + } + var listed []string + for _, e := range Catalog() { + if e.Group != "" { + listed = append(listed, e.ID) + } + } + if !slices.Contains(listed, "group/auto-claude-opus-5-5") || slices.ContainsFunc(listed, func(id string) bool { return strings.HasPrefix(id, AutoPrefix) }) { + t.Errorf("groups listed beside the auto provider: %v", listed) + } + // still the user's to save + p, _ := Find("auto") + p.Name = "Mine" + if err := Save(*p); err != nil { + t.Errorf("saving the stored auto provider: %v", err) + } +} + +// A pick made one model at a time in an agent's lists, saved while a found +// group was listed as group/auto-, holds for it by auto/: a +// group taken out stays out, one picked stays shown, and the order kept. +func TestFoundGroupPicksSavedByTheOldID(t *testing.T) { + autoRefHome(t) + old, now := "group/auto-claude-opus-5-5", "auto/claude-opus-5.5" + s := settings.Load() + s.HiddenModels = map[string][]string{"pi": {old}} + s.PickedModels = map[string][]string{"opencode": {old}} + s.OrderedModels = map[string][]string{"pi": {old, "a/x"}} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if !ModelOff("pi")(now) { + t.Errorf("hidden as %s, listed as %s again", old, now) + } + if ModelOff("opencode")(now) { + t.Errorf("picked as %s, left out as %s", old, now) + } + if got := ModelOrder("pi"); !slices.Equal(got, []string{now, "a/x"}) { + t.Errorf("order: %v", got) + } +} diff --git a/internal/provider/balance.go b/internal/provider/balance.go index 98d491551..a55962093 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -1211,6 +1211,10 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ ctx = p.Via(ctx) p = keyQueryOf(p) src, ok := balanceSourceOf(p) + if !ok && p.Account == nil && p.Key != "" && openCodeZen(p) { + // a balance the vendor keeps from the key: said so, not left out + return "", nil, nil, nil, true, errOpenCodeNoBalance + } if !ok || p.Account != nil || p.Key == "" { return "", nil, nil, nil, false, nil } @@ -1309,6 +1313,35 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ return amount, nil, split, nil, true, err } +// OpenCodeConsole is where OpenCode shows a workspace's credits: the +// Credits card on the console's Overview, to its owners and admins. +const OpenCodeConsole = "https://opencode.ai/console" + +// errOpenCodeNoBalance is a Zen key's balance, which OpenCode tells no +// key: Zen's routes (/zen/v1, the inference API's /inference/v1) have no +// usage or balance query, only Go's /zen/go/v1/usage, which tells Go's +// windows and not the credits (proxyInference's paths in sst/opencode's +// packages/console/app/src/lib/inference-proxy.ts; /zen/v1/usage and +// /inference/v1/usage answer 404), and its docs give the balance only on +// the console's Credits card (console/billing.mdx, "Check your balance"). +// The card used to be left out unsaid (ttmrmx on X). +var errOpenCodeNoBalance = errors.New("OpenCode tells no API key its balance: Zen's pay-as-you-go credits are shown only in the OpenCode console (" + OpenCodeConsole + ", Overview → Credits, to the workspace's owners and admins)") + +// openCodeZen says p is at OpenCode Zen, whose credits OpenCode keeps from +// the key, and not at Go, whose windows are its card (planQuotaSourceOf). +func openCodeZen(p Provider) bool { + zen := false + for _, b := range []string{p.Chat, p.Responses, p.Anthropic} { + switch openCodeGateway(b) { + case "go": + return false + case "zen": + zen = true + } + } + return zen +} + // balanceMethodOf is the HTTP method a Balance URL is asked with: GET // when none is named, else GET or POST in any case. Another is an error, // never a GET in its place. @@ -1409,11 +1442,12 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { continue } src, ok := balanceSourceOf(p) - if !ok && !clineKeyCard(p) { + zen := !ok && openCodeZen(p) + if !ok && !clineKeyCard(p) && !zen { continue } others := 0 - if src.token != "" { + if src.token != "" || zen { // the account's balance is the same whichever key asks jobs = append(jobs, job{p, ""}) continue @@ -1473,6 +1507,12 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { if errors.Is(err, errNoBalance) { return // a reply with no balance for this key: no card } + if errors.Is(err, errOpenCodeNoBalance) { + // nothing to read or keep: where the balance is shown + q.Error, q.SeeAt = err.Error(), OpenCodeConsole + out[i] = q + return + } if err != nil { q.Error = err.Error() } else { diff --git a/internal/provider/bare.go b/internal/provider/bare.go index b68236e38..90d78a5e1 100644 --- a/internal/provider/bare.go +++ b/internal/provider/bare.go @@ -77,7 +77,7 @@ func bareTarget(shown []Entry, all []Group, entries []Entry, id string) int { if !strings.Contains(id, "/") { if gid, ok := groupForIn(all, id); ok { for i, e := range shown { - if e.ID == gid { + if e.ID == gid || e.Group != "" && GroupPrefix+e.Group == gid { return i } } diff --git a/internal/provider/cline.go b/internal/provider/cline.go index bd72719da..38f66043a 100644 --- a/internal/provider/cline.go +++ b/internal/provider/cline.go @@ -174,16 +174,28 @@ func (p Provider) ClinePinnable() bool { return p.IsCline() || p.PluginProvider() == "cline" } +// clineMakers maps a model name's start to its maker's own upstream on +// Cline's AI gateway (Vercel's AI Gateway, whose provider slugs these +// are: ai-gateway.vercel.sh/v1/models//endpoints lists "deepseek" +// for deepseek/deepseek-v4-pro and "zai" for zai/glm-5.3). +var clineMakers = []struct{ prefix, upstream string }{ + {"deepseek", "deepseek"}, + {"glm", "zai"}, // sdytman on Discord: GLM only through Z.ai +} + // ClinePin is the upstream a request for model is pinned to on p -// (PinUpstream): "deepseek" for a DeepSeek model of the Cline API, "" -// for anything else. Cline's free models are served where Cline puts -// them, so they never are. +// (PinUpstream): "deepseek" for a DeepSeek model of the Cline API, "zai" +// for a GLM one, "" for anything else. Cline's free models are served +// where Cline puts them, so they never are. func (p Provider) ClinePin(model string) string { if !p.PinUpstream || !p.ClinePinnable() || strings.HasPrefix(model, clineFreePrefix) { return "" } - if name := model[strings.LastIndex(model, "/")+1:]; strings.HasPrefix(strings.ToLower(name), "deepseek") { - return "deepseek" + name := strings.ToLower(model[strings.LastIndex(model, "/")+1:]) + for _, m := range clineMakers { + if strings.HasPrefix(name, m.prefix) { + return m.upstream + } } return "" } diff --git a/internal/provider/closest.go b/internal/provider/closest.go index c742a05ca..a805f2870 100644 --- a/internal/provider/closest.go +++ b/internal/provider/closest.go @@ -65,8 +65,8 @@ func Closest(asked string, n int) []string { names := slices.Concat(nameWords(e.Name), nameWords(e.Default)) model := nameWords(e.Model) var from []string - if strings.HasPrefix(e.ID, GroupPrefix) { - model = nameWords(strings.TrimPrefix(e.ID, GroupPrefix)) + if e.Group != "" { + model = nameWords(e.Group) } else { from = slices.Concat(nameWords(e.Provider.ID), nameWords(e.Provider.Name)) } diff --git a/internal/provider/codex_zstd.go b/internal/provider/codex_zstd.go index 0ba506699..2ca1d7256 100644 --- a/internal/provider/codex_zstd.go +++ b/internal/provider/codex_zstd.go @@ -31,11 +31,25 @@ import ( // Codex's codex-rs/http-client/src/request.rs uses // zstd::stream::encode_all(.., 3), whose unknown-size stream has a 2 MiB // window. Keep turns within that client envelope too. -var codexZstd, _ = zstd.NewWriter(nil, - zstd.WithEncoderLevel(zstd.SpeedDefault), - zstd.WithEncoderCRC(false), - zstd.WithWindowSize(2<<20), -) +// +// The encoder keeps one coder per concurrent EncodeAll, GOMAXPROCS by +// default, and each keeps its history (4 MiB at a 2 MiB window) for the +// life of the process: 74 MB of a live gateway's 288 MB heap on a 14-core +// Mac. A 1 MiB turn encodes in about half a millisecond, so two coders in +// low-memory mode keep up with dozens of agents and hold ~9 MB. Neither +// option changes the bytes sent. +var codexZstd = newCodexZstd() + +func newCodexZstd() *zstd.Encoder { + z, _ := zstd.NewWriter(nil, + zstd.WithEncoderLevel(zstd.SpeedDefault), + zstd.WithEncoderCRC(false), + zstd.WithWindowSize(2<<20), + zstd.WithEncoderConcurrency(2), + zstd.WithLowerEncoderMem(true), + ) + return z +} // codexZstdOff leaves turns plain, for tests alone: the fake backends of // most of the gateway's and provider's tests read the body as it comes, so diff --git a/internal/provider/codex_zstd_test.go b/internal/provider/codex_zstd_test.go index cf3402ada..e5660b3ae 100644 --- a/internal/provider/codex_zstd_test.go +++ b/internal/provider/codex_zstd_test.go @@ -11,7 +11,9 @@ import ( "math/rand/v2" "net/http" "net/http/httptest" + "runtime" "strings" + "sync" "testing" "github.com/klauspost/compress/zstd" @@ -151,3 +153,34 @@ func TestCodexWarmGoesZstd(t *testing.T) { t.Fatalf("warmed %q: %v", enc, got) } } + +// The encoder's coders and their histories live as long as the process, so +// how many it keeps is set by magpie, not by the machine's cores: 28 turns +// of 1 MiB at once on 16 cores held ~96 MB with the library's default of a +// coder per core. +func TestCodexZstdHoldsLittle(t *testing.T) { + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(16)) + var b bytes.Buffer + for i := 0; b.Len() < 1<<20; i++ { + b.WriteString(`{"role":"user","content":"line `) + b.WriteString(strings.Repeat("x", i*7919%61)) + b.WriteString(`"},`) + } + src := b.Bytes() + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + z := newCodexZstd() + var wg sync.WaitGroup + for range 28 { + wg.Add(1) + go func() { defer wg.Done(); z.EncodeAll(src, nil) }() + } + wg.Wait() + runtime.GC() + runtime.ReadMemStats(&after) + if held := int64(after.HeapInuse) - int64(before.HeapInuse); held > 24<<20 { + t.Fatalf("the encoder holds %d MB after 28 turns at once", held>>20) + } + runtime.KeepAlive(z) +} diff --git a/internal/provider/compact.go b/internal/provider/compact.go index a16e1a4ea..136cb58de 100644 --- a/internal/provider/compact.go +++ b/internal/provider/compact.go @@ -54,7 +54,8 @@ func CompactFor(s settings.Settings, e Entry, find func(string) (Group, []Member // WindowTyped says the window agents are told for a model, by its // catalog id (as CompactSet takes it), is one the user typed: the // group's own size, a group's smallest member's that the user typed -// (smallestWindow, #2224), or one set on the provider for the model or +// (smallestWindow, #2224), its largest member's when it names no size +// and the user typed that one (largestWindow), or one set on the provider for the model or // all of its models. Claude Code then isn't handed magpie's default // compaction window for it (CompactFor's rule, as Entry.WindowSet). func WindowTyped(id string) bool { @@ -75,6 +76,8 @@ func WindowTyped(id string) bool { case g.Context == ContextSmallest: _, typed := smallestWindow(entries, membersIn(entries, all, g)) return typed + case g.Context == 0: + return largestWindow(entries, g) } return false } @@ -111,9 +114,10 @@ func ClaudeGroup(id string) bool { } // catalogID is an agent's model id as the catalog has it: magpie/ and -// Claude Code's [1m] mark taken off. +// Claude Code's [1m] mark taken off, a found group's auto/ as +// group/auto- (CanonicalRef). func catalogID(id string) string { - return strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(id), "magpie/"), "[1m]") + return CanonicalRef(strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(id), "magpie/"), "[1m]")) } func compactSet(s settings.Settings, id string, find func(string) (Group, []Member, bool)) int { diff --git a/internal/provider/decide.go b/internal/provider/decide.go index 3485b2be4..04334b0c8 100644 --- a/internal/provider/decide.go +++ b/internal/provider/decide.go @@ -150,10 +150,18 @@ func openRouterDecisions(base string) string { } // listsDecisions reports whether p's decision models are a list of their -// own, OpenRouter's, oMLX's (omlxDecides) or MLX-Serve's (mlxServeDecides), +// own, OpenRouter's or a server's that marks them (serverMarksDecisions), // rather than Jev's ids among its chat models. func (p Provider) listsDecisions() bool { - return openRouterDecisions(p.Decide) != "" || p.omlxDecides() || p.mlxServeDecides() + return openRouterDecisions(p.Decide) != "" || p.serverMarksDecisions() +} + +// serverMarksDecisions reports whether p's server says which of the models +// it serves are decision models, oMLX's (omlxDecides), MLX-Serve's +// (mlxServeDecides) or Ollama's (ollamaDecides): it has no Jev of its own, +// and lists none while it has none. +func (p Provider) serverMarksDecisions() bool { + return p.omlxDecides() || p.mlxServeDecides() || p.ollamaDecides() } // decisionsID is where a provider that serves conversations too keeps the @@ -195,7 +203,7 @@ func (p Provider) decideListDue() bool { return false } live, _, ok := catalog.Live(id) - if p.omlxDecides() || p.mlxServeDecides() { + if p.serverMarksDecisions() { // a server with no decision model loaded lists none, for good return !ok } @@ -281,8 +289,8 @@ func (p Provider) Jev() string { } // OpenRouter's Jev is ~typesafe/jev-latest, in its list of decision // models; its Jev Router is a chat model - if p.omlxDecides() || p.mlxServeDecides() { - // oMLX and MLX-Serve have no Jev of their own: their first decision + if p.serverMarksDecisions() { + // oMLX, MLX-Serve and Ollama have no Jev of their own: their first decision // model, if any if ms := p.decideListed(); len(ms) > 0 { return ms[0].ID @@ -389,7 +397,7 @@ func (p Provider) decideListed() []catalog.Model { if live, _, ok := catalog.Live(decisionsID(p.ID)); ok && len(live) > 0 { return live } - if p.omlxDecides() || p.mlxServeDecides() { + if p.serverMarksDecisions() { return nil // none until its server says which } return []catalog.Model{{ID: OpenRouterJev, Name: "Jev"}} @@ -818,6 +826,8 @@ func (p Provider) fetchDecide(ctx context.Context) ([]catalog.Model, error) { list = omlxDecisions(p.Decide) } else if p.mlxServeDecides() { list = mlxServeDecisions(p.Decide) + } else if p.ollamaDecides() { + list = ollamaDecisions(p.Decide) } else if bailianDecides(p.Decide) { // Bailian lists its chat models only: its decision model is asked return p.decideAsked(ctx) @@ -860,6 +870,14 @@ func (p Provider) fetchDecide(ctx context.Context) ([]catalog.Model, error) { } return ms, catalog.SaveLive(decisionsID(p.ID), p.Decide, ms) } + if p.ollamaDecides() { + // none is an answer too: no model of the server's is one + ms, err := listedOllamaDecide(p.Decide, b) + if err != nil { + return nil, fmt.Errorf("%s: %s", p.Name, err) + } + return ms, catalog.SaveLive(decisionsID(p.ID), p.Decide, ms) + } ms, err := listedDecide(b, all) if (err != nil || len(ms) == 0) && own { return p.decideAsked(ctx) diff --git a/internal/provider/decide_group.go b/internal/provider/decide_group.go index 5b2acabbb..fd4fc5852 100644 --- a/internal/provider/decide_group.go +++ b/internal/provider/decide_group.go @@ -19,7 +19,7 @@ import ( // "provider/model" whose provider answers model at its decision API, on // or not. A group, or a member with an effort of its own, is not one. func decidingMember(id string) bool { - if strings.HasPrefix(id, GroupPrefix) { + if IsGroupRef(id) { return false } if IsDecider(id) { diff --git a/internal/provider/disabled.go b/internal/provider/disabled.go index b35585807..724d14f98 100644 --- a/internal/provider/disabled.go +++ b/internal/provider/disabled.go @@ -34,6 +34,22 @@ var lastDisabled struct { // disabledList is the patterns in force, and unknown when settings.json // couldn't be read and none was read before. func disabledList() (list []string, unknown bool) { + // read once while a request holds the catalog: each group's members + // (membersIn) asked for it, and parsed settings.json each time + r := heldOf("disabled", func() disabledRead { + list, unknown := readDisabled() + return disabledRead{slices.Clip(list), unknown} + }) + return r.list, r.unknown +} + +type disabledRead struct { + list []string + unknown bool +} + +// readDisabled is disabledList read from settings.json now. +func readDisabled() (list []string, unknown bool) { s, err := settings.LoadChecked() lastDisabled.Lock() defer lastDisabled.Unlock() diff --git a/internal/provider/fastpick.go b/internal/provider/fastpick.go index c31cee0fe..c2ab34a24 100644 --- a/internal/provider/fastpick.go +++ b/internal/provider/fastpick.go @@ -106,7 +106,7 @@ func SetFastTier(agent, id, tier string) error { return fmt.Errorf("magpie knows no tier %q", tier) } if tier != "" { - if strings.HasPrefix(id, GroupPrefix) { + if IsGroupRef(id) { return fmt.Errorf("%s is a routing group: its members are sent fast as it says, on the Routing page", id) } p, model, ok := Resolve(id) diff --git a/internal/provider/group.go b/internal/provider/group.go index d641b5dd0..241d3955d 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -28,6 +28,7 @@ import ( "regexp" "slices" "strings" + "sync/atomic" "time" "github.com/yetone/magpie/internal/catalog" @@ -37,11 +38,12 @@ import ( // GroupPrefix starts a group's id in the catalog: "group/". const GroupPrefix = "group/" -// GroupIDOf is the group id a ref names ("group/"), with spaces and the -// [1m] mark Claude Code puts on a 1M window taken off, as an agent's own -// settings carry it. ok is false for a ref that isn't a group's. +// GroupIDOf is the group id a ref names ("group/", or a found group's +// "auto/": CanonicalRef), with spaces and the [1m] mark Claude Code +// puts on a 1M window taken off, as an agent's own settings carry it. ok is +// false for a ref that isn't a group's. func GroupIDOf(ref string) (string, bool) { - return strings.CutPrefix(strings.TrimSuffix(strings.TrimSpace(ref), "[1m]"), GroupPrefix) + return strings.CutPrefix(CanonicalRef(strings.TrimSuffix(strings.TrimSpace(ref), "[1m]")), GroupPrefix) } // Affinities are how long a conversation stays with the key or account that @@ -235,6 +237,10 @@ type Group struct { // Auto is set on a group magpie found: one model served by several // providers. It is derived, never stored. Auto bool `json:"auto,omitempty"` + // Spelled is how a vendor spells the model of a group magpie found + // (auto-…), which agents are given it by: auto/ (Ref). It is + // derived from the members each time the groups are read, never stored. + Spelled string `json:"-"` // Hidden is stored for a found group the user removed. Hidden bool `json:"hidden,omitempty"` // Disabled is a group of the user's switched off (PAMI on Discord): @@ -351,7 +357,50 @@ func Groups() []Group { return groupsIn(providerEntries()) } +// groupsIn is the groups among entries (Groups), built once while a +// request holds the catalog: a request looked its group up by building +// every group again, matching each pattern and finding the automatic +// groups over every model (FindGroup, then the groups' entries). Each +// caller gets a copy of its own to change. func groupsIn(entries []Entry) []Group { + return cloneGroups(heldFrom("groups", entries, buildGroupsIn)) +} + +// cloneGroups is gs with nothing shared with it: no slice, map or pointer +// of a group or its rules. +func cloneGroups(gs []Group) []Group { + if gs == nil { + return nil + } + out := make([]Group, len(gs)) + for i, g := range gs { + g.Members, g.Match, g.Matched = slices.Clone(g.Members), slices.Clone(g.Match), slices.Clone(g.Matched) + g.Off, g.Levels, g.Fast = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast) + g.Weights = maps.Clone(g.Weights) + if g.Rules != nil { + rs := make([]Rule, len(g.Rules)) + for j, r := range g.Rules { + r.Agents, r.Folders, r.ExceptFolders = slices.Clone(r.Agents), slices.Clone(r.Folders), slices.Clone(r.ExceptFolders) + if r.Time != nil { + t := *r.Time + t.Days = slices.Clone(t.Days) + r.Time = &t + } + rs[j] = r + } + g.Rules = rs + } + out[i] = g + } + return out +} + +// groupsBuilt counts buildGroupsIn, for the test that a held request +// builds the groups once. +var groupsBuilt atomic.Int64 + +func buildGroupsIn(entries []Entry) []Group { + groupsBuilt.Add(1) f := heldOf("file", load) var out []Group hidden := map[string]bool{} @@ -375,15 +424,18 @@ func groupsIn(entries []Entry) []Group { if !served(f.Groups) { // plugins/groups is off: the user's own aren't served out = slices.DeleteFunc(out, func(g Group) bool { return !g.Auto }) } - if f.NoAutoGroups { - return orderedGroups(out, f.GroupOrder) - } - for _, g := range foundGroups(entries) { - if slices.ContainsFunc(out, func(o Group) bool { return o.ID == g.ID }) { - continue // the user changed it: theirs now + if !f.NoAutoGroups { + for _, g := range foundGroups(entries) { + if slices.ContainsFunc(out, func(o Group) bool { return o.ID == g.ID }) { + continue // the user changed it: theirs now + } + g.Hidden = hidden[g.ID] + out = append(out, g) } - g.Hidden = hidden[g.ID] - out = append(out, g) + } + same := heldSettings().ModelSameAs + for i := range out { + out[i].Spelled = spelledIn(out[i], same) } return orderedGroups(out, f.GroupOrder) } @@ -868,10 +920,34 @@ func membersOff(entries []Entry, all []Group, g Group, off func(pid, model strin // every member fixed, the group offers the levels they are fixed at, so // that an agent still asks it to reason. A group that names its own // levels (Group.Levels) offers those, and so does a group in it for its -// models. +// models. Held while a request holds the catalog (heldFrom). func groupEntries(entries []Entry) []Entry { + return heldFrom("group entries", entries, buildGroupEntries) +} + +// entryOf is where in entries the last entry of provider pid's model is, +// -1 when none is. +type entryOf func(pid, model string) int + +// entriesBy is entryOf for entries, looked up in a map built once rather +// than by a pass over every entry for each member of each group. +func entriesBy(entries []Entry) entryOf { + at := make(map[[2]string]int, len(entries)) + for i := range entries { + at[[2]string{entries[i].Provider.ID, entries[i].Model}] = i + } + return func(pid, model string) int { + if i, ok := at[[2]string{pid, model}]; ok { + return i + } + return -1 + } +} + +func buildGroupEntries(entries []Entry) []Entry { var out []Entry all := groupsIn(entries) + find := entriesBy(entries) for _, g := range all { if g.Hidden || g.Disabled { continue @@ -880,7 +956,7 @@ func groupEntries(entries []Entry) []Entry { if len(ms) == 0 || DecisionGroup(ms) { continue // a decision group answers System One, no agent's conversation } - e := Entry{ID: GroupPrefix + g.ID, Model: ms[0].Model, Name: g.Name, Provider: ms[0].Provider, Group: g.ID, Named: !g.Auto} + e := Entry{ID: g.Ref(), Model: ms[0].Model, Name: g.Name, Provider: ms[0].Provider, Group: g.ID, Named: !g.Auto} var fixed []string // the efforts members are fixed at levelled := false // a member that follows the agent's effort was met // Codex's ultra (max, with Codex handing parts of the task to agents @@ -898,12 +974,12 @@ func groupEntries(entries []Entry) []Entry { var efforts []string images, thinks, ctx, output := false, false, 0, 0 var imageInput *bool - unknown, reasonless := false, false - for _, x := range entries { - if x.Provider.ID == m.Provider.ID && x.Model == m.Model { - efforts, images, thinks, ctx, output, imageInput = x.Efforts, x.Images, x.Reasoning, x.Context, x.Output, x.ImageInput - unknown, reasonless = levelsUnknown(x), x.Reasonless - } + unknown, reasonless, typed := false, false, false + if j := find(m.Provider.ID, m.Model); j >= 0 { + x := &entries[j] + efforts, images, thinks, ctx, output, imageInput = x.Efforts, x.Images, x.Reasoning, x.Context, x.Output, x.ImageInput + typed = x.WindowSet + unknown, reasonless = levelsUnknown(*x), x.Reasonless } // it reasons when a member does: the gateway sends the // effort to the members that take it, and a member known not @@ -933,9 +1009,16 @@ func groupEntries(entries []Entry) []Entry { // with room for it (#700, withRoom in the gateway), so the // agent compacts only when none has. The shortest member's, // as it was, had Pi compact a group of 1M DeepSeeks at 200k - // for the one free model among them that holds 200k (#712) + // for the one free model among them that holds 200k (#712). + // It is one the user typed when they typed that member's, as + // smallestWindow says it for a group following its smallest + // (Osal on Discord: an Ultra group of a ChatGPT account's + // GPT-6 Astra, set to its 872K on the codex provider, was + // handed to Codex as magpie's default 272K, ~258K at 95%) if ctx > e.Context { - e.Context = ctx + e.Context, e.WindowSet = ctx, typed + } else if ctx > 0 && ctx == e.Context { + e.WindowSet = e.WindowSet || typed } if i == 0 { e.ImageInput = imageInput @@ -1008,11 +1091,22 @@ func groupEntries(entries []Entry) []Entry { if e.ImageInput != nil && !*e.ImageInput { e.Images = false } + largest := e.Context ruledEntry(&e, g.Live(), ms, entries) + if e.Context != largest { + // lifted by a rule of length to what its members fit, which + // is no member's typed window + e.WindowSet = false + } if g.Context > 0 { e.Context, e.WindowSet = g.Context, true - } else if smallest, typed := smallestWindow(entries, ms); g.Context == ContextSmallest && smallest > 0 { - e.Context, e.WindowSet = smallest, typed + } else if g.Context == ContextSmallest { + // only for a group that follows its smallest member: run for + // every group, it was another pass over the catalog for each + // member of each (8f4d091c6) + if smallest, typed := smallestWindowBy(entries, find, ms); smallest > 0 { + e.Context, e.WindowSet = smallest, typed + } } e.Family = g.Family out = append(out, e) @@ -1029,12 +1123,26 @@ func groupEntries(entries []Entry) []Entry { // group set to 500K itself wasn't). A tie counts as typed: the window is // the user's either way. func smallestWindow(entries []Entry, ms []Member) (n int, typed bool) { + return smallestWindowBy(entries, entriesBy(entries), ms) +} + +// largestWindow is the window a group that names no size of its own is +// told, its largest member's, and whether the user typed it, as +// buildGroupEntries says it (Entry.WindowSet). +func largestWindow(entries []Entry, g Group) (typed bool) { + for _, e := range groupEntries(entries) { + if e.Group == g.ID { + return e.WindowSet + } + } + return false +} + +func smallestWindowBy(entries []Entry, find entryOf, ms []Member) (n int, typed bool) { for _, m := range ms { ctx, set := 0, false - for _, x := range entries { - if x.Provider.ID == m.Provider.ID && x.Model == m.Model { - ctx, set = x.Context, x.WindowSet - } + if j := find(m.Provider.ID, m.Model); j >= 0 { + ctx, set = entries[j].Context, entries[j].WindowSet } switch { case ctx <= 0: @@ -1082,6 +1190,7 @@ func (e Entry) Quiet() bool { // found makes it the user's. func SaveGroup(g Group) error { g = g.own() // cleaned below in place: the caller's lists stay as they were + g.canonicalRefs() g.ID = strings.ToLower(strings.TrimSpace(g.ID)) g.Name = strings.TrimSpace(g.Name) if g.ID == "" { @@ -1126,7 +1235,7 @@ func SaveGroup(g Group) error { return err } for i, m := range g.Members { - if model, effort := memberEffortIn(entries, m); effort != "" && strings.HasPrefix(model, GroupPrefix) { + if model, effort := memberEffortIn(entries, m); effort != "" && IsGroupRef(model) { return fmt.Errorf("%s is a group: its models reason as it says, so it takes no effort of its own (:%s)", model, effort) } g.Members[i] = cleanMember(entries, m) diff --git a/internal/provider/group_held_test.go b/internal/provider/group_held_test.go new file mode 100644 index 000000000..88828cdf7 --- /dev/null +++ b/internal/provider/group_held_test.go @@ -0,0 +1,303 @@ +package provider + +import ( + "fmt" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/yetone/magpie/internal/settings" +) + +// groupHeldFixture is a dozen providers serving the same models, so +// magpie finds a group of each, and a group of the user's of four. +func groupHeldFixture(t *testing.T) { + t.Helper() + isolate(t) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("MAGPIE_NO_ACCOUNTS", "1") + var models []string + for i := range 10 { + models = append(models, fmt.Sprintf("m%d", i)) + } + for i := range 12 { + if err := Save(Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: models, Anthropic: "http://127.0.0.1:9"}); err != nil { + t.Fatal(err) + } + } + if err := settings.Save(settings.Settings{DisabledModels: []string{"p11/m9"}}); err != nil { + t.Fatal(err) + } + if err := SaveGroup(Group{ID: "g4", Name: "G4", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1"}, Routing: Ordered}); err != nil { + t.Fatal(err) + } + Changed() +} + +// A request to a group asks for the catalog's groups several times — +// Resolve's Catalog, and Served for the members' images, the reply's +// length and the window — and each built every group's entry again, from +// every member of every group: the burst of CPU at once that a request to +// a group cost with many providers (colmugx and Yayoi_no_yume on X). While +// a request holds the catalog they are built once. +func TestGroupEntriesBuiltOnceWhileHeld(t *testing.T) { + groupHeldFixture(t) + release := Hold() + defer release() + entries := providerEntries() + first := groupEntries(entries) + if len(first) < 2 { + t.Fatalf("the fixture has %d groups; the test needs the found ones too", len(first)) + } + if again := groupEntries(entries); &again[0] != &first[0] { + t.Fatal("the groups' entries were built again under one Hold") + } + // what a caller is given is its own to change + c := Catalog() + c[0].Name = "changed" + if Catalog()[0].Name == "changed" || Served()[0].Name == "changed" { + t.Fatal("a change to Catalog's entries reached the next caller's") + } + // another catalog than the one held is built from, not answered for + other := append([]Entry(nil), entries[:len(entries)/2]...) + if got := groupEntries(other); len(got) > 0 && &got[0] == &first[0] { + t.Fatal("the groups of another catalog were the held one's") + } + // a write drops them + if err := SaveGroup(Group{ID: "g4", Name: "Renamed", Members: []string{"p0/m1", "p1/m1"}, Routing: Ordered}); err != nil { + t.Fatal(err) + } + found := false + for _, e := range Catalog() { + found = found || e.ID == GroupPrefix+"g4" && e.Name == "Renamed" + } + if !found { + t.Fatal("a group saved under the Hold kept its old entry") + } +} + +// Each group's members (membersIn) asked whether the user disabled them, +// and that parsed settings.json each time: a catalog of found groups +// parsed it once a group, on each of the several looks a request makes. +func TestGroupLooksParseNoSettingsPerGroupWhileHeld(t *testing.T) { + groupHeldFixture(t) + release := Hold() + defer release() + Served() // the first look builds what is held + const looks = 50 + before := settings.Parses() + for range looks { + Served() + Groups() + if _, _, ok := FindGroup(GroupPrefix + "g4"); !ok { + t.Fatal("no group g4") + } + } + if n := settings.Parses() - before; n >= looks { + t.Fatalf("settings.json parsed %d times in %d looks at the groups under one Hold", n, looks) + } + // and a model disabled is still left out + for _, e := range Served() { + if e.ID == "p11/m9" { + t.Fatal("a disabled model was served") + } + } +} + +// BenchmarkGroupEntries is the groups' entries of a catalog of 30 +// providers serving the same 60 models (60 groups magpie finds, of 30 +// members each), built afresh: what each request built several times. +func BenchmarkGroupEntries(b *testing.B) { + isolate(b) + home := b.TempDir() + b.Setenv("HOME", home) + b.Setenv("USERPROFILE", home) + b.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + b.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + b.Setenv("MAGPIE_NO_ACCOUNTS", "1") + var models []string + for i := range 60 { + models = append(models, fmt.Sprintf("m%d", i)) + } + for i := range 30 { + if err := Save(Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: models, Anthropic: "http://127.0.0.1:9"}); err != nil { + b.Fatal(err) + } + } + Changed() + entries := providerEntries() + b.ResetTimer() + for range b.N { + buildGroupEntries(entries) + } +} + +// A request to a group looked its group up through FindGroup and the +// other group readers, and each built every group again: reading +// providers.json's groups, matching each pattern against every model and +// finding the automatic groups over the catalog. While a request holds the +// catalog the groups are built once, and each caller gets its own copy. +func TestGroupsBuiltOnceWhileHeld(t *testing.T) { + groupHeldFixture(t) + release := Hold() + defer release() + Groups() + before := groupsBuilt.Load() + for range 20 { + Groups() + if _, _, ok := FindGroup(GroupPrefix + "g4"); !ok { + t.Fatal("no group g4") + } + } + if n := groupsBuilt.Load() - before; n != 0 { + t.Fatalf("the groups were built %d times more in 40 looks under one Hold, want 0", n) + } + // a caller's change to its copy is not the next caller's + var g4 Group + for _, g := range Groups() { + if g.ID == "g4" { + g4 = g + } + } + g4.Members[0] = "changed" + for _, g := range Groups() { + if g.ID == "g4" && g.Members[0] == "changed" { + t.Fatal("a change to a held group's members reached the next caller") + } + } + // a write builds them again + if err := SaveGroup(Group{ID: "g4", Name: "Renamed", Members: []string{"p0/m1", "p1/m1"}, Routing: Ordered}); err != nil { + t.Fatal(err) + } + if g, _, ok := FindGroup(GroupPrefix + "g4"); !ok || g.Name != "Renamed" { + t.Fatalf("a group saved under the Hold kept its old self: %+v", g) + } +} + +// cloneGroups shares nothing with what it copies: every slice, map and +// pointer of a Group and of its Rules, found by reflection, so a field +// added later is copied too or this fails. +func TestCloneGroupsSharesNothing(t *testing.T) { + var g Group + fillEvery(reflect.ValueOf(&g).Elem()) + if len(g.Rules) == 0 { + t.Fatal("the fill made no rule") + } + c := cloneGroups([]Group{g})[0] + if !reflect.DeepEqual(c, g) { + t.Fatalf("the copy differs:\n%+v\n%+v", c, g) + } + if path := sharedRef(reflect.ValueOf(g), reflect.ValueOf(c), "Group"); path != "" { + t.Fatalf("%s is shared with the held group", path) + } +} + +// fillEvery gives every field of v a value, and each slice, map and pointer one +// element. +func fillEvery(v reflect.Value) { + switch v.Kind() { + case reflect.Struct: + for i := range v.NumField() { + if v.Type().Field(i).IsExported() { + fillEvery(v.Field(i)) + } + } + case reflect.Slice: + v.Set(reflect.MakeSlice(v.Type(), 1, 1)) + fillEvery(v.Index(0)) + case reflect.Map: + v.Set(reflect.MakeMap(v.Type())) + k, e := reflect.New(v.Type().Key()).Elem(), reflect.New(v.Type().Elem()).Elem() + fillEvery(k) + fillEvery(e) + v.SetMapIndex(k, e) + case reflect.Pointer: + v.Set(reflect.New(v.Type().Elem())) + fillEvery(v.Elem()) + case reflect.String: + v.SetString("x") + case reflect.Bool: + v.SetBool(true) + case reflect.Int, reflect.Int64, reflect.Int32: + v.SetInt(1) + case reflect.Float64: + v.SetFloat(1) + } +} + +// sharedRef names the first slice, map or pointer a and b hold in common. +func sharedRef(a, b reflect.Value, path string) string { + switch a.Kind() { + case reflect.Struct: + for i := range a.NumField() { + if a.Type().Field(i).IsExported() { + if p := sharedRef(a.Field(i), b.Field(i), path+"."+a.Type().Field(i).Name); p != "" { + return p + } + } + } + case reflect.Slice: + if a.Len() > 0 && a.Pointer() == b.Pointer() { + return path + } + for i := range a.Len() { + if p := sharedRef(a.Index(i), b.Index(i), fmt.Sprintf("%s[%d]", path, i)); p != "" { + return p + } + } + case reflect.Map, reflect.Pointer: + if !a.IsNil() && a.Pointer() == b.Pointer() { + return path + } + if a.Kind() == reflect.Pointer && !a.IsNil() { + return sharedRef(a.Elem(), b.Elem(), path) + } + } + return "" +} + +// BenchmarkGroupLooksHeld is the group look-ups one request to a group +// makes under its Hold (FindGroup for the route, its members and the +// window, and the group list), over 30 providers serving the same 60 +// models. +func BenchmarkGroupLooksHeld(b *testing.B) { + isolate(b) + home := b.TempDir() + b.Setenv("HOME", home) + b.Setenv("USERPROFILE", home) + b.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + b.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + b.Setenv("MAGPIE_NO_ACCOUNTS", "1") + var models []string + for i := range 60 { + models = append(models, fmt.Sprintf("m%d", i)) + } + for i := range 30 { + if err := Save(Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: models, Anthropic: "http://127.0.0.1:9"}); err != nil { + b.Fatal(err) + } + } + if err := SaveGroup(Group{ID: "g4", Name: "G4", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1"}, Routing: Ordered}); err != nil { + b.Fatal(err) + } + Changed() + defer func(d time.Duration) { heldFor = d }(heldFor) + heldFor = time.Hour // the look-ups of one request, not the Hold's age on a loaded machine + release := Hold() + defer release() + providerEntries() + b.ResetTimer() + for range b.N { + for range 4 { + if _, _, ok := FindGroup(GroupPrefix + "g4"); !ok { + b.Fatal("no group g4") + } + } + Groups() + } +} diff --git a/internal/provider/group_order_test.go b/internal/provider/group_order_test.go index f245112c5..ba8264cb1 100644 --- a/internal/provider/group_order_test.go +++ b/internal/provider/group_order_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "os" "slices" - "strings" "testing" ) @@ -40,7 +39,7 @@ func TestGroupOrder(t *testing.T) { catalogGroups := func() []string { var out []string for _, e := range Catalog() { - if id, ok := strings.CutPrefix(e.ID, GroupPrefix); ok { + if id := e.Group; id != "" { out = append(out, id) } } @@ -59,7 +58,7 @@ func TestGroupOrder(t *testing.T) { if got := catalogGroups(); !slices.Equal(got, want) { t.Fatalf("catalog after SetGroupOrder(%s, two): %v", found, got) } - if e := Catalog(); len(e) == 0 || e[0].ID != GroupPrefix+found { + if e := Catalog(); len(e) == 0 || e[0].Group != found { t.Fatalf("the catalog's first model isn't %s", GroupPrefix+found) } b, err := os.ReadFile(Path()) diff --git a/internal/provider/group_serve.go b/internal/provider/group_serve.go index 60be9496a..9ae4c4ce7 100644 --- a/internal/provider/group_serve.go +++ b/internal/provider/group_serve.go @@ -55,19 +55,21 @@ func ServeGroups() (remove func()) { return holdGate(&groupGate.served) } -// holdGate holds n until the func it gives is called. Nothing built from -// the groups is kept past one call (only the file is, while a request -// holds it), so the next lookup sees the change. +// holdGate holds n until the func it gives is called. What is built from +// the groups and held across requests (heldOf) is dropped either way, so +// the next lookup sees the change. func holdGate(n *int) func() { groupGate.Lock() *n++ groupGate.Unlock() + dropHeld() var once sync.Once return func() { once.Do(func() { groupGate.Lock() *n-- groupGate.Unlock() + dropHeld() }) } } diff --git a/internal/provider/group_serve_test.go b/internal/provider/group_serve_test.go index 21c6d8ce7..ccfa3c5ab 100644 --- a/internal/provider/group_serve_test.go +++ b/internal/provider/group_serve_test.go @@ -31,7 +31,7 @@ func TestOwnGroupsWaitOnThePlugin(t *testing.T) { slices.Sort(ids) return ids } - both, found := []string{"group/auto-m", "group/mine"}, []string{"group/auto-m"} + both, found := []string{"auto/m", "group/mine"}, []string{"auto/m"} check := func(when string, want []string) { t.Helper() if got := listed(); !slices.Equal(got, want) { diff --git a/internal/provider/group_share.go b/internal/provider/group_share.go index 09ee7b5a6..649719756 100644 --- a/internal/provider/group_share.go +++ b/internal/provider/group_share.go @@ -241,7 +241,7 @@ func ImportGroup(text string) (Imported, error) { // (AutoGroupOf) under the first provider here that serves it, in the // Providers order; "" when none does. A member's own effort goes with it. func memberHere(entries []Entry, all []Group, m string) string { - m = strings.TrimPrefix(strings.TrimSpace(m), "magpie/") + m = CanonicalRef(strings.TrimPrefix(strings.TrimSpace(m), "magpie/")) model, effort := memberEffortIn(entries, m) if gid, ok := strings.CutPrefix(model, GroupPrefix); ok { if slices.ContainsFunc(all, func(g Group) bool { return g.ID == gid && !g.Hidden }) { diff --git a/internal/provider/group_test.go b/internal/provider/group_test.go index f35297b8d..d02c747ee 100644 --- a/internal/provider/group_test.go +++ b/internal/provider/group_test.go @@ -57,8 +57,8 @@ func TestGroupImages(t *testing.T) { got[g.ID] = g.Images } want := map[string]bool{ - GroupPrefix + "auto-kimi-k3": true, GroupPrefix + "auto-glm-5-3": true, - GroupPrefix + "auto-deepseek-v4-1-flash": true, GroupPrefix + "auto-glm-5-2": false, + AutoPrefix + "kimi-k3": true, AutoPrefix + "glm-5.3": true, + AutoPrefix + "deepseek-v4.1-flash": true, AutoPrefix + "glm-5.2": false, } if !maps.Equal(got, want) { t.Errorf("%v", got) diff --git a/internal/provider/groupeffort.go b/internal/provider/groupeffort.go index 417510cb4..ba28a4b48 100644 --- a/internal/provider/groupeffort.go +++ b/internal/provider/groupeffort.go @@ -89,8 +89,10 @@ func WithMemberEffort(model, effort string) string { return model + ":" + effort } -// cleanMember spells a member as it is kept: its effort lowercase. +// cleanMember spells a member as it is kept: its effort lowercase, a found +// group by group/auto- (CanonicalRef). func cleanMember(entries []Entry, id string) string { + id = CanonicalRef(id) // a found group by the id magpie keeps it by m, e := memberEffortIn(entries, id) return WithMemberEffort(m, e) } diff --git a/internal/provider/groupfast.go b/internal/provider/groupfast.go index 8dc90a9e6..0bac707a6 100644 --- a/internal/provider/groupfast.go +++ b/internal/provider/groupfast.go @@ -182,7 +182,7 @@ func cleanFast(entries []Entry, g *Group) error { continue // taken out of the group } model, _ := memberEffortIn(entries, f) - if strings.HasPrefix(model, GroupPrefix) { + if IsGroupRef(model) { return fmt.Errorf("%s is a group: its models are sent as it says, so it takes no :%s", model, FastWord) } if p, m, ok := resolveIn(entries, model); ok && !CanFast(p, m) { diff --git a/internal/provider/groupfound_off_test.go b/internal/provider/groupfound_off_test.go index cc9574fdc..90964d835 100644 --- a/internal/provider/groupfound_off_test.go +++ b/internal/provider/groupfound_off_test.go @@ -43,7 +43,7 @@ func TestFoundGroupStaysWithAProviderOff(t *testing.T) { return out } listed := func() bool { - return slices.ContainsFunc(Served(), func(e Entry) bool { return e.ID == GroupPrefix+"auto-x" }) + return slices.ContainsFunc(Served(), func(e Entry) bool { return e.ID == AutoPrefix+"x" }) } all := []string{"a/x", "b/x", "c/x"} if got := members(); !slices.Equal(got, all) { diff --git a/internal/provider/groupfound_test.go b/internal/provider/groupfound_test.go index 86ced008d..5eb841fe9 100644 --- a/internal/provider/groupfound_test.go +++ b/internal/provider/groupfound_test.go @@ -65,7 +65,7 @@ func TestAutoGroupsOff(t *testing.T) { if got := ids(); !slices.Equal(got, []string{"auto-x", "mine"}) { t.Fatalf("off: %v", got) } - if got := catalog(); !slices.Equal(got, []string{"group/auto-x", "group/mine"}) { + if got := catalog(); !slices.Equal(got, []string{"auto/x", "group/mine"}) { t.Fatalf("off, the catalog's groups: %v", got) } if _, _, ok := FindGroup("group/auto-kimi-k3"); ok { diff --git a/internal/provider/hold.go b/internal/provider/hold.go index e5ec66347..52ced4f9e 100644 --- a/internal/provider/hold.go +++ b/internal/provider/hold.go @@ -1,6 +1,8 @@ package provider import ( + "hash/maphash" + "os" "slices" "sync" "time" @@ -22,6 +24,62 @@ var held struct { gen uint64 // what was built, and when, by what it is built map[string]heldValue + // env is the environment it was built in (environSum) + env uint64 + // fgen is filememo's generation it was built in: a write that only + // tells filememo (settings.Save, an account's file) has it built again + fgen uint64 + // roots is the providers' and the settings' files as last looked at + roots [2]rootStamp +} + +// rootStamp is a file's time and size, or that it wasn't there. +type rootStamp struct { + mod time.Time + size int64 + ok bool +} + +func stampOf(path string) rootStamp { + fi, err := os.Stat(path) + if err != nil { + return rootStamp{} + } + return rootStamp{fi.ModTime(), fi.Size(), true} +} + +// heldFreshLocked drops what is built when a file was written since, by +// this process (filememo.Gen) or, for the providers' and the settings' +// files, by another (the CLI's "magpie group add", seen by the next +// request, not a second later). Called with held held. +func heldFreshLocked(look bool) { + if g := filememo.Gen(); g != held.fgen { + held.built, held.fgen = nil, g + } + if !look { + return + } + for i, path := range [2]string{Path(), settings.Path()} { + if st := stampOf(path); st != held.roots[i] { + held.roots[i] = st + held.built = nil + filememo.Look(path) + } + } +} + +var environSeed = maphash.MakeSeed() + +// environSum is a hash of this process's environment: the folders every +// file and account is read from are named by it. +func environSum() uint64 { + var h maphash.Hash + h.SetSeed(environSeed) + for _, kv := range os.Environ() { + h.WriteString(kv) + h.WriteByte(0) + } + return h.Sum64() } type heldValue struct { @@ -47,18 +105,35 @@ func init() { // heldFor is how long a held catalog is used before it is built again, // while one request after another keeps it held. -const heldFor = time.Second +var heldFor = time.Second // Hold keeps the catalog built once until release is called, for a // request that only reads; a write meanwhile (Changed) drops it. func Hold() (release func()) { held.Lock() + if held.holds == 0 { + // what was built under another environment (a HOME or config + // folder of its own: a test's) isn't this one's + if env := environSum(); env != held.env { + held.built, held.env = nil, env + } + heldFreshLocked(true) + } held.holds++ held.Unlock() return sync.OnceFunc(func() { held.Lock() if held.holds--; held.holds == 0 { - held.built = nil + // what is built stays for the next request within heldFor, as + // it stays for one that overlaps this one: one request after + // another, each built the catalog again from every provider's + // files and accounts (a fifth of a request's CPU with 30 + // providers). Only what is past heldFor goes, for memory. + for k, h := range held.built { + if time.Since(h.at) >= heldFor { + delete(held.built, k) + } + } } held.Unlock() }) @@ -87,6 +162,7 @@ func heldOf[T any](key string, build func() T) T { held.Unlock() return build() } + heldFreshLocked(false) if h, ok := held.built[key]; ok && time.Since(h.at) < heldFor { held.Unlock() return h.v.(T) @@ -116,6 +192,51 @@ func heldPlugins() []plugin.Provider { return heldOf("plugins", func() []plugin.Provider { return slices.Clip(plugin.Cached()) }) } +// fromEntries is what was built from a catalog, and which catalog: its +// first entry and its length. +type fromEntries[T any] struct { + at *Entry + n int + v T +} + +// heldFrom is heldOf for what is built from entries: held while a request +// holds the catalog, and built again for another catalog than it was built +// from (providerEntries built afresh after heldFor, or one a caller made). +// A request asks for the groups' entries several times (Catalog, Served), +// and each built them from every member of every group again (the CPU a +// request to a group took at once, with many providers). +func heldFrom[T any](key string, entries []Entry, build func([]Entry) T) T { + var at *Entry + if len(entries) > 0 { + at = &entries[0] + } + held.Lock() + if held.holds == 0 { + held.Unlock() + return build(entries) + } + heldFreshLocked(false) + if h, ok := held.built[key]; ok && time.Since(h.at) < heldFor { + if f := h.v.(fromEntries[T]); f.at == at && f.n == len(entries) { + held.Unlock() + return f.v + } + } + gen := held.gen + held.Unlock() + v := build(entries) + held.Lock() + if held.holds > 0 && held.gen == gen { + if held.built == nil { + held.built = map[string]heldValue{} + } + held.built[key] = heldValue{fromEntries[T]{at, len(entries), v}, time.Now()} + } + held.Unlock() + return v +} + // heldSettings is the settings, read once while a request holds the // catalog: a look at the agents asks them for every model of every agent. // Only for reading — what it gives is shared by the request's look-ups. diff --git a/internal/provider/hold_test.go b/internal/provider/hold_test.go index a49a74824..6b5c415e5 100644 --- a/internal/provider/hold_test.go +++ b/internal/provider/hold_test.go @@ -7,8 +7,10 @@ import ( "slices" "strings" "testing" + "time" "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/testenv" @@ -45,6 +47,99 @@ func TestHoldBuildsOnce(t *testing.T) { } } +// One request after another within heldFor builds the catalog once, as +// requests that overlap do: each built it again from every provider's +// files and accounts (a fifth of a request's CPU with 30 providers). A +// write between them (Changed), or another environment (a test's HOME), +// has it built again. +func TestHoldKeptForTheNextRequest(t *testing.T) { + defer func(d time.Duration) { heldFor = d }(heldFor) + heldFor = time.Minute // a loaded machine's pause between requests isn't the change + t.Setenv("MAGPIE_HOLD_TEST", "1") + n := 0 + build := func() int { n++; return n } + for range 5 { + release := Hold() + heldOf("t-next", build) + heldOf("t-next", build) + release() + } + if n != 1 { + t.Fatalf("five requests one after another: built %d times, want 1", n) + } + Changed() + func() { + defer Hold()() + if heldOf("t-next", build); n != 2 { + t.Fatalf("after a write: built %d times, want 2", n) + } + }() + t.Setenv("MAGPIE_HOLD_TEST", "2") + func() { + defer Hold()() + if heldOf("t-next", build); n != 3 { + t.Fatalf("in another environment: built %d times, want 3", n) + } + }() + if heldOf("t-next", build); n != 4 { + t.Fatalf("unheld: built %d times, want 4", n) + } +} + +// What is held across requests is built again when anything it was built +// from may have moved: a write that only tells filememo (settings.Save, an +// account's file), the providers' or the settings' file written by +// another process (the CLI's "magpie group add"), the groups served or +// not (GateGroups, ServeGroups), and the models.dev catalog read again. +func TestHoldKeptUntilAWrite(t *testing.T) { + defer func(d time.Duration) { heldFor = d }(heldFor) + heldFor = time.Minute // a loaded machine's pause between requests isn't the change + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + n := 0 + build := func() int { n++; return n } + request := func() { + defer Hold()() + heldOf("t-write", build) + } + request() + request() + if n != 1 { + t.Fatalf("two requests: built %d times, want 1", n) + } + for _, c := range []struct { + what string + write func() + }{ + {"filememo told", filememo.Forget}, + {"providers.json written by another process", func() { + os.MkdirAll(filepath.Dir(Path()), 0o700) + os.WriteFile(Path(), []byte(`{"providers":[]}`), 0o600) + }}, + {"settings.json written by another process", func() { + os.MkdirAll(filepath.Dir(settings.Path()), 0o700) + os.WriteFile(settings.Path(), []byte(`{}`), 0o600) + }}, + {"the groups gated", func() { GateGroups(nil)() }}, + // models.dev's catalog read again: the entries' windows and + // output limits come from it (Pi's maxTokens, Crush's default) + {"the catalog reset", catalog.Reset}, + } { + was := n + c.write() + request() + if n != was+1 { + t.Fatalf("%s: built %d times, want 1", c.what, n-was) + } + request() + if n != was+1 { + t.Fatalf("%s, then a request: built again", c.what) + } + } +} + // A change the plugin host tells (a sign-in saved, a plugin added) drops // what a request holds before it returns: a SyncCatalog running held the // plugins as they were before `magpie plugin login` saved its account, diff --git a/internal/provider/install.go b/internal/provider/install.go index 0bdfad9cb..ed0a351f5 100644 --- a/internal/provider/install.go +++ b/internal/provider/install.go @@ -22,7 +22,7 @@ import ( // agentCLI is a CLI a subscription runs through: how to find it, and the // vendor's install one-liners for a POSIX shell and for PowerShell. native, // when there is one, does what the shell one does without a shell, for a -// magpie with none (its Docker image has no bash, curl or wget). setup: the +// magpie with none (its Docker image had no bash, curl or wget until #2834). setup: the // installer ends by running the CLI's own setup, which asks how to sign in; // magpie signs in itself once the CLI is there. type agentCLI struct { @@ -148,8 +148,10 @@ func runUntilInstalled(ctx context.Context, cmd *exec.Cmd, c agentCLI) ([]byte, // bash, and curl, which every one-liner (and the scripts behind them) // downloads with. magpie's Docker image had none of them, and the install // failed there with "exec: bash: not found". Since 7bfe3137 it has bash and -// busybox's wget but still no curl, and the one-liner failed there too. A -// var so tests can say there is none. +// busybox's wget but still no curl, and the one-liner failed there too. +// Since #2834 it is Debian with bash and curl, and the CLIs the one-liners +// install find the loader and libraries they link. A var so tests can say +// there is none. var shellInstallerRuns = func() bool { for _, p := range []string{"bash", "curl"} { if _, err := exec.LookPath(p); err != nil { diff --git a/internal/provider/install_test.go b/internal/provider/install_test.go index d0460c5a6..7fb727692 100644 --- a/internal/provider/install_test.go +++ b/internal/provider/install_test.go @@ -98,7 +98,7 @@ func waitPast(t *testing.T, id, state string) SignInState { return SignInState{} } -// magpie's Docker image has bash and busybox's wget but no curl, which every +// magpie's Docker image had bash and busybox's wget but no curl, which every // vendor's one-liner downloads with: there the native installer is used func TestShellInstallerNeedsCurl(t *testing.T) { if runtime.GOOS == "windows" { diff --git a/internal/provider/migrate_factory.go b/internal/provider/migrate_factory.go index 027bd87de..cfdaf323c 100644 --- a/internal/provider/migrate_factory.go +++ b/internal/provider/migrate_factory.go @@ -14,7 +14,7 @@ import ( func init() { movers["factory"] = &mover{ pkg: "@magpie-community/opencode-factory-auth", - min: "0.1.33", // the update-config entry in a system prompt's configuration section, as claude-code-guide renders it with a slash, adapted the way Factory takes it (plugins #198); a model's token multiplier reaching magpie as its rate, with a running promotion's discount (plugins #158); an OpenAI model's request without temperature and top_p, which OpenAI's reasoning models turn away with 400 (sweanng424 on Discord, Nowledge Mem on gpt-6.1-sol); requests saying droid 0.242.0, the current release (sky杨 on Discord: every model 403 "Factory: Forbidden" from Claude Code); Claude Code on GLM and other /api/llm/o models without the phrases Factory refuses (Echoo on Discord); the Fast Mode models listed last, so GPT-5.3-Codex, Grok and GLM are in the first 24 again (plugins #119); droid's Fast Mode models (Opus 5.5/5/4.8, GPT-5.5/5.4/5.3-Codex), and fast asked of a base model sent to its Fast Mode model (plugins #119); Gemini 4 Argon and Gemini 3.x on Factory's Gemini route (#2080); a 413 asked once more with older images left out, then said as Factory's byte limit (#2082); Haiku 5.5 and Mistral Large 4, in droid 0.240.0's picker (JL); a session continued after Claude Code compaction, whose restored context opens with the invoked-skills reminder (plugins #66); Claude Code's streamed context_management left out, which Factory's streaming route refuses (plugins #71); Claude Code's skill list sent alone as a system message, as text blocks or a string, gets update-config's line Factory takes (plugins #72); Claude Code 2.1.280's restored-context turn after /compact (plugins #68); pi's compaction and branch summary openings reworded (#1316); hook notifications kept in Claude Code compaction context only stop changed-file quoting, summaries quoted like tool output, a cut after a hunk separator (plugins #42); Claude Code compaction/runtime metadata and quoted session summaries (#1132); pi's opening sentence cut to its first half (#952); DeepSeek V4.1 Flash, Kimi K3 and GLM-5.2 offering none, so reasoning turned off stops their thinking (#899); requests saying droid 0.233.0 (JL: every model 403); Claude Code 2.1.288's runtime context as a system message of text blocks (#658); a tool whose input_schema has anyOf/oneOf/allOf at its root (Codex's automation_update) wrapped for Claude models (#646); a failure's status and its sign-in mark as the built-in's; Claude 5's system-role metadata as Factory takes it; Claude Code's standalone model-switch system updates; tool results quoting Claude Code's fixed phrases, and Claude Code's directory updates carrying a model; the sign-in renewed ahead of time through auth.refresh; Claude Code with a global CLAUDE.md or a SessionStart hook, and Claude Desktop's model line (#634) + min: "0.1.34", // Claude Code 2.1.292's instructions re-read after compaction (changed: true), and a 403 that keeps Factory's request id (plugins #243); the update-config entry in a system prompt's configuration section, as claude-code-guide renders it with a slash, adapted the way Factory takes it (plugins #198); a model's token multiplier reaching magpie as its rate, with a running promotion's discount (plugins #158); an OpenAI model's request without temperature and top_p, which OpenAI's reasoning models turn away with 400 (sweanng424 on Discord, Nowledge Mem on gpt-6.1-sol); requests saying droid 0.242.0, the current release (sky杨 on Discord: every model 403 "Factory: Forbidden" from Claude Code); Claude Code on GLM and other /api/llm/o models without the phrases Factory refuses (Echoo on Discord); the Fast Mode models listed last, so GPT-5.3-Codex, Grok and GLM are in the first 24 again (plugins #119); droid's Fast Mode models (Opus 5.5/5/4.8, GPT-5.5/5.4/5.3-Codex), and fast asked of a base model sent to its Fast Mode model (plugins #119); Gemini 4 Argon and Gemini 3.x on Factory's Gemini route (#2080); a 413 asked once more with older images left out, then said as Factory's byte limit (#2082); Haiku 5.5 and Mistral Large 4, in droid 0.240.0's picker (JL); a session continued after Claude Code compaction, whose restored context opens with the invoked-skills reminder (plugins #66); Claude Code's streamed context_management left out, which Factory's streaming route refuses (plugins #71); Claude Code's skill list sent alone as a system message, as text blocks or a string, gets update-config's line Factory takes (plugins #72); Claude Code 2.1.280's restored-context turn after /compact (plugins #68); pi's compaction and branch summary openings reworded (#1316); hook notifications kept in Claude Code compaction context only stop changed-file quoting, summaries quoted like tool output, a cut after a hunk separator (plugins #42); Claude Code compaction/runtime metadata and quoted session summaries (#1132); pi's opening sentence cut to its first half (#952); DeepSeek V4.1 Flash, Kimi K3 and GLM-5.2 offering none, so reasoning turned off stops their thinking (#899); requests saying droid 0.233.0 (JL: every model 403); Claude Code 2.1.288's runtime context as a system message of text blocks (#658); a tool whose input_schema has anyOf/oneOf/allOf at its root (Codex's automation_update) wrapped for Claude models (#646); a failure's status and its sign-in mark as the built-in's; Claude 5's system-role metadata as Factory takes it; Claude Code's standalone model-switch system updates; tool results quoting Claude Code's fixed phrases, and Claude Code's directory updates carrying a model; the sign-in renewed ahead of time through auth.refresh; Claude Code with a global CLAUDE.md or a SessionStart hook, and Claude Desktop's model line (#634) agents: []string{"factory"}, out: func() ([]Moving, error) { ls := factoryLogins() diff --git a/internal/provider/migrate_qoder.go b/internal/provider/migrate_qoder.go index c6f9b6915..478aa569c 100644 --- a/internal/provider/migrate_qoder.go +++ b/internal/provider/migrate_qoder.go @@ -24,7 +24,7 @@ func init() { func qoderMover(id string) *mover { return &mover{ pkg: "@magpie-community/opencode-qoder-auth", - min: "0.2.18", // a 10605 trimmed or wrapped is the model's queue busy, not a lapsed sign-in (plugins #185); 0.2.17: the daily check-in through auth.checkin (plugins #179); 0.2.16: a tool call written into the text that can't be read, or that the stream ends inside, ends the turn as an error (a 502, or the stream's error frame with no finish), never as the answer (plugins #132); 0.2.14: Qoder's 403 code 10605 (the model's queue busy) is a 503 with Retry-After, not a lapsed sign-in; quota and credit codes (110, 112–119, 122) are 429, refusals of the request (406, 416, 430, 80411, 80412, 100400, 100401, 100403) are 400, and only 105 or no code is "sign in again" (plugins #98); 0.2.13: models are listed from Qoder's app scene first, so its new default Fast 0.8× shows (plugins #97); 0.2.12: a chat Qoder refuses keeps Qoder's own reason in the error; 0.2.11: a Qoder CN enterprise VPC account keeps its model list and renewal mark apart from a public account with the same uid (plugins#40); international check-in finds the device identity runtime Qoder CLI caches on macOS and Linux and the Linux desktop installs in /opt/Qoder (ARNO on Discord); sends Qoder's native device identity, without which the daily 100 credits aren't listed (#1268); Qoder CN enterprise VPC (0.2.8); the daily credits claimed through the account's fetch (ARNO on Discord); Qoder CN as "qoder-cn", its device-token chat as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; token usage read; each model's context the largest window Qoder offers it (#722); the window a request is sent holds the reply's max_tokens (#700) + min: "0.2.19", // a model list that can't be read is a 502, so a group falls back to its next member (plugins #249); 0.2.18: a 10605 trimmed or wrapped is the model's queue busy, not a lapsed sign-in (plugins #185); 0.2.17: the daily check-in through auth.checkin (plugins #179); 0.2.16: a tool call written into the text that can't be read, or that the stream ends inside, ends the turn as an error (a 502, or the stream's error frame with no finish), never as the answer (plugins #132); 0.2.14: Qoder's 403 code 10605 (the model's queue busy) is a 503 with Retry-After, not a lapsed sign-in; quota and credit codes (110, 112–119, 122) are 429, refusals of the request (406, 416, 430, 80411, 80412, 100400, 100401, 100403) are 400, and only 105 or no code is "sign in again" (plugins #98); 0.2.13: models are listed from Qoder's app scene first, so its new default Fast 0.8× shows (plugins #97); 0.2.12: a chat Qoder refuses keeps Qoder's own reason in the error; 0.2.11: a Qoder CN enterprise VPC account keeps its model list and renewal mark apart from a public account with the same uid (plugins#40); international check-in finds the device identity runtime Qoder CLI caches on macOS and Linux and the Linux desktop installs in /opt/Qoder (ARNO on Discord); sends Qoder's native device identity, without which the daily 100 credits aren't listed (#1268); Qoder CN enterprise VPC (0.2.8); the daily credits claimed through the account's fetch (ARNO on Discord); Qoder CN as "qoder-cn", its device-token chat as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; token usage read; each model's context the largest window Qoder offers it (#722); the window a request is sent holds the reply's max_tokens (#700) agents: []string{id}, out: func() ([]Moving, error) { // nothing else writes the pairs while they are read diff --git a/internal/provider/migrate_side.go b/internal/provider/migrate_side.go index 61c0055fb..d27fe164d 100644 --- a/internal/provider/migrate_side.go +++ b/internal/provider/migrate_side.go @@ -97,7 +97,7 @@ func init() { // names, as the built-in does: the homes stay where they are. movers["grok"] = &mover{ pkg: "@magpie-community/opencode-grok-auth", - min: "0.1.15", // a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223) + min: "0.1.17", // the sign-in page opens once, where Grok Build opened it and magpie again (andyfmyth on X); a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223); a sign-in with no email (an X account) is kept by its xAI user id, GROK_AUTH_PATH no longer takes it elsewhere, and a login that leaves none says where it looked agents: []string{"grok"}, out: func() ([]Moving, error) { var out []Moving @@ -139,7 +139,7 @@ func init() { movers[CommandCodePlanID] = &mover{ pkg: "@magpie-community/opencode-commandcode-auth", - min: "0.1.13", // the Credits window resets at the plan's period end (#2454); the models the built-in counted free are marked free; max_tokens capped at 200,000 as the built-in; 0.1.12: each plan lists only the models its plan may use, as the CLI's table has it, so a Go account no longer lists GOAT's (plugins 49e9d89, 01huadalang on Discord); 0.1.11: a streamed Go reply the upstream cuts off after it has said something ends cut short with a note, not a lost turn (plugins #91); 0.1.10: a Go request says the agent's folder and git repository as magpie tells them, not the home's (plugins #86); 0.1.9: a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; a Go account lists Go's models; a model the plugin doesn't know takes pictures as models.dev says + min: "0.1.14", // a Zero Data Retention switch (or CMD_ZDR=1) sends x-cmd-zdr: 1 on the Provider API and /alpha/generate, as the CLI does (plugins #246); 0.1.13: the Credits window resets at the plan's period end (#2454); the models the built-in counted free are marked free; max_tokens capped at 200,000 as the built-in; 0.1.12: each plan lists only the models its plan may use, as the CLI's table has it, so a Go account no longer lists GOAT's (plugins 49e9d89, 01huadalang on Discord); 0.1.11: a streamed Go reply the upstream cuts off after it has said something ends cut short with a note, not a lost turn (plugins #91); 0.1.10: a Go request says the agent's folder and git repository as magpie tells them, not the home's (plugins #86); 0.1.9: a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; a Go account lists Go's models; a model the plugin doesn't know takes pictures as models.dev says agents: []string{CommandCodePlanID}, out: func() ([]Moving, error) { var out []Moving diff --git a/internal/provider/migrate_workbuddy.go b/internal/provider/migrate_workbuddy.go index 7475ce14f..7395f0ba5 100644 --- a/internal/provider/migrate_workbuddy.go +++ b/internal/provider/migrate_workbuddy.go @@ -16,7 +16,7 @@ func init() { for _, w := range []*wbSite{wbCN, wbAI} { movers[w.id] = &mover{ pkg: "@magpie-community/opencode-workbuddy-auth", - min: "0.1.24", // a refused sign-in on a chat over 2 MiB says the 401 and to sign in again: WorkBuddy's front door resets such a request instead of answering, so it read as 502 ECONNRESET (wyp on Discord); 0.1.23: credits used up leave the free models counted out of the credits window, so an account is not ranked spent for them (plugins #138); 0.1.22: an MCP server's tool schemas reach Kimi and DeepSeek: an enum with no type, or of several types, is typed, and true or false where a schema goes is {} or {"not": {}}, so they aren't 400 11133 "Invalid request parameters" (plugins #122); 0.1.21: a model free only at night (Hy4 preview) is never said free, and a whole-day discount shows the price before it, from WorkBuddy's modelPromotions (plugins #121); 0.1.20: tool results followed by the user's message reach WorkBuddy AI's gemini-3.8-flash, not 400 "the conversation must end with a user message" (plugins #113); 0.1.19: an enterprise account's card shows its credits, from the enterprise meter WorkBuddy's usage page reads (#1904); 0.1.18: WorkBuddy 5.6+ keeps its desktop sign-in encrypted, and the plugin says so and points to the browser sign-in instead of a 502 (plugins #18); 0.1.17: a restricted account's 403 11140 ends in provider.WBRestrictedHint, so it rests 2h as restricted (#1849); 0.1.16: WorkBuddy AI's GLM models are text-only, so magpie's image-describing model reads their images (Yirasumi on Discord); 0.1.15: a system prompt sent as a developer message passes the channel check, an object tool_choice is sent as WorkBuddy takes it, and max_completion_tokens goes as max_tokens so the cap holds (plugins #96); 0.1.14: the Credits window says when the soonest credits left run out, for Smart routing to spend them first (cdredfox on X); an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659) + min: "0.1.25", // WorkBuddy AI's fast, balanced and primary models keep the credit rate its config gives as "x0.34 credits", not unknown (plugins #216); 0.1.24: a refused sign-in on a chat over 2 MiB says the 401 and to sign in again: WorkBuddy's front door resets such a request instead of answering, so it read as 502 ECONNRESET (wyp on Discord); 0.1.23: credits used up leave the free models counted out of the credits window, so an account is not ranked spent for them (plugins #138); 0.1.22: an MCP server's tool schemas reach Kimi and DeepSeek: an enum with no type, or of several types, is typed, and true or false where a schema goes is {} or {"not": {}}, so they aren't 400 11133 "Invalid request parameters" (plugins #122); 0.1.21: a model free only at night (Hy4 preview) is never said free, and a whole-day discount shows the price before it, from WorkBuddy's modelPromotions (plugins #121); 0.1.20: tool results followed by the user's message reach WorkBuddy AI's gemini-3.8-flash, not 400 "the conversation must end with a user message" (plugins #113); 0.1.19: an enterprise account's card shows its credits, from the enterprise meter WorkBuddy's usage page reads (#1904); 0.1.18: WorkBuddy 5.6+ keeps its desktop sign-in encrypted, and the plugin says so and points to the browser sign-in instead of a 502 (plugins #18); 0.1.17: a restricted account's 403 11140 ends in provider.WBRestrictedHint, so it rests 2h as restricted (#1849); 0.1.16: WorkBuddy AI's GLM models are text-only, so magpie's image-describing model reads their images (Yirasumi on Discord); 0.1.15: a system prompt sent as a developer message passes the channel check, an object tool_choice is sent as WorkBuddy takes it, and max_completion_tokens goes as max_tokens so the cap holds (plugins #96); 0.1.14: the Credits window says when the soonest credits left run out, for Smart routing to spend them first (cdredfox on X); an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659) agents: []string{w.id}, out: func() ([]Moving, error) { var out []Moving diff --git a/internal/provider/migrate_zed.go b/internal/provider/migrate_zed.go index bdb8f7cb5..9f5b15e31 100644 --- a/internal/provider/migrate_zed.go +++ b/internal/provider/migrate_zed.go @@ -13,7 +13,7 @@ import ( func init() { movers["zed"] = &mover{ pkg: "@magpie-community/opencode-zed-auth", - min: "0.1.9", // a signed-in account whose model list was never read says why; 0.1.8: a free account's plan reads "No plan", as the built-in's; 0.1.6: a failure's status and its sign-in mark as the built-in's; a model token refused while listing marks the account + min: "0.1.10", // the organization with a plan is picked, and a 402 for the saved one moves the account (plugins#232); 0.1.9: a signed-in account whose model list was never read says why; 0.1.8: a free account's plan reads "No plan", as the built-in's; 0.1.6: a failure's status and its sign-in mark as the built-in's; a model token refused while listing marks the account agents: []string{"zed"}, out: func() ([]Moving, error) { var out []Moving diff --git a/internal/provider/modelprefs.go b/internal/provider/modelprefs.go index 5b4120b59..209343737 100644 --- a/internal/provider/modelprefs.go +++ b/internal/provider/modelprefs.go @@ -45,7 +45,7 @@ func modelNameIn(names map[string]string, pid, model string) (string, bool) { // and the model. func splitRef(ref string) (*Provider, string, error) { r := strings.TrimPrefix(strings.TrimSpace(ref), "magpie/") - if strings.HasPrefix(r, GroupPrefix) { + if IsGroupRef(r) { return nil, "", errors.New("that is a routing group, not a provider's model") } pid, model, ok := strings.Cut(r, "/") @@ -213,7 +213,7 @@ func PriceKey(pid, model string) (string, bool) { // reset` over a price still in the file would have the user believe it gone. func DropModelPrice(key string) (bool, error) { key = strings.TrimPrefix(strings.TrimSpace(key), "magpie/") - if strings.HasPrefix(key, GroupPrefix) { + if IsGroupRef(key) { return false, errors.New("that is a routing group, not a provider's model") } pid, model, ok := strings.Cut(key, "/") @@ -1166,7 +1166,7 @@ func SetUpstreamName(ref, name string) error { // now. func DropUpstreamName(key string) (bool, error) { key = strings.TrimPrefix(strings.TrimSpace(key), "magpie/") - if strings.HasPrefix(key, GroupPrefix) { + if IsGroupRef(key) { return false, errors.New("that is a routing group, not a provider's model") } pid, model, ok := strings.Cut(key, "/") diff --git a/internal/provider/modelprefs_test.go b/internal/provider/modelprefs_test.go index 9a2c12d34..29825f539 100644 --- a/internal/provider/modelprefs_test.go +++ b/internal/provider/modelprefs_test.go @@ -94,7 +94,7 @@ func TestModelName(t *testing.T) { if b.Name != "Sol" || b.Default != "" || b.Label() != "Sol · B" { t.Fatalf("%+v %q", b, b.Label()) } - if g := entry(t, "group/auto-sol"); g.Name != "Sol" { + if g := entry(t, "auto/sol"); g.Name != "Sol" { t.Fatalf("the group took a provider's name: %+v", g) } if p, m, ok := Resolve("a/sol"); !ok || p.ID != "a" || m != "sol" { @@ -170,7 +170,7 @@ func TestModelEfforts(t *testing.T) { if got := entry(t, "b/sol").Efforts; !slices.Equal(got, []string{"low", "medium", "high", "max"}) { t.Fatal(got) } - if got := entry(t, "group/auto-sol").Efforts; !slices.Equal(got, []string{"low", "high"}) { + if got := entry(t, "auto/sol").Efforts; !slices.Equal(got, []string{"low", "high"}) { t.Fatal(got) } // the vendor is still asked at any level it has diff --git a/internal/provider/models.go b/internal/provider/models.go index 9d2060d3c..f195280a8 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -257,9 +257,18 @@ func (p Provider) refetch(ctx context.Context) ([]catalog.Model, []string, map[s log.Println(p.ID + ": " + derr.Error()) } } - if err != nil || len(before) == 0 { + if err != nil { return ms, nil, before, err } + if len(before) == 0 { + // nothing to drop against, but a pick set aside comes back + if now := liveIDs(p.ID); len(now) > 0 && len(p.Delisted) > 0 { + if _, derr := dropGonePicks(p.ID, nil, now); derr != nil { + log.Println(p.ID + ": " + derr.Error()) + } + } + return ms, nil, before, nil + } now := liveIDs(p.ID) if len(now) == 0 { return ms, nil, before, nil @@ -284,7 +293,9 @@ func liveIDs(id string) map[string]bool { } // dropGonePicks takes out of the saved provider's picks those before had -// and now doesn't, and answers them. +// and now doesn't, and answers them. They are set aside in its Delisted, +// not forgotten, and those of its Delisted now has go back among the picks +// (relistPicks): a list that shrank for a while gives back what it took. func dropGonePicks(id string, before, now map[string]bool) ([]string, error) { f, err := read() if err != nil { @@ -294,21 +305,56 @@ func dropGonePicks(id string, before, now map[string]bool) ([]string, error) { if i < 0 { return nil, nil } + q := &f.Providers[i] var kept, dropped []string - for _, m := range f.Providers[i].Models { + for _, m := range q.Models { if before[m] && !now[m] { dropped = append(dropped, m) } else { kept = append(kept, m) } } - if len(dropped) == 0 { + back := relistPicks(q, now) + if len(dropped) == 0 && !back { return nil, nil } - f.Providers[i].Models = kept + if len(dropped) > 0 { + q.Models = kept + for _, m := range dropped { + if !slices.Contains(q.Delisted, m) { + q.Delisted = append(q.Delisted, m) + } + } + } return dropped, store(f) } +// relistPicks puts back among q's picks those of its Delisted the list now +// has, and says whether it put any back. +func relistPicks(q *Provider, now map[string]bool) bool { + if len(q.Delisted) == 0 || len(now) == 0 { + return false + } + var still, back []string + for _, m := range q.Delisted { + if now[m] { + back = append(back, m) + } else { + still = append(still, m) + } + } + if len(back) == 0 { + return false + } + for _, m := range back { + if !slices.Contains(q.Models, m) { + q.Models = append(q.Models, m) + } + } + q.Delisted = still + return true +} + // fetch is Fetch without the picks looked after. func (p Provider) fetch(ctx context.Context) ([]catalog.Model, error) { ctx = p.Via(ctx) @@ -1382,11 +1428,16 @@ func (p Provider) keyLists() (*keyLists, bool) { // none of its models are served, its balance and usage still read. func (p Provider) ServesNone() bool { return p.NoModels && len(p.Models) == 0 } +// waitsForPicks is a provider whose every pick its list stopped listing +// (Delisted, none left in Models): none are served until one comes back, +// not the vendor's whole list as for a provider nothing was picked of. +func (p Provider) waitsForPicks() bool { return len(p.Models) == 0 && len(p.Delisted) > 0 } + // Exposed lists the models magpie offers to agents for this provider: the // user's picks; else the preset's; else everything, when that is few; none // after Select none (ServesNone). func (p Provider) Exposed() []catalog.Model { - if p.ServesNone() { + if p.ServesNone() || p.waitsForPicks() { return nil } avail := p.Available() @@ -2282,7 +2333,7 @@ type Entry struct { // provider not kept unlisted. A provider switched off has none in it. func Catalog() []Entry { entries := providerEntries() - out := groupEntries(entries) + out := slices.Clone(groupEntries(entries)) // held: the caller's to change kept := unlistedByGroups(entries) for _, e := range entries { if !e.Provider.Unlisted && !kept[e.ID] { @@ -2321,7 +2372,7 @@ func unlistedByGroups(entries []Entry) map[string]bool { // model a routing group can be made of, or a request can name. func Served() []Entry { entries := providerEntries() - return append(groupEntries(entries), entries...) + return append(slices.Clone(groupEntries(entries)), entries...) } // Unlisted are the models Served has and Catalog doesn't: those of the @@ -2494,6 +2545,13 @@ func entryIn(entries []Entry, id string) (Entry, bool) { return e, true } } + if gid, ok := GroupIDOf(id); ok { // a found group by either of its ids + for _, e := range entries { + if e.Group == gid { + return e, true + } + } + } return Entry{}, false } @@ -2510,11 +2568,9 @@ func Resolve(id string) (Provider, string, bool) { // Claude Code's mark for a model with a 1M window; it drops it before // asking, but a value in its settings still has it id = strings.TrimSuffix(strings.TrimSpace(id), "[1m]") - if strings.HasPrefix(id, GroupPrefix) { - for _, e := range Catalog() { - if e.ID == id { - return e.Provider, e.Model, true - } + if IsGroupRef(id) { + if e, ok := entryIn(Catalog(), id); ok { + return e.Provider, e.Model, true } return Provider{}, "", false } @@ -2522,8 +2578,10 @@ func Resolve(id string) (Provider, string, bool) { } func resolveIn(entries []Entry, id string) (Provider, string, bool) { - for _, e := range entries { - if e.ID == id { + // by index: an Entry, its Provider in it, is large, and a copy of each + // one looked past was most of a group's members resolved (membersIn) + for i := range entries { + if e := &entries[i]; e.ID == id { return e.Provider, e.Model, true } } @@ -2534,15 +2592,11 @@ func resolveIn(entries []Entry, id string) (Provider, string, bool) { return *p, model, true } } - var hits []Entry - for _, e := range entries { - if e.Model == id { - hits = append(hits, e) + for i := range entries { + if e := &entries[i]; e.Model == id { + return e.Provider, e.Model, true // the first that serves it } } - if len(hits) >= 1 { - return hits[0].Provider, hits[0].Model, true - } // not exposed, but some provider lists it var found []Provider for _, p := range heldOf("listed", listedBy)[id] { @@ -2870,7 +2924,7 @@ func DropModelOutput(id string) (string, bool, error) { // display name, and the same resolution outputOf reads it back under. func outputKeyOf(id string) (string, error) { r := strings.TrimPrefix(strings.TrimSpace(id), "magpie/") - if strings.HasPrefix(r, GroupPrefix) { + if IsGroupRef(r) { return "", errorf("that is a routing group, not a provider's model") } pid, model, ok := strings.Cut(r, "/") diff --git a/internal/provider/ollama_decide.go b/internal/provider/ollama_decide.go new file mode 100644 index 000000000..465d1791a --- /dev/null +++ b/internal/provider/ollama_decide.go @@ -0,0 +1,74 @@ +package provider + +import ( + "encoding/json" + "fmt" + "slices" + "strings" + + "github.com/yetone/magpie/internal/catalog" +) + +// Ollama (0.35.0 and later, 0.40.5 for its cloud models) serves decision +// models (Nimble, Clef, Tev …) at POST /v1/systemone, System One's +// questions and answers, on the local server and at ollama.com with an API +// key alike (docs.ollama.com/api/systemone; Nanka on Discord). Its +// /v1/models lists them among its chat models with nothing to tell them +// apart; its /api/tags, asked with the same key, gives each model its +// capabilities, "decision" for these (and "vision" for one that reads +// images, as Clef does). That list is the provider's decision models, as +// oMLX's and MLX-Serve's are (listsDecisions), and a model it doesn't mark +// stays a chat model. An Ollama older than its System One lists no +// capabilities, so none. +func (p Provider) ollamaDecides() bool { + return (p.Preset == "ollama" || p.Preset == "ollama-cloud") && p.Decide != "" && !p.DecideOnly() +} + +// ollamaCloudContext is the window Ollama's docs give a System One model +// in its cloud. +const ollamaCloudContext = 65_536 + +// ollamaDecisions is where an Ollama server lists its models with their +// capabilities: /api/tags at the root its /v1 is under. +func ollamaDecisions(base string) string { + return strings.TrimSuffix(strings.TrimRight(base, "/"), "/v1") + "/api/tags" +} + +// listedOllamaDecide are the decision models in Ollama's /api/tags, by the +// name /v1/models gives them too, with the window the list gives (a GGUF's +// details.context_length), else, in Ollama's cloud (at ollama.com, or a +// local server's cloud model, which names its remote_host), the cloud's. +func listedOllamaDecide(base string, b []byte) ([]catalog.Model, error) { + var out struct { + Models *[]struct { + Name string `json:"name"` + Model string `json:"model"` + RemoteHost string `json:"remote_host"` + Capabilities []string `json:"capabilities"` + Details struct { + ContextLength int `json:"context_length"` + } `json:"details"` + } `json:"models"` + } + if err := json.Unmarshal(b, &out); err != nil || out.Models == nil { + return nil, fmt.Errorf("not Ollama's model list") + } + cloud := HostOf(base) == "ollama.com" + ms := []catalog.Model{} + for _, m := range *out.Models { + id := m.Model + if id == "" { + id = m.Name + } + if id == "" || !slices.Contains(m.Capabilities, "decision") { + continue + } + images := slices.Contains(m.Capabilities, "vision") + ctx := m.Details.ContextLength + if ctx <= 0 && (cloud || m.RemoteHost != "") { + ctx = ollamaCloudContext + } + ms = append(ms, catalog.Model{ID: id, Name: id, Context: ctx, ImageInput: &images, Images: images}) + } + return ms, nil +} diff --git a/internal/provider/ollama_decide_test.go b/internal/provider/ollama_decide_test.go new file mode 100644 index 000000000..692f5940a --- /dev/null +++ b/internal/provider/ollama_decide_test.go @@ -0,0 +1,160 @@ +package provider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "slices" + "sync" + "testing" +) + +// The bytes below were saved from Ollama 0.40.6 (a local server with +// tev1:0.8b and smollm:135m pulled) and from ollama.com/api/tags on +// 2026-10-19, trimmed to the rows a test needs. +const ( + ollamaLocalTags = `{"models":[{"name":"smollm:135m","model":"smollm:135m","modified_at":"2026-10-19T23:15:35.885392239+08:00","size":91739413,"digest":"b0b2a46174385c0adcaa77ff245ffeced5fc4a61447b6f221b2beb5c5a760133","details":{"parent_model":"","format":"gguf","family":"llama","families":["llama"],"parameter_size":"134.52M","quantization_level":"Q4_0","context_length":2048,"embedding_length":576,"runner":"ggml"},"capabilities":["completion"]},{"name":"tev1:0.8b","model":"tev1:0.8b","modified_at":"2026-10-19T23:14:31.147707454+08:00","size":1524372929,"digest":"b661d56508169d2b6c4cab5a047409f50bd9694a215bc232469d44291f4bdbf1","details":{"parent_model":"","format":"safetensors","family":"qwen3_5","families":["qwen3_5"],"parameter_size":"752M","quantization_level":"BF16","runner":"mlx"},"capabilities":["decision"]}]}` + ollamaLocalModels = `{"object":"list","data":[{"id":"smollm:135m","object":"model","created":1792422935,"owned_by":"library"},{"id":"tev1:0.8b","object":"model","created":1792422871,"owned_by":"library"}]}` + ollamaSystemOne = `{"model":"tev1:0.8b","answers":{"ok":{"type":"noul","noul":0.2234409293546222}},"usage":{"input_tokens":107,"output_tokens":0},"prompt_eval_cached_count":0}` + ollamaNoChat = `{"error":{"message":"\"tev1:0.8b\" does not support chat","type":"invalid_request_error","param":null,"code":null}}` + ollamaCloudTags = `{"models":[{"name":"glm-5.3","model":"glm-5.3","modified_at":"2026-08-28T08:00:00-07:00","size":755433728000,"digest":"632dfda18c6d","details":{"parent_model":"","format":"","family":"","families":null,"parameter_size":"","quantization_level":""},"capabilities":["completion","thinking","tools"]},{"name":"clef:27b","model":"clef:27b","modified_at":"2026-10-04T09:00:00-07:00","size":54969731792,"digest":"490a326b58a0","details":{"parent_model":"","format":"","family":"","families":null,"parameter_size":"","quantization_level":""},"capabilities":["decision","vision"]}]}` + // Ollama before System One (0.6.8) lists no capabilities + ollamaOldTags = `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","modified_at":"2025-05-01T10:00:00+08:00","size":5225388164,"digest":"500a1f067a9f","details":{"parent_model":"","format":"gguf","family":"qwen3","families":["qwen3"],"parameter_size":"8.2B","quantization_level":"Q4_K_M"}}]}` +) + +// fakeOllama answers as Ollama 0.40.6 does: /api/tags and /v1/models list +// a chat model and a decision model, /v1/systemone answers System One, and +// chat completions turn the decision model away. +func fakeOllama(t *testing.T) (base string, asked func() []string) { + t.Helper() + var mu sync.Mutex + var models []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/api/tags": + w.Write([]byte(ollamaLocalTags)) + case "/v1/models": + w.Write([]byte(ollamaLocalModels)) + case "/v1/systemone": + var q struct{ Model string } + json.NewDecoder(r.Body).Decode(&q) + mu.Lock() + models = append(models, q.Model) + mu.Unlock() + w.Write([]byte(ollamaSystemOne)) + case "/v1/chat/completions": + var q struct{ Model string } + json.NewDecoder(r.Body).Decode(&q) + if q.Model == "tev1:0.8b" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(ollamaNoChat)) + return + } + w.Write([]byte(`{"id":"chatcmpl-382","object":"chat.completion","created":1792422957,"model":"smollm:135m","system_fingerprint":"fp_ollama","choices":[{"index":0,"message":{"role":"assistant","content":"Hello! How can I"},"finish_reason":"length"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}`)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { + mu.Lock() + defer mu.Unlock() + return slices.Clone(models) + } +} + +// An Ollama provider saved before its preset had System One (Nanka on +// Discord): the models its /api/tags marks "decision" classify routing +// groups through /v1/systemone, and agents no longer see them as chat +// models. +func TestOllamaDecisionModels(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + base, asked := fakeOllama(t) + + if err := Save(Provider{ID: "ollama", Name: "Ollama", Preset: "ollama", Chat: base + "/v1", Anthropic: base}); err != nil { + t.Fatal(err) + } + p, err := Find("ollama") + if err != nil || !p.Decides() || p.DecideOnly() || p.Decide != base+"/v1" { + t.Fatalf("Ollama has no decision API at its own server: %+v", p) + } + if _, _, _, err := p.refetch(context.Background()); err != nil { + t.Fatal(err) + } + p, _ = Find("ollama") + + if !p.DecidesModel("tev1:0.8b") || p.DecidesModel("smollm:135m") { + t.Fatal("decision models are not the ones Ollama's capabilities say are") + } + var deciders []string + for _, e := range Deciders() { + deciders = append(deciders, e.ID) + } + if !slices.Equal(deciders, []string{"ollama/tev1:0.8b"}) { + t.Fatalf("deciders: %v", deciders) + } + var agents []string + for _, e := range providerEntries() { + agents = append(agents, e.Model) + } + if !slices.Equal(agents, []string{"smollm:135m"}) { + t.Fatalf("agents' models: %v", agents) + } + + q, m, err := RouteDecider("ollama/tev1:0.8b") + if err != nil || q.ID != "ollama" || m != "tev1:0.8b" { + t.Fatalf("routed to %s %s: %v", q.ID, m, err) + } + if err := q.AskSystemOne(context.Background(), m); err != nil { + t.Fatal(err) + } + if _, m, _ := RouteDecider("ollama"); m != "tev1:0.8b" { + t.Fatalf("Ollama's default decision model: %q", m) + } + if got := asked(); !slices.Equal(got, []string{"tev1:0.8b"}) { + t.Fatalf("asked: %v", got) + } + results := p.TestModels(context.Background(), []string{"tev1:0.8b"}) + if len(results) != 1 || !results[0].OK || results[0].Protocol != "decide" { + t.Fatalf("TestModels tev1:0.8b: %+v", results) + } +} + +// Ollama Cloud's list marks Clef a decision model that reads images, with +// the cloud's window; a chat model, and every model of an Ollama from +// before System One, is none. +func TestListedOllamaDecide(t *testing.T) { + ms, err := listedOllamaDecide("https://ollama.com/v1", []byte(ollamaCloudTags)) + if err != nil || len(ms) != 1 || ms[0].ID != "clef:27b" || ms[0].Context != 65_536 || ms[0].ImageInput == nil || !*ms[0].ImageInput { + t.Fatalf("cloud: %+v %v", ms, err) + } + ms, err = listedOllamaDecide("http://localhost:11434/v1", []byte(ollamaLocalTags)) + if err != nil || len(ms) != 1 || ms[0].ID != "tev1:0.8b" || ms[0].Context != 0 || ms[0].ImageInput == nil || *ms[0].ImageInput { + t.Fatalf("local: %+v %v", ms, err) + } + if ms, err := listedOllamaDecide("http://localhost:11434/v1", []byte(ollamaOldTags)); err != nil || len(ms) != 0 { + t.Fatalf("old Ollama: %+v %v", ms, err) + } + if _, err := listedOllamaDecide("http://localhost:11434/v1", []byte(`404 page not found`)); err == nil { + t.Fatal("a 404's body read as a list") + } + if got := ollamaDecisions("https://ollama.com/v1"); got != "https://ollama.com/api/tags" { + t.Fatalf("list at %s", got) + } + for _, id := range []string{"ollama", "ollama-cloud"} { + pr := Preset(id) + if pr == nil || pr.Decide == "" || pr.Decide != pr.Chat { + t.Fatalf("%s's preset has no System One beside its chat: %+v", id, pr) + } + } + p := Provider{ID: "ollama-x", Preset: "ollama-cloud", Chat: "http://127.0.0.1:1/v1", Decide: "http://127.0.0.1:1/v1"} + if got := p.decideListed(); len(got) != 0 || p.Jev() != "" { + t.Fatalf("made up: %v %q", got, p.Jev()) + } +} diff --git a/internal/provider/opencode_balance_test.go b/internal/provider/opencode_balance_test.go new file mode 100644 index 000000000..4558a9f02 --- /dev/null +++ b/internal/provider/opencode_balance_test.go @@ -0,0 +1,109 @@ +package provider + +import ( + "context" + "errors" + "net/http" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/agentenv" +) + +// noVendor answers no request and keeps what was asked: OpenCode tells +// a Zen key no balance, so there is nothing to ask. +type noVendor struct{ asked *[]string } + +func (n noVendor) RoundTrip(r *http.Request) (*http.Response, error) { + *n.asked = append(*n.asked, r.URL.String()) + return nil, errors.New("no network in this test") +} + +// ttmrmx on X: an OpenCode Zen key's balance card wasn't shown at all. +// OpenCode tells no key the workspace's credits, so the card says that, +// and where they are shown, on every surface that asks a key's balance: +// the Usage page's cards (KeyBalances) and the editor, TUI and CLI +// (Balance). One card a provider, however many keys: the credits are the +// workspace's. +func TestOpenCodeZenSaysItTellsNoBalance(t *testing.T) { + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("PATH", h) + for _, v := range agentenv.Vars { + t.Setenv(v, "") + } + keyBalanceCache.data = nil + t.Cleanup(func() { keyBalanceCache.data = nil }) + old := http.DefaultClient.Transport + var asked []string + http.DefaultClient.Transport = noVendor{&asked} + t.Cleanup(func() { http.DefaultClient.Transport = old }) + + zen := Provider{ID: "opencode-zen", Name: "OpenCode Zen", Chat: "https://opencode.ai/zen/v1", Responses: "https://opencode.ai/zen/v1", + Anthropic: "https://opencode.ai/zen", Key: "zen-a", Keys: []KeyAccount{{Key: "zen-a"}, {Key: "zen-b", Name: "spare"}}} + for _, p := range []Provider{ + zen, + // Zen at the inference API, models.dev's URL for it + {ID: "zen-inference", Name: "Zen", Chat: "https://opencode.ai/inference/openai/v1", Key: "zen-c"}, + // OpenCode Go: its plan windows are its card, not a balance + {ID: "opencode-go", Name: "OpenCode Go", Chat: "https://opencode.ai/zen/go/v1", Key: "go-k"}, + // a provider of the user's own at the inference API: its vendor's + {ID: "custom", Name: "Custom", Chat: "https://opencode.ai/inference/custom/acme/v1", Key: "c"}, + } { + if err := Save(p); err != nil { + t.Fatal(err) + } + } + var lines []string + for _, q := range KeyBalances(context.Background()) { + lines = append(lines, q.Provider+"|"+q.User+"|"+q.Balance+"|"+q.SeeAt) + if !strings.HasPrefix(q.Error, "OpenCode tells no API key its balance") || !strings.Contains(q.Error, "Overview → Credits") { + t.Errorf("%s's card says %q", q.Provider, q.Error) + } + } + want := "opencode-zen|||https://opencode.ai/console,zen-inference|||https://opencode.ai/console" + if got := strings.Join(lines, ","); got != want { + t.Fatalf("cards:\n%s\nwant\n%s", got, want) + } + if len(asked) != 0 { + t.Fatalf("asked %v", asked) + } + amount, ok, err := Balance(context.Background(), zen) + if !ok || amount != "" || !errors.Is(err, errOpenCodeNoBalance) { + t.Fatalf("Balance = %q %v %v", amount, ok, err) + } + // a Balance URL of the user's own is still asked + zen.BalanceURL = "https://opencode.ai/somewhere" + if _, ok, err := Balance(context.Background(), zen); !ok || errors.Is(err, errOpenCodeNoBalance) { + t.Fatalf("own Balance URL: %v %v", ok, err) + } + if strings.Join(asked, ",") != "https://opencode.ai/somewhere" { + t.Fatalf("asked %v", asked) + } +} + +func TestOpenCodeGateway(t *testing.T) { + for base, want := range map[string]string{ + "https://opencode.ai/zen/v1": "zen", + "https://opencode.ai/zen": "zen", + "https://opencode.ai/inference/openai/v1": "zen", + "https://opencode.ai/inference/anthropic": "zen", + "https://opencode.ai/zen/go/v1": "go", + "https://opencode.ai/zen/go": "go", + "https://opencode.ai/inference/go/openai/v1": "go", + "https://opencode.ai/inference/go/anthropic": "go", + "https://opencode.ai/inference/custom/x/v1": "", + "https://opencode.ai/console": "", + "https://example.com/zen/go/v1": "", + "": "", + } { + if got := openCodeGateway(base); got != want { + t.Errorf("%q: %q, want %q", base, got, want) + } + } +} diff --git a/internal/provider/opencode_endpoints.go b/internal/provider/opencode_endpoints.go index e39b2d863..f49cbf7d2 100644 --- a/internal/provider/opencode_endpoints.go +++ b/internal/provider/opencode_endpoints.go @@ -29,6 +29,32 @@ func openCodeRoot(base string) (root, catalogID string) { return "", "" } +// openCodeGateway says which of OpenCode's gateways base is at: "go" for +// Go's (…/zen/go, or the inference API's …/inference/go, whatever follows: +// /v1, or /openai/v1 and /anthropic, the URLs models.dev and Go's docs +// give since October 2026), "zen" for Zen's (…/zen, …/inference: the +// workspace's pay-as-you-go credits), "" for any other, a provider of the +// user's own at …/inference/custom among them, which its vendor bills. +func openCodeGateway(base string) string { + u, err := url.Parse(strings.TrimSpace(base)) + if err != nil || !openCodeHost(u.Hostname()) { + return "" + } + seg := strings.Split(strings.Trim(u.Path, "/"), "/") + if seg[0] != "zen" && seg[0] != "inference" { + return "" + } + if len(seg) > 1 { + switch seg[1] { + case "go": + return "go" + case "custom": + return "" + } + } + return "zen" +} + // openCodeGemini is the base of Gemini's generateContent at the gateway // root is: models/{model}:streamGenerateContent is asked under it. Zen's // /zen/v1 relays it to the inference API's Google route, reading the key diff --git a/internal/provider/plainnames_test.go b/internal/provider/plainnames_test.go index f76879b0b..117c886c5 100644 --- a/internal/provider/plainnames_test.go +++ b/internal/provider/plainnames_test.go @@ -39,7 +39,7 @@ func TestPlainNames(t *testing.T) { return out } - full := []string{"a/sol=My Sol · A", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"} + full := []string{"a/sol=My Sol · A", "auto/sol=Sol · routing group", "b/sol=Sol · B"} if got := codex(); !slices.Equal(got, full) { t.Fatalf("by default: %q", got) } @@ -51,7 +51,7 @@ func TestPlainNames(t *testing.T) { t.Fatalf("agents told %d times, setting %v", touched, settings.Load().PlainNames) } // the group found for sol and b's sol are both "Sol": they keep theirs - want := []string{"a/sol=My Sol", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"} + want := []string{"a/sol=My Sol", "auto/sol=Sol · routing group", "b/sol=Sol · B"} if got := codex(); !slices.Equal(got, want) { t.Fatalf("plain: %q", got) } @@ -66,7 +66,7 @@ func TestPlainNames(t *testing.T) { if err := settings.Save(s); err != nil { t.Fatal(err) } - if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "group/auto-sol=Sol"}) { + if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "auto/sol=Sol"}) { t.Fatalf("plain, b hidden: %q", got) } if got := other(); !slices.Equal(got, []string{"My Sol", "Sol · B", "Sol · routing group"}) { @@ -76,7 +76,7 @@ func TestPlainNames(t *testing.T) { if err := SetPlainNames(false); err != nil { t.Fatal(err) } - if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol · A", "group/auto-sol=Sol · routing group"}) || touched != 2 { + if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol · A", "auto/sol=Sol · routing group"}) || touched != 2 { t.Fatalf("off again: %q, told %d", got, touched) } } diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index e0defa263..476e5d6fd 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -37,6 +37,12 @@ type planQuotaSource struct { func planQuotaSourceOf(p Provider) (planQuotaSource, bool) { for _, base := range []string{p.Chat, p.Anthropic, p.Responses} { coding := strings.Contains(base, "/api/coding/") + if openCodeGateway(base) == "go" { + // Go at Zen's gateway or at the inference API, the URL + // models.dev and Go's docs give since October 2026: the same + // key, told its windows at the same usage query + return planQuotaSource{"https://opencode.ai/zen/go/v1/usage", true, readOpenCodeGo, true}, true + } switch hostOf(base) { case "open.bigmodel.cn": return planQuotaSource{"https://open.bigmodel.cn/api/monitor/usage/quota/limit", false, readZhipuPlan, coding}, true @@ -55,10 +61,6 @@ func planQuotaSourceOf(p Provider) (planQuotaSource, bool) { // a Coding Plan key (sk-cp-…) is told its windows; a // pay-as-you-go key isn't, and gets no card (#387) return planQuotaSource{"https://" + hostOf(base) + "/v1/token_plan/remains", true, readMiniMaxPlan, false}, true - case "opencode.ai": - if u := strings.TrimSuffix(base, "/"); strings.HasSuffix(u, "/zen/go") || strings.Contains(u, "/zen/go/") { - return planQuotaSource{"https://opencode.ai/zen/go/v1/usage", true, readOpenCodeGo, true}, true - } case "ollama.com": // Ollama Cloud's included allowance (#1888); a key with none // gets no card diff --git a/internal/provider/planquota_test.go b/internal/provider/planquota_test.go index 858fd102a..2ca41b1e4 100644 --- a/internal/provider/planquota_test.go +++ b/internal/provider/planquota_test.go @@ -27,6 +27,14 @@ func TestPlanQuotaSource(t *testing.T) { {Provider{Chat: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go"}, "https://opencode.ai/zen/go/v1/usage", true, true}, {Provider{Anthropic: "https://opencode.ai/zen/go"}, "https://opencode.ai/zen/go/v1/usage", true, true}, {Provider{Chat: "https://opencode.ai/zen/v1"}, "", false, false}, // Zen is pay as you go + // Go at the inference API, as models.dev and Go's docs give it + // since October 2026 (ttmrmx on X: no card) + {Provider{Chat: "https://opencode.ai/inference/go/openai/v1"}, "https://opencode.ai/zen/go/v1/usage", true, true}, + {Provider{Chat: "https://opencode.ai/inference/go/v1", Anthropic: "https://opencode.ai/inference/go"}, "https://opencode.ai/zen/go/v1/usage", true, true}, + {Provider{Anthropic: "https://opencode.ai/inference/go/anthropic"}, "https://opencode.ai/zen/go/v1/usage", true, true}, + {Provider{Chat: "https://opencode.ai/inference/openai/v1"}, "", false, false}, // Zen's + {Provider{Chat: "https://opencode.ai/inference/custom/acme/v1"}, "", false, false}, // the user's own provider + {Provider{Chat: "https://example.com/zen/go/v1"}, "", false, false}, {Provider{Chat: "https://api.kimi.com/coding/v1", Anthropic: "https://api.kimi.com/coding"}, "https://api.kimi.com/coding/v1/usages", true, true}, {Provider{Anthropic: "https://api.kimi.ai/coding/"}, "https://api.kimi.ai/coding/v1/usages", true, true}, {Provider{Chat: "https://api.commandcode.ai/provider/v1", Anthropic: "https://api.commandcode.ai/provider"}, "https://api.commandcode.ai/alpha/billing/credits", true, false}, @@ -335,6 +343,8 @@ func TestPlanQuotas(t *testing.T) { Keys: []KeyAccount{{Key: "glm-a"}, {Key: "glm-b", Name: "home"}, {Key: "glm-off", Off: true}}}, {ID: "glm-api", Name: "GLM API", Chat: "https://open.bigmodel.cn/api/paas/v4", Key: "glm-payg"}, {ID: "go", Name: "OpenCode Go", Chat: "https://opencode.ai/zen/go/v1", Key: "go-k"}, + // Go at models.dev's URL for it: the same card (ttmrmx on X) + {ID: "go-inference", Name: "OpenCode Go", Chat: "https://opencode.ai/inference/go/openai/v1", Key: "go-k"}, {ID: "zen", Name: "Zen", Chat: "https://opencode.ai/zen/v1", Key: "zen-k"}, {ID: "minimax-cn", Name: "MiniMax (China)", Chat: "https://api.minimaxi.com/v1", Anthropic: "https://api.minimaxi.com/anthropic", Key: "sk-cp-k"}, {ID: "minimax-payg", Name: "MiniMax API", Anthropic: "https://api.minimaxi.com/anthropic", Key: "sk-api-k"}, @@ -347,7 +357,7 @@ func TestPlanQuotas(t *testing.T) { for _, q := range PlanQuotas(context.Background()) { got[q.Provider+"/"+q.User] = q } - if len(got) != 4 { + if len(got) != 5 { t.Fatalf("cards: %+v", got) } if q := got["minimax-cn/"]; len(q.Windows) != 2 || q.Windows[0].Name != "5 hours" && q.Windows[0].Name != "Allowance" || q.Windows[0].Used != 25 || q.Windows[1].Name != "7 days" || q.Windows[1].Used != 4 { @@ -370,6 +380,9 @@ func TestPlanQuotas(t *testing.T) { if q := got["go/"]; q.Name != "OpenCode Go" || len(q.Windows) != 1 || q.Windows[0].Name != "5 hours" { t.Errorf("go: %+v", q) } + if q := got["go-inference/"]; len(q.Windows) != 1 || q.Windows[0].Name != "5 hours" || q.Error != "" { + t.Errorf("go at the inference API: %+v", q) + } // The custom GLM provider is recognized by its endpoint, not its id // or key labels, and the provenance survives PlanQuotas' cache. reset := time.UnixMilli(4102444800000) @@ -380,7 +393,7 @@ func TestPlanQuotas(t *testing.T) { t.Errorf("%s/%s: hidden=%v", q.Provider, q.User, hidden) } } - if qs := notShown(PlanQuotas(context.Background()), []SubscriptionQuota{sub}); len(qs) != 2 { + if qs := notShown(PlanQuotas(context.Background()), []SubscriptionQuota{sub}); len(qs) != 3 { t.Fatalf("cached plans after deduplication: %+v", qs) } // A restart loses the in-memory provenance; a failed read restores @@ -393,10 +406,10 @@ func TestPlanQuotas(t *testing.T) { lastQuotas.m, lastQuotas.loaded = nil, false lastQuotas.Unlock() qs := PlanQuotas(context.Background()) - if len(qs) != 4 { + if len(qs) != 5 { t.Fatalf("restored plans: %+v", qs) } - if kept := notShown(qs, []SubscriptionQuota{sub}); len(kept) != 2 { + if kept := notShown(qs, []SubscriptionQuota{sub}); len(kept) != 3 { t.Fatalf("restored plans after deduplication: %+v", kept) } } diff --git a/internal/provider/plugin_accounts.go b/internal/provider/plugin_accounts.go index c5fb8af12..3febd1b24 100644 --- a/internal/provider/plugin_accounts.go +++ b/internal/provider/plugin_accounts.go @@ -345,13 +345,19 @@ func pluginSignInAt() uint64 { // a request's 401 that ended clean took the mark off an account the // vendor had just refused. func notePluginLapseSince(pp plugin.Provider, key string, status int, began uint64) { + notePluginLapseOf(pluginAgent(pp), key, status, began, func(user string) string { return lapsedText(pp, user) }) +} + +// notePluginLapseOf is notePluginLapseSince by the account's agent, so a +// mark can be cleared without the plugin's provider at hand. +func notePluginLapseOf(agent, key string, status int, began uint64, text func(user string) string) { refused := status == http.StatusUnauthorized if !refused && (status < 200 || status > 299) { return } loginsMu.Lock() defer loginsMu.Unlock() - said := pluginAgent(pp) + "/" + key + said := agent + "/" + key if pluginSignInSaid[said] > began { return } @@ -362,10 +368,10 @@ func notePluginLapseSince(pp plugin.Provider, key string, status int, began uint pluginSignInSaid[said] = began ls := readLogins() for i, l := range ls { - if l.Agent == pluginAgent(pp) && l.Home == key { + if l.Agent == agent && l.Home == key { want := "" if refused { - want = lapsedText(pp, l.User) + want = text(l.User) } if l.Lapsed != want { ls[i].Lapsed = want @@ -387,11 +393,14 @@ func lapsedText(pp plugin.Provider, user string) string { // the built-in's did (#320). The account's kept usage reading goes too: it // was read under the old sign-in, and for a minute it would answer the // next reading with the old sign-in's "expired" without asking the plugin, -// and so without marking or clearing anything. +// and so without marking or clearing anything. The mark goes by the +// account alone: the providers' list is empty while another magpie's +// change to plugins.json is read again, and a sign-in finished then left +// the account saying "sign in again" (#2748). func clearPluginLapse(saved plugin.Saved) { + notePluginLapseOf("plugin:"+saved.Provider, saved.Account, http.StatusOK, toldNow, nil) for _, pp := range plugin.Cached() { if pp.ID == saved.Provider { - notePluginLapse(pp, saved.Account, http.StatusOK) if user := pluginLabels(pp)[saved.Account]; user != "" { StaleAllowance(pluginAgent(pp), user) } diff --git a/internal/provider/plugin_delisted_test.go b/internal/provider/plugin_delisted_test.go new file mode 100644 index 000000000..0689367f1 --- /dev/null +++ b/internal/provider/plugin_delisted_test.go @@ -0,0 +1,243 @@ +package provider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/settings" +) + +// ourFree is a provider listing ids as Our Free Model's plugin does: its +// free pools' models, and its account channels' as "channel/model". +func ourFree(ids ...string) []plugin.Provider { + p := plugin.Provider{ID: "our-free-model", Spec: "magpie-our-free-model", Name: "Our Free Model", + NPM: "@ai-sdk/openai-compatible"} + for _, id := range ids { + p.Models = append(p.Models, plugin.Model{ID: id, Name: id, NPM: "@ai-sdk/openai-compatible"}) + } + return []plugin.Provider{p} +} + +// Our Free Model's service, started again with magpie after an update, +// lists its free pools at once and its account channels' models only once +// it has read them, so the list the gateway's magpie read a minute after +// it started was short. The picks it didn't have were dropped for good, +// and its user picked every model again after each update (多喝热水 on +// Discord). They are set aside now, not served while the list leaves them +// out, and picked again when it lists them; the loop asks again soon after +// a list left a pick out, not an hour later. +func TestPluginPicksComeBackWithTheirList(t *testing.T) { + claudeHome(t) + t.Setenv("MAGPIE_BUN", "") + write := func(name string, v any) { + t.Helper() + b, _ := json.Marshal(v) + if err := os.MkdirAll(settings.Dir(), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(settings.Dir(), name), b, 0o600); err != nil { + t.Fatal(err) + } + } + write("plugins.json", map[string]any{"plugins": []map[string]any{{"spec": "magpie-our-free-model"}}}) + write("plugin-auth.json", map[string]any{"our-free-model": map[string]any{"type": "api", "key": "managed"}}) + full := ourFree("pool-a", "pool-b", "qoder/claude-x", "kiro/claude-y", "kiro/claude-z") + plugin.UseCached(full) + t.Cleanup(func() { plugin.UseCached(nil) }) + // picked in the editor from the full list: kiro/claude-z left unpicked + if err := Save(Provider{ID: "our-free-model", Models: []string{"pool-a", "qoder/claude-x", "kiro/claude-y"}}); err != nil { + t.Fatal(err) + } + + answers := make(chan []plugin.Provider) + asked := make(chan struct{}) + oldList, oldFirst, oldEvery, oldSoon := relistPlugins, relistFirst, relistEvery, relistSoon + relistPlugins = func(ctx context.Context) ([]plugin.Provider, error) { + select { + case asked <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + select { + case ps := <-answers: + plugin.UseCached(ps) // as plugin.Providers keeps it + return ps, nil + case <-ctx.Done(): + return nil, ctx.Err() + } + } + // an hour between lists, unless one left a pick out + relistFirst, relistEvery, relistSoon = time.Millisecond, time.Hour, time.Millisecond + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + t.Cleanup(func() { + cancel() + <-done + relistPlugins, relistFirst, relistEvery, relistSoon = oldList, oldFirst, oldEvery, oldSoon + }) + go func() { defer close(done); KeepPluginsListed(ctx) }() + wait := func(what string) { + t.Helper() + select { + case <-asked: + case <-time.After(10 * time.Second): + t.Fatal(what) + } + } + wait("the plugins weren't asked") + answers <- ourFree("pool-a", "pool-b") // the channels not read yet + // asked again soon: the hour's wait would fail this + wait("a list that left picks out wasn't asked for again soon") + + p, err := Find("our-free-model") + if err != nil { + t.Fatal(err) + } + if !slices.Equal(p.Models, []string{"pool-a"}) || !slices.Equal(p.Delisted, []string{"qoder/claude-x", "kiro/claude-y"}) { + t.Fatalf("short list: picks %v, set aside %v", p.Models, p.Delisted) + } + if got := servedIDs(t, "our-free-model"); !slices.Equal(got, []string{"pool-a"}) { + t.Fatalf("served while the list is short: %v", got) + } + // the editor saves something else, sending no Delisted: kept + p.Models = []string{"pool-a", "pool-b"} + if err := Save(*p); err != nil { + t.Fatal(err) + } + + answers <- full + select { + case <-asked: + t.Fatal("asked again soon after a list that left nothing out") + case <-time.After(200 * time.Millisecond): + } + p, err = Find("our-free-model") + if err != nil { + t.Fatal(err) + } + if !slices.Equal(p.Models, []string{"pool-a", "pool-b", "qoder/claude-x", "kiro/claude-y"}) || len(p.Delisted) != 0 { + t.Fatalf("full list again: picks %v, set aside %v", p.Models, p.Delisted) + } + if got := servedIDs(t, "our-free-model"); slices.Contains(got, "kiro/claude-z") { + t.Fatalf("a model left unpicked is served: %v", got) + } +} + +// Every pick set aside: none of the plugin's models is served, not the +// whole list as for a provider nothing was ever picked of; Select none +// forgets what was set aside. +func TestEveryPickDelistedServesNone(t *testing.T) { + claudeHome(t) + t.Setenv("MAGPIE_BUN", "") + if err := os.MkdirAll(settings.Dir(), 0o700); err != nil { + t.Fatal(err) + } + for name, v := range map[string]any{ + "plugins.json": map[string]any{"plugins": []map[string]any{{"spec": "magpie-our-free-model"}}}, + "plugin-auth.json": map[string]any{"our-free-model": map[string]any{"type": "api", "key": "managed"}}, + } { + b, _ := json.Marshal(v) + if err := os.WriteFile(filepath.Join(settings.Dir(), name), b, 0o600); err != nil { + t.Fatal(err) + } + } + before := ourFree("pool-a", "kiro/claude-y") + plugin.UseCached(before) + t.Cleanup(func() { plugin.UseCached(nil) }) + if err := Save(Provider{ID: "our-free-model", Models: []string{"kiro/claude-y"}}); err != nil { + t.Fatal(err) + } + now := ourFree("pool-a") + plugin.UseCached(now) + if got := dropGonePluginPicks(before, now)["our-free-model"]; !slices.Equal(got, []string{"kiro/claude-y"}) { + t.Fatalf("dropped %v", got) + } + if got := servedIDs(t, "our-free-model"); len(got) != 0 { + t.Fatalf("served with every pick set aside: %v", got) + } + // another setting saved: still waiting for its picks + p, _ := Find("our-free-model") + p.Off = false + p.MaxRPM = 10 + if err := Save(*p); err != nil { + t.Fatal(err) + } + if got := servedIDs(t, "our-free-model"); len(got) != 0 { + t.Fatalf("served after another setting was saved: %v", got) + } + p, _ = Find("our-free-model") + p.Models, p.NoModels = nil, true + if err := Save(*p); err != nil { + t.Fatal(err) + } + if p, _ = Find("our-free-model"); len(p.Delisted) != 0 { + t.Fatalf("Select none kept %v set aside", p.Delisted) + } +} + +// The same for a provider of the user's own whose list is fetched again, +// by Fetch models or by itself (RefreshEvery): a relay that leaves a model +// out of one list gives the pick back with the list that has it. +func TestRelayPicksComeBackWithTheirList(t *testing.T) { + oneHome(t) + var short atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.URL.Path, "/models") { + http.NotFound(w, r) + return + } + ids := []string{"m-a", "m-b", "m-c"} + if short.Load() { + ids = []string{"m-a", "m-c"} + } + var data []map[string]string + for _, id := range ids { + data = append(data, map[string]string{"id": id, "object": "model"}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": data}) + })) + t.Cleanup(srv.Close) + if err := Save(Provider{ID: "relay", Name: "Relay", Key: "k", Chat: srv.URL + "/v1"}); err != nil { + t.Fatal(err) + } + refetch := func() []string { + t.Helper() + p, err := Find("relay") + if err != nil { + t.Fatal(err) + } + _, dropped, err := p.Refetch(context.Background()) + if err != nil { + t.Fatal(err) + } + return dropped + } + refetch() + p, _ := Find("relay") + p.Models = []string{"m-a", "m-b"} + if err := Save(*p); err != nil { + t.Fatal(err) + } + short.Store(true) + if got := refetch(); !slices.Equal(got, []string{"m-b"}) { + t.Fatalf("dropped %v", got) + } + if got := servedIDs(t, "relay"); !slices.Equal(got, []string{"m-a"}) { + t.Fatalf("served while m-b isn't listed: %v", got) + } + short.Store(false) + refetch() + if p, _ = Find("relay"); !slices.Equal(p.Models, []string{"m-a", "m-b"}) || len(p.Delisted) != 0 { + t.Fatalf("listed again: picks %v, set aside %v", p.Models, p.Delisted) + } +} diff --git a/internal/provider/plugin_fetch_lapse_test.go b/internal/provider/plugin_fetch_lapse_test.go index 108e1fc11..9c5b828ea 100644 --- a/internal/provider/plugin_fetch_lapse_test.go +++ b/internal/provider/plugin_fetch_lapse_test.go @@ -61,3 +61,28 @@ func TestPluginFetchSignInExpiredLapses(t *testing.T) { time.Sleep(50 * time.Millisecond) } } + +// Signing in again takes the mark off by the account alone, when the +// providers' list is empty too: it is, while another magpie's change to +// plugins.json is read again, and a sign-in finished then left the +// account saying "sign in again" (#2748). +func TestPluginSignInClearsLapseWithoutTheList(t *testing.T) { + claudeHome(t) + saveLogins(t, + savedLogin{Agent: "plugin:fakeco", User: "gone@fake", Home: "k-gone", On: true, Lapsed: "gone@fake's FakeCo sign-in has expired — sign in again"}, + savedLogin{Agent: "plugin:fakeco", User: "other@fake", Home: "k-other", On: true, Lapsed: "other@fake's FakeCo sign-in has expired — sign in again"}, + ) + if ps := plugin.Cached(); len(ps) != 0 { + t.Fatalf("the list isn't empty: %d", len(ps)) + } + clearPluginLapse(plugin.Saved{Provider: "fakeco", Account: "k-gone"}) + loginsMu.Lock() + ls := readLogins() + loginsMu.Unlock() + if l := loginOf(t, ls, "plugin:fakeco", "gone@fake"); l.Lapsed != "" { + t.Fatalf("signed in again, but still lapsed: %q", l.Lapsed) + } + if l := loginOf(t, ls, "plugin:fakeco", "other@fake"); l.Lapsed == "" { + t.Fatal("the other account's mark went too") + } +} diff --git a/internal/provider/plugin_relist.go b/internal/provider/plugin_relist.go index a3acf0c5a..5d488a197 100644 --- a/internal/provider/plugin_relist.go +++ b/internal/provider/plugin_relist.go @@ -9,6 +9,11 @@ package provider // the user's picks too, as Refetch does for a built-in's. A list that // fell back (the vendor's couldn't be read) is the one told before // (plugin.keepListed): nothing is dropped for it. +// +// A pick that leaves is set aside (Delisted), not forgotten, and comes back +// when a list has it again: Our Free Model's list is short for a while +// after its service starts and while a free pool is down, and each magpie +// update left its user to pick every model again (多喝热水 on Discord). import ( "context" @@ -20,10 +25,13 @@ import ( ) // relistEvery is how often the gateway's magpie lists the plugins' -// models again; relistFirst is how long after it starts it first does. +// models again; relistFirst is how long after it starts it first does; +// relistSoon is how soon it asks again after a list left out a pick, as +// a plugin's service just started may not have listed everything yet. var ( relistEvery = time.Hour relistFirst = time.Minute + relistSoon = 5 * time.Minute ) // relistPlugins asks the plugins for their providers and models again, @@ -53,6 +61,7 @@ func KeepPluginsListed(ctx context.Context) { if len(before) == 0 { before = plugin.Cached() } + next := relistEvery c, cancel := context.WithTimeout(ctx, 2*time.Minute) now, err := relistPlugins(c) cancel() @@ -60,11 +69,12 @@ func KeepPluginsListed(ctx context.Context) { log.Printf("listing the plugins' models again: %s (the last lists stay)", err) } else if now != nil { for id, gone := range dropGonePluginPicks(before, now) { - log.Printf("%s: %v left its plugin's list, and its picks", id, gone) + log.Printf("%s: %v left its plugin's list, and its picks until it lists them again", id, gone) + next = relistSoon } before = keptListed(before, now) } - t.Reset(relistEvery) + t.Reset(next) } } @@ -91,12 +101,10 @@ func pluginListedIDs(ps []plugin.Provider) map[string]map[string]bool { func dropGonePluginPicks(before, now []plugin.Provider) map[string][]string { was, is := pluginListedIDs(before), pluginListedIDs(now) out := map[string][]string{} - for id, b := range was { - n, ok := is[id] - if !ok { - continue // not listed now, or fell back: nothing is known gone - } - dropped, err := dropGonePicks(id, b, n) + // by what is listed now: not listed now, or fell back, nothing is known + // gone; listed now and not before, a pick set aside may come back + for id, n := range is { + dropped, err := dropGonePicks(id, was[id], n) if err != nil { log.Println(id + ": " + err.Error()) } diff --git a/internal/provider/plugin_relist_test.go b/internal/provider/plugin_relist_test.go index a24928a48..379a930b8 100644 --- a/internal/provider/plugin_relist_test.go +++ b/internal/provider/plugin_relist_test.go @@ -50,7 +50,7 @@ func TestPluginsListedAgainWhileRunning(t *testing.T) { answers := make(chan []plugin.Provider) asked := make(chan struct{}) - oldList, oldFirst, oldEvery := relistPlugins, relistFirst, relistEvery + oldList, oldFirst, oldEvery, oldSoon := relistPlugins, relistFirst, relistEvery, relistSoon // asked says the loop asks again, so all it did with the last answer // is done relistPlugins = func(ctx context.Context) ([]plugin.Provider, error) { @@ -69,13 +69,13 @@ func TestPluginsListedAgainWhileRunning(t *testing.T) { return nil, ctx.Err() } } - relistFirst, relistEvery = time.Millisecond, time.Millisecond + relistFirst, relistEvery, relistSoon = time.Millisecond, time.Millisecond, time.Millisecond ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) t.Cleanup(func() { cancel() <-done - relistPlugins, relistFirst, relistEvery = oldList, oldFirst, oldEvery + relistPlugins, relistFirst, relistEvery, relistSoon = oldList, oldFirst, oldEvery, oldSoon }) go func() { defer close(done); KeepPluginsListed(ctx) }() select { diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index d9814e664..26142b507 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -45,13 +45,14 @@ const ( // PluginID is the id magpie gives the provider OpenCode calls id: the same, // unless a preset or a built-in subscription has it (google, openai, // anthropic), or a provider of the user's own made before the plugin was -// installed (zenmux, #867), when it is id-plugin — but for a built-in moved +// installed (zenmux, #867), or "auto" or "group", which start the ids of +// routing groups, when it is id-plugin — but for a built-in moved // onto the plugin, whose id the plugin has now. func PluginID(id string) string { if PluginServes(id) { return id } - if slices.Contains(accountIDs, id) || Preset(id) != nil || id == "magpie" || customIDs()[id] { + if slices.Contains(accountIDs, id) || Preset(id) != nil || id == "magpie" || id == autoID || id == strings.TrimSuffix(GroupPrefix, "/") || customIDs()[id] { return id + "-plugin" } return id diff --git a/internal/provider/pluginsignin.go b/internal/provider/pluginsignin.go index 4025af0ba..cdfa75300 100644 --- a/internal/provider/pluginsignin.go +++ b/internal/provider/pluginsignin.go @@ -132,7 +132,7 @@ func (s *signInFlow) pluginBegin(id string, method int, inputs map[string]string return nil } s.st.State, s.st.Installing = "waiting", "" - s.st.URL, s.st.Instructions, s.st.Code = a.URL, a.Instructions, codeIn(a.Instructions) + s.st.URL, s.st.Instructions, s.st.Code, s.st.Opened = a.URL, a.Instructions, codeIn(a.Instructions), a.Opened s.stop = stop if a.Method == "code" { s.st.PasteCode, s.plugin = true, a.Session diff --git a/internal/provider/presets.go b/internal/provider/presets.go index 25ca6b3a4..79e7609cf 100644 --- a/internal/provider/presets.go +++ b/internal/provider/presets.go @@ -415,9 +415,12 @@ var presets = []PresetDef{ Endpoint: "https://.openai.azure.com", EndpointHint: "Your resource's endpoint, from Keys and Endpoint in the Azure portal. Once added, magpie asks the resource for its deployments with this key, over its v1 API; the deployments' names are the model ids.", Website: "https://ai.azure.com", KeysURL: "https://portal.azure.com/#view/Microsoft_Azure_ProjectOxford/CognitiveServicesHub/~/OpenAI"}, - // Ollama's own hosted models: the local server's API, at ollama.com with a key + // Ollama's own hosted models: the local server's API, at ollama.com with + // a key. Its decision models (Clef), served at /v1/systemone, are the + // ones its /api/tags gives the "decision" capability (ollama_decide.go) {ID: "ollama-cloud", Name: "Ollama Cloud", Icon: "ollama", Kind: KindVendor, Catalog: "ollama-cloud", Hosts: true, Chat: "https://ollama.com/v1", Anthropic: "https://ollama.com", + Decide: "https://ollama.com/v1", Note: "cloud models, with an API key", Website: "https://docs.ollama.com/cloud", KeysURL: "https://ollama.com/settings/keys"}, // Nous Research's Nous Portal (#392): its own Hermes models and other @@ -569,9 +572,13 @@ var presets = []PresetDef{ Decide: "https://maas.qianwenaiapi.com/compatible-mode/v1", Note: "routes groups · picks model and effort", Website: "https://www.qianwenai.com/models/decision-model-preview", KeysURL: "https://platform.qianwenai.com/home/api-keys"}, + // its decision models (Nimble, Clef, Tev …), served at /v1/systemone + // since 0.35.0, are the ones its /api/tags gives the "decision" + // capability (ollama_decide.go) {ID: "ollama", Name: "Ollama", Icon: "ollama", Kind: KindLocal, NoKey: true, Chat: "http://localhost:11434/v1", Anthropic: "http://localhost:11434", - Note: "your local models", Website: "https://ollama.com"}, + Decide: "http://localhost:11434/v1", + Note: "your local models", Website: "https://ollama.com"}, {ID: "lmstudio", Name: "LM Studio", Icon: "lmstudio", Kind: KindLocal, NoKey: true, Chat: "http://localhost:1234/v1", Note: "local server, port 1234 by default", Website: "https://lmstudio.ai"}, diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 4458dd273..dc4241bf3 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -251,9 +251,10 @@ type Provider struct { PassUserAgent bool `json:"passUserAgent,omitempty"` // PinUpstream, on the Cline API, has its DeepSeek models answered only - // by DeepSeek's own API (White Immortal on Discord): Cline routes a - // model through an AI gateway that may serve it from any host, and - // DeepSeek's own keeps its prompt cache. See ClinePin. + // by DeepSeek's own API (White Immortal on Discord) and its GLM models + // only by Z.ai's (sdytman on Discord): Cline routes a model through an + // AI gateway that may serve it from any host, and the maker's own + // keeps its prompt cache. See ClinePin. PinUpstream bool `json:"pinUpstream,omitempty"` // AuthHeader is which header the key goes in on a third-party @@ -359,6 +360,15 @@ type Provider struct { // listed since is served beside picks that held every one listed then // (withNewlyListed), and one listed then and left unpicked stays out. PickedFrom []string `json:"pickedFrom,omitempty"` + // Delisted are picks the provider's list stopped listing (dropGonePicks): + // out of Models, so not served, until a list has them again, when they + // go back among the picks (relistPicks). A plugin's list shrinks for a + // while and comes back (多喝热水 on Discord: Our Free Model lists its + // account channels' models only once its service has read them after a + // restart, and a free pool it finds down leaves its list until it is + // up), and the user's picks came back with it no more. Every save keeps + // it but for what it picks again; Select none clears it. + Delisted []string `json:"delisted,omitempty"` // RefreshEvery, for a provider of the user's own, is how often the // gateway fetches its model list by itself ("6h", "1d"; none, only when // asked), as Fetch models does (#2135). See autolist.go. @@ -585,6 +595,7 @@ func (p Provider) clone() Provider { p.Fallback = slices.Clone(p.Fallback) p.Models = slices.Clone(p.Models) p.PickedFrom = slices.Clone(p.PickedFrom) + p.Delisted = slices.Clone(p.Delisted) p.AutoInclude = slices.Clone(p.AutoInclude) p.Headers = maps.Clone(p.Headers) p.ExtraBody = maps.Clone(p.ExtraBody) @@ -662,7 +673,7 @@ func allProviders() []Provider { // the provider keeps the same settings (#1899: a second WorkBuddy AI // account queued 62s with the wait set to 1s). func withPicks(a, pk Provider) Provider { - a.PickedFrom = pk.PickedFrom + a.PickedFrom, a.Delisted = pk.PickedFrom, pk.Delisted a.Models, a.Unlisted, a.Off, a.Fallback, a.Routing, a.Affinity, a.KeepLogin, a.KeepLoginAs, a.Contexts, a.Family = pk.Models, pk.Unlisted, pk.Off, pk.Fallback, pk.Routing, pk.Affinity, pk.KeepLogin, pk.KeepLoginAs, pk.Contexts, pk.Family a.SwitchOnly = pk.SwitchOnly a.Sink, a.NoModels = pk.Sink, pk.NoModels @@ -771,6 +782,9 @@ func Save(p Provider) error { if p.ID == strings.TrimSuffix(GroupPrefix, "/") { return errors.New(`"group" starts the ids of routing groups; pick another id`) } + if p.ID == autoID && !stored(p.ID) { // one saved before keeps it (autoRefsOn) + return errAutoID + } if err := settings.CheckProxy(p.Proxy); err != nil { return err } @@ -790,7 +804,7 @@ func Save(p Provider) error { if p.ID == "kiro" { key = p.Key } - p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, PickedFrom: p.PickedFrom, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)} + p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)} } else { p.AccountProxies = keyProxies(p) // a provider of keys proxies each key apart if subscriptionID(p.ID) && !stored(p.ID) { @@ -827,6 +841,7 @@ func Save(p Provider) error { was = &f.Providers[i] } p.PickedFrom = listedWith(p, was) + p.Delisted = delistedWith(p, was) if was != nil { if p.Was == nil { p.Was = was.Was @@ -863,9 +878,34 @@ func sameStored(a, b Provider) bool { return err == nil && bytes.Equal(x, y) } +// delistedWith is what p.Delisted is saved as: what was set aside before, +// as an editor sends none and couldn't show them to unpick, less what p +// picks again; none after Select none, or the vendor's list picked in +// place of picks (no picks saved over some). +func delistedWith(p Provider, was *Provider) []string { + if p.ServesNone() || len(p.Models) == 0 && was != nil && len(was.Models) > 0 { + return nil + } + d := p.Delisted + if d == nil && was != nil { + d = was.Delisted + } + d = slices.DeleteFunc(slices.Clone(d), func(id string) bool { return slices.Contains(p.Models, id) }) + if len(d) == 0 { + return nil + } + return d +} + // listedWith is what p.PickedFrom is saved as: none without picks; what was // kept with the picks when they are the same picks; and the models listed -// now when the picks are new, as the user picked them from that list. +// now when the picks are new, as the user picked them from that list. While +// some picks are set aside, the list is known to be short, so those listed +// when the picks were saved before are kept too: a model the user saw and +// left unpicked isn't new when the list that left it out for a while has it +// again (an Our Free Model channel not read yet when the picks were saved). +// A list short of no pick is taken as it is: what it left out and lists +// again later is new (TestClaudePicksOfEveryModelTakeOnesListedSince). func listedWith(p Provider, was *Provider) []string { if len(p.Models) == 0 { return nil @@ -881,6 +921,13 @@ func listedWith(p Provider, was *Provider) []string { for _, m := range from.Available() { ids = append(ids, m.ID) } + if was != nil && len(ids) > 0 && len(delistedWith(p, was)) > 0 { + for _, id := range was.PickedFrom { + if !slices.Contains(ids, id) { + ids = append(ids, id) + } + } + } return ids } @@ -1228,9 +1275,10 @@ func normalize(p Provider) Provider { p.Decide = pr.Decide } } - // an oMLX or MLX-Serve provider saved before its preset had System One (#1641) - // asks it where its chat completions are, at whatever port it was given - if (p.Preset == OMLXPreset || p.Preset == MLXServePreset) && p.Decide == "" && p.Chat != "" { + // an oMLX, MLX-Serve or Ollama provider saved before its preset had + // System One (#1641; Nanka on Discord) asks it where its chat + // completions are, at whatever address it was given + if (p.Preset == OMLXPreset || p.Preset == MLXServePreset || p.Preset == "ollama" || p.Preset == "ollama-cloud") && p.Decide == "" && p.Chat != "" { p.Decide = p.Chat } if p.Routing != Ordered && p.Routing != Rotate && p.Routing != LeastUsed && p.Routing != Pace && p.Routing != Weighted && !PluginRouting(p.Routing) { diff --git a/internal/provider/rename.go b/internal/provider/rename.go index 0494943e6..66acc0275 100644 --- a/internal/provider/rename.go +++ b/internal/provider/rename.go @@ -47,6 +47,8 @@ func Rename(from, to string) error { return errors.New(`"magpie" is what agents call the gateway itself; pick another id`) case to == strings.TrimSuffix(GroupPrefix, "/"): return errors.New(`"group" starts the ids of routing groups; pick another id`) + case to == autoID: + return errAutoID case subscriptionID(to): return fmt.Errorf("%q is the id of the %s subscription; pick another", to, to) } diff --git a/internal/provider/retired.go b/internal/provider/retired.go index 7251aebb4..42cfe0619 100644 --- a/internal/provider/retired.go +++ b/internal/provider/retired.go @@ -33,8 +33,17 @@ var retired struct { at map[string]time.Time // "provider/model" → when the vendor said it is retired from string // the file read, and its time then mod time.Time + // checked is when the file was last looked at: within retiredLook it + // isn't looked at again. Every answered request asks Unretire, and a + // look at the disk each time was a stat per request; this process's + // own writes keep retired.at current, and another magpie's is seen + // within retiredLook. + checked time.Time + looks int // looks at the disk, for tests } +var retiredLook = time.Second + func retiredPath() string { return filepath.Join(filepath.Dir(Path()), "retired.json") } // readRetired brings retired.at up to the file, when the file changed since @@ -42,6 +51,11 @@ func retiredPath() string { return filepath.Join(filepath.Dir(Path()), "retired. // retired held. func readRetired() { path := retiredPath() + if path == retired.from && !retired.checked.IsZero() && time.Since(retired.checked) < retiredLook { + return + } + retired.looks++ + retired.checked = time.Now() fi, err := os.Stat(path) if err != nil { if path != retired.from { @@ -81,7 +95,7 @@ func writeRetired() { return } if fi, err := os.Stat(path); err == nil { - retired.from, retired.mod = path, fi.ModTime() + retired.from, retired.mod, retired.checked = path, fi.ModTime(), time.Now() } } diff --git a/internal/provider/retired_test.go b/internal/provider/retired_test.go new file mode 100644 index 000000000..363272459 --- /dev/null +++ b/internal/provider/retired_test.go @@ -0,0 +1,85 @@ +package provider + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + "time" +) + +func retiredLooks() int { + retired.Lock() + defer retired.Unlock() + return retired.looks +} + +// Every answered request asks Unretire (the gateway's servedCandidate): +// retired.json isn't looked at on disk for each, only once in retiredLook. +// What this process retires or brings back is told at once, another +// magpie's write within retiredLook, and a config path of its own (a new +// HOME) is read at once. +func TestRetiredLooksOnceInAWhile(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + before := retiredLooks() + for range 200 { + Unretire("p", "m") + if Retired("p", "m") { + t.Fatal("retired out of nothing") + } + } + if n := retiredLooks() - before; n > 2 { + t.Fatalf("%d looks at retired.json for 200 requests", n) + } + Retire("p", "m") + if !Retired("p", "m") { + t.Fatal("this process's retirement isn't told at once") + } + Unretire("p", "m") + if Retired("p", "m") { + t.Fatal("this process's unretirement isn't told at once") + } + + // another magpie's write + defer func(d time.Duration) { retiredLook = d }(retiredLook) + retiredLook = 20 * time.Millisecond + b, _ := json.Marshal(map[string]time.Time{"p/other": time.Now()}) + if err := os.MkdirAll(filepath.Dir(retiredPath()), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(retiredPath(), b, 0o600); err != nil { + t.Fatal(err) + } + later := time.Now().Add(time.Minute) + os.Chtimes(retiredPath(), later, later) + for deadline := time.Now().Add(10 * time.Second); !Retired("p", "other"); time.Sleep(5 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("another magpie's write isn't seen") + } + } + + // a config of its own is read at once + home2 := t.TempDir() + t.Setenv("HOME", home2) + t.Setenv("USERPROFILE", home2) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + retiredLook = time.Hour + if Retired("p", "other") { + t.Fatal("another config's retirement told") + } +} + +// BenchmarkUnretire is what an answered request's Unretire costs it. +func BenchmarkUnretire(b *testing.B) { + home := b.TempDir() + b.Setenv("HOME", home) + b.Setenv("USERPROFILE", home) + b.Setenv("XDG_CONFIG_HOME", b.TempDir()) + Retire("p", "x") + for b.Loop() { + Unretire("p", "m") + } +} diff --git a/internal/provider/served.go b/internal/provider/served.go index bc26e92da..c86700d75 100644 --- a/internal/provider/served.go +++ b/internal/provider/served.go @@ -15,6 +15,7 @@ import ( "strings" "sync" "sync/atomic" + "testing" "time" ) @@ -66,6 +67,7 @@ func servedOf(id string) string { func ours(path string) map[string]time.Time { if servedAt.path != path { servedAt.path, servedAt.m, servedAt.by = path, map[string]time.Time{}, map[string]string{} + servedFlush.pending = false // what was noted for the other file isn't this one's } return servedAt.m } @@ -85,14 +87,44 @@ func ServedID(p Provider) string { return p.ID } -// NoteServed records that p just answered a request, at at. +// servedFlushAfter is how long NoteServed waits before it writes the file: +// what is noted meanwhile goes in the same write, so a gateway answering +// many requests a second writes it once in a while, not once a request +// (a read, a write and a rename on every answer). A crash loses what was +// noted in that last moment; FlushServed, as the gateway ends, loses +// nothing. In a test binary it is 0, the file written at once, as it +// was: a write waiting outlived the test that noted it and wrote into its +// temp folder as the folder was being removed ("directory not empty"). +var servedFlushAfter = writeBehind(2 * time.Second) + +// writeBehind is d, or 0 in a test binary: no timer outlives a test. +func writeBehind(d time.Duration) time.Duration { + if testing.Testing() { + return 0 + } + return d +} + +// servedFlush is the write NoteServed has waiting, and the one being made. +var servedFlush struct { + sync.Mutex // one write of the file at a time + pending bool // a write is waiting (servedAt held to read or set it) + writes uint64 // the writes made, for tests +} + +// NoteServed records that p just answered a request, at at. The file +// follows within servedFlushAfter (FlushServed): this process's LastServed +// has it at once. func NoteServed(p Provider, at time.Time) { id := ServedID(p) path := servedPath() servedAt.Lock() - moved := false + moved, now := false, false defer func() { servedAt.Unlock() + if now { + flushServed(path) + } if moved { servedMoved() } @@ -108,19 +140,51 @@ func NoteServed(p Provider, at time.Time) { moved = true servedAt.by[of] = id } + if !servedFlush.pending { + servedFlush.pending = true + if now = servedFlushAfter <= 0; !now { + time.AfterFunc(servedFlushAfter, func() { flushServed(path) }) + } + } +} + +// FlushServed writes what NoteServed noted and hasn't written yet: the +// gateway calls it as it ends. +func FlushServed() { flushServed(servedPath()) } + +// flushServed writes what this process noted to the file at path, merged +// with what the file holds (another gateway's), when path is still the one +// noted for: what a test noted under a HOME of its own isn't written into +// the next one's. +func flushServed(path string) { + servedFlush.Lock() + defer servedFlush.Unlock() + servedAt.Lock() + if !servedFlush.pending || servedAt.path != path { + servedAt.Unlock() + return + } + servedFlush.pending = false + mine := make(map[string]time.Time, len(servedAt.m)) + for k, t := range servedAt.m { + mine[k] = t + } + servedAt.Unlock() m := readServed(path) + now := time.Now() for k, t := range mine { if t.After(m[k]) { m[k] = t } } for k, t := range m { - if at.Sub(t) > servedKeep { + if now.Sub(t) > servedKeep { delete(m, k) } } if b, err := json.Marshal(m); err == nil && os.MkdirAll(filepath.Dir(path), 0o700) == nil { writeFileAtomic(path, b) + servedFlush.writes++ } } diff --git a/internal/provider/served_test.go b/internal/provider/served_test.go index b93c12d62..c99d15ae9 100644 --- a/internal/provider/served_test.go +++ b/internal/provider/served_test.go @@ -3,6 +3,7 @@ package provider import ( "encoding/json" "os" + "path/filepath" "strings" "testing" "time" @@ -24,6 +25,7 @@ func TestQuotasLastServed(t *testing.T) { NoteServed(Provider{ID: "codex", Account: &Account{Agent: "codex", User: "A@x.com"}}, now.Add(-time.Hour)) NoteServed(Provider{ID: "dk", Key: "sk-other-key-0002"}, now.Add(-time.Minute)) NoteServed(Provider{ID: "solo", Key: "sk-solo"}, now.Add(-2*time.Hour)) + FlushServed() // as the gateway ending writes it // the CLI is a process of its own: what it is told is read from the file servedAt.Lock() servedAt.m = map[string]time.Time{} @@ -95,3 +97,106 @@ func TestCardsLastServed(t *testing.T) { t.Errorf("json %s", b) } } + +// In a test binary served.json is written as an answer is noted: a write +// left waiting outlived the test that noted it, and wrote into its temp +// folder as the folder was being removed (BenchmarkGroupOverhead failed +// "TempDir RemoveAll cleanup: … directory not empty"). +func TestNoteServedInATestWritesAtOnce(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + at := time.Now().Truncate(time.Second) + NoteServed(Provider{ID: "dk", Key: "sk-key-0002"}, at) + var m map[string]time.Time + if b, err := os.ReadFile(servedPath()); err != nil || json.Unmarshal(b, &m) != nil || !m["dk#"+KeyID("sk-key-0002")].Equal(at) { + t.Fatalf("not written as the answer was noted: %v %v", err, m) + } + servedFlush.Lock() + pending := servedFlush.pending + servedFlush.Unlock() + if pending { + t.Fatal("a write left waiting past the test") + } +} + +// A request answered isn't a read and a write of served.json: what is +// noted is written once, within servedFlushAfter, however many requests +// were answered meanwhile, or as the gateway ends (FlushServed); the file +// is as it was, merged with what another gateway wrote, and this process +// tells what it noted at once. +func TestNoteServedWritesBehind(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + now := time.Now().Truncate(time.Second) + // another gateway's, already in the file + if err := os.MkdirAll(filepath.Dir(servedPath()), 0o700); err != nil { + t.Fatal(err) + } + other, _ := json.Marshal(map[string]time.Time{"other#k1": now.Add(-time.Hour)}) + if err := os.WriteFile(servedPath(), other, 0o600); err != nil { + t.Fatal(err) + } + defer func(d time.Duration) { servedFlushAfter = d }(servedFlushAfter) + servedFlushAfter = 2 * time.Second // as outside a test binary + servedFlush.Lock() + writes := servedFlush.writes + servedFlush.Unlock() + key := "dk#" + KeyID("sk-key-0001") + for i := range 200 { + NoteServed(Provider{ID: "dk", Key: "sk-key-0001"}, now.Add(time.Duration(i)*time.Millisecond)) + } + if b, _ := os.ReadFile(servedPath()); string(b) != string(other) { + t.Fatalf("written on a request answered: %s", b) + } + if at := LastServed()[key]; !at.Equal(now.Add(199 * time.Millisecond)) { + t.Fatalf("this process isn't told at once: %v", LastServed()) + } + FlushServed() + FlushServed() // nothing new: no write + servedFlush.Lock() + n := servedFlush.writes - writes + servedFlush.Unlock() + if n != 1 { + t.Fatalf("%d writes for 200 answers", n) + } + b, err := os.ReadFile(servedPath()) + if err != nil { + t.Fatal(err) + } + var m map[string]time.Time + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err, string(b)) + } + if len(m) != 2 || !m["other#k1"].Equal(now.Add(-time.Hour)) || !m[key].Equal(now.Add(199*time.Millisecond)) { + t.Fatalf("file %s", b) + } + // and by itself, a moment later + servedFlushAfter = time.Millisecond + NoteServed(Provider{ID: "dk", Key: "sk-key-0001"}, now.Add(time.Second)) + for deadline := time.Now().Add(10 * time.Second); ; { + if b, _ := os.ReadFile(servedPath()); json.Unmarshal(b, &m) == nil && m[key].Equal(now.Add(time.Second)) { + break + } + if time.Now().After(deadline) { + t.Fatal("never written") + } + time.Sleep(5 * time.Millisecond) + } +} + +// BenchmarkNoteServed is what noting a request answered costs the request. +func BenchmarkNoteServed(b *testing.B) { + home := b.TempDir() + b.Setenv("HOME", home) + b.Setenv("USERPROFILE", home) + b.Setenv("XDG_CONFIG_HOME", b.TempDir()) + p := Provider{ID: "dk", Key: "sk-key-0001"} + for b.Loop() { + NoteServed(p, time.Now()) + } + FlushServed() +} diff --git a/internal/provider/signin.go b/internal/provider/signin.go index 4e73232c0..ac5a3292b 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -75,6 +75,9 @@ type SignInState struct { PasteKey bool `json:"pasteKey,omitempty"` KeysURL string `json:"keysURL,omitempty"` Instructions string `json:"instructions,omitempty"` // a plugin's words for its page + // Opened is a page the plugin's own CLI opened already (Grok Build's + // `grok login`), shown but not opened a second time + Opened bool `json:"opened,omitempty"` // Installing is the CLI being installed before the sign-in can start Installing string `json:"installing,omitempty"` User string `json:"user,omitempty"` // the account, once done diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 313e0a4f2..af6bbfd0e 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -135,6 +135,10 @@ type SubscriptionQuota struct { // its provider hasn't (accessKeyCard, #1821): the Usage page offers // the provider's settings to give it in. NeedsAccessKey bool `json:"needsAccessKey,omitempty"` + // SeeAt is the vendor's page that shows what its API tells no key: + // OpenCode Zen's credits, on its console (errOpenCodeNoBalance). The + // Usage page offers to open it. + SeeAt string `json:"seeAt,omitempty"` // AsOf is when an allowance shown in place of one that couldn't be // read was read (see keepLast); nil for a reading just made. AsOf *time.Time `json:"asOf,omitempty"` diff --git a/internal/provider/suffix_mode_test.go b/internal/provider/suffix_mode_test.go index fc59d311f..4c853f86b 100644 --- a/internal/provider/suffix_mode_test.go +++ b/internal/provider/suffix_mode_test.go @@ -35,7 +35,7 @@ func TestSuffixMode(t *testing.T) { if SuffixMode() != SuffixOn { t.Fatalf("default %q", SuffixMode()) } - if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol · A", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"}) { + if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol · A", "auto/sol=Sol · routing group", "b/sol=Sol · B"}) { t.Fatalf("on: %q", got) } @@ -45,7 +45,7 @@ func TestSuffixMode(t *testing.T) { if s := settings.Load(); SuffixMode() != SuffixOwn || s.PlainNames || !s.PlainOwnNames || touched != 1 { t.Fatalf("own: %q %+v, told %d", SuffixMode(), s, touched) } - if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"}) { + if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "auto/sol=Sol · routing group", "b/sol=Sol · B"}) { t.Fatalf("own: %q", got) } if err := SetSuffixMode(SuffixOwn); err != nil || touched != 1 { @@ -59,7 +59,7 @@ func TestSuffixMode(t *testing.T) { t.Fatalf("off: %q %+v, told %d", SuffixMode(), s, touched) } // b's sol and the group found for it would both read "Sol": they keep theirs - if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"}) { + if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "auto/sol=Sol · routing group", "b/sol=Sol · B"}) { t.Fatalf("off: %q", got) } diff --git a/internal/provider/visible.go b/internal/provider/visible.go index e38c9d4e0..83d793726 100644 --- a/internal/provider/visible.go +++ b/internal/provider/visible.go @@ -17,14 +17,19 @@ import ( // the two never differ. // Names are what an entry answers to in a visibility: its family, and its -// provider's id or its group's id (as group/ too). +// provider's id or its group's id (as group/ too, and a found group's +// auto/). func (e Entry) Names() []string { var out []string if e.Family != "" { out = append(out, e.Family) } if e.Group != "" { - return append(out, e.Group, GroupPrefix+e.Group) + out = append(out, e.Group, GroupPrefix+e.Group) + if e.ID != GroupPrefix+e.Group { // a found group's auto/ + out = append(out, e.ID) + } + return out } return append(out, e.Provider.ID) } @@ -90,17 +95,20 @@ func ListedFor(agent string) (listed, kept []Entry) { return InOrder(agent, listed), kept } -// HiddenModels are the ids of the entries taken out of agent's lists. +// HiddenModels are the ids of the entries taken out of agent's lists, a +// found group saved by its old id, group/auto-, by the one it is +// listed by now (PublicRef). func HiddenModels(agent string) map[string]bool { ids := heldSettings().HiddenModels[strings.ToLower(agent)] out := make(map[string]bool, len(ids)) for _, id := range ids { - out[id] = true + out[PublicRef(id)] = true } return out } -// PickedModels are the only entries agent's lists show, by id, and whether +// PickedModels are the only entries agent's lists show, by id (a found +// group by the id it is listed by now, PublicRef), and whether // it is shown only those (#1337): a model not among them, one that came // after the user switched to it among them, is not shown. func PickedModels(agent string) (map[string]bool, bool) { @@ -110,7 +118,7 @@ func PickedModels(agent string) (map[string]bool, bool) { } out := make(map[string]bool, len(ids)) for _, id := range ids { - out[id] = true + out[PublicRef(id)] = true } return out, true } @@ -308,9 +316,14 @@ func Families() []string { } // ModelOrder is the order the user put agent's models in (OrderedModels), -// by entry id; none when they never did. +// by entry id, a found group by the id it is listed by now (PublicRef); +// none when they never did. func ModelOrder(agent string) []string { - return slices.Clone(heldSettings().OrderedModels[strings.ToLower(agent)]) + ids := slices.Clone(heldSettings().OrderedModels[strings.ToLower(agent)]) + for i, id := range ids { + ids[i] = PublicRef(id) + } + return ids } // SetModelOrder lists agent's models in this order, by entry id: the ones diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 5f79a8b9c..04e9f759c 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -8,6 +8,7 @@ import ( "bytes" "encoding/binary" "encoding/gob" + "encoding/json" "hash/crc32" "hash/fnv" "io" @@ -176,21 +177,51 @@ func keepCalls(path string, st *callFile) { // wholeCallReaders read an agent's calls from one session file at a time, // rather than a line at a time: its calls are not lines, or its file cannot // be read on from the middle of one. Every agent in callSources that is not -// in callFiles needs an entry here, or its calls are never read. +// in callFiles needs an entry here, in lineCallReaders or in +// resumeCallReaders, or its calls are never read. var wholeCallReaders = map[string]func(file) (*callFile, bool){ "opencode": readOpenCodeCalls, "zcode": readZCodeCalls, - "dsh": readDshCalls, "workbuddy": readWorkBuddyCalls, "codebuddy": readWorkBuddyCalls, // #1779 // #1605 "minimax-code": readMiniMaxCalls, - "kimi": readKimiCalls, // #1607 - "pi": readPiCalls, // #1951 - "omp": readPiCalls, "agy": readAgyCalls, // #2097 } +// resumeCallReaders read an agent's calls from a file only appended to that +// the line reader can't read on through, as dsh's packed file of zstd +// frames: each is handed what the last read came to and reads on from +// where it left off, or whole when it can't. It gives how many of the +// calls it hands back were in old, kept as they were (0 when it read +// whole, or what it had counted no longer stands), so only the rest are +// appended to the disk shard. +var resumeCallReaders = map[string]func(f file, old *callFile) (st *callFile, kept int, ok bool){ + "dsh": readDshCalls, +} + +// lineCallReader reads an agent's calls a line at a time, as Claude Code's +// and Codex's are: a file that only grew is read on from where the last read +// left off (prepareCalls), and only the calls it adds are written to the +// disk shard. begin starts a file read from its start; line reads one whole +// line of it. Nothing a line leaves for the next may live outside st. kept, +// when a reader carries something from line to line, says whether st holds +// it: a read kept on disk before it was carried there does not, and is +// read whole again. +type lineCallReader struct { + begin func(st *callFile, f file) + line func(st *callFile, b []byte) + kept func(st *callFile) bool +} + +// lineCallReaders are the agents in callSources, beside callFiles' own, +// whose calls are each one line of a file only appended to. +var lineCallReaders = map[string]lineCallReader{ + "kimi": {kimiCallsBegin, kimiCallLine, nil}, // #1607 + "pi": {piCallsBegin, readPiCallLine, piCallsKept}, // #1951 + "omp": {piCallsBegin, readPiCallLine, piCallsKept}, +} + func readCalls(f file) *callFile { h := fnv.New32a() _, _ = h.Write([]byte(f.path)) @@ -225,6 +256,22 @@ func readCalls(f file) *callFile { // that changed is read again, and one that did not is kept. OpenCode's // and ZCode's are rows of a database or JSON documents; dsh's file is // packed in frames, so it cannot be read on from the middle of one. + if read, ok := resumeCallReaders[f.agent]; ok { + st, kept, readOK := read(f, old) + if !readOK && old != nil { + return old + } + if readOK { + st.Size, st.Mod = f.size, f.mod.UnixNano() + writeCalls(st, kept, kept > 0) + } + callsMu.Lock() + if readOK && generation == callGeneration { + keepCalls(f.path, st) + } + callsMu.Unlock() + return st + } if read, ok := wholeCallReaders[f.agent]; ok { st, readOK := read(f) if !readOK && old != nil { @@ -241,24 +288,35 @@ func readCalls(f file) *callFile { callsMu.Unlock() return st } + if r, ok := lineCallReaders[f.agent]; ok && r.kept != nil && old != nil && !r.kept(old) { + old = nil + } st := prepareCalls(f, old) continued := old != nil && st.Off == old.Off && st.Off > 0 start := 0 if continued { start = len(old.Calls) } + line := claudeCallLine + if f.agent == "codex" { + line = codexCallLine + } else if r, ok := lineCallReaders[f.agent]; ok { + if st.Off == 0 { + r.begin(st, f) + } + line = r.line + } off, err := scanAt(f.path, st.Off, func(b []byte) bool { return callHead(st, b) }, func(b []byte, start, end int64) bool { st.At, st.End = start, end - if f.agent == "codex" { - codexCallLine(st, b) - } else { - claudeCallLine(st, b) - } + line(st, b) return true }) if err == nil { st.Off, st.Size, st.Mod = off, f.size, f.mod.UnixNano() - st.ContentHash = prefixHash(f.path, f.size) + // the bytes read, not the listed size: a listing may fold another + // file's size into this one's (Kimi's state.json), and hashing past + // the end would leave no hash to read on from + st.ContentHash = prefixHash(f.path, off) writeCalls(st, start, continued) } // Do not turn a one-time historical scan into an indefinitely retained @@ -301,16 +359,41 @@ type callDiskState struct { At, End, AsstEnd int64 Session, Requested string LastUser, LastAsst time.Time + // dsh's carry (dshCarry), as JSON: nil when there is none + Dsh []byte + // Pi's and omp's carry (piCarry), flat: PiOn when there is one + PiOn, PiHeader bool + PiCwd string + PiSince time.Time + PiProvider, PiModel string } func diskCallState(s *callFile) callDiskState { - return callDiskState{s.ContentHash, s.Size, s.Mod, s.Off, s.Head, s.HeadSize, - s.Path, s.Agent, s.At, s.End, s.AsstEnd, s.Session, s.Requested, s.LastUser, s.LastAsst} + d := callDiskState{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head, HeadSize: s.HeadSize, + Path: s.Path, Agent: s.Agent, At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, + LastUser: s.LastUser, LastAsst: s.LastAsst} + if s.Dsh != nil { + d.Dsh, _ = json.Marshal(s.Dsh) + } + if p := s.Pi; p != nil { + d.PiOn, d.PiHeader, d.PiCwd, d.PiSince, d.PiProvider, d.PiModel = true, p.Header, p.Cwd, p.Since, p.Provider, p.Model + } + return d } func (s callDiskState) restore() *callFile { - return &callFile{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, + st := &callFile{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head, HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, LastUser: s.LastUser, LastAsst: s.LastAsst} + if len(s.Dsh) > 0 { + var c dshCarry + if json.Unmarshal(s.Dsh, &c) == nil { + st.Dsh = &c + } + } + if s.PiOn { + st.Pi = &piCarry{s.PiHeader, s.PiCwd, s.PiSince, s.PiProvider, s.PiModel} + } + return st } func callText(c *Call) [13]*string { diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index 7c640bc6f..ab2863655 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -94,6 +94,10 @@ type callFile struct { CompactMs int64 // Codex CX *cxRun + // Pi and omp + Pi *piCarry + // dsh + Dsh *dshCarry } // cxRun is where a rollout's read stands: what its lines have said so far. @@ -306,15 +310,16 @@ func callFiles() []file { return out } -// callSources are callFiles and the agents whose calls are read whole -// rather than line by line: OpenCode's (#680) and ZCode's, whose calls are -// rows of their database or their JSON files; DeepSeek Harness's, whose -// session file is packed in frames and so cannot be read on from the middle -// of one; and WorkBuddy's, whose usage lines repeat a reply's id as it goes -// on, as CodeBuddy Code's do (#1779); and MiniMax Code's, whose messages -// file a later generation of its history may replace (#1605); and Kimi -// Code's, whose forks copy their parent's records (#1607). Every agent here -// needs an entry in wholeCallReaders. +// callSources are callFiles and the other agents' session files. Most are +// read whole rather than line by line: OpenCode's (#680) and ZCode's, whose +// calls are rows of their database or their JSON files; and WorkBuddy's, whose usage lines repeat a reply's id as it +// goes on, as CodeBuddy Code's do (#1779); and MiniMax Code's, whose messages +// file a later generation of its history may replace (#1605). Kimi Code's +// (#1607), Pi's and omp's (#1951) are lines of a file only appended to, +// read on as callFiles' are; DeepSeek Harness's, a file only appended to +// that may be packed in zstd frames, is read on from the frame it was +// left in (readDshCalls). Every agent here needs an entry in +// wholeCallReaders, lineCallReaders or resumeCallReaders. func callSources() []file { out := callFiles() out = append(out, openCodeCallFiles()...) @@ -365,7 +370,7 @@ func prepareCalls(f file, old *callFile) *callFile { head := headOf(f.path) var st *callFile - if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != "" && prefixHash(f.path, old.Size) == old.ContentHash { + if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != "" && prefixHash(f.path, old.Off) == old.ContentHash { st = old.clone() } else { st = &callFile{Agent: f.agent} @@ -397,6 +402,18 @@ func (st *callFile) clone() *callFile { r.Timings = append([]cxCallTiming(nil), r.Timings...) c.CX = &r } + if st.Pi != nil { + p := *st.Pi + c.Pi = &p + } + if st.Dsh != nil { + d := *st.Dsh + if d.Tail != nil { + t := *d.Tail + d.Tail = &t + } + c.Dsh = &d + } return &c } diff --git a/internal/sessions/calls_agy.go b/internal/sessions/calls_agy.go index f5d21ca80..7cd92a0b2 100644 --- a/internal/sessions/calls_agy.go +++ b/internal/sessions/calls_agy.go @@ -82,7 +82,7 @@ func readAgyCalls(f file) (*callFile, bool) { defer r.Close() st := &callFile{Agent: "agy", Path: f.path, Session: strings.TrimPrefix(f.key, "agy:")} at := map[int]int{} // a step's index → its call in st.Calls - br := bufio.NewReaderSize(r, 1<<20) + br := bufio.NewReaderSize(r, scanBuffer(r, 0)) for { b, err := br.ReadBytes('\n') if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) { diff --git a/internal/sessions/calls_dsh.go b/internal/sessions/calls_dsh.go index cc8f72563..e93cf2997 100644 --- a/internal/sessions/calls_dsh.go +++ b/internal/sessions/calls_dsh.go @@ -1,11 +1,8 @@ package sessions import ( - "bufio" "bytes" "encoding/json" - "errors" - "io" "strings" ) @@ -37,82 +34,89 @@ func dshCallFiles() []file { return dshFiles() } -// readDshCalls reads a dsh session whole: packed in frames, it can't be read -// on from the middle of one (as parseDsh says). -func readDshCalls(f file) (*callFile, bool) { - r, err := dshOpen(f.path) - if err != nil { - return &callFile{Path: f.path, Agent: "dsh"}, false +// readDshCalls reads a dsh session's calls. dsh only appends to a session +// file, a line at a time or, packed, a frame of lines at a time, so a file +// read before is read on from where that read left off, a packed one from +// the frame it left off in (frames.go), as parseDsh reads it. A file cut +// short or replaced is read whole again, and a line or frame not yet +// written whole waits for the next read. kept is how many of st's calls +// were old's. +func readDshCalls(f file, old *callFile) (st *callFile, kept int, ok bool) { + var c dshCarry + var off, skip int64 + if old != nil && old.Dsh != nil && old.Dsh.Tail.holds(f.path) { + st = old.clone() + c, off, skip = *st.Dsh, st.Dsh.Tail.Off, st.Dsh.Tail.Skip + kept = len(st.Calls) + } else { + st = &callFile{Agent: "dsh", Path: f.path, Session: strings.TrimPrefix(f.key, "dsh:")} } - defer r.Close() - st := &callFile{Agent: "dsh", Path: f.path, Session: strings.TrimPrefix(f.key, "dsh:")} - br := bufio.NewReaderSize(r, 1<<20) - var h dshHead - // the events a fork was seeded with are the session it came from, not - // this one: parseDsh skips them, and counting them here would spend the - // same request once per fork (dsh-a's first reply is also dsh-c's and - // dsh-d's first lines) - var evs []dshEvent - var seeds []bool - cut := -1 - for first := true; ; first = false { - b, err := br.ReadBytes('\n') - if err != nil { - // a line still being written, or a frame cut short - if !errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0 { - break - } - } + headed := c.Head.Type == "session" + ok = true + each := func(b []byte) bool { b = bytes.TrimSpace(b) if len(b) == 0 || len(b) > maxLine { - if err != nil { - break - } - continue + return true } - if first { - if json.Unmarshal(b, &h) != nil || h.Type != "session" { - return st, false + if !headed { + headed = true + if json.Unmarshal(b, &c.Head) != nil || c.Head.Type != "session" { + ok = false + return false } if st.Session == "" { - st.Session = h.ID + st.Session = c.Head.ID } - continue + return true } // only an assistant/message carries a call, and only the ones a // seed ends: every other line is passed over undecoded - if bytes.Contains(b, []byte(`"assistant/message"`)) || bytes.Contains(b, []byte(`"session/end-seed"`)) { - var e dshEvent - if json.Unmarshal(b, &e) == nil && e.Type != "" { - evs = append(evs, e) - seeds = append(seeds, e.Type == "session/end-seed" && e.Data.Inherited) + if !bytes.Contains(b, []byte(`"assistant/message"`)) && !bytes.Contains(b, []byte(`"session/end-seed"`)) { + return true + } + var e dshEvent + if json.Unmarshal(b, &e) != nil { + return true + } + switch e.Type { + case "session/end-seed": + // the events a fork was seeded with are the session it came + // from, not this one: parseDsh skips them, and counting them + // here would spend the same request once per fork (dsh-a's + // first reply is also dsh-c's and dsh-d's first lines). From + // format 2 the seed ends with this marker: what came before + // it is not this session's. + if e.Data.Inherited && c.Head.Version >= 2 && c.Head.IsSeeded { + st.Calls, kept = nil, 0 + } + case "assistant/message": + // before format 2 the seed is counted in events + if c.Head.Version < 2 && e.Seq != nil && *e.Seq < c.Head.SeedLength { + return true + } + if call, ok := dshCall(st, e); ok { + st.Calls = append(st.Calls, call) } } - if err != nil { - break - } + return true } - if h.Version >= 2 && h.IsSeeded { - for i, seed := range seeds { - if seed { - cut = i - } - } + var next, nextSkip, end int64 + var err error + if packed(f.path) { + next, nextSkip, end, err = scanFrames(f.path, off, skip, each) + } else { + next, err = scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { return each(b) }) + end = next } - for i, e := range evs { - if e.Type != "assistant/message" { - continue - } - // before format 2 the seed is counted in events, after it by the - // marker it ends with - if i <= cut || h.Version < 2 && e.Seq != nil && *e.Seq < h.SeedLength { - continue - } - if c, ok := dshCall(st, e); ok { - st.Calls = append(st.Calls, c) - } + if !ok || err != nil && !headed { + return &callFile{Path: f.path, Agent: "dsh"}, 0, false } - return st, true + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, next, nextSkip, end) + } + st.Dsh = &c + return st, kept, true } // dshCall is an assistant/message as a call: its model, its tokens and the diff --git a/internal/sessions/calls_dsh_test.go b/internal/sessions/calls_dsh_test.go index ca5a26773..36f16cf83 100644 --- a/internal/sessions/calls_dsh_test.go +++ b/internal/sessions/calls_dsh_test.go @@ -1,8 +1,16 @@ package sessions import ( + "bytes" + "fmt" + "os" + "path/filepath" + "slices" + "sync" "testing" "time" + + "github.com/klauspost/compress/zstd" ) // dshCalls are the DeepSeek Harness calls Calls gives. @@ -129,3 +137,157 @@ func TestDshGatewayProviderTakesEveryRouteOfMagpies(t *testing.T) { } } } + +// dshCallReader reads the calls of the dsh session file at path as the +// ledger does, and says where each scan of it started. +func dshCallReader(t *testing.T, path string) func() ([]int, []int64) { + var mu sync.Mutex + var starts []int64 + scanHook = func(p string, off int64) { + if p == path { + mu.Lock() + starts = append(starts, off) + mu.Unlock() + } + } + t.Cleanup(func() { scanHook = nil }) + return func() ([]int, []int64) { + t.Helper() + mu.Lock() + starts = nil + mu.Unlock() + var in []int + found := false + for _, s := range CallSources() { + if s.Path == path { + found = true + for _, c := range ReadCallSource(s) { + in = append(in, c.Input) + } + } + } + if !found { + t.Fatalf("%s is no call source", path) + } + slices.Sort(in) + mu.Lock() + defer mu.Unlock() + return in, append([]int64(nil), starts...) + } +} + +// A dsh session read for calls before is read on from where it was left, +// packed or not: a frame appended is read alone, a frame or line not yet +// written whole waits, the read goes on from the disk shard after the +// in-memory one is let go, and a file cut short is read whole again. +func TestDshCallsReadOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + plain := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-a", "session.v3.jsonl") + b, err := os.ReadFile(plain) + if err != nil { + t.Fatal(err) + } + os.Remove(plain) + enc, _ := zstd.NewWriter(nil) + defer enc.Close() + frame := func(s string) string { return string(enc.EncodeAll([]byte(s), nil)) } + p := plain + ".zstd" + half := bytes.IndexByte(b[len(b)/2:], '\n') + len(b)/2 + 1 + orig := frame(string(b[:half])) + frame(string(b[half:])) + if err := os.WriteFile(p, []byte(orig), 0o644); err != nil { + t.Fatal(err) + } + reply := func(n int) string { + return fmt.Sprintf(`{"type":"assistant/message","seq":%d,"time":%d,"data":{"message":{"source":{"model":"deepseek-v4-flash"}},"usage":{"inputTokens":%d,"outputTokens":1,"cacheReadTokens":0}}}`+"\n", n, 1790503290000+int64(n)*1000, n) + } + size := func() int64 { + t.Helper() + fi, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + return fi.Size() + } + read := dshCallReader(t, p) + check := func(what string, from int64, want ...int) { + t.Helper() + in, starts := read() + if len(starts) == 0 { + t.Fatalf("%s: not read", what) + } + for _, at := range starts { + if at != from { + t.Fatalf("%s: read from %d, want %d (%v)", what, at, from, starts) + } + } + if !slices.Equal(in, want) { + t.Fatalf("%s: calls %v, want %v", what, in, want) + } + } + check("first read", 0, 10, 100) + + was := size() + appendText(t, p, frame(reply(6))) + check("a frame appended", was, 6, 10, 100) + + was = size() + f := frame(reply(7)) + appendText(t, p, f[:len(f)/2]) + check("half a frame", was, 6, 10, 100) + appendText(t, p, f[len(f)/2:]) + check("the half frame finished", was, 6, 7, 10, 100) + + // a frame ending inside a line: the line is read once whole, from + // the frame it starts in + was = size() + r9 := reply(9) + appendText(t, p, frame(reply(8)+r9[:20])) + check("a frame ending in a line", was, 6, 7, 8, 10, 100) + appendText(t, p, frame(r9[20:])) + check("the line finished in the next frame", was, 6, 7, 8, 9, 10, 100) + + resetCalls() + was = size() + appendText(t, p, frame(reply(11))) + check("from the disk shard", was, 6, 7, 8, 9, 10, 11, 100) + + if err := os.WriteFile(p, []byte(orig), 0o644); err != nil { + t.Fatal(err) + } + check("cut short", 0, 10, 100) +} + +// A fork's end-seed that comes in a later read still ends what it was +// seeded with: what was counted before it is its source's, in memory and +// in the disk shard. +func TestDshCallsEndSeedAcrossReads(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + p := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-c", "session.v3.jsonl") + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + cut := bytes.Index(b, []byte(`{"type":"session/end-seed"`)) + rest := bytes.IndexByte(b[cut:], '\n') + cut + 1 + if err := os.WriteFile(p, b[:cut], 0o644); err != nil { + t.Fatal(err) + } + read := dshCallReader(t, p) + if in, _ := read(); !slices.Equal(in, []int{100}) { + t.Fatalf("before its end-seed: %v", in) + } + appendText(t, p, string(b[cut:rest])) + if in, starts := read(); len(in) != 0 || !slices.Equal(starts, []int64{int64(cut)}) { + t.Fatalf("its end-seed read on from %v: %v, want none", starts, in) + } + appendText(t, p, string(b[rest:])) + if in, starts := read(); !slices.Equal(in, []int{50}) || !slices.Equal(starts, []int64{int64(rest)}) { + t.Fatalf("the fork's own, read on from %v: %v", starts, in) + } + resetCalls() + if in, starts := read(); !slices.Equal(in, []int{50}) || len(starts) != 0 { + t.Fatalf("from the disk shard (read from %v): %v", starts, in) + } +} diff --git a/internal/sessions/calls_kimi.go b/internal/sessions/calls_kimi.go index d0c1c45ce..a242b2f03 100644 --- a/internal/sessions/calls_kimi.go +++ b/internal/sessions/calls_kimi.go @@ -1,12 +1,9 @@ package sessions import ( - "bufio" "bytes" "cmp" "encoding/json" - "errors" - "io" "os" "path/filepath" "strconv" @@ -88,35 +85,27 @@ type kimiRecord struct { var kimiUsageRecord = []byte(`"usage.record"`) -// readKimiCalls reads one agent's wire file whole. -func readKimiCalls(f file) (*callFile, bool) { - r, err := os.Open(f.path) - if err != nil { - return &callFile{Path: f.path, Agent: "kimi"}, false +// kimiCallsBegin starts an agent's wire file read from its start. Kimi Code +// only appends to it, each record a line of its own, so readCalls reads one +// that grew on from where it left off (lineCallReaders). +func kimiCallsBegin(st *callFile, f file) { + st.Session = strings.TrimPrefix(f.key, "kimi:") +} + +// kimiCallLine reads one line of an agent's wire file: a usage.record is a +// call. +func kimiCallLine(st *callFile, b []byte) { + b = bytes.TrimSpace(b) + if len(b) == 0 || len(b) > maxLine || !bytes.Contains(b, kimiUsageRecord) { + return } - defer r.Close() - agentDir := filepath.Base(filepath.Dir(f.path)) - st := &callFile{Agent: "kimi", Path: f.path, Session: strings.TrimPrefix(f.key, "kimi:")} - br := bufio.NewReaderSize(r, 1<<20) - for { - b, err := br.ReadBytes('\n') - if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) { - break - } - b = bytes.TrimSpace(b) - if len(b) > 0 && len(b) <= maxLine && bytes.Contains(b, kimiUsageRecord) { - var rec kimiRecord - if json.Unmarshal(b, &rec) == nil { - if c, ok := kimiCall(st, agentDir, rec); ok { - st.Calls = append(st.Calls, c) - } - } - } - if err != nil { - break - } + var rec kimiRecord + if json.Unmarshal(b, &rec) != nil { + return + } + if c, ok := kimiCall(st, filepath.Base(filepath.Dir(st.Path)), rec); ok { + st.Calls = append(st.Calls, c) } - return st, true } // kimiCall is a usage.record as a call. diff --git a/internal/sessions/calls_kimi_test.go b/internal/sessions/calls_kimi_test.go index b7cd7b0bf..70cfc6e98 100644 --- a/internal/sessions/calls_kimi_test.go +++ b/internal/sessions/calls_kimi_test.go @@ -4,7 +4,10 @@ import ( "bytes" "os" "path/filepath" + "slices" + "strconv" "strings" + "sync" "testing" "time" ) @@ -175,8 +178,8 @@ func TestKimiCodeForkCountsOnce(t *testing.T) { // and two subagents of one session whose 1.5 records name themselves: // the same call in two agents' files is two calls sub := strings.Replace(kimiRecordLine, `"agentId":"main"`, `"agentId":"agent-0"`, 1) - writeKimiWire(t, home, "session_agents", "agent-0", sub) - writeKimiWire(t, home, "session_agents", "main", kimiRecordLine) + writeKimiWire(t, home, "session_agents", "agent-0", sub, "") + writeKimiWire(t, home, "session_agents", "main", kimiRecordLine, "") tot := kimiTotals(kimiCalls()) if got := tot["session_169766c9-86f5-4577-97a3-a51d402db5b9"]; got != kimiWant["session_169766c9-86f5-4577-97a3-a51d402db5b9"] { @@ -232,3 +235,89 @@ func TestKimiCodeBrokenFiles(t *testing.T) { } } } + +// A Kimi Code wire file that grew is read on from where the last read of +// its calls left off, not whole again; a half-written last line waits for +// the rest; a file cut shorter or written over is read whole again. Before +// this, every poll after an append decoded the whole file again. +func TestKimiCodeCallsReadOnlyWhatWasAppended(t *testing.T) { + home := kimiHome(t) + rec := func(i int) string { + r := strings.Replace(kimiRecordLine, `1791696952640`, strconv.FormatInt(1791696900000+int64(i)*1000, 10), 1) + return strings.Replace(r, `"inputOther":20257`, `"inputOther":`+strconv.Itoa(20000+i), 1) + } + writeKimiWire(t, home, "session_grow", "main", rec(1), rec(2), rec(3), "") + path := filepath.Join(home, "sessions", "wd_test_000000000009", "session_grow", "agents", "main", "wire.jsonl") + // the listing folds state.json's size into the main wire file's + if err := os.WriteFile(filepath.Join(home, "sessions", "wd_test_000000000009", "session_grow", "state.json"), []byte(`{"title":"Grow","cwd":"/work/grow"}`), 0o644); err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var starts []int64 + scanHook = func(p string, off int64) { + if p == path { + mu.Lock() + starts = append(starts, off) + mu.Unlock() + } + } + t.Cleanup(func() { scanHook = nil }) + read := func(what string, from int64, want ...int) { + t.Helper() + mu.Lock() + starts = nil + mu.Unlock() + var calls []Call + for _, s := range CallSources() { + if s.Path == path { + calls = ReadCallSource(s) + } + } + mu.Lock() + got := append([]int64(nil), starts...) + mu.Unlock() + if len(got) == 0 { + t.Fatalf("%s: not read", what) + } + for _, off := range got { + if off != from { + t.Fatalf("%s: read from %d, want %d (%v)", what, off, from, got) + } + } + var in []int + for _, c := range calls { + in = append(in, c.Input-20000) + } + if !slices.Equal(in, want) { + t.Fatalf("%s: calls %v, want %v", what, in, want) + } + } + size := func() int64 { + t.Helper() + st, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + return st.Size() + } + read("first read", 0, 1, 2, 3) + + end := size() + appendText(t, path, rec(4)+"\n"+rec(5)[:40]) + read("appended, half a line after", end, 1, 2, 3, 4) + + appendText(t, path, rec(5)[40:]+"\n") + read("the half line finished", end+int64(len(rec(4))+1), 1, 2, 3, 4, 5) + + // cut shorter: read whole again + writeKimiWire(t, home, "session_grow", "main", rec(7), "") + read("cut shorter", 0, 7) + + // written over, longer than it was: read whole again + writeKimiWire(t, home, "session_grow", "main", rec(8), rec(9), "") + later := time.Now().Add(time.Hour) + if err := os.Chtimes(path, later, later); err != nil { + t.Fatal(err) + } + read("written over", 0, 8, 9) +} diff --git a/internal/sessions/calls_minimax.go b/internal/sessions/calls_minimax.go index 7a7061205..b48383518 100644 --- a/internal/sessions/calls_minimax.go +++ b/internal/sessions/calls_minimax.go @@ -106,7 +106,7 @@ func readMiniMaxCalls(f file) (*callFile, bool) { } defer r.Close() st := &callFile{Agent: "minimax-code", Path: f.path, Session: strings.TrimPrefix(f.key, "minimax-code:")} - br := bufio.NewReaderSize(r, 1<<20) + br := bufio.NewReaderSize(r, scanBuffer(r, 0)) for { b, err := br.ReadBytes('\n') if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) { diff --git a/internal/sessions/calls_pi.go b/internal/sessions/calls_pi.go index 1a462fdae..a9e161f90 100644 --- a/internal/sessions/calls_pi.go +++ b/internal/sessions/calls_pi.go @@ -1,13 +1,9 @@ package sessions import ( - "bufio" "bytes" "encoding/json" - "errors" - "io" "math" - "os" "strings" "time" ) @@ -73,59 +69,65 @@ type piCallLine struct { } `json:"message"` } -// readPiCalls reads one Pi or omp session file whole. -func readPiCalls(f file) (*callFile, bool) { - r, err := os.Open(f.path) - if err != nil { - return &callFile{Path: f.path, Agent: f.agent}, false +// piCarry is what a Pi or omp session file's lines have said so far that a +// later line's call is read with: the header's cwd and, for a fork, when it +// began (what was written before is its parent's), and the provider and +// model in use. Pi and omp only append to the file, a line an entry, so a +// file that grew is read on from where the last read left off with it +// (lineCallReaders). +type piCarry struct { + Header bool + Cwd string + Since time.Time + Provider, Model string +} + +// piCallsBegin starts a session file read from its start. +func piCallsBegin(st *callFile, f file) { + st.Session = strings.TrimPrefix(f.key, f.agent+":") + st.Pi = &piCarry{} +} + +// piCallsKept is whether st holds what reading on needs: a disk shard +// written before the carry was kept there does not, and its file is read +// whole again once it changes. +func piCallsKept(st *callFile) bool { return st.Pi != nil } + +// readPiCallLine reads one line of a Pi or omp session file. +func readPiCallLine(st *callFile, b []byte) { + if len(b) == 0 || len(b) > maxLine || !(bytes.Contains(b, piUsed) || bytes.Contains(b, piHeader) || bytes.Contains(b, piModel)) { + return } - defer r.Close() - st := &callFile{Agent: f.agent, Path: f.path, Session: strings.TrimPrefix(f.key, f.agent+":")} - var cwd, provider, model string - var header bool - var since time.Time // a fork's: what was written before it is its parent's - br := bufio.NewReaderSize(r, 1<<20) - for { - b, err := br.ReadBytes('\n') - if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) { - break - } - b = bytes.TrimSpace(b) - if len(b) > 0 && len(b) <= maxLine && (bytes.Contains(b, piUsed) || bytes.Contains(b, piHeader) || bytes.Contains(b, piModel)) { - var l piCallLine - if json.Unmarshal(b, &l) == nil { - switch l.Type { - case "session": - if !header { - header, cwd = true, l.Cwd - if l.Parent != "" { - since, _ = time.Parse(time.RFC3339Nano, l.Timestamp) - } - } - case "model_change": - p, id := l.Provider, l.ModelID - if id == "" { - p, id, _ = strings.Cut(l.Model, "/") - } - if id != "" { - provider, model = p, id - } - case "message": - if m := l.Message; m != nil && m.Role == "assistant" && m.Model != "" { - provider, model = m.Provider, m.Model - } - } - if c, ok := piCall(st, f.agent, l, provider, model); ok && !c.Time.Before(since) { - c.Cwd = st.str(cwd) - st.Calls = append(st.Calls, c) - } + var l piCallLine + if json.Unmarshal(b, &l) != nil { + return + } + p := st.Pi + switch l.Type { + case "session": + if !p.Header { + p.Header, p.Cwd = true, l.Cwd + if l.Parent != "" { + p.Since, _ = time.Parse(time.RFC3339Nano, l.Timestamp) } } - if err != nil { - break + case "model_change": + prov, id := l.Provider, l.ModelID + if id == "" { + prov, id, _ = strings.Cut(l.Model, "/") + } + if id != "" { + p.Provider, p.Model = prov, id + } + case "message": + if m := l.Message; m != nil && m.Role == "assistant" && m.Model != "" { + p.Provider, p.Model = m.Provider, m.Model } } - return st, true + if c, ok := piCall(st, st.Agent, l, p.Provider, p.Model); ok && !c.Time.Before(p.Since) { + c.Cwd = st.str(p.Cwd) + st.Calls = append(st.Calls, c) + } } // piCall is an entry as a call, on the provider and model in use for the diff --git a/internal/sessions/calls_pi_test.go b/internal/sessions/calls_pi_test.go index 7c3c17484..d1785ccc1 100644 --- a/internal/sessions/calls_pi_test.go +++ b/internal/sessions/calls_pi_test.go @@ -1,8 +1,12 @@ package sessions import ( + "os" "path/filepath" + "slices" "sort" + "strconv" + "sync" "testing" "time" ) @@ -57,7 +61,7 @@ func TestPiCalls(t *testing.T) { // first for _, f := range piFiles() { if f.key == "pi:"+fork { - if st, ok := readPiCalls(f); !ok || len(st.Calls) != 1 { + if st := readCalls(f); len(st.Calls) != 1 { t.Errorf("the fork's own calls: %+v", st.Calls) } } @@ -108,3 +112,116 @@ func TestPiCallsBesideReplies(t *testing.T) { } } } + +// A Pi session file that grew is read on from where the last read left +// off, with what its earlier lines said (its cwd, a fork's start, the +// model in use) carried on, in memory and in the disk shard; a half +// line waits for the rest, and a file cut shorter or written over is +// read whole again. +func TestPiCallsReadOnlyWhatWasAppended(t *testing.T) { + claude, _ := setup(t) + dir := filepath.Join(filepath.Dir(claude), "pi", "sessions", "--work-grow--") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "2026-10-13T08-00-00-000Z_01a1343b-0000-7000-8000-000000000077.jsonl") + t0 := time.Date(2026, 10, 13, 8, 0, 0, 0, time.UTC) + // a fork: what was written before its own time is its parent's + head := `{"type":"session","version":3,"id":"01a1343b-0000-7000-8000-000000000077","timestamp":"2026-10-13T08:00:00.000Z","cwd":"/work/grow","parentSession":"/p.jsonl"}` + "\n" + + `{"type":"model_change","id":"m0","timestamp":"2026-10-13T08:00:00.000Z","provider":"relay","modelId":"deepseek-v4"}` + "\n" + // a compaction's usage is on the provider and model in use + rec := func(i int) string { + at := t0.Add(time.Duration(i) * time.Second).Format("2006-01-02T15:04:05.000Z") + return `{"type":"compaction","id":"c` + strconv.Itoa(i+100) + `","timestamp":"` + at + `","usage":{"input":` + strconv.Itoa(20000+i) + `,"output":5,"cacheRead":0,"cacheWrite":0}}` + } + write := func(lines ...string) { + t.Helper() + b := head + for _, l := range lines { + b += l + "\n" + } + if err := os.WriteFile(path, []byte(b), 0o644); err != nil { + t.Fatal(err) + } + } + write(rec(-5), rec(1), rec(2)) + var mu sync.Mutex + var starts []int64 + scanHook = func(p string, off int64) { + if p == path { + mu.Lock() + starts = append(starts, off) + mu.Unlock() + } + } + t.Cleanup(func() { scanHook = nil }) + read := func(what string, from int64, want ...int) { + t.Helper() + mu.Lock() + starts = nil + mu.Unlock() + var calls []Call + for _, s := range CallSources() { + if s.Path == path { + calls = ReadCallSource(s) + } + } + mu.Lock() + got := append([]int64(nil), starts...) + mu.Unlock() + if len(got) == 0 { + t.Fatalf("%s: not read", what) + } + for _, off := range got { + if off != from { + t.Fatalf("%s: read from %d, want %d (%v)", what, off, from, got) + } + } + var in []int + for _, c := range calls { + if c.Model != "deepseek-v4" || c.Upstream != "relay" || c.Cwd != "/work/grow" || c.Agent != "pi" { + t.Fatalf("%s: call %+v lost what the earlier lines said", what, c) + } + in = append(in, c.Input-20000) + } + if !slices.Equal(in, want) { + t.Fatalf("%s: calls %v, want %v", what, in, want) + } + } + size := func() int64 { + t.Helper() + st, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + return st.Size() + } + read("first read", 0, 1, 2) + + end := size() + appendText(t, path, rec(3)+"\n"+rec(-4)+"\n"+rec(5)[:40]) + read("appended, half a line after", end, 1, 2, 3) + + end += int64(len(rec(3)) + len(rec(-4)) + 2) + appendText(t, path, rec(5)[40:]+"\n") + read("the half line finished", end, 1, 2, 3, 5) + + // read again after the in-memory reads are gone: from the disk shard, + // with what it carried + resetCalls() + end = size() + appendText(t, path, rec(6)+"\n") + read("from the disk shard", end, 1, 2, 3, 5, 6) + + // cut shorter: read whole again + write(rec(7)) + read("cut shorter", 0, 7) + + // written over, longer than it was: read whole again + write(rec(8), rec(9), rec(10)) + later := time.Now().Add(time.Hour) + if err := os.Chtimes(path, later, later); err != nil { + t.Fatal(err) + } + read("written over", 0, 8, 9, 10) +} diff --git a/internal/sessions/calls_workbuddy.go b/internal/sessions/calls_workbuddy.go index 63ae13e27..ec057724d 100644 --- a/internal/sessions/calls_workbuddy.go +++ b/internal/sessions/calls_workbuddy.go @@ -104,7 +104,7 @@ func buddyGateway(dir, id string) bool { return false } id = id[len(local):] - return strings.HasPrefix(id, provider.GroupPrefix) || buddyGatewayIDs(dir)[id] + return provider.IsGroupRef(id) || buddyGatewayIDs(dir)[id] } // wbEntry is what is read of a models.json entry: its id and whose it is. @@ -167,7 +167,7 @@ func readWorkBuddyCalls(f file) (*callFile, bool) { defer r.Close() st := &callFile{Agent: f.agent, Path: f.path, Session: strings.TrimPrefix(f.key, f.agent+":")} dir := buddyDir(f.agent) - br := bufio.NewReaderSize(r, 1<<20) + br := bufio.NewReaderSize(r, scanBuffer(r, 0)) last := "" // the messageId the call before this line carried for { b, err := br.ReadBytes('\n') @@ -185,7 +185,9 @@ func readWorkBuddyCalls(f file) (*callFile, bool) { // it is a new one, so both readers end on the same call id := st.str(l.ProviderData.MessageID) if c, ok := workbuddyCall(st, dir, l, b); ok { - if c.Msg != "" && c.Msg == last { + // a zero-token line made no call, so the call before is + // this reply's only when it carries the same id + if n := len(st.Calls); c.Msg != "" && c.Msg == last && n > 0 && st.Calls[n-1].Msg == c.Msg { st.Calls[len(st.Calls)-1] = c // another line of the reply before it } else { st.Calls = append(st.Calls, c) diff --git a/internal/sessions/calls_workbuddy_test.go b/internal/sessions/calls_workbuddy_test.go index 73093ebab..8739ffc88 100644 --- a/internal/sessions/calls_workbuddy_test.go +++ b/internal/sessions/calls_workbuddy_test.go @@ -3,6 +3,7 @@ package sessions import ( "os" "path/filepath" + "strconv" "testing" "time" ) @@ -167,3 +168,42 @@ func TestWorkBuddyGatewayFollowsModelsJSON(t *testing.T) { t.Fatal("a routing group's name stopped being the gateway's") } } + +// A reply whose first usage line spent nothing, before any call of the +// session's, is one call when its next line spends: there is no call +// before it to stand for, and reading it must not take one that isn't +// there. +func TestWorkBuddyCallsReplyStartingAtZero(t *testing.T) { + home := setupAgents(t) + p := filepath.Join(home, ".workbuddy", "projects", "Users-me-zero", "44444444-aaaa-4bbb-8ccc-000000000009.jsonl") + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + line := func(msg string, in, out int) string { + return `{"id":"a9","timestamp":1790503210000,"type":"message","role":"assistant","providerData":{"messageId":"` + msg + `","model":"hy3","requestModelId":"hy3","usage":{"inputTokens":` + strconv.Itoa(in) + `,"outputTokens":` + strconv.Itoa(out) + `}},"sessionId":"44444444-aaaa-4bbb-8ccc-000000000009","cwd":"/work/zero"}` + "\n" + } + read := func() []Call { + resetCalls() + for _, s := range CallSources() { + if s.Path == p { + return ReadCallSource(s) + } + } + t.Fatal("no call source for the session") + return nil + } + if err := os.WriteFile(p, []byte(line("m9", 0, 0)+line("m9", 300, 20)), 0o644); err != nil { + t.Fatal(err) + } + if got := read(); len(got) != 1 || got[0].Tokens != (Tokens{Input: 300, Output: 20}) { + t.Fatalf("calls %+v, want the reply's one", got) + } + // after another reply's call: that call is not this reply's to replace + if err := os.WriteFile(p, []byte(line("m8", 50, 5)+line("m9", 0, 0)+line("m9", 300, 20)), 0o644); err != nil { + t.Fatal(err) + } + got := read() + if len(got) != 2 || got[0].Msg != "m8" || got[0].Tokens != (Tokens{Input: 50, Output: 5}) || got[1].Msg != "m9" || got[1].Tokens != (Tokens{Input: 300, Output: 20}) { + t.Fatalf("calls %+v, want m8's and m9's", got) + } +} diff --git a/internal/sessions/cline.go b/internal/sessions/cline.go index 7374e2ce1..4b3d2d150 100644 --- a/internal/sessions/cline.go +++ b/internal/sessions/cline.go @@ -95,38 +95,87 @@ type clineMessage struct { } `json:"metrics"` } -// parseCline reads a session's messages whole, as they are written. -func parseCline(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - var since time.Time +// clineCarry is what a read of a session's messages.json keeps, to know +// whether it can stand for the next: the file as it was read, and what of +// the manifest its counts were made under. Prompt is the first prompt in +// it that names the session, for when the manifest's doesn't. +type clineCarry struct { + Size int64 `json:"size"` + Mod int64 `json:"mod"` + Since time.Time `json:"since,omitzero"` + Start time.Time `json:"start,omitzero"` + Prompt string `json:"prompt,omitempty"` +} + +// parseCline reads a session's messages whole, as they are written, with +// its manifest. Cline rewrites the manifest on its own (a title given, the +// session touched), so when only that changed and it still says the same +// start and fork, what the messages were counted as stands and only the +// manifest is read again. +func parseCline(f file, old *state) *state { + var since, start time.Time + var m clineManifest + hasM := false if f.manifest != "" { - var m clineManifest if b, err := os.ReadFile(f.manifest); err == nil && json.Unmarshal(b, &m) == nil { - s.ID, s.Cwd = m.SessionID, m.Cwd - s.Named = title(m.Metadata.Title) + hasM = true if m.Metadata.Fork != nil { since, _ = time.Parse(time.RFC3339Nano, m.Metadata.Fork.ForkedAt) } - start, _ := time.Parse(time.RFC3339Nano, m.StartedAt) - if since.IsZero() || !start.Before(since) { - s.saw(start, f.main) + at, _ := time.Parse(time.RFC3339Nano, m.StartedAt) + if since.IsZero() || !at.Before(since) { + start = at } + } + } + name := func(s *state, prompt string) *state { + s.Size, s.Mod = f.size, f.mod.UnixNano() + s.ID, s.Cwd, s.Named, s.Title, s.First = "", "", "", "", "" + if hasM { + s.ID, s.Cwd = m.SessionID, m.Cwd + s.Named = title(m.Metadata.Title) clineTitle(s, m.Prompt) } + if f.main { + clineTitle(s, prompt) + } + return s + } + fi, err := os.Stat(f.path) + if err != nil { + return name(&state{}, "") + } + if o := old; o != nil && o.Cline != nil && o.Cline.Size == fi.Size() && o.Cline.Mod == fi.ModTime().UnixNano() && o.Cline.Since.Equal(since) && o.Cline.Start.Equal(start) { + s := o.clone() + return name(s, o.Cline.Prompt) // the title its messages gave, when the manifest gives none + + } + s := &state{} + s.saw(start, f.main) + c := &clineCarry{Size: fi.Size(), Mod: fi.ModTime().UnixNano(), Since: since, Start: start} + if clineHook != nil { + clineHook(f.path) } b, err := os.ReadFile(f.path) if err != nil { - return s + return name(s, "") } var doc struct { Messages []clineMessage `json:"messages"` } if json.Unmarshal(b, &doc) != nil { - return s + // half written, or not Cline's: read again when it changes + return name(s, "") } + named := false for _, m := range doc.Messages { - if f.main && m.Role == "user" && s.Title == "" && s.First == "" { - clineTitle(s, ccText(m.Content)) + if !named && m.Role == "user" { + // the first prompt that names the session by itself + var t state + text := ccText(m.Content) + if clineTitle(&t, text); t.Title != "" || t.First != "" { + c.Prompt, named = text, true + } } at := ms(m.TS) if !since.IsZero() && at.Before(since) { @@ -137,9 +186,14 @@ func parseCline(f file) *state { s.use(dateOf(at), m.ModelInfo.ID, Tokens{Input: max(0, u.Input-u.CacheRead-u.CacheWrite), Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}) } } - return s + s.Cline = c + return name(s, c.Prompt) } +// clineHook, when a test sets it, is told each time a messages file is +// read. +var clineHook func(path string) + var ( clineNotice = regexp.MustCompile(`(?s)]*>.*?`) clineInput = regexp.MustCompile(`]*>`) diff --git a/internal/sessions/codex.go b/internal/sessions/codex.go index 50730fc22..8d27e7bc0 100644 --- a/internal/sessions/codex.go +++ b/internal/sessions/codex.go @@ -277,12 +277,12 @@ func noteCodexIdentity(s *state, identity CodexIdentity, conflict bool) { // CodexIdentities returns an independent snapshot of the native thread identities. func CodexIdentities() map[string]CodexIdentity { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() want := append(codexFiles(), wslFiles("codex")...) refresh(want, nil) return codexIdentitySnapshot(want) diff --git a/internal/sessions/codex_provider.go b/internal/sessions/codex_provider.go index 6a1de69c0..52ca0e870 100644 --- a/internal/sessions/codex_provider.go +++ b/internal/sessions/codex_provider.go @@ -195,12 +195,12 @@ func MoveCodexProvider(id, to string) (CodexMove, error) { if !codexProviderRe.MatchString(to) { return CodexMove{}, fmt.Errorf("%q isn't a provider id", to) } - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.Lock() + defer storeMu.Unlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() all := allFiles() groups := map[string][]file{} var mine []file diff --git a/internal/sessions/droid.go b/internal/sessions/droid.go index cbf7473ff..3d9eb5602 100644 --- a/internal/sessions/droid.go +++ b/internal/sessions/droid.go @@ -64,10 +64,18 @@ func readDroidStart(path string) (droidStart, bool) { return s, ok } +// droidCallers is whose subagent each transcript is, as its session_start +// line said when the listing last read it: a listing runs on every poll, and +// opening every session's transcript for its first line each time cost more +// than the rest of the listing together. +var droidCallers listMemo[string] + func droidFiles() []file { root := filepath.Join(FactoryDir(), "sessions") a, _ := filepath.Glob(filepath.Join(root, "*.jsonl")) b, _ := filepath.Glob(filepath.Join(root, "*", "*.jsonl")) + callers := droidCallers.round() + defer callers.done() var out []file for _, p := range append(a, b...) { id := strings.TrimSuffix(filepath.Base(p), ".jsonl") @@ -78,6 +86,10 @@ func droidFiles() []file { if !stat(&f) { continue } + calling, _ := callers.get(p, f.size, f.mod, func() (string, bool) { + s, ok := readDroidStart(p) + return s.Calling, ok + }) // what it spent and on which model are in its settings m := file{path: strings.TrimSuffix(p, ".jsonl") + ".settings.json"} if stat(&m) { @@ -87,8 +99,8 @@ func droidFiles() []file { f.mod = m.mod } } - if s, ok := readDroidStart(p); ok && s.Calling != "" && s.Calling != id && safeID.MatchString(s.Calling) { - f.key, f.main = "droid:"+s.Calling, false + if calling != "" && calling != id && safeID.MatchString(calling) { + f.key, f.main = "droid:"+calling, false } out = append(out, f) } @@ -153,68 +165,46 @@ func droidTools(raw json.RawMessage) []string { return out } -// parseDroid reads a session's transcript whole, with its settings. -func parseDroid(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - // a fork's lines up to upto are copies of its source's - upto, copied := "", false - first := true - scan(f.path, 0, func(b []byte) { - var l droidLine - if json.Unmarshal(b, &l) != nil { - return - } - if first { - first = false - var st droidStart - if l.Type == "session_start" && json.Unmarshal(b, &st) == nil { - s.ID, s.Cwd, s.Named = st.ID, st.Cwd, title(st.Title) - if s.Named == "New Session" { - s.Named = "" // Droid's until it names one - } - if st.LastCwd != "" { - s.Cwd = st.LastCwd - } - upto, copied = st.Forked, st.Forked != "" - } - return - } - if l.Type != "message" { - return - } - if copied { - if l.ID == upto { - copied = false - } - return - } - at := tsAt(b, false) - s.saw(at, f.main) - switch l.Message.Role { - case "user": - text := droidText(l.Message.Content) - if strings.TrimSpace(text) == "" || !f.main { - return - } - if strings.HasPrefix(strings.TrimSpace(text), "<") { - if s.First == "" { - s.First = untagged(text) - } - return - } - s.day(dateOf(at)).Prompts++ - if s.Title == "" { - s.Title = title(text) - } - case "assistant": - if f.main { - s.day(dateOf(at)).Replies++ - } - for _, name := range droidTools(l.Message.Content) { - s.tool(at, name, "") - } - } +// droidCarry is what a read of a Droid transcript carries on with: where +// it read to, whether it has passed the session_start line and a fork's +// copied lines, and what its settings' total was counted as, to be taken +// back when the total moves on. +type droidCarry struct { + Tail *tail `json:"tail,omitempty"` + Started bool `json:"started,omitempty"` + Upto string `json:"upto,omitempty"` + Copied bool `json:"copied,omitempty"` + // the settings' total, as counted + Date string `json:"date,omitempty"` + Model string `json:"model,omitempty"` + Tokens Tokens `json:"tokens,omitzero"` +} + +// parseDroid reads a session's transcript, with its settings. Droid only +// appends to a transcript, so one read before is read on from where that +// read left off, and its settings' running total, counted on the day of +// the last message, is taken back and counted again as it is now. A +// transcript cut short or replaced is read whole again. +func parseDroid(f file, old *state) *state { + var s *state + var c droidCarry + var off int64 + if old != nil && old.Droid != nil && old.Droid.Tail.holds(f.path) { + s, c, off = old.clone(), *old.Droid, old.Droid.Tail.Off + s.dropUse(c.Date, c.Model, c.Tokens) + } else { + s = &state{} + } + s.Size, s.Mod = f.size, f.mod.UnixNano() + end, err := scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { + droidLineOf(s, &c, b, f.main) + return true }) + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, end, 0, end) + } + c.Date, c.Model, c.Tokens = "", "", Tokens{} if f.manifest != "" { var st droidSettings if b, err := os.ReadFile(f.manifest); err == nil && json.Unmarshal(b, &st) == nil && st.Usage != nil { @@ -223,12 +213,74 @@ func parseDroid(f file) *state { when = time.Unix(0, s.Mod) } u := st.Usage - s.use(dateOf(when), droidModelName(st.Model), Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}) + c.Date, c.Model = dateOf(when), droidModelName(st.Model) + c.Tokens = Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite} + s.use(c.Date, c.Model, c.Tokens) } } + s.Droid = &c return s } +// droidLineOf counts one line of a transcript. +func droidLineOf(s *state, c *droidCarry, b []byte, main bool) { + var l droidLine + if json.Unmarshal(b, &l) != nil { + return + } + if !c.Started { + c.Started = true + var st droidStart + if l.Type == "session_start" && json.Unmarshal(b, &st) == nil { + s.ID, s.Cwd, s.Named = st.ID, st.Cwd, title(st.Title) + if s.Named == "New Session" { + s.Named = "" // Droid's until it names one + } + if st.LastCwd != "" { + s.Cwd = st.LastCwd + } + // a fork's lines up to Upto are copies of its source's + c.Upto, c.Copied = st.Forked, st.Forked != "" + } + return + } + if l.Type != "message" { + return + } + if c.Copied { + if l.ID == c.Upto { + c.Copied = false + } + return + } + at := tsAt(b, false) + s.saw(at, main) + switch l.Message.Role { + case "user": + text := droidText(l.Message.Content) + if strings.TrimSpace(text) == "" || !main { + return + } + if strings.HasPrefix(strings.TrimSpace(text), "<") { + if s.First == "" { + s.First = untagged(text) + } + return + } + s.day(dateOf(at)).Prompts++ + if s.Title == "" { + s.Title = title(text) + } + case "assistant": + if main { + s.day(dateOf(at)).Replies++ + } + for _, name := range droidTools(l.Message.Content) { + s.tool(at, name, "") + } + } +} + // droidSlot is the tail droid gives a custom model's id made of its name // ("custom:Kimi-K2-[Groq]-0"). var droidSlot = regexp.MustCompile(`(-\[[^\]]*\])?-\d+$`) diff --git a/internal/sessions/dsh.go b/internal/sessions/dsh.go index 55c0865db..baf62c6c2 100644 --- a/internal/sessions/dsh.go +++ b/internal/sessions/dsh.go @@ -4,7 +4,6 @@ import ( "bufio" "bytes" "encoding/json" - "errors" "fmt" "io" "os" @@ -242,88 +241,118 @@ type dshEvent struct { var dshWanted = [][]byte{[]byte(`"user/message"`), []byte(`"session/title"`), []byte(`"assistant/message"`), []byte(`"session/end-seed"`)} -// parseDsh reads a session file whole: compressed, it can't be read on from -// the middle of a frame. -func parseDsh(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - r, err := dshOpen(f.path) - if err != nil { - return s +// dshCarry is what a read of a dsh session file carries on with: where it +// read to and the header it read first. +type dshCarry struct { + Tail *tail `json:"tail,omitempty"` + Head dshHead `json:"head"` +} + +// parseDsh reads a session file. dsh only appends to one, a line at a time +// or, packed, a frame of lines at a time, so a file read before is read on +// from where that read left off: a packed one from the frame it left off +// in. A file cut short or replaced is read whole again, and a line or frame +// not yet written whole waits for the next read. +func parseDsh(f file, old *state) *state { + var s *state + var c dshCarry + var off, skip int64 + if old != nil && old.Dsh != nil && old.Dsh.Tail.holds(f.path) { + s, c = old.clone(), *old.Dsh + off, skip = c.Tail.Off, c.Tail.Skip + } else { + s = &state{} } - defer r.Close() - br := bufio.NewReaderSize(r, 1<<20) - var h dshHead - var evs []dshEvent - for first := true; ; first = false { - b, err := br.ReadBytes('\n') - if err != nil { - // a line still being written, or a frame cut short - if !errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0 { - break + s.Size, s.Mod = f.size, f.mod.UnixNano() + headed := c.Tail != nil + ok := true + each := func(b []byte) bool { + b = bytes.TrimSpace(b) + if len(b) == 0 || len(b) > maxLine { + return true + } + if !headed { + headed = true + if json.Unmarshal(b, &c.Head) != nil || c.Head.Type != "session" { + ok = false + return false } + s.ID, s.Cwd = c.Head.ID, c.Head.Cwd + s.saw(ms(c.Head.CreatedAt), f.main) + return true } - if b = bytes.TrimSpace(b); len(b) > 0 && len(b) <= maxLine { - if first { - if json.Unmarshal(b, &h) != nil || h.Type != "session" { - return s - } - } else if dshWant(b) { - var e dshEvent - if json.Unmarshal(b, &e) == nil && e.Type != "" { - evs = append(evs, e) - } - } else if t := dshNum(b, "time"); t > 0 { - // only its time and place looked at - e := dshEvent{Time: t} - if n := dshNum(b, "seq"); n >= 0 { - e.Seq = &n - } - evs = append(evs, e) - } - } - if err != nil { - break - } + dshCount(s, &c.Head, b, f.main) + return true } - s.ID, s.Cwd = h.ID, h.Cwd - // the events a fork was seeded with - cut := -1 - if h.Version >= 2 && h.IsSeeded { - for i, e := range evs { - if e.Type == "session/end-seed" && e.Data.Inherited { - cut = i - } - } + var next, nextSkip, end int64 + var err error + if packed(f.path) { + next, nextSkip, end, err = scanFrames(f.path, off, skip, each) + } else { + next, err = scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { return each(b) }) + end = next } - s.saw(ms(h.CreatedAt), f.main) - for i, e := range evs { - inherited := i <= cut || h.Version < 2 && e.Seq != nil && *e.Seq < h.SeedLength - switch e.Type { - case "user/message": - if f.main && s.Title == "" && s.First == "" && e.Data.Source.Kind == "user" { - if t := ccText(e.Data.Content); strings.HasPrefix(t, "<") { - s.First = untagged(t) - } else { - s.Title = title(t) - } - } - case "session/title": - if t := title(e.Data.Title); t != "" { - s.Named = t - } - } - if inherited { - continue - } - at := ms(e.Time) - s.saw(at, f.main) - if u := e.Data.Usage; e.Type == "assistant/message" && u != nil && e.Data.Message.Source.Model != "" { - s.use(dateOf(at), e.Data.Message.Source.Model, Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}) - } + if !ok { + // not a session's file: only its size and time + return &state{Size: f.size, Mod: f.mod.UnixNano()} } + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, next, nextSkip, end) + } + s.Dsh = &c return s } +// dshCount counts one event of a session file after its header. +func dshCount(s *state, h *dshHead, b []byte, main bool) { + var e dshEvent + if dshWant(b) { + if json.Unmarshal(b, &e) != nil || e.Type == "" { + return + } + } else if t := dshNum(b, "time"); t > 0 { + // only its time and place looked at + e.Time = t + if n := dshNum(b, "seq"); n >= 0 { + e.Seq = &n + } + } else { + return + } + switch e.Type { + case "user/message": + if main && s.Title == "" && s.First == "" && e.Data.Source.Kind == "user" { + if t := ccText(e.Data.Content); strings.HasPrefix(t, "<") { + s.First = untagged(t) + } else { + s.Title = title(t) + } + } + case "session/title": + if t := title(e.Data.Title); t != "" { + s.Named = t + } + case "session/end-seed": + if h.Version >= 2 && h.IsSeeded && e.Data.Inherited { + // the events a fork was seeded with end here: what was + // counted of them is its source's + n := &state{ID: s.ID, Cwd: s.Cwd, Title: s.Title, First: s.First, Named: s.Named, Size: s.Size, Mod: s.Mod} + n.saw(ms(h.CreatedAt), main) + *s = *n + return + } + } + if h.Version < 2 && e.Seq != nil && *e.Seq < h.SeedLength { + return + } + at := ms(e.Time) + s.saw(at, main) + if u := e.Data.Usage; e.Type == "assistant/message" && u != nil && e.Data.Message.Source.Model != "" { + s.use(dateOf(at), e.Data.Message.Source.Model, Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}) + } +} + func dshWant(b []byte) bool { for _, w := range dshWanted { if bytes.Contains(b, w) { diff --git a/internal/sessions/frames.go b/internal/sessions/frames.go new file mode 100644 index 000000000..a661e834e --- /dev/null +++ b/internal/sessions/frames.go @@ -0,0 +1,203 @@ +package sessions + +import ( + "bufio" + "bytes" + "encoding/binary" + "errors" + "io" + "os" + + "github.com/klauspost/compress/zstd" +) + +// Reading on through a file of zstd frames, as dsh writes its sessions: a +// batch of whole lines a frame, appended. A frame can't be read from its +// middle, but it can be found without decoding it (RFC 8878: its header, +// then blocks that each say how long they are), so a read goes on from the +// frame it left off in, passing over what that frame gave it before. A +// last frame not yet written whole waits for the next read. + +var errFrame = errors.New("not a zstd frame") + +// readFrame reads the frame at r into buf: a zstd frame whole, nil for a +// skippable one. io.ErrUnexpectedEOF when the file ends inside it, io.EOF +// when it ends before it. +func readFrame(r *bufio.Reader, buf []byte) ([]byte, int64, error) { + buf = buf[:0] + var n int64 + take := func(k int) ([]byte, error) { + start := len(buf) + buf = append(buf, make([]byte, k)...) + if _, err := io.ReadFull(r, buf[start:]); err != nil { + if errors.Is(err, io.EOF) { + err = io.ErrUnexpectedEOF + } + return nil, err + } + n += int64(k) + return buf[start:], nil + } + if _, err := r.Peek(1); err != nil { + return nil, 0, io.EOF + } + magic, err := take(4) + if err != nil { + return nil, 0, err + } + m := binary.LittleEndian.Uint32(magic) + if m&0xFFFFFFF0 == 0x184D2A50 { + size, err := take(4) + if err != nil { + return nil, 0, err + } + k := int64(binary.LittleEndian.Uint32(size)) + if d, err := r.Discard(int(k)); err != nil || int64(d) < k { + return nil, 0, io.ErrUnexpectedEOF + } + return nil, n + k, nil + } + if m != 0xFD2FB528 { + return nil, 0, errFrame + } + fhd, err := take(1) + if err != nil { + return nil, 0, err + } + d := fhd[0] + single := d>>5&1 == 1 + extra := 0 + if !single { + extra++ // window descriptor + } + extra += []int{0, 1, 2, 4}[d&3] // dictionary id + switch d >> 6 { + case 0: + if single { + extra++ + } + case 1: + extra += 2 + case 2: + extra += 4 + case 3: + extra += 8 + } + if _, err := take(extra); err != nil { + return nil, 0, err + } + for { + h, err := take(3) + if err != nil { + return nil, 0, err + } + v := uint32(h[0]) | uint32(h[1])<<8 | uint32(h[2])<<16 + size := int(v >> 3) + switch v >> 1 & 3 { + case 1: + size = 1 // RLE: one byte, repeated + case 3: + return nil, 0, errFrame + } + if _, err := take(size); err != nil { + return nil, 0, err + } + if v&1 == 1 { + break + } + } + if d>>2&1 == 1 { + if _, err := take(4); err != nil { + return nil, 0, err + } + } + return buf, n, nil +} + +// scanFrames hands fn each whole line of a file of zstd frames, from the +// frame at off, skip bytes into what that frame holds. It returns where to +// go on from (the frame the first line not yet whole starts in, and how far +// into it) and where the last whole frame read ends. +func scanFrames(path string, off, skip int64, fn func([]byte) bool) (next, nextSkip, end int64, err error) { + if scanHook != nil { + scanHook(path, off) + } + next, nextSkip, end = off, skip, off + f, err := os.Open(path) + if err != nil { + return + } + defer f.Close() + if _, err = f.Seek(off, io.SeekStart); err != nil { + return + } + dec, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1), zstd.WithDecoderLowmem(true)) + if err != nil { + return + } + defer dec.Close() + r := bufio.NewReaderSize(f, scanBuffer(f, off)) + var frame, out, pending []byte + at := off + first := true + for { + var n int64 + frame, n, err = readFrame(r, frame) + if err != nil { + // the end, a frame still being written, or not one at all: + // what was read stands, the rest waits for the next read + err = nil + return + } + start := at + at += n + end = at + if frame == nil { + if len(pending) == 0 { + next, nextSkip = at, 0 + } + continue + } + if out, err = dec.DecodeAll(frame, out[:0]); err != nil { + err = nil + end = start + return + } + from := int64(0) + if first { + first = false + if skip > int64(len(out)) { + err = errFrame + return + } + from = skip + } + data := out[from:] + for { + i := bytes.IndexByte(data, '\n') + if i < 0 { + break + } + line := data[:i] + if len(pending) > 0 { + line = append(pending, line...) + pending = pending[:0] + } + if !fn(line) { + return + } + from += int64(i + 1) + data = data[i+1:] + } + if len(data) == 0 { + if len(pending) == 0 { + next, nextSkip = at, 0 + } + continue + } + if len(pending) == 0 { + next, nextSkip = start, from + } + pending = append(pending, data...) + } +} diff --git a/internal/sessions/grok.go b/internal/sessions/grok.go index a0bb3b7ee..ea68115a5 100644 --- a/internal/sessions/grok.go +++ b/internal/sessions/grok.go @@ -51,13 +51,31 @@ type grokSummary struct { Kind string `json:"session_kind"` } +// grokSummaryHook, when a test sets it, is told each time a summary.json +// is read. +var grokSummaryHook func(path string) + func readGrokSummary(path string) (grokSummary, bool) { + if grokSummaryHook != nil { + grokSummaryHook(path) + } var s grokSummary b, err := os.ReadFile(path) return s, err == nil && json.Unmarshal(b, &s) == nil } +// grokKind is what a listing needs of a session's summary.json: whether it +// is a subagent's, and whose. +type grokKind struct{ Kind, Parent string } + +// grokKinds keeps each summary's kind as the listing last read it: a +// listing runs on every poll, and reading and decoding every session's +// summary each time cost more than the rest of the listing together. +var grokKinds listMemo[grokKind] + func grokFiles() []file { + kinds := grokKinds.round() + defer kinds.done() root := filepath.Join(GrokDir(), "sessions") paths, _ := filepath.Glob(filepath.Join(root, "*", "*", "updates.jsonl")) // a session's subagents are named in its subagents/ folder too @@ -83,7 +101,11 @@ func grokFiles() []file { if m.mod.After(f.mod) { f.mod = m.mod } - if s, ok := readGrokSummary(m.path); ok && strings.HasPrefix(s.Kind, "subagent") { + s, ok := kinds.get(m.path, m.size, m.mod, func() (grokKind, bool) { + s, ok := readGrokSummary(m.path) + return grokKind{s.Kind, s.Parent}, ok + }) + if ok && strings.HasPrefix(s.Kind, "subagent") { parent := s.Parent if parent == "" { parent = parentOf[id] @@ -132,80 +154,123 @@ var ( grokHook = []byte(`"sessionUpdate":"hook_execution"`) ) -// parseGrok reads a session's updates whole, with its summary. -func parseGrok(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - var since time.Time - model := "" +// grokCarry is what a read of a Grok Build session's updates carries on +// with: where it read to, what of its summary the updates were counted +// under, and its first prompt as far as it was read. +type grokCarry struct { + Tail *tail `json:"tail,omitempty"` + Created time.Time `json:"created,omitzero"` + Since time.Time `json:"since,omitzero"` + Model string `json:"model,omitempty"` + Prompt string `json:"prompt,omitempty"` + InPrompt bool `json:"in_prompt,omitempty"` + // the first prompt, before it is told from a tag + Title string `json:"title,omitempty"` +} + +// parseGrok reads a session's updates, with its summary. Grok Build only +// appends to updates.jsonl, so a session read before is read on from where +// that read left off; its summary, rewritten as it goes on, is read again +// each time. When the file was cut short or replaced, or the summary now +// says another time or model the updates are counted under, it is read +// whole again. +func parseGrok(f file, old *state) *state { + var c grokCarry + var m grokSummary + hasM := false if f.manifest != "" { - if m, ok := readGrokSummary(f.manifest); ok { - s.ID, s.Cwd, model = m.Info.ID, m.Info.Cwd, m.CurrentModel - s.Named = title(m.GeneratedTitle) - if s.Named == "" { - s.Named = title(m.SessionSummary) - } - created, _ := time.Parse(time.RFC3339Nano, m.CreatedAt) + if m, hasM = readGrokSummary(f.manifest); hasM { + c.Model = m.CurrentModel + c.Created, _ = time.Parse(time.RFC3339Nano, m.CreatedAt) if m.Parent != "" { // what it copied from its source is older than it - since = created.Truncate(time.Second) + c.Since = c.Created.Truncate(time.Second) } - s.saw(created, f.main) + } else { + m = grokSummary{} } } - prompt, inPrompt := "", false - scan(f.path, 0, func(b []byte) { - at := numTS(b) - if !since.IsZero() && at.Before(since) { - return - } - if bytes.Contains(b, grokHook) { - // its hooks run as it starts and ends too: a session left open - // overnight isn't at work till it is closed - return - } - s.saw(at, f.main) - user := f.main && s.Title == "" && bytes.Contains(b, grokUser) - if !user && inPrompt { - // the first prompt's chunks are over - s.Title, inPrompt = title(prompt), false - } - if !user && !bytes.Contains(b, grokTurn) { - return - } - var l grokLine - if json.Unmarshal(b, &l) != nil { - return - } - u := l.Params.Update - switch u.SessionUpdate { - case "user_message_chunk": - if user && u.Content.Type == "text" { - prompt += u.Content.Text - inPrompt = true - } - case "turn_completed": - if u.Usage == nil { - return - } - date := dateOf(at) - if len(u.Usage.ModelUsage) == 0 { - s.use(date, cmp.Or(model, "grok"), u.Usage.tokens()) - return - } - for name, mu := range u.Usage.ModelUsage { - s.use(date, name, mu.tokens()) - } + var s *state + var off int64 + if o := old; o != nil && o.Grok != nil && o.Grok.Model == c.Model && o.Grok.Created.Equal(c.Created) && o.Grok.Since.Equal(c.Since) && o.Grok.Tail.holds(f.path) { + s, c, off = o.clone(), *o.Grok, o.Grok.Tail.Off + } else { + s = &state{} + if hasM { + s.saw(c.Created, f.main) } + } + s.Size, s.Mod = f.size, f.mod.UnixNano() + s.ID, s.Cwd, s.Named = m.Info.ID, m.Info.Cwd, title(m.GeneratedTitle) + if s.Named == "" { + s.Named = title(m.SessionSummary) + } + end, err := scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { + grokUpdate(s, &c, b, f.main) + return true }) - if inPrompt { - s.Title = title(prompt) + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, end, 0, end) } - if strings.HasPrefix(s.Title, "<") { - s.Title, s.First = "", untagged(s.Title) + t := c.Title + if c.InPrompt { + t = title(c.Prompt) } + s.Title, s.First = t, "" + if strings.HasPrefix(t, "<") { + s.Title, s.First = "", untagged(t) + } + s.Grok = &c return s } +// grokUpdate counts one line of a session's updates. +func grokUpdate(s *state, c *grokCarry, b []byte, main bool) { + at := numTS(b) + if !c.Since.IsZero() && at.Before(c.Since) { + return + } + if bytes.Contains(b, grokHook) { + // its hooks run as it starts and ends too: a session left open + // overnight isn't at work till it is closed + return + } + s.saw(at, main) + user := main && c.Title == "" && bytes.Contains(b, grokUser) + if !user && c.InPrompt { + // the first prompt's chunks are over + c.Title, c.Prompt, c.InPrompt = title(c.Prompt), "", false + } + if !user && !bytes.Contains(b, grokTurn) { + return + } + var l grokLine + if json.Unmarshal(b, &l) != nil { + return + } + u := l.Params.Update + switch u.SessionUpdate { + case "user_message_chunk": + if user && u.Content.Type == "text" { + c.Prompt += u.Content.Text + c.InPrompt = true + } + case "turn_completed": + if u.Usage == nil { + return + } + date := dateOf(at) + if len(u.Usage.ModelUsage) == 0 { + s.use(date, cmp.Or(c.Model, "grok"), u.Usage.tokens()) + return + } + for name, mu := range u.Usage.ModelUsage { + s.use(date, name, mu.tokens()) + } + } +} + var tsKey = []byte(`"timestamp":`) // numTS reads the time of a line from its first "timestamp" key when it is diff --git a/internal/sessions/grow_test.go b/internal/sessions/grow_test.go new file mode 100644 index 000000000..a67233d66 --- /dev/null +++ b/internal/sessions/grow_test.go @@ -0,0 +1,503 @@ +package sessions + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/klauspost/compress/zstd" +) + +// grower reads one session file as refresh does, each parse on from the +// one kept before, and checks every such parse against a whole read of the +// same file: a summary read on from where it was is the one a whole read +// makes. start is where the last parse began reading the file. +type grower struct { + t *testing.T + files func() []file + path string + old *state + start int64 +} + +func (g *grower) file() file { + g.t.Helper() + for _, f := range g.files() { + if f.path == g.path { + return f + } + } + g.t.Fatalf("no file %s", g.path) + return file{} +} + +// read parses the file on from the last parse and says where it started. +func (g *grower) read() int64 { + g.t.Helper() + f := g.file() + g.start = -1 + scanHook = func(p string, off int64) { + if p == g.path && g.start < 0 { + g.start = off + } + } + defer func() { scanHook = nil }() + s := parse(f, g.old) + scanHook = nil + whole := parse(f, nil) + got, _ := json.Marshal(s) + want, _ := json.Marshal(whole) + if !bytes.Equal(got, want) { + g.t.Fatalf("read on from %d:\n%s\nread whole:\n%s", g.start, got, want) + } + g.old = s + return g.start +} + +func (g *grower) size() int64 { + g.t.Helper() + fi, err := os.Stat(g.path) + if err != nil { + g.t.Fatal(err) + } + return fi.Size() +} + +func (g *grower) append(s string) { + g.t.Helper() + f, err := os.OpenFile(g.path, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + g.t.Fatal(err) + } + defer f.Close() + if _, err := f.WriteString(s); err != nil { + g.t.Fatal(err) + } +} + +// grows runs the cases every reader of an appended file meets: a line +// appended is the only thing read; half a line waits for the rest and is +// counted once; a file cut short, or replaced by one as long, is read whole +// again. line is a whole line the file may take, with its newline. +func checkGrows(t *testing.T, g *grower, line string) { + t.Helper() + orig, err := os.ReadFile(g.path) + if err != nil { + t.Fatal(err) + } + if at := g.read(); at != 0 { + t.Fatalf("first read started at %d", at) + } + // a line appended: only it is read + was := g.size() + g.append(line) + if at := g.read(); at != was { + t.Fatalf("after a line appended to %d bytes, read from %d", was, at) + } + // half a line, still being written: it waits for the rest + was = g.size() + half := len(line) / 2 + g.append(line[:half]) + if at := g.read(); at != was { + t.Fatalf("with half a line at %d, read from %d", was, at) + } + g.append(line[half:]) + if at := g.read(); at != was { + t.Fatalf("the half line finished at %d, read from %d", was, at) + } + // cut short: read whole again + if err := os.WriteFile(g.path, orig, 0o644); err != nil { + t.Fatal(err) + } + if at := g.read(); at != 0 { + t.Fatalf("cut short, read from %d", at) + } + // replaced by another as long, its first line changed: read whole + g.append(line) + g.read() + b, _ := os.ReadFile(g.path) + other := append([]byte(nil), b...) + other[len(orig)-2] ^= 1 // a line it had, changed in place + if bytes.Equal(other, b) { + t.Fatal("not changed") + } + if err := os.WriteFile(g.path, other, 0o644); err != nil { + t.Fatal(err) + } + if at := g.read(); at != 0 { + t.Fatalf("rewritten in place, read from %d", at) + } +} + +// Grok Build appends to a session's updates.jsonl: a turn that ended is +// read alone, not the session again. +func TestGrokReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + dir := filepath.Join(home, ".grok", "sessions", "%2Fwork%2Fgrok", grokMain) + g := &grower{t: t, files: grokFiles, path: filepath.Join(dir, "updates.jsonl")} + turn := `{"timestamp":1790496140,"method":"_x.ai/session/update","params":{"sessionId":"` + grokMain + `","update":{"sessionUpdate":"turn_completed","usage":{"inputTokens":200,"outputTokens":6,"cachedReadTokens":100,"cacheCreationTokens":0,"modelUsage":{"grok-4.7-build":{"inputTokens":200,"outputTokens":6,"cachedReadTokens":100,"cacheCreationTokens":0}}}}}}` + "\n" + checkGrows(t, g, turn) + + // its summary rewritten, a title given: nothing of the updates read + g.read() + summary := filepath.Join(dir, "summary.json") + b, _ := os.ReadFile(summary) + os.WriteFile(summary, bytes.Replace(b, []byte(`"generated_title": "Parser port"`), []byte(`"generated_title": "Port of the parser"`), 1), 0o644) + if at, end := g.read(), g.size(); at != end || g.old.Named != "Port of the parser" { + t.Fatalf("summary changed: read from %d of %d, named %q", at, end, g.old.Named) + } + // the model its turns are counted under changed: read whole + b, _ = os.ReadFile(summary) + os.WriteFile(summary, bytes.Replace(b, []byte(`"current_model_id": "grok-4.7"`), []byte(`"current_model_id": "grok-5"`), 1), 0o644) + if at := g.read(); at != 0 { + t.Fatalf("model changed: read from %d", at) + } +} + +// A first prompt still coming in chunks when a read ends goes on in the +// next one. +func TestGrokPromptAcrossReads(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + dir := filepath.Join(home, ".grok", "sessions", "%2Fwork%2Fgrok", "0190aaaa-0000-7000-8000-0000000000ee") + os.MkdirAll(dir, 0o755) + os.WriteFile(filepath.Join(dir, "summary.json"), []byte(`{"info":{"id":"0190aaaa-0000-7000-8000-0000000000ee","cwd":"/w"},"created_at":"2026-09-27T08:00:00Z"}`), 0o644) + chunk := func(ts int, text string) string { + return fmt.Sprintf(`{"timestamp":%d,"params":{"update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":%q}}}}`+"\n", ts, text) + } + p := filepath.Join(dir, "updates.jsonl") + os.WriteFile(p, []byte(chunk(1790496001, "Port the ")), 0o644) + g := &grower{t: t, files: grokFiles, path: p} + g.read() + g.append(chunk(1790496002, "parser")) + g.read() + g.append(`{"timestamp":1790496003,"params":{"update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ok"}}}}` + "\n") + g.read() + g.append(chunk(1790496004, "and more")) + if g.read(); g.old.Title != "Port the parser" { + t.Fatalf("title %q", g.old.Title) + } +} + +// Droid appends to a transcript and keeps a running total in its +// settings: a message appended is read alone, and the total, counted on +// the day of the last message, moves with it instead of being counted twice. +func TestDroidReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + putDroid(t, home) + dir := filepath.Join(home, ".factory", "sessions", "-work-droid") + g := &grower{t: t, files: droidFiles, path: filepath.Join(dir, droidMain+".jsonl")} + msg := `{"type":"message","id":"m5","timestamp":"2026-09-27T08:03:00.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Fixed"},{"type":"tool_use","id":"t2","name":"Edit","input":{}}]}}` + "\n" + checkGrows(t, g, msg) + + // a day later, the total grown: counted once, on the new day + g.read() + was := g.size() + g.append(`{"type":"message","id":"m6","timestamp":"2026-09-28T09:00:00.000Z","message":{"role":"user","content":"and the logout one"}}` + "\n") + os.WriteFile(filepath.Join(dir, droidMain+".settings.json"), []byte(`{"model":"claude-opus-4-5","tokenUsage":{"inputTokens":300,"outputTokens":80,"cacheCreationTokens":10,"cacheReadTokens":2000}}`), 0o644) + if at := g.read(); at != was { + t.Fatalf("read from %d, not %d", at, was) + } + if d := g.old.Days["2026-09-27"]; d == nil || len(d.Models) != 0 { + t.Fatalf("the total is still on the day before: %+v", d) + } + if m := g.old.Days["2026-09-28"].Models["claude-opus-4-5"]; m.Input != 300 { + t.Fatalf("the total on its day: %+v", g.old.Days["2026-09-28"]) + } + // only the settings changed: nothing of the transcript read + os.WriteFile(filepath.Join(dir, droidMain+".settings.json"), []byte(`{"model":"claude-opus-4-5","tokenUsage":{"inputTokens":400,"outputTokens":90}}`), 0o644) + if at, end := g.read(), g.size(); at != end { + t.Fatalf("settings changed: read from %d of %d", at, end) + } +} + +// A fork's copied lines that end in a later read are still passed over. +func TestDroidForkAcrossReads(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + putDroid(t, home) + p := filepath.Join(home, ".factory", "sessions", "-work-droid", droidFork+".jsonl") + b, _ := os.ReadFile(p) + lines := bytes.SplitAfter(b, []byte("\n")) + os.WriteFile(p, bytes.Join(lines[:3], nil), 0o644) + g := &grower{t: t, files: droidFiles, path: p} + g.read() + for _, l := range lines[3:] { + g.append(string(l)) + g.read() + } + if g.old.Title != "Try another way" { + t.Fatalf("title %q", g.old.Title) + } +} + +// Kimi Code appends to an agent's wire.jsonl: a record appended is read +// alone, and a state.json rewritten reads nothing of the wire. +func TestKimiReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + dir := filepath.Join(filepath.Dir(claude), "home", ".kimi-code") + kimiSessionsIn(t, dir) + sessions := filepath.Join(dir, "sessions") + slug := "wd_v14-cancel_000000000003" + g := &grower{t: t, files: kimiFiles, path: filepath.Join(sessions, slug, kimiCancel, "agents", "main", "wire.jsonl")} + rec := `{"type":"usage.record","model":"kimi-code/k3","usage":{"inputOther":40,"output":5,"inputCacheRead":900,"inputCacheCreation":0},"usageScope":"turn","time":1784687340000}` + "\n" + checkGrows(t, g, rec) + + g.read() + kimiSetState(t, sessions, slug, kimiCancel, map[string]any{"title": "Cancelled twice", "isCustomTitle": true}) + if at, end := g.read(), g.size(); at != end || g.old.Custom != "Cancelled twice" { + t.Fatalf("state.json changed: read from %d of %d, custom %q", at, end, g.old.Custom) + } + // the session now says it was forked: what it counted is read again + kimiSetState(t, sessions, slug, kimiCancel, map[string]any{"forkedFrom": kimiJune}) + if at := g.read(); at != 0 { + t.Fatalf("made a fork: read from %d", at) + } +} + +// A fork's marker that comes in a later read still ends its copy of its +// source: what was counted before it is taken back. +func TestKimiForkMarkerAcrossReads(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + dir := filepath.Join(filepath.Dir(claude), "home", ".kimi-code") + kimiSessionsIn(t, dir) + sessions := filepath.Join(dir, "sessions") + slug := "wd_v14-cancel_000000000003" + src, err := os.ReadFile(filepath.Join(sessions, slug, kimiCancel, "agents", "main", "wire.jsonl")) + if err != nil { + t.Fatal(err) + } + id := "session_f0000000-0000-4000-8000-0000000000aa" + w := filepath.Join(sessions, slug, id, "agents", "main", "wire.jsonl") + os.MkdirAll(filepath.Dir(w), 0o755) + os.WriteFile(w, src, 0o644) + kimiSetState(t, sessions, slug, id, map[string]any{"cwd": "/w", "createdAt": int64(1784687000000), "title": "Again", "forkedFrom": kimiCancel}) + g := &grower{t: t, files: kimiFiles, path: w} + g.read() + g.append(`{"type":"forked","agentId":"main","time":1791700000000}` + "\n") + g.read() + g.append(`{"type":"usage.record","model":"kimi-code/k3","usage":{"inputOther":7,"output":3,"inputCacheRead":0,"inputCacheCreation":0},"usageScope":"turn","time":1791700005000}` + "\n") + g.read() + if g.old.Models["kimi-code/k3"] != (Tokens{Input: 7, Output: 3}) || len(g.old.Models) != 1 { + t.Fatalf("the fork's own: %+v", g.old.Models) + } +} + +const dshReply = `{"type":"assistant/message","seq":6,"time":1790503290000,"data":{"message":{"source":{"model":"deepseek-v4-flash"}},"usage":{"inputTokens":1,"outputTokens":1,"cacheReadTokens":0}}}` + "\n" + +// dsh appends to a session file a line at a time: a reply is read alone. +func TestDshReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + p := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-a", "session.v3.jsonl") + checkGrows(t, &grower{t: t, files: dshFiles, path: p}, dshReply) +} + +// Packed, dsh appends a frame of lines at a time: a frame appended is read +// alone, from where it starts; a frame not yet written whole waits, and so +// does a line a frame ends inside of, read on from the frame it starts in. +func TestDshPackedReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + plain := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-a", "session.v3.jsonl") + b, err := os.ReadFile(plain) + if err != nil { + t.Fatal(err) + } + os.Remove(plain) + enc, _ := zstd.NewWriter(nil) + defer enc.Close() + frame := func(s string) []byte { return enc.EncodeAll([]byte(s), nil) } + p := plain + ".zstd" + half := bytes.IndexByte(b[len(b)/2:], '\n') + len(b)/2 + 1 + orig := append(frame(string(b[:half])), frame(string(b[half:]))...) + os.WriteFile(p, orig, 0o644) + g := &grower{t: t, files: dshFiles, path: p} + if at := g.read(); at != 0 { + t.Fatalf("first read started at %d", at) + } + reply := func(seq int) string { + return fmt.Sprintf(`{"type":"assistant/message","seq":%d,"time":%d,"data":{"message":{"source":{"model":"deepseek-v4-flash"}},"usage":{"inputTokens":%d,"outputTokens":1,"cacheReadTokens":0}}}`+"\n", seq, 1790503290000+int64(seq)*1000, seq) + } + // a frame appended: only it is read + was := g.size() + g.append(string(frame(reply(6)))) + if at := g.read(); at != was { + t.Fatalf("after a frame appended to %d bytes, read from %d", was, at) + } + // half a frame, still being written: it waits for the rest + was = g.size() + f := frame(reply(7)) + g.append(string(f[:len(f)/2])) + if at := g.read(); at != was { + t.Fatalf("with half a frame at %d, read from %d", was, at) + } + g.append(string(f[len(f)/2:])) + if at := g.read(); at != was { + t.Fatalf("the half frame finished at %d, read from %d", was, at) + } + // a frame that ends inside a line: the line goes on in the next + // frame, and the next read starts at the frame it starts in, past + // what of that frame it counted + was = g.size() + r9 := reply(9) + g.append(string(frame(reply(8) + r9[:20]))) + if at := g.read(); at != was { + t.Fatalf("a frame ending in a line at %d, read from %d", was, at) + } + g.append(string(frame(r9[20:]))) + if at := g.read(); at != was { + t.Fatalf("the line finished in the next frame, read from %d, not its frame's %d", at, was) + } + if m := g.old.Models["deepseek-v4-flash"]; m.Input != 10+6+7+8+9 { + t.Fatalf("flash, each reply once: %+v", m) + } + // cut short: read whole again + os.WriteFile(p, orig, 0o644) + if at := g.read(); at != 0 { + t.Fatalf("cut short, read from %d", at) + } + // replaced by one longer, its first frame changed: read whole + g.append(string(frame(reply(6)))) + g.read() + other := append(frame(string(bytes.Replace(b[:half], []byte("house rules"), []byte("house_rules"), 1))), frame(string(b[half:]))...) + for len(other) <= int(g.size()) { + other = append(other, frame(reply(6))...) + } + os.WriteFile(p, other, 0o644) + if at := g.read(); at != 0 { + t.Fatalf("replaced, read from %d", at) + } +} + +// A fork's end-seed that comes in a later read still ends what it was +// seeded with: what was counted before it is its source's. +func TestDshEndSeedAcrossReads(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + p := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-c", "session.v3.jsonl") + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + cut := bytes.Index(b, []byte(`{"type":"session/end-seed"`)) + rest := bytes.IndexByte(b[cut:], '\n') + cut + 1 + os.WriteFile(p, b[:cut], 0o644) + g := &grower{t: t, files: dshFiles, path: p} + g.read() + g.append(string(b[cut:rest])) + g.read() + g.append(string(b[rest:])) + g.read() + if m := g.old.Models["deepseek-v4-pro"]; m.Input != 50 || len(g.old.Models) != 1 || g.old.Title != "Tidy the build script" { + t.Fatalf("the fork's own: %+v, title %q", g.old.Models, g.old.Title) + } +} + +// Cline rewrites a session's manifest on its own (a title given, the +// session touched), and its size and time are the session file's: when only +// it changed, the messages are not read again. When they changed, or the +// manifest moved the start or the fork their counts were made under, they +// are. +func TestClineReadsMessagesOnlyWhenTheyChange(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + dir := filepath.Join(home, ".cline", "data", "sessions", clineMain) + path := filepath.Join(dir, clineMain+".messages.json") + manifest := filepath.Join(dir, clineMain+".json") + reads := 0 + clineHook = func(p string) { + if p == path { + reads++ + } + } + t.Cleanup(func() { clineHook = nil }) + at := time.Now() + touch := func(p string) { + at = at.Add(time.Minute) + if err := os.Chtimes(p, at, at); err != nil { + t.Fatal(err) + } + } + edit := func(p, from, to string) { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(b, []byte(from)) { + t.Fatalf("no %q in %s", from, p) + } + os.WriteFile(p, bytes.Replace(b, []byte(from), []byte(to), 1), 0o644) + touch(p) + } + var old *state + // read reads the session on from old and says whether it read its + // messages, checking it against a whole read + read := func() bool { + t.Helper() + var f file + for _, c := range clineFiles() { + if c.path == path { + f = c + } + } + was := reads + s := parse(f, old) + read := reads > was + whole := parse(f, nil) + got, _ := json.Marshal(s) + want, _ := json.Marshal(whole) + if !bytes.Equal(got, want) { + t.Fatalf("read on:\n%s\nread whole:\n%s", got, want) + } + old = s + return read + } + // no title of its own, so the first prompt names it + edit(manifest, `"title": "Importer speed-up"`, `"status": "x"`) + edit(manifest, `"prompt": "Speed up the\nimporter",`, ``) + if !read() { + t.Fatal("first read: messages not read") + } + if old.Title != "Speed up the importer" { + t.Fatalf("title %q", old.Title) + } + // the manifest touched and given a title: the messages are not read + edit(manifest, `"status": "completed"`, `"status": "running"`) + if read() { + t.Fatal("manifest touched: messages read again") + } + edit(manifest, `"status": "x"`, `"title": "Faster importer"`) + if read() || old.Named != "Faster importer" || old.Title != "Speed up the importer" { + t.Fatalf("manifest titled: named %q, title %q", old.Named, old.Title) + } + // a message more: read again + edit(path, `"content": "done",`, `"content": "done, all of it",`) + if !read() { + t.Fatal("messages changed: not read") + } + // the same size, a later time: read again + touch(path) + if !read() { + t.Fatal("messages touched: not read") + } + // made a fork after its first reply: what came before is its source's + edit(manifest, `"metadata": {`, `"metadata": {"fork": {"forkedAt": "2026-09-27T10:01:00.000Z"},`) + if !read() || old.Models["claude-opus-5-5"] != (Tokens{}) { + t.Fatalf("forked: %+v", old.Models) + } + // started at another time: read again + edit(manifest, `"started_at": "2026-09-27T10:00:00.000Z"`, `"started_at": "2026-09-27T10:05:00.000Z"`) + if !read() { + t.Fatal("start moved: not read") + } +} diff --git a/internal/sessions/hermes.go b/internal/sessions/hermes.go index 1c1869660..0cdbdae24 100644 --- a/internal/sessions/hermes.go +++ b/internal/sessions/hermes.go @@ -12,6 +12,7 @@ import ( "path/filepath" "strconv" "strings" + "sync" "time" "github.com/yetone/magpie/internal/appdir" @@ -51,7 +52,13 @@ func HermesDirs() []string { return out } +// canonicalHook, when a test sets it, runs on each canonicalHermesPath. +var canonicalHook func() + func canonicalHermesPath(path string) string { + if canonicalHook != nil { + canonicalHook() + } if abs, err := filepath.Abs(path); err == nil { path = abs } @@ -61,11 +68,16 @@ func canonicalHermesPath(path string) string { return filepath.Clean(path) } -func hermesID(path, sid string) string { - // Include the store even for the default profile so selecting another home - // cannot collide with a previously indexed store or a copied session id. +func hermesID(path, sid string) string { return hermesStoreID(path) + "-" + sid } + +// hermesStoreID is what a store's session ids begin with. Include the store +// even for the default profile so selecting another home cannot collide +// with a previously indexed store or a copied session id. Resolving the +// path walks every folder in it (EvalSymlinks), so it is done once per +// store, not once per session. +func hermesStoreID(path string) string { h := sha256.Sum256([]byte(canonicalHermesPath(path))) - return "h" + hex.EncodeToString(h[:8]) + "-" + sid + return "h" + hex.EncodeToString(h[:8]) } type hermesDB struct { @@ -92,6 +104,141 @@ func hermesRevision(path string) string { return strings.Join(parts, ":") } +// hermesPrinted is each store's sessions' fingerprints, as of the store's +// revision they were read at. +var hermesPrinted = struct { + sync.Mutex + stores map[string]hermesPrintSet +}{stores: map[string]hermesPrintSet{}} + +type hermesPrintSet struct { + revision string + prints map[string]string +} + +// hermesPrintsFor is the fingerprint of each session in the store at path, +// read again only when the store's revision moved. nil when they could not +// be read: then no session's parse is reused. +func hermesPrintsFor(path string, h *hermesDB) map[string]string { + hermesPrinted.Lock() + defer hermesPrinted.Unlock() + if set, ok := hermesPrinted.stores[path]; ok && h.revision != "" && set.revision == h.revision { + return set.prints + } + prints := h.fingerprints() + if prints != nil && h.revision != "" { + hermesPrinted.stores[path] = hermesPrintSet{h.revision, prints} + } else { + delete(hermesPrinted.stores, path) + } + return prints +} + +func forgetHermesPrints() { + hermesPrinted.Lock() + hermesPrinted.stores = map[string]hermesPrintSet{} + hermesPrinted.Unlock() +} + +// fingerprints is, for each session, what parseHermes reads of it in a few +// values: its sessions row, and over its messages and usage rows a count, +// the ids, and the sums of every read column's values or byte lengths. A +// row added, removed or rewritten in place (active and compacted flipped +// by a rewind or a compaction, a tool call's content filled in later) +// moves it. Any write moves the whole store's revision, and parsing every +// session again on each one read, de-duplicated and decoded every message +// Hermes ever kept, again and again while it ran (#2776); this reads only +// the tables' pages, in SQLite. A rewrite to text of the very same length, +// with no other column moving, is the one change it can miss. nil when any +// of it could not be read. +func (h *hermesDB) fingerprints() map[string]string { + if !h.sessions["id"] { + return nil + } + tx, err := h.db.BeginTx(context.Background(), nil) + if err != nil { + return nil + } + defer tx.Rollback() + parts := map[string][]string{} + read := func(table, query string) bool { + rows, err := tx.Query(query) + if err != nil { + return false + } + defer rows.Close() + cols, err := rows.Columns() + if err != nil { + return false + } + vals := make([]sql.NullString, len(cols)) + ptrs := make([]any, len(cols)) + for i := range vals { + ptrs[i] = &vals[i] + } + for rows.Next() { + if rows.Scan(ptrs...) != nil { + return false + } + var b strings.Builder + b.WriteString(table) + b.WriteByte(':') + for _, v := range vals[1:] { + if v.Valid { + b.WriteString(strconv.Quote(v.String)) + } else { + b.WriteString("~") + } + b.WriteByte(',') + } + parts[vals[0].String] = append(parts[vals[0].String], b.String()) + } + return rows.Err() == nil + } + // metadata()'s columns, as it reads them + if !read("s", "SELECT id, "+hermesSelect(h.sessions, []string{"title", "cwd", "model", "billing_provider"}, "''")+", "+ + hermesSelect(h.sessions, []string{"started_at", "ended_at", "last_activity_at", "input_tokens", "output_tokens", + "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "api_call_count"}, "0")+" FROM sessions") { + return nil + } + column := func(cols map[string]bool, name string) string { + if cols[name] { + return name + } + return "NULL" + } + if h.messages["session_id"] { + q := []string{"session_id", "count(*)", "max(" + hermesExpr(h.messages, "id", "rowid") + ")", "total(" + hermesExpr(h.messages, "id", "rowid") + ")"} + for _, c := range []string{"timestamp", "active", "compacted"} { + q = append(q, "total("+column(h.messages, c)+")") + } + for _, c := range []string{"role", "content", "tool_calls", "tool_call_id", "tool_name", "display_kind", "display_metadata"} { + q = append(q, "total(octet_length("+column(h.messages, c)+"))") + } + if !read("m", "SELECT "+strings.Join(q, ", ")+" FROM messages GROUP BY session_id") { + return nil + } + } + if h.usage["session_id"] { + q := []string{"session_id", "count(*)"} + for _, c := range []string{"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "api_call_count", "last_seen"} { + q = append(q, "total("+column(h.usage, c)+")") + } + for _, c := range []string{"model", "billing_provider", "task"} { + q = append(q, "total(octet_length("+column(h.usage, c)+"))", "max("+column(h.usage, c)+")", "min("+column(h.usage, c)+")") + } + if !read("u", "SELECT "+strings.Join(q, ", ")+" FROM session_model_usage GROUP BY session_id") { + return nil + } + } + out := make(map[string]string, len(parts)) + for sid, p := range parts { + sum := sha256.Sum256([]byte(strings.Join(p, "|"))) + out[sid] = "fp1:" + hex.EncodeToString(sum[:16]) + } + return out +} + type hermesQuery interface { Query(string, ...any) (*sql.Rows, error) QueryRow(string, ...any) *sql.Row @@ -154,6 +301,8 @@ func hermesFiles() []file { if !store.sessions["id"] { continue } + prints := hermesPrintsFor(path, store) + storeID := hermesStoreID(path) messageLast, usageLast := "0", "0" if store.messages["session_id"] && store.messages["timestamp"] { messageLast = "COALESCE((SELECT MAX(timestamp) FROM messages m WHERE m.session_id = sessions.id), 0)" @@ -176,7 +325,7 @@ func hermesFiles() []file { if rows.Scan(&sid, &start, &end, &last, &messageAt, &usageAt) != nil || sid == "" { continue } - id := hermesID(path, sid) + id := storeID + "-" + sid out = append(out, file{ agent: "hermes", key: "hermes:" + id, @@ -185,6 +334,7 @@ func hermesFiles() []file { main: true, mod: hermesTime(max(start, end, last, messageAt, usageAt)), hermes: store, + rev: prints[sid], // "" when unknown: parsed again readOnly: true, }) } @@ -462,7 +612,7 @@ func parseHermes(f file) *state { s.Last = at } } - s.DBRevision = f.hermes.revision + s.DBRevision = f.rev return s } diff --git a/internal/sessions/hermes_fingerprint_test.go b/internal/sessions/hermes_fingerprint_test.go new file mode 100644 index 000000000..47922716a --- /dev/null +++ b/internal/sessions/hermes_fingerprint_test.go @@ -0,0 +1,136 @@ +package sessions + +import ( + "database/sql" + "path/filepath" + "sync/atomic" + "testing" + "time" +) + +// A write to one Hermes session moves the whole store's revision. Only that +// session is parsed again (#2776): every session was, each poll while +// Hermes ran. A message rewritten in place, with no row added, still is. +func TestHermesWriteParsesOnlyItsSession(t *testing.T) { + setup(t) + root := filepath.Join(t.TempDir(), "hermes") + t.Setenv("HERMES_HOME", root) + path := hermesFixture(t, root, "", "busy", true) + db, err := sql.Open("sqlite", path+"?_pragma=journal_mode(WAL)") + if err != nil { + t.Fatal(err) + } + defer db.Close() + base := float64(time.Date(2026, 9, 28, 10, 0, 0, 0, time.UTC).Unix()) + for _, sid := range []string{"idle1", "idle2", "idle3"} { + if _, err := db.Exec(`INSERT INTO sessions (id, title, started_at) VALUES (?, NULL, ?)`, sid, base); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO messages (session_id, role, content, tool_calls, timestamp) VALUES (?, 'user', 'first words', '[]', ?)`, sid, base+1); err != nil { + t.Fatal(err) + } + } + var parsed atomic.Int32 + parseHook = func() { parsed.Add(1) } + t.Cleanup(func() { parseHook = nil }) + + List(0) + parsed.Store(0) + List(0) + if n := parsed.Load(); n != 0 { + t.Fatalf("nothing changed, yet %d parsed again", n) + } + + if _, err := db.Exec(`INSERT INTO messages (session_id, role, content, tool_calls, timestamp) VALUES ('busy', 'user', 'one more', '[]', ?)`, base+20); err != nil { + t.Fatal(err) + } + List(0) + if n := parsed.Load(); n != 1 { + t.Fatalf("one session written, %d parsed again", n) + } + + // in place: the row count, ids and times all stay + parsed.Store(0) + if _, err := db.Exec(`UPDATE messages SET content = 'rewritten first words' WHERE session_id = 'idle2'`); err != nil { + t.Fatal(err) + } + if got := hermesSessionByID(t, hermesID(path, "idle2")).Title; got != "rewritten first words" { + t.Errorf("in-place rewrite not read: title %q", got) + } + if n := parsed.Load(); n != 1 { + t.Fatalf("one message rewritten in place, %d parsed again", n) + } +} + +// Fingerprints that can't be read are unknown: no session's parse is kept. +func TestHermesUnreadFingerprintsParseAgain(t *testing.T) { + setup(t) + root := filepath.Join(t.TempDir(), "hermes") + path := hermesFixture(t, root, "", "s", true) + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + h := newHermesDB(db) + h.revision = hermesRevision(path) + if p := hermesPrintsFor(path, h); p["s"] == "" { + t.Fatalf("fingerprints of a readable store: %v", p) + } + db.Close() + h.revision = "moved" + if p := hermesPrintsFor(path, h); p != nil { + t.Fatalf("a closed store's fingerprints read as %v", p) + } + // the same size and time as what was parsed: only the fingerprint can + // tell it changed, and it is unknown + f := file{agent: "hermes", path: path + "#s", hermes: h, rev: "", mod: time.Unix(1790000000, 0)} + s := state{Mod: f.mod.UnixNano(), DBRevision: ""} + cache = map[string]*state{f.path: &s} + t.Cleanup(func() { cache = nil }) + parsed := 0 + parseHook = func() { parsed++ } + t.Cleanup(func() { parseHook = nil }) + mu.Lock() + refresh([]file{f}, nil) + mu.Unlock() + if parsed != 1 { + t.Fatalf("an unknown fingerprint reused a parse (%d parsed)", parsed) + } +} + +// A store's path is resolved (EvalSymlinks walks every folder in it) once +// per listing, not once per session: 2000 sessions spent ~30ms on it per +// poll (#2776). +func TestHermesStoreResolvedOncePerListing(t *testing.T) { + setup(t) + root := filepath.Join(t.TempDir(), "hermes") + t.Setenv("HERMES_HOME", root) + path := hermesFixture(t, root, "", "s0", true) + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + for i := 1; i < 10; i++ { + sid := "s" + string(rune('0'+i)) + if _, err := db.Exec(`INSERT INTO sessions (id, title, started_at) VALUES (?, 'x', 1790000000)`, sid); err != nil { + t.Fatal(err) + } + } + var n atomic.Int32 + canonicalHook = func() { n.Add(1) } + t.Cleanup(func() { canonicalHook = nil }) + mu.Lock() + files := hermesFiles() + closeDBs() + mu.Unlock() + if len(files) != 10 { + t.Fatalf("%d files, want 10", len(files)) + } + if got := int(n.Load()); got >= len(files) { + t.Fatalf("the store's path was resolved %d times for %d sessions", got, len(files)) + } + if want := "hermes:" + hermesID(path, files[0].sid); files[0].key != want { + t.Fatalf("key %q, want %q", files[0].key, want) + } +} diff --git a/internal/sessions/kimi.go b/internal/sessions/kimi.go index 4ebcaf1ff..42b76fdd6 100644 --- a/internal/sessions/kimi.go +++ b/internal/sessions/kimi.go @@ -196,103 +196,132 @@ var ( kimiCounts = [][]byte{kimiUsageRecord, []byte(`"turn.prompt"`), []byte(`"step.end"`), []byte(`"tool.call"`)} ) -// parseKimi reads one agent's wire file of a session whole, with the -// session's state.json for its own. -func parseKimi(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - var since time.Time - forked := false - if st, ok := kimiStateOf(f.path); ok { - created := kimiTime(st.CreatedAt) - forked = st.ForkedFrom != "" - if forked { - since = created - } - if f.main { - s.Cwd = cmp.Or(st.Cwd, st.WorkDir, kimiIndexedWorkDir(f.path)) - s.Custom, s.Named = st.names() - s.Custom, s.Named = title(s.Custom), title(s.Named) - s.saw(created, true) +// kimiCarry is what a read of a Kimi Code wire file carries on with: +// where it read to, what of state.json its records were counted under, +// and the time before which a fork's records are its source's. +type kimiCarry struct { + Tail *tail `json:"tail,omitempty"` + Created time.Time `json:"created,omitzero"` + Forked bool `json:"forked,omitempty"` + Since time.Time `json:"since,omitzero"` +} + +// parseKimi reads one agent's wire file of a session, with the session's +// state.json for its own. Kimi only appends to a wire file, so one read +// before is read on from where that read left off; state.json, rewritten +// as the session goes on, is read again each time. A file cut short or +// replaced, or a state.json that now says another creation or fork, is +// read whole again. +func parseKimi(f file, old *state) *state { + var c kimiCarry + var st kimiState + hasSt := false + if st, hasSt = kimiStateOf(f.path); hasSt { + c.Created = kimiTime(st.CreatedAt) + c.Forked = st.ForkedFrom != "" + if c.Forked { + c.Since = c.Created } } - // a fork's copy of its source ends at its last marker - skip := 0 - if forked { - n := 0 - scan(f.path, 0, func(b []byte) { - n++ - if bytes.Contains(b, kimiForked) { - var r kimiWire - if json.Unmarshal(b, &r) == nil && r.Type == "forked" { - skip, since = n, time.Time{} - } - } - }) + fresh := func() *state { + s := &state{} + if hasSt && f.main { + s.saw(c.Created, true) + } + return s } - n := 0 - scan(f.path, 0, func(b []byte) { - n++ - if n <= skip { - return - } - count := false - for _, k := range kimiCounts { - if bytes.Contains(b, k) { - count = true - break - } - } - var r kimiWire - if !count { - // only its time: a light read of the rest - var t struct { - Time int64 `json:"time"` - } - if json.Unmarshal(b, &t) == nil { - if at := ms(t.Time); !at.IsZero() && !at.Before(since) { - s.saw(at, f.main) - } - } - return - } - if json.Unmarshal(b, &r) != nil { - return - } - at := ms(r.Time) - if at.IsZero() || at.Before(since) { - return - } - s.saw(at, f.main) - switch r.Type { - case "usage.record": - if u := r.Usage; u != nil && u.InputOther >= 0 && u.Output >= 0 && u.InputCacheRead >= 0 && u.InputCacheCreation >= 0 { - model := cmp.Or(strings.TrimPrefix(r.Model, kimiGateway), "kimi") - s.use(dateOf(at), model, Tokens{Input: u.InputOther, Output: u.Output, CacheRead: u.InputCacheRead, CacheWrite: u.InputCacheCreation}) - } - case "turn.prompt": - if !f.main || r.Origin.Kind != "user" { - return - } - s.day(dateOf(at)).Prompts++ - if s.Title == "" { - var text []string - for _, p := range r.Input { - if p.Type == "text" { - text = append(text, p.Text) - } - } - s.Title = title(strings.Join(text, " ")) - } - case "context.append_loop_event": - switch r.Event.Type { - case "step.end": - if f.main && r.Event.FinishReason == "end_turn" { - s.day(dateOf(at)).Replies++ - } - case "tool.call": - s.tool(at, r.Event.Name, "") + var s *state + var off int64 + if o := old; o != nil && o.Kimi != nil && o.Kimi.Created.Equal(c.Created) && o.Kimi.Forked == c.Forked && o.Kimi.Tail.holds(f.path) { + s, c, off = o.clone(), *o.Kimi, o.Kimi.Tail.Off + } else { + s = fresh() + } + end, err := scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { + if c.Forked && bytes.Contains(b, kimiForked) { + var r kimiWire + if json.Unmarshal(b, &r) == nil && r.Type == "forked" { + // a fork's copy of its source ends at its last marker: + // what was counted before it is its source's + s, c.Since = fresh(), time.Time{} + return true } } + kimiCount(s, b, c.Since, f.main) + return true }) + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, end, 0, end) + } + s.Size, s.Mod = f.size, f.mod.UnixNano() + if hasSt && f.main { + s.Cwd = cmp.Or(st.Cwd, st.WorkDir, kimiIndexedWorkDir(f.path)) + s.Custom, s.Named = st.names() + s.Custom, s.Named = title(s.Custom), title(s.Named) + } + s.Kimi = &c return s } + +// kimiCount counts one record of a wire file, none before since. +func kimiCount(s *state, b []byte, since time.Time, main bool) { + count := false + for _, k := range kimiCounts { + if bytes.Contains(b, k) { + count = true + break + } + } + var r kimiWire + if !count { + // only its time: a light read of the rest + var t struct { + Time int64 `json:"time"` + } + if json.Unmarshal(b, &t) == nil { + if at := ms(t.Time); !at.IsZero() && !at.Before(since) { + s.saw(at, main) + } + } + return + } + if json.Unmarshal(b, &r) != nil { + return + } + at := ms(r.Time) + if at.IsZero() || at.Before(since) { + return + } + s.saw(at, main) + switch r.Type { + case "usage.record": + if u := r.Usage; u != nil && u.InputOther >= 0 && u.Output >= 0 && u.InputCacheRead >= 0 && u.InputCacheCreation >= 0 { + model := cmp.Or(strings.TrimPrefix(r.Model, kimiGateway), "kimi") + s.use(dateOf(at), model, Tokens{Input: u.InputOther, Output: u.Output, CacheRead: u.InputCacheRead, CacheWrite: u.InputCacheCreation}) + } + case "turn.prompt": + if !main || r.Origin.Kind != "user" { + return + } + s.day(dateOf(at)).Prompts++ + if s.Title == "" { + var text []string + for _, p := range r.Input { + if p.Type == "text" { + text = append(text, p.Text) + } + } + s.Title = title(strings.Join(text, " ")) + } + case "context.append_loop_event": + switch r.Event.Type { + case "step.end": + if main && r.Event.FinishReason == "end_turn" { + s.day(dateOf(at)).Replies++ + } + case "tool.call": + s.tool(at, r.Event.Name, "") + } + } +} diff --git a/internal/sessions/kimi_test.go b/internal/sessions/kimi_test.go index e4967bc90..53255462e 100644 --- a/internal/sessions/kimi_test.go +++ b/internal/sessions/kimi_test.go @@ -187,7 +187,7 @@ func TestKimiCodeSessionCounts(t *testing.T) { } sum := func(id string) (prompts, replies, tools int, custom, named string) { for _, f := range byKey["kimi:"+id] { - s := parseKimi(f) + s := parseKimi(f, nil) for _, d := range s.Days { prompts += d.Prompts replies += d.Replies diff --git a/internal/sessions/listmemo.go b/internal/sessions/listmemo.go new file mode 100644 index 000000000..912d7935d --- /dev/null +++ b/internal/sessions/listmemo.go @@ -0,0 +1,62 @@ +package sessions + +import ( + "sync" + "time" +) + +// listMemo keeps what a listing read from each of many small files, by the +// file's own size and mtime, so a listing that runs on every poll opens only +// the files that changed since the last one rather than every session's. +// Each listing is a round: a file it did not ask about (a session deleted) +// is dropped when the round ends. A read that failed is not kept, so the +// next listing tries again: a failed read means unknown, not empty. +type listMemo[T any] struct { + sync.Mutex + m map[string]memoEntry[T] +} + +type memoEntry[T any] struct { + size, mod int64 + v T +} + +type memoRound[T any] struct { + l *listMemo[T] + old, next map[string]memoEntry[T] +} + +// round starts a listing. +func (l *listMemo[T]) round() *memoRound[T] { + l.Lock() + old := l.m + l.Unlock() + return &memoRound[T]{l: l, old: old, next: make(map[string]memoEntry[T], len(old))} +} + +// get is what read gives for the file at path, read again only when its +// size or mtime is not what it was when last read. +func (r *memoRound[T]) get(path string, size int64, mod time.Time, read func() (T, bool)) (T, bool) { + if e, ok := r.old[path]; ok && e.size == size && e.mod == mod.UnixNano() { + r.next[path] = e + return e.v, true + } + v, ok := read() + if ok { + r.next[path] = memoEntry[T]{size, mod.UnixNano(), v} + } + return v, ok +} + +// done keeps what this round read, and only that, for the next. +func (r *memoRound[T]) done() { + r.l.Lock() + r.l.m = r.next + r.l.Unlock() +} + +func (l *listMemo[T]) reset() { + l.Lock() + l.m = nil + l.Unlock() +} diff --git a/internal/sessions/listmemo_test.go b/internal/sessions/listmemo_test.go new file mode 100644 index 000000000..5648ac468 --- /dev/null +++ b/internal/sessions/listmemo_test.go @@ -0,0 +1,157 @@ +package sessions + +import ( + "os" + "path/filepath" + "sync" + "testing" +) + +// keyOf is the key a listing gives the file at path. +func keyOf(t *testing.T, fs []file, path string) string { + t.Helper() + for _, f := range fs { + if f.path == path { + return f.key + } + } + t.Fatalf("%s not listed", path) + return "" +} + +// readCounter counts reads of each file a hook is told of. +type readCounter struct { + mu sync.Mutex + n map[string]int +} + +func (c *readCounter) saw(p string) { + c.mu.Lock() + c.n[p]++ + c.mu.Unlock() +} + +func (c *readCounter) take() map[string]int { + c.mu.Lock() + defer c.mu.Unlock() + n := c.n + c.n = map[string]int{} + return n +} + +// Droid's listing, run on every poll, opens a transcript for whose +// subagent it is only when the transcript changed; a transcript it could +// not read is tried again on the next listing, not taken as nobody's. +func TestDroidListingReadsOnlyChangedTranscripts(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + putDroid(t, home) + dir := filepath.Join(home, ".factory", "sessions", "-work-droid") + sub := filepath.Join(dir, "d0000000-0000-4000-8000-0000000000aa.jsonl") + start := `{"type":"session_start","id":"d0000000-0000-4000-8000-0000000000aa","title":"Sub","cwd":"/work","callingSessionId":"` + droidMain + `"}` + "\n" + if err := os.WriteFile(sub, []byte(start), 0o644); err != nil { + t.Fatal(err) + } + half := filepath.Join(dir, "d0000000-0000-4000-8000-0000000000bb.jsonl") + if err := os.WriteFile(half, []byte(`{"type":"session_start","id":"d0000000-0000-4000-8000-0000000000bb","callingSessionId":"`+droidMain), 0o644); err != nil { + t.Fatal(err) + } + c := &readCounter{n: map[string]int{}} + scanHook = func(p string, _ int64) { c.saw(p) } + t.Cleanup(func() { scanHook = nil }) + + fs := droidFiles() + if n := c.take(); n[sub] != 1 || n[half] != 1 || len(n) < 3 { + t.Fatalf("first listing read %v", n) + } + if k := keyOf(t, fs, sub); k != "droid:"+droidMain { + t.Fatalf("subagent keyed %q", k) + } + fs = droidFiles() + if n := c.take(); len(n) != 1 || n[half] != 1 { + t.Fatalf("nothing changed: read %v, want only the half-written one again", n) + } + if k := keyOf(t, fs, sub); k != "droid:"+droidMain { + t.Fatalf("subagent keyed %q from what was kept", k) + } + + // appended to: read again, still the same caller + appendText(t, sub, `{"type":"message","id":"m1","timestamp":"2026-09-27T08:00:00.000Z","message":{"role":"user","content":"go"}}`+"\n") + fs = droidFiles() + if n := c.take(); n[sub] != 1 || n[half] != 1 || len(n) != 2 { + t.Fatalf("one appended to: read %v", n) + } + // the half-written line finished: read, and kept from then on + appendText(t, half, `"}`+"\n") + fs = droidFiles() + if k := keyOf(t, fs, half); k != "droid:"+droidMain { + t.Fatalf("finished line keyed %q", k) + } + c.take() + droidFiles() + if n := c.take(); len(n) != 0 { + t.Fatalf("nothing changed: read %v", n) + } + // written over without a caller: its own session now + if err := os.WriteFile(sub, []byte(`{"type":"session_start","id":"d0000000-0000-4000-8000-0000000000aa","title":"Own"}`+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if k := keyOf(t, droidFiles(), sub); k != "droid:d0000000-0000-4000-8000-0000000000aa" { + t.Fatalf("written over: keyed %q", k) + } +} + +// Grok Build's listing reads a session's summary.json, for whether it is +// a subagent's, only when the summary changed. +func TestGrokListingReadsOnlyChangedSummaries(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + id := "0190aaaa-0000-7000-8000-0000000000dd" + dir := filepath.Join(home, ".grok", "sessions", "%2Fwork%2Fgrok", id) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, "updates.jsonl") + if err := os.WriteFile(p, []byte(`{"timestamp":1790496001}`+"\n"), 0o644); err != nil { + t.Fatal(err) + } + summary := filepath.Join(dir, "summary.json") + if err := os.WriteFile(summary, []byte(`{"info":{"id":"`+id+`"},"session_kind":"subagent","parent_session_id":"`+grokMain+`"}`), 0o644); err != nil { + t.Fatal(err) + } + c := &readCounter{n: map[string]int{}} + grokSummaryHook = c.saw + t.Cleanup(func() { grokSummaryHook = nil }) + + fs := grokFiles() + if n := c.take(); n[summary] != 1 || len(n) < 2 { + t.Fatalf("first listing read %v", n) + } + if k := keyOf(t, fs, p); k != "grok:"+grokMain { + t.Fatalf("subagent keyed %q", k) + } + fs = grokFiles() + if n := c.take(); len(n) != 0 { + t.Fatalf("nothing changed: read %v", n) + } + if k := keyOf(t, fs, p); k != "grok:"+grokMain { + t.Fatalf("subagent keyed %q from what was kept", k) + } + // the updates grew: the summary is not read for that + appendText(t, p, `{"timestamp":1790496002}`+"\n") + grokFiles() + if n := c.take(); len(n) != 0 { + t.Fatalf("updates grew: read %v", n) + } + // the summary written over, no longer a subagent's: read, its own now + if err := os.WriteFile(summary, []byte(`{"info":{"id":"`+id+`"},"session_kind":"main","generated_title":"Own"}`), 0o644); err != nil { + t.Fatal(err) + } + fs = grokFiles() + if n := c.take(); n[summary] != 1 || len(n) != 1 { + t.Fatalf("summary changed: read %v", n) + } + if k := keyOf(t, fs, p); k != "grok:"+id { + t.Fatalf("written over: keyed %q", k) + } +} diff --git a/internal/sessions/manage.go b/internal/sessions/manage.go index 46c3bc6fc..aa673df85 100644 --- a/internal/sessions/manage.go +++ b/internal/sessions/manage.go @@ -73,13 +73,17 @@ var ErrActive = errors.New("the session was written to in the last minute; it ma // Agents are the agents with sessions on this computer, by how many. func Agents() []AgentCount { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() - defer closeDBs() + defer useDBs()() + return agentCounts(allFiles()) +} + +func agentCounts(all []file) []AgentCount { n := map[string]map[string]bool{} - for _, f := range allFiles() { + for _, f := range all { if n[f.agent] == nil { n[f.agent] = map[string]bool{} } @@ -101,13 +105,96 @@ func Agents() []AgentCount { // ListAgent is every session of one agent, the most recently active first, // with no limit; one nothing was said in is listed too, to be cleared away. func ListAgent(agent string) []Managed { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() + return listAgent(agent, allFiles()) +} + +// NativeIDs are the ids of every session the agents named keep themselves, +// by agent: one nothing was said in too, as ListAgent lists it. It tells a +// gateway session an agent keeps from one only magpie saw. Only the named +// agents' files are looked at, and of those only the ones whose session id +// is inside the file are read when they changed. +func NativeIDs(agents map[string]bool) map[string]map[string]bool { + storeMu.RLock() + defer storeMu.RUnlock() + mu.Lock() + defer mu.Unlock() + loadCache() + defer useDBs()() + return nativeIDs(agents, allFiles()) +} + +// ManageView is the session management page, read in one pass over every +// agent's files: the agents with sessions, the ids of the sessions of those +// asked for (as NativeIDs), and the agent shown with its sessions (as +// ListAgent). +type ManageView struct { + Agents []AgentCount + Native map[string]map[string]bool + Agent string + Sessions []Managed +} + +// Manage reads the management page. pick, given the counts and the native +// ids of the agents in native, names the agent to list ("" for none); it +// runs under the sessions lock and must not call back into this package. +// Only native's agents and the one picked are read: a change to another +// agent's sessions waits for a page that shows it (#2776). +func Manage(native map[string]bool, pick func([]AgentCount, map[string]map[string]bool) string) ManageView { + storeMu.RLock() + defer storeMu.RUnlock() + mu.Lock() + defer mu.Unlock() + loadCache() + defer useDBs()() all := allFiles() + v := ManageView{Agents: agentCounts(all), Native: nativeIDs(native, all)} + v.Agent = pick(v.Agents, v.Native) + if v.Agent != "" { + v.Sessions = listAgent(v.Agent, all) + } + return v +} + +// idInFile says which agents' session ids are read from inside the +// session's file, not taken from its name (as assemble does). +func idInFile(agent string) bool { + switch agent { + case "codex", "pi", "omp", "dsh", "grok", "droid": + return true + } + return false +} + +func nativeIDs(agents map[string]bool, all []file) map[string]map[string]bool { + groups := map[string][]file{} + var want []file + for _, f := range all { + if !agents[f.agent] { + continue + } + groups[f.key] = append(groups[f.key], f) + if idInFile(f.agent) { + want = append(want, f) + } + } + refresh(want, all) + out := map[string]map[string]bool{} + for a := range agents { + out[a] = map[string]bool{} + } + for _, fs := range groups { + out[fs[0].agent][sessionID(fs)] = true + } + return out +} + +func listAgent(agent string, all []file) []Managed { groups := map[string][]file{} var mine []file for _, f := range all { @@ -211,12 +298,12 @@ func Delete(agent, id string) (Trashed, error) { if !safeID.MatchString(id) { return Trashed{}, errors.New("no such session") } - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.Lock() + defer storeMu.Unlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() all := allFiles() groups := map[string][]file{} var mine []file diff --git a/internal/sessions/manage_read_test.go b/internal/sessions/manage_read_test.go new file mode 100644 index 000000000..076ed4a77 --- /dev/null +++ b/internal/sessions/manage_read_test.go @@ -0,0 +1,77 @@ +package sessions + +import ( + "os" + "path/filepath" + "sort" + "testing" + "time" +) + +// The management page of one agent reads that agent's changed files, and +// those of the agents whose gateway sessions it tells apart, not every +// agent's (#2776): it read them all to build that set, through List(All). +func TestManageReadsOnlyTheAgentsItShows(t *testing.T) { + _, codex := setup(t) + claude := func([]AgentCount, map[string]map[string]bool) string { return "claude" } + Manage(map[string]bool{}, claude) + now := time.Now() + err := filepath.WalkDir(filepath.Join(codex, "sessions"), func(p string, d os.DirEntry, err error) error { + if err == nil && !d.IsDir() { + now = now.Add(time.Second) + return os.Chtimes(p, now, now) + } + return err + }) + if err != nil { + t.Fatal(err) + } + parsed := 0 + parseHook = func() { parsed++ } + t.Cleanup(func() { parseHook = nil }) + + v := Manage(map[string]bool{}, claude) + if parsed != 0 { + t.Fatalf("Codex's files changed and Claude Code's page read %d of them", parsed) + } + if v.Agent != "claude" || len(v.Sessions) == 0 { + t.Fatalf("listed %q with %d sessions", v.Agent, len(v.Sessions)) + } + counted := false + for _, a := range v.Agents { + counted = counted || a.Agent == "codex" && a.Count == 1 + } + if !counted { + t.Fatalf("codex not counted: %+v", v.Agents) + } + + // asked for Codex's ids: its changed files are read, as the id is in them + v = Manage(map[string]bool{"codex": true, "claude": true}, claude) + if parsed == 0 { + t.Fatal("Codex's ids were asked for and its changed files not read") + } + if !v.Native["codex"]["01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd"] { + t.Fatalf("codex ids %v", v.Native["codex"]) + } + // the same ids as the agent's list: one nothing was said in too + var listed, native []string + for _, m := range v.Sessions { + listed = append(listed, m.ID) + } + for id := range v.Native["claude"] { + native = append(native, id) + } + sort.Strings(listed) + sort.Strings(native) + if len(listed) < 2 || len(listed) != len(native) { + t.Fatalf("claude list %v, native ids %v", listed, native) + } + for i := range listed { + if listed[i] != native[i] { + t.Fatalf("claude list %v, native ids %v", listed, native) + } + } + if got := NativeIDs(map[string]bool{"codex": true}); len(got) != 1 || len(got["codex"]) != 1 { + t.Fatalf("NativeIDs: %v", got) + } +} diff --git a/internal/sessions/opencode.go b/internal/sessions/opencode.go index 0e36617f0..60e1fff8c 100644 --- a/internal/sessions/opencode.go +++ b/internal/sessions/opencode.go @@ -8,6 +8,7 @@ import ( "path/filepath" "sort" "strings" + "sync" "time" "github.com/yetone/magpie/internal/appdir" @@ -170,9 +171,25 @@ func ocRoots(out []file, parent map[string]string) []file { // ---- the database ------------------------------------------------------------- // dbs are the databases open while List or Stats reads them, closed when -// they are done (closeDBs). +// the last of the reads using them is done (useDBs). var dbs = map[string]*sql.DB{} +// dbUsers is how many reads use dbs now. A read lets mu go while it parses +// with them, and another read may then start and end: it must not close +// what the first is still reading (#2776). +var dbUsers int + +// useDBs counts a read, with mu held, as a user of dbs until the release it +// returns is called, with mu held again; the last to go closes them. +func useDBs() (release func()) { + dbUsers++ + return sync.OnceFunc(func() { + if dbUsers--; dbUsers == 0 { + closeDBs() + } + }) +} + // Snapshot readers also remove their temporary database when a scan ends. var dbCleanup = map[string]func(){} diff --git a/internal/sessions/refresh_shared_test.go b/internal/sessions/refresh_shared_test.go new file mode 100644 index 000000000..57dd9d5ec --- /dev/null +++ b/internal/sessions/refresh_shared_test.go @@ -0,0 +1,171 @@ +package sessions + +import ( + "fmt" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" +) + +// growSessions adds a line to each of moreSessions' files, so each has to +// be read again. +func growSessions(t *testing.T, claude string, n int) { + t.Helper() + dir := filepath.Join(claude, "projects", "-work-many") + for i := range n { + p := filepath.Join(dir, fmt.Sprintf("33333333-2222-3333-4444-%012d.jsonl", i)) + f, err := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + f.WriteString(ccMsg(fmt.Sprintf("n%d", i), "2026-09-21T11:00:00.000Z", 100, 10)) + f.Close() + } +} + +// A page asked for while the start's warm-up reads the changed files is +// answered with the parses kept of them, not held until the warm-up has +// read them all (#2776: the warm-up held the page for its whole read). +func TestReadNotHeldByAnotherRead(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + moreSessions(t, claude, 12) + if n := len(List(0)); n < 12 { + t.Fatalf("listed %d sessions", n) + } + growSessions(t, claude, 12) + + hold, started := make(chan struct{}), make(chan struct{}) + var once sync.Once + var parsed atomic.Int32 + parseHook = func() { + parsed.Add(1) + once.Do(func() { close(started) }) + <-hold + } + release := sync.OnceFunc(func() { close(hold) }) + t.Cleanup(func() { release(); parseHook = nil }) + + warm := make(chan struct{}) + go func() { defer close(warm); statsAt(0, statsNow) }() + <-started + + listed := make(chan []Session, 1) + go func() { listed <- List(0) }() + select { + case got := <-listed: + if len(got) < 12 { + t.Fatalf("listed %d sessions while another read ran", len(got)) + } + case <-time.After(10 * time.Second): + t.Fatal("List waited for another read of the same files to end") + } + managed := make(chan ManageView, 1) + go func() { + managed <- Manage(map[string]bool{"claude": true}, func([]AgentCount, map[string]map[string]bool) string { return "claude" }) + }() + select { + case v := <-managed: + if len(v.Sessions) < 12 { + t.Fatalf("managed %d sessions while another read ran", len(v.Sessions)) + } + case <-time.After(10 * time.Second): + t.Fatal("Manage waited for another read of the same files to end") + } + release() + <-warm + if n := parsed.Load(); n != 12 { + t.Fatalf("the 12 changed files were read %d times", n) + } + // and what the warm-up read is in, for the next page + parsed.Store(0) + List(0) + if n := parsed.Load(); n != 0 { + t.Fatalf("read %d files again after the warm-up had read them", n) + } +} + +// A file never read before has no parse to serve: a page waits for the +// read already under way, rather than reading it a second time. +func TestReadWaitsForAFirstReadUnderWay(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + moreSessions(t, claude, 12) + + hold, started := make(chan struct{}), make(chan struct{}) + var once sync.Once + var parsed atomic.Int32 + parseHook = func() { + parsed.Add(1) + once.Do(func() { close(started) }) + <-hold + } + release := sync.OnceFunc(func() { close(hold) }) + t.Cleanup(func() { release(); parseHook = nil }) + + warm := make(chan struct{}) + go func() { defer close(warm); statsAt(0, statsNow) }() + <-started + before := parsed.Load() + + listed := make(chan []Session, 1) + go func() { listed <- List(0) }() + select { + case <-listed: + t.Fatal("List answered without the files being read") + case <-time.After(200 * time.Millisecond): + } + release() + var got []Session + select { + case got = <-listed: + case <-time.After(30 * time.Second): + t.Fatal("List never answered") + } + <-warm + if len(got) < 12 { + t.Fatalf("listed %d sessions", len(got)) + } + total := before + mu.Lock() + n := len(cache) + mu.Unlock() + if p := parsed.Load(); p != int32(n) { + t.Fatalf("%d files read %d times (%d before the page asked)", n, p, total) + } +} + +// The stores two reads share stay open until the last of them is done: a +// read that ends first must not close what the other still reads. +func TestStoresLiveAsLongAsTheirLastUser(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.db") + if err := os.WriteFile(path, nil, 0o644); err != nil { + t.Fatal(err) + } + mu.Lock() + first := useDBs() + db := openDB(path) + second := useDBs() + if openDB(path) != db { + mu.Unlock() + t.Fatal("a second read opened its own handle") + } + second() + mu.Unlock() + if db == nil { + t.Fatal("not opened") + } + if err := db.Ping(); err != nil { + t.Fatalf("closed while a read still used it: %v", err) + } + mu.Lock() + first() + open := dbs[path] != nil + mu.Unlock() + if open || db.Ping() == nil { + t.Fatal("left open after the last read") + } +} diff --git a/internal/sessions/relocate_claude.go b/internal/sessions/relocate_claude.go index 9ae12f7c1..3d4b682e4 100644 --- a/internal/sessions/relocate_claude.go +++ b/internal/sessions/relocate_claude.go @@ -39,8 +39,8 @@ type ClaudeRelocationResult struct { // session-ID-keyed files (file-history, todos and session-env). IDs stay intact. // Clients must be closed: the in-process lock cannot exclude Claude itself. func RelocateClaudeProject(in ClaudeRelocation) (ClaudeRelocationResult, error) { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.Lock() + defer storeMu.Unlock() mu.Lock() defer mu.Unlock() root, target, err := claudeRelocationRoot(in) diff --git a/internal/sessions/scan_buffer_test.go b/internal/sessions/scan_buffer_test.go new file mode 100644 index 000000000..a81278fb3 --- /dev/null +++ b/internal/sessions/scan_buffer_test.go @@ -0,0 +1,114 @@ +package sessions + +import ( + "context" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/klauspost/compress/zstd" +) + +// A scan of a small session file takes a buffer the size of the file, not +// 1 MiB: a start reads thousands of them, and their buffers were most of +// what it allocated (#2776). +func TestScanOfASmallFileTakesASmallBuffer(t *testing.T) { + p := filepath.Join(t.TempDir(), "s.jsonl") + if err := os.WriteFile(p, []byte(`{"type":"user","n":1}`+"\n"+`{"type":"assistant","n":2}`+"\n"), 0o600); err != nil { + t.Fatal(err) + } + const scans = 200 + lines := 0 + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for range scans { + if _, err := scanAt(p, 0, nil, func(b []byte, _, _ int64) bool { lines++; return true }); err != nil { + t.Fatal(err) + } + } + runtime.ReadMemStats(&after) + if lines != 2*scans { + t.Fatalf("read %d lines, want %d", lines, 2*scans) + } + // 16 KiB each, with room for the file handles and anything else + if per := (after.TotalAlloc - before.TotalAlloc) / scans; per > 64<<10 { + t.Fatalf("a scan of a two-line file allocated %d bytes", per) + } +} + +// A line longer than the buffer (the file grew after its size was read) is +// still handed over whole. +func TestScanReadsALineLongerThanItsBuffer(t *testing.T) { + p := filepath.Join(t.TempDir(), "s.jsonl") + if err := os.WriteFile(p, []byte("{}\n"), 0o600); err != nil { + t.Fatal(err) + } + f, err := os.Open(p) + if err != nil { + t.Fatal(err) + } + size := scanBuffer(f, 0) + f.Close() + long := `{"text":"` + strings.Repeat("x", 3*size) + `"}` + if err := os.WriteFile(p, []byte(long+"\n{}\n"), 0o600); err != nil { + t.Fatal(err) + } + var got []int + if _, err := scanAt(p, 0, nil, func(b []byte, _, _ int64) bool { got = append(got, len(b)); return true }); err != nil { + t.Fatal(err) + } + if len(got) != 2 || got[0] != len(long) || got[1] != 2 { + t.Fatalf("lines %v, want [%d 2]", got, len(long)) + } +} + +// Every other reader of a session file sizes its buffer as scanAt does: +// the calls readers of MiniMax Code, agy and WorkBuddy, dsh's packed +// frames and a search's first look each took 1 MiB per file read (#2776). +func TestReadersOfASmallFileTakeASmallBuffer(t *testing.T) { + dir := t.TempDir() + write := func(name, body string) string { + t.Helper() + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return p + } + line := `{"type":"user","n":1}` + "\n" + plain := write("s.jsonl", line+line) + enc, err := zstd.NewWriter(nil) + if err != nil { + t.Fatal(err) + } + framed := write("s.v3.jsonl.zstd", string(enc.EncodeAll([]byte(line+line), nil))) + enc.Close() + for _, c := range []struct { + name string + read func() + }{ + {"minimax", func() { readMiniMaxCalls(file{path: plain, key: "minimax-code:s"}) }}, + {"agy", func() { readAgyCalls(file{path: plain, key: "agy:s"}) }}, + {"workbuddy", func() { readWorkBuddyCalls(file{agent: "workbuddy", path: plain, key: "workbuddy:s"}) }}, + {"frames", func() { scanFrames(framed, 0, 0, func([]byte) bool { return true }) }}, + {"search", func() { mayHold(context.Background(), plain, "absent") }}, + } { + t.Run(c.name, func(t *testing.T) { + const reads = 50 + c.read() // anything a first read sets up once + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for range reads { + c.read() + } + runtime.ReadMemStats(&after) + if per := (after.TotalAlloc - before.TotalAlloc) / reads; per > 256<<10 { + t.Fatalf("a read of a two-line file allocated %d bytes", per) + } + }) + } +} diff --git a/internal/sessions/search.go b/internal/sessions/search.go index f09b87dd4..00f8d4250 100644 --- a/internal/sessions/search.go +++ b/internal/sessions/search.go @@ -157,7 +157,7 @@ func mayHold(ctx context.Context, path, needle string) bool { defer f.Close() nb := []byte(needle) keep := len(nb) - 1 - buf := make([]byte, 1<<20+keep) + buf := make([]byte, scanBuffer(f, 0)+keep) have := 0 for { if ctx.Err() != nil { diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 5afb21a51..f689dd23a 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -210,6 +210,19 @@ type state struct { // Pi: in a forked session, the time it was forked; the lines before // it are the copy of the session it was forked from Since time.Time `json:"since,omitzero"` + // Grok Build: where its updates were read to, and what the read + // carries on with + Grok *grokCarry `json:"grok,omitempty"` + // Droid: where its transcript was read to, and what the read carries + // on with + Droid *droidCarry `json:"droid,omitempty"` + // Kimi Code: where its wire file was read to, and what the read + // carries on with + Kimi *kimiCarry `json:"kimi,omitempty"` + // dsh: where its file was read to, and its header + Dsh *dshCarry `json:"dsh,omitempty"` + // Cline: the messages file its counts were read from + Cline *clineCarry `json:"cline,omitempty"` } // day is one local date's share of a file: tokens by model, and the time @@ -469,7 +482,14 @@ func ccFiles(agent, dir string) []file { } // allFiles are every agent's session files. +// filesHook, when a test sets it, runs on each pass over every agent's +// files. +var filesHook func() + func allFiles() []file { + if filesHook != nil { + filesHook() + } var out []file for _, fs := range [][]file{callFiles(), openCodeFiles(), piFiles(), wslFiles("pi", "omp", "kimi"), zcodeFiles(), dshFiles(), clineFiles(), ccFiles("qoder", QoderDir("qoder")), ccFiles("qoder-cn", QoderDir("qoder-cn")), @@ -595,10 +615,20 @@ func rolloutTwin(p string) string { } var ( - // DB readers share connection lifetimes; call-file readers need only mu. - dbReadMu sync.Mutex - mu sync.Mutex - cache map[string]*state // path → parse + // storeMu keeps the reads of the sessions apart from the changes made + // to their files (Delete, a provider move, a project relocation): a + // read takes it shared, so reads never wait on one another, and a + // change alone. The store handles they share live as long as their last + // user (useDBs), not as long as the read that opened them. + storeMu sync.RWMutex + mu sync.Mutex + cache map[string]*state // path → parse + // parsing holds the files a refresh is reading now, each closed when + // its parse is in the cache: another reader serves the parse kept of + // such a file rather than reading it a second time, and waits only for + // one it has no parse of yet (#2776: the start's warm-up held every + // page for its whole read) + parsing = map[string]chan struct{}{} loaded bool cacheGeneration uint64 // the zone the parses in memory date their days in @@ -750,15 +780,26 @@ func writeCache(c *save) { // cached agents alone, for a Codex-only identity refresh. func refresh(want, all []file) { defer func() { trimSummaryRevisions(time.Now()) }() - var todo []file + var todo, waits []file for _, f := range want { if f.cold { continue // in a stopped WSL distro: what was read of it stands } - if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.hermes.revision == "" || s.DBRevision != f.hermes.revision)) || ((f.agent == "alma" || f.agent == "cursor") && s.DBRevision != f.rev) { + if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.rev == "" || s.DBRevision != f.rev)) || ((f.agent == "alma" || f.agent == "cursor") && s.DBRevision != f.rev) { + if parsing[f.path] != nil { + // another refresh is reading it: its last parse stands + // until that one is in, and one never read is waited for + if s == nil { + waits = append(waits, f) + } + continue + } todo = append(todo, f) } } + if len(waits) > 0 { + defer waitParsing(waits) + } gone := false if len(cache) > 0 && all != nil { on := make(map[string]bool, len(all)) @@ -801,6 +842,7 @@ func refresh(want, all []file) { jobs := make([]job, len(todo)) for i, f := range todo { jobs[i] = job{f: f, old: cache[f.path]} + parsing[f.path] = make(chan struct{}) } generation := cacheGeneration mu.Unlock() @@ -833,15 +875,16 @@ func refresh(want, all []file) { } close(ch) }() - // publish puts the parses finished since last time in the cache. - publish := func(done []int) { - for _, i := range done { - j := &jobs[i] - // A concurrent read may already have published a newer parse. - if generation == cacheGeneration && cache[j.f.path] == j.old { - cache[j.f.path] = j.parsed - } + // publish puts a finished parse in the cache at once, for a reader + // waiting on it, and lets the file be read again. + publish := func(i int) { + j := &jobs[i] + // A concurrent read may already have published a newer parse. + if generation == cacheGeneration && cache[j.f.path] == j.old { + cache[j.f.path] = j.parsed } + close(parsing[j.f.path]) + delete(parsing, j.f.path) } // What is read is kept on disk every checkpointEvery, not only at the // end: a first read of a long history on a slow disk runs for minutes, @@ -849,33 +892,65 @@ func refresh(want, all []file) { // of it, so the next start read it all again. tick := time.NewTicker(checkpointEvery) defer tick.Stop() - var done []int + unsaved := false for n := 0; n < len(jobs); { select { case i := <-finished: - done = append(done, i) + mu.Lock() + publish(i) + mu.Unlock() + unsaved = true n++ case <-tick.C: - if len(done) == 0 { + if !unsaved { continue } mu.Lock() - publish(done) if generation == cacheGeneration { saveCache() } mu.Unlock() - done = done[:0] + unsaved = false } } mu.Lock() - publish(done) progress.finish() if generation == cacheGeneration { saveCache() } } +// waitParsing waits, with mu let go, for the files other refreshes are +// reading, and reads itself any of them that came to nothing (a Reset +// dropped its parse). +func waitParsing(fs []file) { + for { + var chans []chan struct{} + for _, f := range fs { + if ch := parsing[f.path]; ch != nil { + chans = append(chans, ch) + } + } + if len(chans) == 0 { + break + } + mu.Unlock() + for _, ch := range chans { + <-ch + } + mu.Lock() + } + var missing []file + for _, f := range fs { + if cache[f.path] == nil { + missing = append(missing, f) + } + } + if len(missing) > 0 { + refresh(missing, nil) + } +} + // checkpointEvery is how often a long read of changed files keeps what it // has read so far on disk. var checkpointEvery = 5 * time.Second @@ -974,7 +1049,10 @@ func Reset() { directoryCache.entries = map[string]directoryEntry{} directoryCache.Unlock() resetCalls() + droidCallers.reset() + grokKinds.reset() wslReset() + forgetHermesPrints() mu.Lock() defer mu.Unlock() saved() @@ -985,8 +1063,8 @@ func Reset() { // List reads the latest sessions of every agent, the most recently active // first, at most limit of them (Limit when 0). func List(limit int) []Session { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() if limit <= 0 { limit = Limit } @@ -994,7 +1072,7 @@ func List(limit int) []Session { defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() files := allFiles() groups := map[string][]file{} latest := map[string]time.Time{} @@ -1040,20 +1118,38 @@ func List(limit int) []Session { return out } -// assemble puts a session together from its files' parses. -func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) { - // the session's own file first; for Codex the earliest segment +// sortSessionFiles puts a session's own file first; for Codex the earliest +// segment. +func sortSessionFiles(fs []file) { sort.SliceStable(fs, func(i, j int) bool { if fs[i].main != fs[j].main { return fs[i].main } return filepath.Base(fs[i].path) < filepath.Base(fs[j].path) }) +} + +// sessionID is a session's id: its key's, or for an agent that writes it +// inside the file (idInFile), what its own file's parse read. +func sessionID(fs []file) string { + sortSessionFiles(fs) + id := strings.TrimPrefix(fs[0].key, fs[0].agent+":") + if idInFile(fs[0].agent) && fs[0].main { + if st := cache[fs[0].path]; st != nil && st.ID != "" { + id = st.ID + } + } + return id +} + +// assemble puts a session together from its files' parses. +func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) { + sortSessionFiles(fs) s := Session{Agent: fs[0].agent, Path: fs[0].path, Models: []Model{}, WSL: fs[0].wsl} for _, f := range fs { s.ReadOnly = s.ReadOnly || f.readOnly } - s.ID = strings.TrimPrefix(fs[0].key, s.Agent+":") + s.ID = sessionID(fs) var custom, named, first string models := map[string]*Model{} for _, f := range fs { @@ -1077,9 +1173,6 @@ func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) { if first == "" { first = st.First } - if (s.Agent == "codex" || s.Agent == "pi" || s.Agent == "omp" || s.Agent == "dsh" || s.Agent == "grok" || s.Agent == "droid") && st.ID != "" && f.path == fs[0].path { - s.ID = st.ID - } } if s.Agent == "codex" && st.CodexNickname != "" { s.Nickname = st.CodexNickname @@ -1147,7 +1240,10 @@ func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) { // parserFor is the source of truth for both parsing and window admission. // A default line reader is Claude-compatible, including both Qoder variants. type sessionParser struct { - whole func(file) *state + whole func(file) *state + // grow reads a file on from where the kept parse of it left off, when + // the file has only grown since (tail.go), else whole + grow func(file, *state) *state line func(*state, []byte, bool) claude bool } @@ -1161,15 +1257,15 @@ func parserFor(agent string) sessionParser { case "opencode", "zcode": return sessionParser{whole: parseOpenCode} case "dsh": - return sessionParser{whole: parseDsh} + return sessionParser{grow: parseDsh} case "cline": - return sessionParser{whole: parseCline} + return sessionParser{grow: parseCline} case "grok": - return sessionParser{whole: parseGrok} + return sessionParser{grow: parseGrok} case "kimi": - return sessionParser{whole: parseKimi} + return sessionParser{grow: parseKimi} case "droid": - return sessionParser{whole: parseDroid} + return sessionParser{grow: parseDroid} case "cursor": return sessionParser{whole: parseCursor} case "codex": @@ -1194,6 +1290,9 @@ func parse(f file, old *state) *state { if parser.whole != nil { return parser.whole(f) } + if parser.grow != nil { + return parser.grow(f, old) + } // Every source using claudeLine must rebuild a missing transient window. if parser.claude && old != nil && old.Claude == nil { old = nil @@ -1272,7 +1371,7 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st } return off, err } - r := bufio.NewReaderSize(f, 1<<20) + r := bufio.NewReaderSize(f, scanBuffer(f, off)) var long []byte var n int64 // bytes of the line so far skip, seen := false, false @@ -1314,6 +1413,23 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st } } +// scanBuffer is the read buffer a reader of f needs for what is left of it +// from off: 1 MiB at most, and no more than that rest of a plain file. +// Every line reader of a session file sizes its buffer by it. Every scan +// took 1 MiB, and a start's read of ~4,600 mostly small session files +// (each read again from where it was left) allocated ~9 GB of them, which +// the GC's heap target followed up (#2776). A line longer than the buffer +// (a file grown since) is still read whole, through scanAt's long line. +func scanBuffer(f io.Reader, off int64) int { + const most, least = 1 << 20, 16 << 10 + if pf, ok := f.(*os.File); ok { + if info, err := pf.Stat(); err == nil { + return int(min(most, max(least, info.Size()-off+1))) + } + } + return most +} + // packed says whether a session file is compressed: a Codex rollout the // Codex app has packed (.zst), a dsh session (.zstd). A packed rollout is // written whole, so it is read whole again whenever it changes. @@ -1583,7 +1699,7 @@ func Titles(keys []string) map[string]string { mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() files := allFiles() groups := map[string][]file{} var fs []file @@ -1631,7 +1747,7 @@ func get(key string) (s Session, ok, found bool) { mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() files := allFiles() var fs []file for _, f := range files { diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go index c4aa927fd..67c8a10de 100644 --- a/internal/sessions/stats.go +++ b/internal/sessions/stats.go @@ -108,7 +108,19 @@ func StatsFor(days int) Stats { // StatsAt is StatsFor as if it were now. func StatsAt(days int, now time.Time) Stats { return statsAt(days, now) } -func statsAt(days int, now time.Time) Stats { +// StatsAndNative is StatsFor, and the agent|id of every session List would +// list, with no limit: what tells a gateway session the agent keeps too +// from one only magpie saw. Both come of one pass over the files, as the +// overview asks for both on every poll (#2776). +func StatsAndNative(days int) (Stats, map[string]bool) { + native := map[string]bool{} + return statsIn(days, time.Now(), native), native +} + +func statsAt(days int, now time.Time) Stats { return statsIn(days, now, nil) } + +// statsIn is statsAt, filling native as StatsAndNative says when not nil. +func statsIn(days int, now time.Time, native map[string]bool) Stats { now = now.In(time.Local) today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local) var since time.Time @@ -119,18 +131,31 @@ func statsAt(days int, now time.Time) Stats { } out := Stats{From: from, To: today.Format(time.DateOnly), Days: []Day{}, Sessions: []Summary{}, Keys: []string{}} - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() files := allFiles() // every changed file, whatever the range, so a wider range picked later // finds them read rather than starting another run refresh(files, files) identities := codexIdentitySnapshot(files) taskTitles := codexSubagentTaskTitles(files) + if native != nil { + groups := map[string][]file{} + for _, f := range files { + groups[f.key] = append(groups[f.key], f) + } + price := pricer() + for _, fs := range groups { + // as List: a session nothing was said in is not listed + if s, ok := assemble(fs, price); ok { + native[s.Agent+"|"+s.ID] = true + } + } + } var want []file for _, f := range files { if !f.mod.Before(since) { diff --git a/internal/sessions/stats_native_test.go b/internal/sessions/stats_native_test.go new file mode 100644 index 000000000..66b988563 --- /dev/null +++ b/internal/sessions/stats_native_test.go @@ -0,0 +1,32 @@ +package sessions + +import "testing" + +// The overview's stats and the sessions that tell its gateway sessions +// apart come of one pass over every agent's files (#2776): it took a second +// pass, through List(All), on every refresh. The keys are List's. +func TestStatsAndNativeOnePass(t *testing.T) { + setup(t) + want := map[string]bool{} + for _, s := range List(All) { + want[s.Agent+"|"+s.ID] = true + } + passes := 0 + filesHook = func() { passes++ } + t.Cleanup(func() { filesHook = nil }) + st, native := StatsAndNative(0) + if passes != 1 { + t.Fatalf("%d passes over the files", passes) + } + if len(st.Sessions) == 0 { + t.Fatalf("no stats: %+v", st) + } + if len(native) != len(want) || len(want) < 2 { + t.Fatalf("native %v, List's %v", native, want) + } + for k := range want { + if !native[k] { + t.Fatalf("native %v, List's %v", native, want) + } + } +} diff --git a/internal/sessions/tail.go b/internal/sessions/tail.go new file mode 100644 index 000000000..3ceb8553c --- /dev/null +++ b/internal/sessions/tail.go @@ -0,0 +1,77 @@ +package sessions + +import "os" + +// tail is where a reader of a file another agent appends to left off: the +// offset after the last whole line it handled, and enough of the file as it +// was to know it again. A summary kept with one reads on from Off when the +// file has only grown, instead of reading it whole again (dsh's, Grok +// Build's, Droid's and Kimi Code's sessions are kept so). A file that +// shrank, or whose start or sampled prefix is no longer what was read, is +// read whole again: it was rewritten or replaced, not appended to. +// +// A packed file (frames of zstd, frames.go) is read on from the frame at +// Off, Skip bytes into what that frame holds, and Size there is the end of +// that frame: the bytes hashed always take in what is read again. +type tail struct { + Off int64 `json:"off"` + Skip int64 `json:"skip,omitempty"` + Size int64 `json:"size"` + Head string `json:"head"` + HeadSize int `json:"head_size"` + Hash string `json:"hash"` +} + +// markTail is the tail of a file read up to off, its first size bytes the +// ones read and to be found again. +func markTail(path string, off, skip, size int64) *tail { + head := headOf(path) + if int64(len(head)) > size { + head = head[:size] + } + h := prefixHash(path, size) + if h == "" && size > 0 { + return nil + } + return &tail{Off: off, Skip: skip, Size: size, Head: hashHead(head), HeadSize: len(head), Hash: h} +} + +// holds says whether the file at path is still the one t was read from, +// grown or as it was, so it can be read on from t.Off. +func (t *tail) holds(path string) bool { + if t == nil { + return false + } + fi, err := os.Stat(path) + if err != nil || fi.Size() < t.Size || t.Off > t.Size { + return false + } + return sameHead(headOf(path), t.Head, t.HeadSize) && prefixHash(path, t.Size) == t.Hash +} + +// dropUse takes back what use counted, leaving no model or day it made +// with nothing in it: a summary read on from where it was is then the one +// a whole read makes. +func (s *state) dropUse(date, model string, t Tokens) { + if t.zero() { + return + } + s.unuse(date, model, t) + if m, ok := s.Models[model]; ok && m.zero() { + delete(s.Models, model) + if len(s.Models) == 0 { + s.Models = nil + } + } + if d := s.Days[date]; d != nil { + if m, ok := d.Models[model]; ok && m.zero() { + delete(d.Models, model) + if len(d.Models) == 0 { + d.Models = nil + } + } + if len(d.Models) == 0 && d.Active == 0 && d.Hours == nil && d.Prompts == 0 && d.Replies == 0 && d.Tools == nil && d.Skills == nil { + delete(s.Days, date) + } + } +} diff --git a/internal/sessions/traces_opencode_db.go b/internal/sessions/traces_opencode_db.go index cfd386f3f..74140ee54 100644 --- a/internal/sessions/traces_opencode_db.go +++ b/internal/sessions/traces_opencode_db.go @@ -12,7 +12,7 @@ import ( // These connections belong to the trace reader, not the Sessions listing cache. // Updates are read in timestamp/ID order in bounded batches; large histories -// neither hold dbReadMu nor force the entire conversation to be re-exported. +// neither hold storeMu nor force the entire conversation to be re-exported. type ocTraceState struct { messages map[string]ocTraceMessage order []string diff --git a/internal/sessions/traces_review_test.go b/internal/sessions/traces_review_test.go index c5ab8f71f..9af8a793b 100644 --- a/internal/sessions/traces_review_test.go +++ b/internal/sessions/traces_review_test.go @@ -156,15 +156,15 @@ func TestOpenCodeTraceLargeSessionProgressAndIncrementalUpdate(t *testing.T) { for i := 0; i < 12; i++ { budget := int64(8 << 20) // Trace reading must not acquire the Sessions listing mutex. - dbReadMu.Lock() + storeMu.Lock() done := make(chan []TraceSpan, 1) go func() { done <- r.pollOpenCode(false, &budget) }() var spans []TraceSpan select { case spans = <-done: - dbReadMu.Unlock() + storeMu.Unlock() case <-time.After(10 * time.Second): - dbReadMu.Unlock() + storeMu.Unlock() <-done t.Fatal("trace reading blocked on the listing mutex") } diff --git a/internal/sessions/transcript_opencode.go b/internal/sessions/transcript_opencode.go index 833616feb..92b6d7fc4 100644 --- a/internal/sessions/transcript_opencode.go +++ b/internal/sessions/transcript_opencode.go @@ -8,10 +8,20 @@ import ( // openCodeTranscript reads the conversation in message order from the same // store the listing chose, including while a v1 to v2 migration is underway. func openCodeTranscript(s Session, add func(bool, Part) bool) error { - dbReadMu.Lock() - defer dbReadMu.Unlock() - defer closeDBs() - for _, f := range openCodeFiles() { + storeMu.RLock() + defer storeMu.RUnlock() + // the store handles are shared with the reads that hold mu: they are + // opened and given back under it, and read from without it + mu.Lock() + release := useDBs() + files := openCodeFiles() + mu.Unlock() + defer func() { + mu.Lock() + release() + mu.Unlock() + }() + for _, f := range files { if f.sid != s.ID { continue } diff --git a/internal/settings/image_timeout_test.go b/internal/settings/image_timeout_test.go new file mode 100644 index 000000000..0b5f5766e --- /dev/null +++ b/internal/settings/image_timeout_test.go @@ -0,0 +1,40 @@ +package settings + +import ( + "testing" + "time" +) + +// Settings' Image generation timeout (neighbads on X: a slow image +// endpoint needs more than 5 minutes) is kept from 1 to 60 minutes, and +// 0, which is what a settings.json without it reads as, is the 5 drawing +// was always given. +func TestImageTimeoutKeptAndBounded(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if w := Load().ImageWait(); w != 5*time.Minute { + t.Fatalf("unset: %v", w) + } + for _, m := range []int{1, 30, 60} { + if err := Save(Settings{ImageTimeout: m}); err != nil { + t.Fatalf("%d: %v", m, err) + } + if s := Load(); s.ImageTimeout != m || s.ImageWait() != time.Duration(m)*time.Minute { + t.Fatalf("%d read back as %d, %v", m, s.ImageTimeout, s.ImageWait()) + } + } + for _, m := range []int{-1, 61, 600} { + if Save(Settings{ImageTimeout: m}) == nil { + t.Fatalf("%d minutes accepted", m) + } + } + if Load().ImageTimeout != 60 { + t.Fatal("a refused value overwrote the saved one") + } + // a settings.json written by hand past the bounds still waits within them + if w := (Settings{ImageTimeout: 600}).ImageWait(); w != time.Hour { + t.Fatalf("600 waits %v", w) + } + if w := (Settings{ImageTimeout: -3}).ImageWait(); w != 5*time.Minute { + t.Fatalf("-3 waits %v", w) + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 8eac0c241..a90bf649c 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -307,6 +307,11 @@ type Settings struct { // "off" turns the video a request that names no model gets off too // (gateway.videomaker). ImageGen string `json:"imageGen,omitempty"` + // ImageTimeout is how long, in minutes, a vendor is given to draw an + // image and send it (neighbads on X: a slow image endpoint needs more + // than 5): from 1 to ImageTimeoutMost, 0 for ImageTimeoutDefault. + // ImageWait reads it. + ImageTimeout int `json:"imageTimeout,omitempty"` // Searcher is the provider that searches the web for a model that // can't: "" with the small model magpie picks of it, // "/", or empty for the one magpie picks @@ -822,6 +827,25 @@ func Arrange[T any](s Settings, items []T, id func(T) string) (shown, hidden []T return shown, hidden } +// ImageTimeoutDefault is the minutes an image is given to be drawn when +// ImageTimeout is 0, and ImageTimeoutMost the most it can be set to. +const ( + ImageTimeoutDefault = 5 + ImageTimeoutMost = 60 +) + +// ImageWait is how long a vendor is given to draw an image and send it: +// ImageTimeout's minutes, ImageTimeoutDefault's when it is 0 (or below), +// and no more than ImageTimeoutMost's when settings.json was written by +// hand past it. +func (s Settings) ImageWait() time.Duration { + m := s.ImageTimeout + if m < 1 { + m = ImageTimeoutDefault + } + return time.Duration(min(m, ImageTimeoutMost)) * time.Minute +} + // Themes and Langs are the accepted values, in the order the UI offers them. var ( Themes = []string{"system", "light", "dark"} @@ -1241,6 +1265,9 @@ func save(s Settings, recording bool) error { return fmt.Errorf("an update mirror is an http(s) address put before the github.com URL, like https://mirror.example/, not %q", m) } } + if s.ImageTimeout < 0 || s.ImageTimeout > ImageTimeoutMost { + return fmt.Errorf("image generation is given from 1 to %d minutes, or 0 for %d, not %d", ImageTimeoutMost, ImageTimeoutDefault, s.ImageTimeout) + } if s.UsageAlert < 0 || s.UsageAlert > 100 { return fmt.Errorf("a usage alert is at a percentage from 1 to 100, or 0 for off, not %d", s.UsageAlert) } diff --git a/internal/stats/usage.go b/internal/stats/usage.go index 89fda879c..3b6ba4dca 100644 --- a/internal/stats/usage.go +++ b/internal/stats/usage.go @@ -91,7 +91,7 @@ func agentLabel(id string) string { // goes only when models.dev knows it, else as "other"; a subscription's // or plugin's ids are its vendor's. func modelLabel(ref string) string { - if strings.HasPrefix(ref, provider.GroupPrefix) { + if provider.IsGroupRef(ref) { return "group" } p, m, ok := provider.Resolve(ref) diff --git a/internal/tui/library.go b/internal/tui/library.go index 87db01153..a6c52feed 100644 --- a/internal/tui/library.go +++ b/internal/tui/library.go @@ -340,12 +340,12 @@ func (m *model) openLibAdd() { input: newInput("filter"), items: []agent.Option{ {Value: "mcp server", Note: "a URL, or a command it runs"}, - {Value: "skills", Note: "from a GitHub repository, or a folder on this machine"}, + {Value: "skills", Note: "from GitHub, GitLab or any git repository, or a folder on this machine"}, }, onPick: func(v string) tea.Cmd { return func() tea.Msg { if v == "skills" { - in := newInput("a GitHub link (owner/repo, or a folder in one) or a folder's full path") + in := newInput("owner/repo, a GitHub or GitLab link, a git address (git@host:group/repo.git), or a folder's full path") in.CharLimit = 400 return askMsg{ask{crumbs: []string{"library", "add", "skills"}, input: in, hint: "magpie looks there for skills, then you pick one", diff --git a/internal/tui/routing.go b/internal/tui/routing.go index ba90a40e2..268e1c3ff 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -199,7 +199,7 @@ func memberOptions(skip []string, self string) []agent.Option { // agents see too (a provider kept for routing groups, a group's // with listed=no, #1783), as the Routing view's picker offers for _, e := range provider.Served() { - if slices.Contains(skip, e.ID) || e.ID == provider.GroupPrefix+self { + if slices.Contains(skip, e.ID) || slices.Contains(skip, provider.CanonicalRef(e.ID)) || e.Group != "" && e.Group == self { continue } note := e.Name @@ -414,7 +414,7 @@ func (m model) updateGroup(msg tea.KeyMsg) (tea.Model, tea.Cmd) { m.openClassifier(g) case "E", "F": // the model's own effort and fast mode, whatever the agent asks - if onRule || n == 0 || strings.HasPrefix(g.Members[m.gsel], provider.GroupPrefix) { + if onRule || n == 0 || provider.IsGroupRef(g.Members[m.gsel]) { return m, nil } id := g.Members[m.gsel] @@ -557,7 +557,7 @@ func (m model) viewGroups() string { } nameW, idW := 0, 0 for _, g := range m.groups { - nameW, idW = max(nameW, lipgloss.Width(dash(g.Name))), max(idW, lipgloss.Width(provider.GroupPrefix+g.ID)) + nameW, idW = max(nameW, lipgloss.Width(dash(g.Name))), max(idW, lipgloss.Width(g.Ref())) } visible := max(3, m.h-7) start := 0 @@ -576,7 +576,7 @@ func (m model) viewGroups() string { if i == m.grow { marker, name = sCursor.Render("▸ "), sNameOn.Render(padRight(dash(g.Name), nameW)) } - line := pad + marker + name + " " + sFaint.Render(padRight(provider.GroupPrefix+g.ID, idW)) + line := pad + marker + name + " " + sFaint.Render(padRight(g.Ref(), idW)) if g.Hidden { b.WriteString(line + "\n") continue @@ -612,7 +612,7 @@ func (m model) viewGroup() string { var b strings.Builder b.WriteString(m.header("routing", g.Name)) b.WriteString("\n\n") - head := []string{provider.GroupPrefix + g.ID, groupRouting(g), staysName(g.Affinity)} + head := []string{g.Ref(), groupRouting(g), staysName(g.Affinity)} if g.Context > 0 { head = append(head, "context "+fmtTokens(g.Context)) } diff --git a/internal/update/aside_test.go b/internal/update/aside_test.go index a27ec5788..687fdc343 100644 --- a/internal/update/aside_test.go +++ b/internal/update/aside_test.go @@ -11,8 +11,9 @@ import ( // fakeRename has renameFile fail with err the first n times, then rename. func fakeRename(t *testing.T, n int, err error) *int { calls := 0 - waits, rename := asideWaits, renameFile + waits, rename, held := asideWaits, renameFile, heldFor asideWaits = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond} + heldFor = 0 renameFile = func(from, to string) error { calls++ if calls <= n { @@ -20,7 +21,7 @@ func fakeRename(t *testing.T, n int, err error) *int { } return os.Rename(from, to) } - t.Cleanup(func() { asideWaits, renameFile = waits, rename }) + t.Cleanup(func() { asideWaits, renameFile, heldFor = waits, rename, held }) return &calls } @@ -78,3 +79,31 @@ func TestMoveAsideSaysWhy(t *testing.T) { t.Fatalf("%d tries of a missing exe", *calls) } } + +// An antivirus checking a new program can hold a file longer than the +// short pauses (白菜 on Discord: every restart failed the same way): a +// file held open is waited for on, up to heldFor, rather than given up on +// after three seconds. +func TestMoveAsideWaitsOutALongHold(t *testing.T) { + exe := filepath.Join(t.TempDir(), "magpie-windows-amd64.exe") + os.WriteFile(exe, []byte("v1"), 0o755) + calls := fakeRename(t, 10, errSharingViolation) + heldFor = 5 * time.Second + if _, err := moveAside(exe); err != nil { + t.Fatal(err) + } + if *calls != 11 { + t.Fatalf("%d tries, want 11", *calls) + } + + // what isn't a file held open isn't waited for past the short pauses + os.WriteFile(exe, []byte("v2"), 0o755) + calls = fakeRename(t, 100, os.ErrPermission) + heldFor = 5 * time.Second + if _, err := moveAside(exe); err == nil { + t.Fatal("moved") + } + if *calls != 4 { + t.Fatalf("%d tries of a refused move, want 4", *calls) + } +} diff --git a/internal/update/install_blocked_windows_test.go b/internal/update/install_blocked_windows_test.go index 38ad499d6..fc4cfa11a 100644 --- a/internal/update/install_blocked_windows_test.go +++ b/internal/update/install_blocked_windows_test.go @@ -4,6 +4,7 @@ import ( "errors" "os" "path/filepath" + "strings" "testing" "time" ) @@ -150,3 +151,52 @@ func TestStartCheckedPutsBackForReal(t *testing.T) { }) } } + +// 白菜 on Discord: a download an antivirus holds longer than the short +// pauses after the trial start goes in once it is let go, and a restart +// that failed anyway, tried again, doesn't start the same download again +// (which had the antivirus hold it again) but does a new one. +func TestInstallBinaryWaitsOutALongHold(t *testing.T) { + waits, held := asideWaits, heldFor + asideWaits, heldFor = []time.Duration{time.Millisecond, 20 * time.Millisecond}, 5*time.Second + t.Cleanup(func() { asideWaits, heldFor = waits, held }) + exe, staged := rollbackFiles(t) + release := holdForRollbackTest(t, staged) + go func() { time.Sleep(600 * time.Millisecond); release() }() + if _, err := InstallBinaryAside(staged, exe); err != nil { + t.Fatal("install while the download is held past the short pauses:", err) + } + wantInstallFile(t, exe, "new version") +} + +func TestInstallBinaryTrialsADownloadOnce(t *testing.T) { + waits, held, was := asideWaits, heldFor, canStart + asideWaits, heldFor = []time.Duration{time.Millisecond}, 0 + trials := 0 + canStart = func(string) error { trials++; return nil } + t.Cleanup(func() { asideWaits, heldFor, canStart = waits, held, was }) + exe, staged := rollbackFiles(t) + release := holdForRollbackTest(t, staged) + _, err := InstallBinaryAside(staged, exe) + if err == nil || !strings.Contains(err.Error(), "another program still has the download open") { + t.Fatalf("held for good: %v", err) + } + wantInstallFile(t, exe, "old version") + release() + if _, err := InstallBinaryAside(staged, exe); err != nil { + t.Fatal("tried again:", err) + } + wantInstallFile(t, exe, "new version") + if trials != 1 { + t.Fatalf("%d trial starts of one download, want 1", trials) + } + + // a new download is tried + os.WriteFile(staged, []byte("newer version"), 0o755) + if _, err := InstallBinaryAside(staged, exe); err != nil { + t.Fatal(err) + } + if trials != 2 { + t.Fatalf("%d trial starts after a new download, want 2", trials) + } +} diff --git a/internal/update/install_rollback_windows_test.go b/internal/update/install_rollback_windows_test.go index 2be597157..029eb910d 100644 --- a/internal/update/install_rollback_windows_test.go +++ b/internal/update/install_rollback_windows_test.go @@ -26,9 +26,9 @@ func rollbackFiles(t *testing.T) (string, string) { // shortWaits has moveIn and moveAside give up on a file held for good // at once. func shortWaits(t *testing.T) { - was := asideWaits - asideWaits = []time.Duration{time.Millisecond} - t.Cleanup(func() { asideWaits = was }) + was, held := asideWaits, heldFor + asideWaits, heldFor = []time.Duration{time.Millisecond}, 0 + t.Cleanup(func() { asideWaits, heldFor = was, held }) } func holdForRollbackTest(t *testing.T, path string) func() { diff --git a/internal/update/install_windows_test.go b/internal/update/install_windows_test.go index 7fc42c2e1..e4a406127 100644 --- a/internal/update/install_windows_test.go +++ b/internal/update/install_windows_test.go @@ -80,6 +80,9 @@ func TestInstallBinaryHeldOpen(t *testing.T) { } os.WriteFile(staged, []byte("newer version"), 0o755) + held := heldFor + heldFor = 0 // held for good: no use waiting it out + t.Cleanup(func() { heldFor = held }) h = holdOpen(t, exe) defer syscall.CloseHandle(h) err := InstallBinary(staged, exe) diff --git a/internal/update/update.go b/internal/update/update.go index 0d4d64d1f..976afa814 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -26,6 +26,7 @@ import ( "runtime" "strconv" "strings" + "sync" "syscall" "time" @@ -440,9 +441,15 @@ func InstallBinary(staged, exe string) error { func InstallBinaryAside(staged, exe string) (string, error) { var old string if runtime.GOOS == "windows" { - if err := canStart(staged); err != nil { - os.Remove(staged) - return "", &BlockedError{Err: err} + // tried once per download: a restart clicked again after a failed + // one doesn't start it again, which would have an antivirus that + // checks a program as it starts hold it again for the move below + if !trialled.passed(staged) { + if err := canStart(staged); err != nil { + os.Remove(staged) + return "", &BlockedError{Err: err} + } + trialled.note(staged) } // A running .exe cannot be overwritten, but it can be moved aside. // What the last update moved aside may still be running too (a @@ -456,6 +463,11 @@ func InstallBinaryAside(staged, exe string) (string, error) { } } if err := moveIn(staged, exe); err != nil { + if heldOpen(err) { + // the reason and what to do, shown as is in the version row + // and the Update pill's tooltip, without the paths + err = &saidError{fmt.Sprintf("couldn't put the new version in place of %s: another program still has the download open (often an antivirus checking it): let magpie through it and restart to update again, or download the new version and put it in place of this one", filepath.Base(exe)), err} + } if old != "" { if restoreErr := moveIn(old, exe); restoreErr != nil { return "", errors.Join(err, fmt.Errorf("couldn't restore %s from %s: %w", filepath.Base(exe), old, restoreErr)) @@ -468,6 +480,16 @@ func InstallBinaryAside(staged, exe string) (string, error) { return old, nil } +// saidError is err said in other words: what is shown, err what +// errors.Is and errors.As find. +type saidError struct { + said string + err error +} + +func (e *saidError) Error() string { return e.said } +func (e *saidError) Unwrap() error { return e.err } + // renameFile is os.Rename; tests make it fail. var renameFile = os.Rename @@ -476,6 +498,69 @@ var renameFile = os.Rename // open, which Windows won't rename under, for a moment, and lets go. var asideWaits = []time.Duration{100 * time.Millisecond, 200 * time.Millisecond, 400 * time.Millisecond, 800 * time.Millisecond, 1500 * time.Millisecond} +// heldFor is how long a file Windows says another program holds open is +// waited for, past asideWaits, the last pause repeated: an antivirus that +// checks a new program as it starts may hold a 50 MB download longer than +// asideWaits' three seconds, and a restart that gave up then would fail +// the same way on every click, each click's trial start having it checked +// again (白菜 on Discord). The user clicked restart and sees "Restarting…" +// meanwhile. A var for tests. +var heldFor = 30 * time.Second + +// waitHeld is whether to try again after try i (from 0) failed with err, +// begun at start, sleeping first when so: through asideWaits for any error +// retry allows, then on while err is a file held open, up to heldFor. +func waitHeld(i int, err error, start time.Time, retry bool) bool { + if !retry { + return false + } + if i < len(asideWaits) { + time.Sleep(asideWaits[i]) + return true + } + if !heldOpen(err) || len(asideWaits) == 0 { + return false + } + pause := asideWaits[len(asideWaits)-1] + if time.Since(start)+pause > heldFor { + return false + } + time.Sleep(pause) + return true +} + +// trialled is the download canStart last let through, by path, size and +// time written, so a restart tried again on it doesn't start it again. +var trialled trialNote + +type trialNote struct { + mu sync.Mutex + path string + size int64 + mod time.Time +} + +func (n *trialNote) passed(path string) bool { + fi, err := os.Stat(path) + if err != nil { + return false + } + n.mu.Lock() + defer n.mu.Unlock() + return n.path == path && n.size == fi.Size() && n.mod.Equal(fi.ModTime()) +} + +func (n *trialNote) note(path string) { + fi, err := os.Stat(path) + n.mu.Lock() + defer n.mu.Unlock() + if err != nil { + n.path = "" + return + } + n.path, n.size, n.mod = path, fi.Size(), fi.ModTime() +} + // Windows' errors for a file another program holds open without letting // it be renamed. const ( @@ -490,12 +575,12 @@ const ( // after the process has ended, and a move made at once failed the first // install of every update (#2272). Any other failure is returned at once. func moveIn(from, exe string) error { - var err error + start := time.Now() for i := 0; ; i++ { - if err = os.Rename(from, exe); err == nil || i == len(asideWaits) || !heldOpen(err) { + err := os.Rename(from, exe) + if err == nil || !waitHeld(i, err, start, heldOpen(err)) { return err } - time.Sleep(asideWaits[i]) } } @@ -512,18 +597,18 @@ func heldOpen(err error) bool { // so a failed installation can put the running exe back. func moveAside(exe string) (string, error) { var err error + start := time.Now() for i := 0; ; i++ { old := oldName(exe) if err = renameFile(exe, old); err == nil { return old, nil } - if errors.Is(err, fs.ErrNotExist) || i == len(asideWaits) { - break - } if i == 0 { os.Chmod(exe, 0o755) // a read-only exe: the attribute off } - time.Sleep(asideWaits[i]) + if !waitHeld(i, err, start, !errors.Is(err, fs.ErrNotExist)) { + break + } } why := err.Error() var le *os.LinkError diff --git a/internal/usage/client_agents_test.go b/internal/usage/client_agents_test.go index a8795a6e3..e13c2c34c 100644 --- a/internal/usage/client_agents_test.go +++ b/internal/usage/client_agents_test.go @@ -51,7 +51,7 @@ func TestClientCountedAsAgent(t *testing.T) { if sum.Agents[0].Calls != 3 || sum.Agents[0].Input != 22 { t.Fatalf("Codex's row doesn't hold the bridge's calls: %+v", sum.Agents[0]) } - if got := Vias(time.Time{}); len(got["codex|thread-1"]) != 1 || len(got["hermes-codex-thread-bridge|thread-1"]) != 0 { + if got := Vias(time.Time{}); len(got.Of("codex|thread-1")) != 1 || len(got.Of("hermes-codex-thread-bridge|thread-1")) != 0 { t.Fatalf("Routing's sessions: %v", got) } g, ok := GatewaySessionByID("codex", "thread-1", nil) diff --git a/internal/usage/codex_effort_rows_test.go b/internal/usage/codex_effort_rows_test.go new file mode 100644 index 000000000..28db18e1c --- /dev/null +++ b/internal/usage/codex_effort_rows_test.go @@ -0,0 +1,92 @@ +package usage + +import ( + "fmt" + "path/filepath" + "reflect" + "runtime" + "slices" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// threadRows are the rows of a whole ledger that carry a Codex thread. +func threadRows(l Ledgered) []Row { + return slices.DeleteFunc(slices.Clone(l.Rows), func(r Row) bool { return r.codexActor == "" }) +} + +// CodexModelEffort's rows are the whole ledger's rows that carry a thread, +// row for row, though it keeps only the gateway calls a session file's call +// can be matched to: paired by response id, an ambiguous response id, +// matched by session and tokens, and unrelated calls around them (#2776). +func TestCodexEffortRowsAreTheWholeLedgers(t *testing.T) { + now, _ := effortFixture(t) + root := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30") + at := func(d time.Duration) time.Time { return now.Add(-d) } + writeCodexCall(t, filepath.Join(root, "rollout-2026-09-30T09-00-00-main-b.jsonl"), "main-b", "main-b", `"cli"`, "resp-b", "m", "high", at(30*time.Minute), 300, 30) + writeCodexCall(t, filepath.Join(root, "rollout-2026-09-30T09-10-00-main-c.jsonl"), "main-c", "main-c", `"cli"`, "resp-c", "m2", "low", at(25*time.Minute), 70, 7) + writeCodexCall(t, filepath.Join(root, "rollout-2026-09-30T09-20-00-main-d.jsonl"), "main-d", "main-d", `"cli"`, "resp-d", "m", "medium", at(20*time.Minute), 50, 5) + writeCodexCall(t, filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "28", "rollout-2026-09-28T09-00-00-old-e.jsonl"), "old-e", "old-e", `"cli"`, "resp-e", "m", "low", now.Add(-50*time.Hour), 11, 1) + // paired by its response id, which the gateway's call alone has + Append(Record{Time: at(30 * time.Minute), Agent: "codex", Provider: "openai", Model: "m", Effort: "xhigh", Input: 300, Output: 30, Status: 200, ResponseID: "resp-b", Session: "main-b"}) + // two gateway calls with one response id: neither is paired + Append(Record{Time: at(25 * time.Minute), Agent: "codex", Provider: "openai", Model: "m2", Input: 70, Output: 7, Status: 200, ResponseID: "resp-c"}) + Append(Record{Time: at(25 * time.Minute), Agent: "codex", Provider: "openai", Model: "m2", Input: 70, Output: 7, Status: 200, ResponseID: "resp-c"}) + // matched by session and tokens: the session file's call is the gateway's + Append(Record{Time: at(20 * time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 50, Output: 5, Status: 200, NativeSession: "main-d"}) + // paired two days ago + Append(Record{Time: now.Add(-50 * time.Hour), Agent: "codex", Provider: "openai", Model: "m", Input: 11, Output: 1, Status: 200, ResponseID: "resp-e", Session: "old-e"}) + for i := range 40 { + Append(Record{Time: at(time.Duration(i) * time.Minute), Agent: "claude-code", Provider: "anthropic", Model: "claude-opus-5-5", Input: 40 + i, Output: 4, Status: 200, RequestID: fmt.Sprintf("req_%d", i), Session: "sess1"}) + Append(Record{Time: at(time.Duration(i) * time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 9, Output: 9, Status: 200, ResponseID: fmt.Sprintf("resp-other-%d", i), Session: "elsewhere"}) + } + for _, p := range []Period{All, Today, Week} { + for name, reader := range map[string]func(time.Time) []sessions.Call{"codex": codexCalls, "every agent": sessions.Calls} { + whole := threadRows(ledgerOfAt(p, Filter{}, now, reader)) + if p == All && len(whole) < 3 { + t.Fatalf("fixture: the whole ledger has %d thread rows: %+v", len(whole), whole) + } + if got := codexEffortRows(p, now, reader); !reflect.DeepEqual(got, whole) { + t.Fatalf("%s, %s:\n got %+v\nwant %+v", p, name, got, whole) + } + } + } +} + +// A build of CodexModelEffort takes no more for a gateway call no Codex +// session file's call can be matched to than a visit of the log does: it +// made every such call a record, a packed row and a priced row, and over +// ~720k calls that was most of the start's peak (#2776). +func TestCodexModelEffortLetsUnrelatedCallsGo(t *testing.T) { + now, _ := effortFixture(t) + Append(Record{Time: now.Add(-time.Hour), Agent: "codex", Provider: "openai", Model: "m", Input: 20, Output: 3, Status: 200, ResponseID: "resp-1", Session: "main-a"}) + const calls = 3000 + for i := range calls { + Append(Record{Time: now.Add(-time.Duration(i) * time.Second), Agent: "claude-code", Provider: "anthropic", Model: "claude-opus-5-5", Input: 40 + i, Output: 4, Status: 200, RequestID: fmt.Sprintf("req_%d", i), Session: fmt.Sprintf("sess%d", i%50)}) + } + measure := func(fn func()) uint64 { + fn() // anything a first read sets up once + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + fn() + runtime.ReadMemStats(&after) + return after.TotalAlloc - before.TotalAlloc + } + // the session files read by a reader of their own: a build each ask + old := LogCalls + LogCalls = codexCalls + t.Cleanup(func() { LogCalls = old }) + if got := CodexModelEffort(All); len(got["main-a"]) != 1 { + t.Fatalf("main-a's consumption: %+v", got) + } + visit := measure(func() { Visit(time.Time{}, func(Record) {}) }) + build := measure(func() { CodexModelEffort(All) }) + t.Logf("a build allocated %d bytes, a visit %d", build, visit) + // the visit itself, the thread's own rows and the sets of its ids + if build > visit+visit/2+256<<10 { + t.Fatalf("a build over %d unrelated calls allocated %d bytes, a visit of the log %d", calls, build, visit) + } +} diff --git a/internal/usage/codex_identity.go b/internal/usage/codex_identity.go index a948f80ce..046b9068c 100644 --- a/internal/usage/codex_identity.go +++ b/internal/usage/codex_identity.go @@ -329,7 +329,7 @@ var effortBuilt func() // CodexModelEffort reports each Codex thread's own priced ledger consumption. func CodexModelEffort(p Period) map[string][]sessions.ModelEffort { if LogCalls != nil { // synthetic logs carry no state to key on - return codexModelEffort(LedgerOf(p, Filter{}).Rows) + return codexModelEffort(codexEffortRows(p, Clock(), LogCalls)) } now := Clock() st := readRequestState(now) @@ -378,10 +378,71 @@ func CodexModelEffort(p Period) map[string][]sessions.ModelEffort { // Only Codex's own calls carry a Codex thread: a gateway call is told // its thread by the Codex call that has its response id, so the other // agents' session files are not read for this. - value = codexModelEffort(ledgerOfAt(p, Filter{}, now, codexCalls).Rows) + value = codexModelEffort(codexEffortRows(p, now, codexCalls)) return cloneEffort(value) } +// codexEffortRows are the rows of ledgerOfAt(p, Filter{}, now, reader) that +// carry a Codex thread, in the same order, without the rest of the ledger. +// A gateway call is told its thread only by the session file's call it is +// paired with, and a session file's call is matched (and so not a row of +// its own) only by a gateway call with its request id, its session or its +// response id: only those gateway calls are kept from the log, each read +// and let go as the log is visited. Over ~720k gateway calls a build held +// every one of them three times over (a record, a packed row and a priced +// row) at the start's peak (#2776). +func codexEffortRows(p Period, now time.Time, reader func(time.Time) []sessions.Call) []Row { + since := p.Since(now) + gatewaySince := since + if !since.IsZero() { + gatewaySince = since.Add(-24 * time.Hour) + } + logs := reader(since) + if len(logs) == 0 { + return nil + } + recs := matchingRecords(gatewaySince, logs) + matched, pairs, actors, compactions := gatewayMatchesDetails(recs, logs) + // only a gateway call paired with a session file's call has a thread + paired := make([]Record, 0, len(pairs)) + byRecord := make(map[int]int, len(pairs)) + for i, r := range recs { + if call, ok := pairs[i]; ok { + byRecord[len(paired)] = call + paired = append(paired, r) + } + } + rows, _, _, _ := ledgerMatched(since, p.Until(now), Filter{}, paired, logs, nil, matched, byRecord, actors, compactions) + return slices.DeleteFunc(rows, func(r Row) bool { return r.codexActor == "" }) +} + +// matchingRecords are the gateway's calls from since on that can be matched +// to one of logs, in the log's order: the ones with a response id, a request +// id or a session one of them has (an agy call by its agent: agy names no +// session). Any other gateway call leaves gatewayMatchesDetails' answer for +// logs as it is. +func matchingRecords(since time.Time, logs []sessions.Call) []Record { + responses, requests, sessionIDs := map[string]bool{}, map[string]bool{}, map[string]bool{} + agy := false + for _, c := range logs { + responses[c.ResponseID] = true + requests[c.RequestID] = true + sessionIDs[c.Session] = true + agy = agy || c.Agent == "agy" + } + delete(responses, "") + delete(requests, "") + delete(sessionIDs, "") + var out []Record + Visit(since, func(r Record) { + if responses[r.ResponseID] || requests[r.RequestID] || sessionIDs[r.NativeSession] || sessionIDs[r.Session] || + agy && ReportedAs(r.Agent) == "agy" { + out = append(out, r) + } + }) + return out +} + func codexCalls(since time.Time) []sessions.Call { return sessions.AgentCalls(since, "codex") } // forgetEffortPeriods drops the answers asked for longest ago, keeping p's diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.go index dd5cf04e4..c1fe4bcf1 100644 --- a/internal/usage/gateway_sessions.go +++ b/internal/usage/gateway_sessions.go @@ -4,6 +4,7 @@ import ( "slices" "sort" "sync" + "sync/atomic" "time" "github.com/yetone/magpie/internal/catalog" @@ -26,6 +27,10 @@ type GatewayDayUsage struct { sessions.Tokens Cost float64 Priced bool + // first and last bound the day's requests (last includes the request's + // own duration), so a session seen from a later midnight is derived + // from the one kept projection instead of a second copy (#2776). + first, last time.Time } // GatewaySession is a read-only projection of requests served by this @@ -53,15 +58,110 @@ type GatewayModel struct { // GatewaySessions aggregates one usage snapshot without reading routing // history or agent files. NativeKeys contains identities already represented // by local session files and is used to suppress the duplicate projection. +// +// A session's Models and Daily are the kept projection's own, shared by +// every caller, which reads them and never changes them: each ask cloned +// every session's days, and the start's first asks together held ~450 MB +// of copies over ~720k calls (#2776). They are clipped, so an append +// makes a slice of the caller's own. func GatewaySessions(since time.Time, nativeKeys map[string]bool) []GatewaySession { - e := gatewayProjection(since) - out := make([]GatewaySession, 0, len(e.sessions)) - for _, s := range e.sessions { - if !nativeKeys[s.Agent+"|"+s.ID] { - out = append(out, cloneGatewaySession(s)) + if since.IsZero() { + e := gatewayProjection() + out := make([]GatewaySession, 0, len(e.sessions)) + for _, s := range e.sessions { + if !nativeKeys[s.Agent+"|"+s.ID] { + out = append(out, s) + } + } + return out + } + if date, ok := localMidnight(since); ok { + // a range of whole days is the all-time projection's days from + // its first on: no copy of it is kept per range (#2776) + e := gatewayProjection() + out := make([]GatewaySession, 0, len(e.sessions)) + for _, s := range e.sessions { + if nativeKeys[s.Agent+"|"+s.ID] || !s.Last.After(since) { + continue + } + if w, ok := gatewaySessionFrom(s, date); ok { + out = append(out, w) + } + } + return out + } + // any other start is read from the log, and not kept + snapshot := readLogSnapshot() + out, _ := buildGatewaySessions(snapshot, since, nativeKeys) + return out +} + +// localMidnight is since's local date when since is that date's start. +func localMidnight(since time.Time) (string, bool) { + date := since.In(time.Local).Format(time.DateOnly) + start, err := time.ParseInLocation(time.DateOnly, date, time.Local) + return date, err == nil && start.Equal(since) +} + +// gatewaySessionFrom is s as it was read from the start of date on: its +// days from then, and its models, tokens, cost and times summed from them. +func gatewaySessionFrom(s GatewaySession, date string) (GatewaySession, bool) { + i := sort.Search(len(s.Daily), func(i int) bool { return s.Daily[i].Date >= date }) + if i == len(s.Daily) { + return GatewaySession{}, false + } + if i == 0 { + return s, true + } + w := GatewaySession{Agent: s.Agent, ID: s.ID, Models: []GatewayModel{}, Daily: s.Daily[i:]} + models := map[string]int{} // index in w.Models, which grows + for _, d := range w.Daily { + if w.Start.IsZero() || d.first.Before(w.Start) { + w.Start = d.first + } + if d.last.After(w.Last) { + w.Last = d.last + } + w.Input += d.Input + w.Output += d.Output + w.CacheRead += d.CacheRead + w.CacheWrite += d.CacheWrite + w.CacheWrite1h += d.CacheWrite1h + at, ok := models[d.Model] + if !ok { + at = len(w.Models) + w.Models = append(w.Models, GatewayModel{Model: d.Model, Priced: true}) + models[d.Model] = at + } + m := &w.Models[at] + m.Input += d.Input + m.Output += d.Output + m.CacheRead += d.CacheRead + m.CacheWrite += d.CacheWrite + m.CacheWrite1h += d.CacheWrite1h + m.Cost += d.Cost + m.Priced = m.Priced && d.Priced + } + finishGatewayModels(&w) + return w, true +} + +// finishGatewayModels sums s's models' cost into it, counts those not priced +// and puts the models in order, the most tokens first. +func finishGatewayModels(s *GatewaySession) { + for _, m := range s.Models { + s.Cost += m.Cost + if !m.Priced && m.Input+m.Output > 0 { + s.Unpriced++ } } - return out + sort.Slice(s.Models, func(i, j int) bool { + a, b := s.Models[i], s.Models[j] + if a.Input+a.Output != b.Input+b.Output { + return a.Input+a.Output > b.Input+b.Output + } + return a.Model < b.Model + }) } func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySession, bool) { @@ -72,7 +172,7 @@ func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySe if nativeKeys[agent+"|"+id] { return GatewaySession{}, false } - entry := gatewayProjection(time.Time{}) + entry := gatewayProjection() i, ok := entry.byID[agent+"|"+id] if !ok { return GatewaySession{}, false @@ -83,42 +183,39 @@ func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySe type gatewayProjectionEntry struct { version uint64 meta string - since time.Time + zone *time.Location // the zone its days are dates in sessions []GatewaySession byID map[string]int } +// gatewayCache keeps one projection, of all time, not one copy for every +// native exclusion set or range: a range of days is read out of it. With +// ~600k calls each range kept was another ~37 MB, four of them at once +// (#2776). The log snapshot version also detects rewrites and changes of +// config directory. var gatewayCache struct { sync.Mutex - entries []gatewayProjectionEntry + entry *gatewayProjectionEntry } -// Retain a few window projections, not one copy for every native exclusion set. -// The log snapshot version also detects rewrites and changes of config directory. -func gatewayProjection(since time.Time) gatewayProjectionEntry { +func gatewayProjection() gatewayProjectionEntry { snapshot := readLogSnapshot() meta := usagePriceCacheKey(time.Now()) gatewayCache.Lock() defer gatewayCache.Unlock() - for _, e := range gatewayCache.entries { - if e.version == snapshot.version && e.meta == meta && e.since.Equal(since) { - return e - } + if e := gatewayCache.entry; e != nil && e.version == snapshot.version && e.meta == meta && e.zone == time.Local { + return *e } - ss, _ := buildGatewaySessions(snapshot, since, nil) - e := gatewayProjectionEntry{version: snapshot.version, meta: meta, since: since, sessions: ss, byID: make(map[string]int, len(ss))} + ss, _ := buildGatewaySessions(snapshot, time.Time{}, nil) + e := gatewayProjectionEntry{version: snapshot.version, meta: meta, zone: time.Local, sessions: ss, byID: make(map[string]int, len(ss))} for i, s := range ss { e.byID[s.Agent+"|"+s.ID] = i + // handed out as they are: an append is the caller's own + ss[i].Models, ss[i].Daily = slices.Clip(s.Models), slices.Clip(s.Daily) } // A failed or partial read must be retried, not published as current. if snapshot.info != nil && snapshot.off == snapshot.info.Size() { - gatewayCache.entries = slices.DeleteFunc(gatewayCache.entries, func(old gatewayProjectionEntry) bool { - return old.version != e.version || old.meta != e.meta || old.since.Equal(since) - }) - if len(gatewayCache.entries) >= 4 { - gatewayCache.entries = gatewayCache.entries[1:] - } - gatewayCache.entries = append(gatewayCache.entries, e) + gatewayCache.entry = &e } return e } @@ -170,7 +267,11 @@ func gatewayDays(ss []GatewaySession) []GatewayDayUsage { return out } +// gatewayBuilds counts the projections built from the log, for tests. +var gatewayBuilds atomic.Int64 + func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage) { + gatewayBuilds.Add(1) priceOf := Pricer() type key struct{ agent, id string } groups := map[key]*GatewaySession{} @@ -178,11 +279,13 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map type dayKey struct{ date, agent, model string } daily := map[dayKey]*GatewayDayUsage{} perSession := map[key]map[dayKey]*GatewayDayUsage{} + keep := keptStrings{} snapshot.visit(since, func(r Record) { if r.IsRejected() || r.IsReported() || r.Session == "" { return } - a := ReportedAs(r.Agent) + a := keep.of(ReportedAs(r.Agent)) + r.Session, r.Model = keep.of(r.Session), keep.of(r.Model) k := key{a, r.Session} if nativeKeys != nil && nativeKeys[a+"|"+r.Session] { return @@ -197,7 +300,8 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map if s.Start.IsZero() || r.Time.Before(s.Start) { s.Start = r.Time } - if end := r.Time.Add(time.Duration(max(0, r.Millis)) * time.Millisecond); end.After(s.Last) { + end := r.Time.Add(time.Duration(max(0, r.Millis)) * time.Millisecond) + if end.After(s.Last) { s.Last = end } p := priceOf(r) @@ -224,6 +328,12 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map d.CacheWrite1h += tokens.CacheWrite1h d.Cost += cost d.Priced = d.Priced && priced + if d.first.IsZero() || r.Time.Before(d.first) { + d.first = r.Time + } + if end.After(d.last) { + d.last = end + } } s.Input += r.Input s.Output += r.Output @@ -238,6 +348,10 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map m.addRecord(r, p) }) for k, s := range groups { + // of their own size: the projection keeps them, and grown an item + // at a time they kept append's spare room, ~40% of them (#2776) + s.Daily = make([]GatewayDayUsage, 0, len(perSession[k])) + s.Models = make([]GatewayModel, 0, len(models[k])) for _, d := range perSession[k] { s.Daily = append(s.Daily, *d) } @@ -249,18 +363,8 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map }) for _, m := range models[k] { s.Models = append(s.Models, *m) - s.Cost += m.Cost - if !m.Priced && m.Input+m.Output > 0 { - s.Unpriced++ - } } - sort.Slice(s.Models, func(i, j int) bool { - a, b := s.Models[i], s.Models[j] - if a.Input+a.Output != b.Input+b.Output { - return a.Input+a.Output > b.Input+b.Output - } - return a.Model < b.Model - }) + finishGatewayModels(s) } out := make([]GatewaySession, 0, len(groups)) for _, s := range groups { diff --git a/internal/usage/gateway_sessions_kept_test.go b/internal/usage/gateway_sessions_kept_test.go new file mode 100644 index 000000000..0c1b3843b --- /dev/null +++ b/internal/usage/gateway_sessions_kept_test.go @@ -0,0 +1,70 @@ +package usage + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "unsafe" +) + +// The kept projection holds each session's days and models in lists of +// their own size: grown an item at a time they kept the room append had +// left them (five days took eight), which is most of what a start keeps +// for the Sessions page over ~720k calls (#2776). +func TestGatewayProjectionKeepsNoSpareRoom(t *testing.T) { + pageHome(t) + settleLogClock(t) + const sessionCount, days = 3000, 5 + if err := os.MkdirAll(filepath.Dir(Path()), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(Path()) + if err != nil { + t.Fatal(err) + } + enc := json.NewEncoder(f) + now := Clock() + for d := range days { + for i := range sessionCount { + at := now.AddDate(0, 0, -d) + for _, model := range []string{"m1", "m2", "m3", "m4", "m5"}[:1+i%5] { + if err := enc.Encode(Record{Time: at, Agent: "pi", Session: fmt.Sprintf("s%d", i), Provider: "p", Model: model, Input: 10, Status: 200}); err != nil { + t.Fatal(err) + } + } + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + readLogSnapshot() // kept whether or not a projection is + gatewayCache.Lock() + gatewayCache.entry = nil + gatewayCache.Unlock() + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + e := gatewayProjection() + runtime.GC() + runtime.ReadMemStats(&after) + kept := int64(after.HeapAlloc) - int64(before.HeapAlloc) + items, models := 0, 0 + for _, s := range e.sessions { + items += len(s.Daily) + models += len(s.Models) + } + if len(e.sessions) != sessionCount || items != sessionCount*days*3 { + t.Fatalf("%d sessions, %d days", len(e.sessions), items) + } + // the lists themselves, and the sessions' list and index beside them + lists := int64(items)*int64(unsafe.Sizeof(GatewayDayUsage{})) + int64(models)*int64(unsafe.Sizeof(GatewayModel{})) + beside := int64(sessionCount) * (int64(unsafe.Sizeof(GatewaySession{})) + 64) + t.Logf("the projection keeps %d bytes; its days and models are %d, its list and index ~%d", kept, lists, beside) + if kept > lists*13/10+beside { + t.Fatalf("the projection keeps %d bytes for %d bytes of days and models", kept, lists) + } + runtime.KeepAlive(e) +} diff --git a/internal/usage/gateway_sessions_shared_test.go b/internal/usage/gateway_sessions_shared_test.go new file mode 100644 index 000000000..0cab4790d --- /dev/null +++ b/internal/usage/gateway_sessions_shared_test.go @@ -0,0 +1,60 @@ +package usage + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "time" + "unsafe" +) + +// GatewaySessions hands every caller the kept projection's sessions, not a +// clone of each one's models and days: the start's first asks (the +// Sessions list, Manage for each agent, Stats) each cloned all of them, +// ~450 MB of copies at once over ~720k calls (#2776). +func TestGatewaySessionsHandOutTheKeptProjection(t *testing.T) { + pageHome(t) + settleLogClock(t) + const sessionCount, days = 2000, 10 + if err := os.MkdirAll(filepath.Dir(Path()), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(Path()) + if err != nil { + t.Fatal(err) + } + enc := json.NewEncoder(f) + now := Clock() + for d := range days { + for i := range sessionCount { + at := now.AddDate(0, 0, -d).Add(-time.Duration(i) * time.Second) + if err := enc.Encode(Record{Time: at, Agent: "pi", Session: fmt.Sprintf("s%d", i), Provider: "p", Model: "m", Input: 10, Status: 200}); err != nil { + t.Fatal(err) + } + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + if got := GatewaySessions(time.Time{}, nil); len(got) != sessionCount || len(got[0].Daily) < days { + t.Fatalf("%d sessions, the first with %d days", len(got), len(got[0].Daily)) + } + const asks = 10 + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for range asks { + GatewaySessions(time.Time{}, nil) + } + runtime.ReadMemStats(&after) + per := (after.TotalAlloc - before.TotalAlloc) / asks + list := uint64(sessionCount) * uint64(unsafe.Sizeof(GatewaySession{})) + t.Logf("an ask allocated %d bytes; the list it answers is %d", per, list) + // the list itself, and the log's check + if per > list+list/2 { + t.Fatalf("an ask allocated %d bytes, its list is %d", per, list) + } +} diff --git a/internal/usage/gateway_sessions_test.go b/internal/usage/gateway_sessions_test.go index 5158c5a76..61b06e89a 100644 --- a/internal/usage/gateway_sessions_test.go +++ b/internal/usage/gateway_sessions_test.go @@ -2,6 +2,7 @@ package usage import ( "github.com/yetone/magpie/internal/settings" + "math" "os" "path/filepath" "testing" @@ -39,10 +40,19 @@ func TestGatewaySessionsCacheRefreshAndOwnership(t *testing.T) { if len(first) != 1 { t.Fatalf("first: %+v", first) } - first[0].Models[0].Model = "changed by caller" - first[0].Daily[0].Input = 999 + // the lists are the kept projection's, read only; an append is the + // caller's own (#2776) again := GatewaySessions(time.Time{}, nil) - if again[0].Models[0].Model != "m" || again[0].Daily[0].Input != 10 { + if &again[0].Daily[0] != &first[0].Daily[0] { + t.Fatal("each ask has a copy of the days of its own") + } + mine := append(first[0].Daily, GatewayDayUsage{Date: "mine"}) + theirs := append(again[0].Daily, GatewayDayUsage{Date: "theirs"}) + models := append(first[0].Models, GatewayModel{Model: "mine"}) + if mine[1].Date != "mine" || theirs[1].Date != "theirs" || &mine[0] == &first[0].Daily[0] || &models[0] == &first[0].Models[0] { + t.Fatalf("two callers' appends share the kept lists: %+v %+v", mine, theirs) + } + if again := GatewaySessions(time.Time{}, nil); len(again[0].Models) != 1 || len(again[0].Daily) != 1 || again[0].Models[0].Model != "m" || again[0].Daily[0].Input != 10 { t.Fatalf("caller changed cache: %+v", again) } if got := GatewaySessions(time.Time{}, map[string]bool{"pi|native": true}); len(got) != 0 { @@ -63,7 +73,7 @@ func TestClientRequestPrefixedSessionsCount(t *testing.T) { if len(summary.Sessions) != 1 || summary.Sessions[0].ID != "request-mine" { t.Fatalf("the client's session is missing from Usage: %+v", summary.Sessions) } - if got := Vias(time.Time{}); len(got["pi|request-mine"]) != 1 { + if got := Vias(time.Time{}); len(got.Of("pi|request-mine")) != 1 { t.Fatalf("the client's session is missing from Routing: %+v", got) } if _, ok := GatewaySessionByID("pi", "request-mine", nil); !ok { @@ -99,11 +109,11 @@ func TestGatewaySessionsCachePricesWindowsAndRewrite(t *testing.T) { } } vias := Vias(time.Time{}) - vias["pi|native"][0].Calls = 999 - if got := Vias(time.Time{})["pi|native"][0].Calls; got != 2 { + vias.Of("pi|native")[0].Calls = 999 + if got := Vias(time.Time{}).Of("pi|native")[0].Calls; got != 2 { t.Fatalf("caller mutated routing cache: %d", got) } - if got := Vias(at.Add(-time.Minute))["pi|native"][0].Calls; got != 1 { + if got := Vias(at.Add(-time.Minute)).Of("pi|native")[0].Calls; got != 1 { t.Fatalf("routing window: %d", got) } if err := os.WriteFile(Path(), nil, 0600); err != nil { @@ -112,7 +122,74 @@ func TestGatewaySessionsCachePricesWindowsAndRewrite(t *testing.T) { if got := GatewaySessions(time.Time{}, nil); len(got) != 0 { t.Fatalf("rewrite retained sessions: %+v", got) } - if got := Vias(time.Time{}); len(got) != 0 { + if got := Vias(time.Time{}); got.Len() != 0 { t.Fatalf("rewrite retained routing: %+v", got) } } + +// A range of whole days is read out of the one all-time projection: no +// second copy is built or kept for it, and what it reads equals a direct +// build from that midnight (#2776). +func TestGatewayWindowsShareOneProjection(t *testing.T) { + resetUsageTest(t) + price := 3.0 + cfg := settings.Load() + cfg.ModelPrices = map[string]settings.ModelPrice{"*/priced": {Input: &price, Output: &price, CacheRead: new(0.0), CacheWrite: new(0.0)}} + if err := settings.Save(cfg); err != nil { + t.Fatal(err) + } + today := time.Now() + day := func(back int) time.Time { + y, m, d := today.AddDate(0, 0, -back).Date() + return time.Date(y, m, d, 0, 0, 0, 0, time.Local) + } + for back := 5; back >= 0; back-- { + at := day(back).Add(10 * time.Hour) + Append(Record{Time: at, Agent: "pi", Session: "long", Provider: "p", Model: "priced", Input: 1000 * (back + 1), Output: 7, Millis: 1500, Status: 200}) + Append(Record{Time: at.Add(time.Minute), Agent: "pi", Session: "long", Provider: "p", Model: "free", Input: 11, Output: 3, CacheRead: 5, Status: 200}) + if back%2 == 0 { + Append(Record{Time: at.Add(2 * time.Minute), Agent: "codex", Session: "even", Provider: "p", Model: "priced", Input: 300, Output: 9, Millis: 250, Status: 200}) + } + } + Append(Record{Time: day(5).Add(time.Hour), Agent: "pi", Session: "old", Provider: "p", Model: "priced", Input: 9, Status: 200}) + + key := func(ss []GatewaySession) map[string]GatewaySession { + m := map[string]GatewaySession{} + for _, s := range ss { + m[s.Agent+"|"+s.ID] = s + } + return m + } + backs := []int{0, 1, 2, 3, 7} + base := gatewayBuilds.Load() + GatewaySessions(time.Time{}, nil) + got := map[int][]GatewaySession{} + for _, back := range backs { + got[back] = GatewaySessions(day(back), nil) + } + if built := gatewayBuilds.Load() - base; built != 1 { + t.Fatalf("built %d projections for one log and %d ranges, want 1 kept and shared by them all", built, len(backs)) + } + for _, back := range backs { + want, _ := buildGatewaySessions(readLogSnapshot(), day(back), nil) + g, w := key(got[back]), key(want) + if len(g) != len(w) { + t.Fatalf("from %d days back: %d sessions, want %d: %+v", back, len(g), len(w), got[back]) + } + for k, ws := range w { + gs, ok := g[k] + if !ok { + t.Fatalf("from %d days back: %s missing", back, k) + } + if !gs.Start.Equal(ws.Start) || !gs.Last.Equal(ws.Last) || gs.Tokens != ws.Tokens || gs.Unpriced != ws.Unpriced || math.Abs(gs.Cost-ws.Cost) > 1e-9 || len(gs.Models) != len(ws.Models) || len(gs.Daily) != len(ws.Daily) { + t.Fatalf("from %d days back, %s:\n got %+v\nwant %+v", back, k, gs, ws) + } + for i := range ws.Models { + a, b := gs.Models[i], ws.Models[i] + if a.Model != b.Model || a.Tokens != b.Tokens || a.Priced != b.Priced || math.Abs(a.Cost-b.Cost) > 1e-9 { + t.Fatalf("from %d days back, %s model %d: got %+v want %+v", back, k, i, a, b) + } + } + } + } +} diff --git a/internal/usage/growing_rewrite_test.go b/internal/usage/growing_rewrite_test.go index c4937d23d..73f891665 100644 --- a/internal/usage/growing_rewrite_test.go +++ b/internal/usage/growing_rewrite_test.go @@ -76,7 +76,7 @@ func TestLogGrowingRewriteThenAppend(t *testing.T) { } vias := Vias(time.Time{}) for session, input := range map[string]int{"edited-prefix": 73, "appended-tail": 19} { - v := vias["codex|"+session] + v := vias.Of("codex|" + session) if len(v) != 1 || v[0].Calls != 1 || v[0].Tokens != input { t.Fatalf("%s vias stale: %+v", session, v) } diff --git a/internal/usage/incremental_log_test.go b/internal/usage/incremental_log_test.go index 0b1d6a739..7e50a3192 100644 --- a/internal/usage/incremental_log_test.go +++ b/internal/usage/incremental_log_test.go @@ -75,7 +75,7 @@ func TestUsageViasSkipsOldHistory(t *testing.T) { settleLogClock(t) historyLog(t, 4000) since := time.Now().Add(-time.Hour) - if v := Vias(since); len(v) != 1 || v["codex|s"][0].Calls != 1 { + if v := Vias(since); v.Len() != 1 || v.Of("codex|s")[0].Calls != 1 { t.Fatal(v) } if n := testing.AllocsPerRun(2, func() { Vias(since) }); n > 1500 { diff --git a/internal/usage/kept_strings_test.go b/internal/usage/kept_strings_test.go new file mode 100644 index 000000000..f2953b3a7 --- /dev/null +++ b/internal/usage/kept_strings_test.go @@ -0,0 +1,76 @@ +package usage + +import ( + "bufio" + "crypto/rand" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "runtime" + "testing" + "time" +) + +// An unpacked block's strings share one allocation, so a cache that keeps a +// session id or a model name read from a block must copy it out, or it keeps +// every string of that block: over a long history, the decoded text of all +// of it. This test fills each block with 1 KB of unique error text and gives +// each block its own session, then measures what the Sessions and Routing +// caches hold once the log index itself is let go. +func TestSessionCachesHoldNoDecodedBlocks(t *testing.T) { + resetUsageTest(t) + const blocks, text = 16, 1024 + path := Path() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + w := bufio.NewWriter(f) + at := time.Now().Add(-time.Hour) + noise := make([]byte, text/2) + for b := range blocks { + for range logBlockRows { + rand.Read(noise) + line, _ := json.Marshal(Record{Time: at, Agent: "codex", Session: "s" + string(rune('a'+b)), Provider: "p", Model: "m", Effort: "high", Input: 10, Output: 2, Status: 200, Error: hex.EncodeToString(noise)}) + w.Write(append(line, '\n')) + } + } + if err := w.Flush(); err != nil { + t.Fatal(err) + } + f.Close() + + held := func() uint64 { + var m runtime.MemStats + runtime.GC() + runtime.GC() + runtime.ReadMemStats(&m) + return m.HeapAlloc + } + if got := GatewaySessions(time.Time{}, nil); len(got) != blocks { + t.Fatalf("sessions: %d, want %d", len(got), blocks) + } + if got := Vias(time.Time{}); got.Len() != blocks { + t.Fatalf("vias: %d, want %d", got.Len(), blocks) + } + // the index is kept by design; only what the caches hold is measured + logIndex.Lock() + logIndex.snapshot = nil + logIndex.Unlock() + withCaches := held() + gatewayCache.Lock() + gatewayCache.entry = nil + gatewayCache.Unlock() + viasCache.Lock() + viasCache.all, viasCache.window.m = nil, nil + viasCache.Unlock() + without := held() + decoded := uint64(blocks * logBlockRows * text) + if withCaches > without && withCaches-without > decoded/8 { + t.Fatalf("the caches hold %d KB for %d sessions: the decoded text of their blocks (%d KB)", (withCaches-without)>>10, blocks, decoded>>10) + } +} diff --git a/internal/usage/plan_credits_test.go b/internal/usage/plan_credits_test.go index f61c30390..f069c0ef4 100644 --- a/internal/usage/plan_credits_test.go +++ b/internal/usage/plan_credits_test.go @@ -49,10 +49,10 @@ func TestPlanCreditsSummed(t *testing.T) { } } vias := Vias(time.Time{}) - if v := vias["claude-code|s1"]; len(v) != 1 || !near(v[0].Credits, 0.7) || v[0].Credited != 70 { + if v := vias.Of("claude-code|s1"); len(v) != 1 || !near(v[0].Credits, 0.7) || v[0].Credited != 70 { t.Fatalf("session s1: %+v", v) } - if v := vias["codex|s2"]; len(v) != 2 || v[0].Credited+v[1].Credited != 1 { + if v := vias.Of("codex|s2"); len(v) != 2 || v[0].Credited+v[1].Credited != 1 { t.Fatalf("session s2: %+v", v) } if got := FormatCredits(page.Sum); got != "0.7 credits" { diff --git a/internal/usage/reported_test.go b/internal/usage/reported_test.go index 5a9fc5244..7fd1aac03 100644 --- a/internal/usage/reported_test.go +++ b/internal/usage/reported_test.go @@ -199,7 +199,7 @@ func TestReportedTouchesNothingLive(t *testing.T) { t.Fatalf("a reported session is a gateway session: %+v", g) } } - if v := Vias(time.Time{})["claude|s-rep"]; len(v) != 0 { + if v := Vias(time.Time{}).Of("claude|s-rep"); len(v) != 0 { t.Fatalf("a reported session was routed: %+v", v) } if !(Record{Source: SourceReported}).IsReported() || (Record{}).IsReported() { diff --git a/internal/usage/request_snapshot.go b/internal/usage/request_snapshot.go index 29ab2430c..c73300b31 100644 --- a/internal/usage/request_snapshot.go +++ b/internal/usage/request_snapshot.go @@ -12,6 +12,7 @@ import ( "encoding/binary" "math" "slices" + "strings" "sync" "time" "unsafe" @@ -79,6 +80,27 @@ func (c *rowChunk) pack() *rowChunk { func (c *rowChunk) unpack() *rowChunk { return c.unpackInto(nil) } +// keptStrings copies out the strings that a result kept after a read takes +// from the rows it visited. An unpacked block's strings are cut from one +// allocation (unpackInto), so a cache holding one session id from a block +// holds every string of that block: its request and response ids and its +// errors. The Sessions and Routing caches kept a session id from nearly +// every block, and so the decoded text of the whole history: ~200 MB at +// rest for 600k calls. +type keptStrings map[string]string + +func (k keptStrings) of(s string) string { + if s == "" { + return "" + } + if kept, ok := k[s]; ok { + return kept + } + kept := strings.Clone(s) + k[kept] = kept + return kept +} + // unpackInto is unpack decoding the rows into rows when it is large enough: // every field of a row is written, so a reused slice needs no clearing. func (c *rowChunk) unpackInto(into []packedRow) *rowChunk { diff --git a/internal/usage/review_test.go b/internal/usage/review_test.go index bcdfe2ed9..75c5991c4 100644 --- a/internal/usage/review_test.go +++ b/internal/usage/review_test.go @@ -158,12 +158,12 @@ func TestZeroTokenFailuresDeduplicateAndRejectedStayVisible(t *testing.T) { t.Fatal("local rejection consumed a real API call") } Append(r) - if len(Vias(time.Time{})) != 0 { + if Vias(time.Time{}).Len() != 0 { t.Fatal("rejected request appears as a session provider") } Append(Record{Time: at, Agent: "claude", Provider: "relay", Model: "m", Session: "s", Status: 200}) Append(Record{Time: at, Agent: "claude", Model: "m", Session: "s", Status: 400}) // legacy rejection - if vias := Vias(time.Time{}); len(vias) != 1 || len(vias["claude|s"]) != 1 || vias["claude|s"][0].Calls != 1 { + if vias := Vias(time.Time{}); vias.Len() != 1 || len(vias.Of("claude|s")) != 1 || vias.Of("claude|s")[0].Calls != 1 { t.Fatalf("session via includes a local rejection: %+v", vias) } var out bytes.Buffer diff --git a/internal/usage/served.go b/internal/usage/served.go index a42b07e44..39bfbc611 100644 --- a/internal/usage/served.go +++ b/internal/usage/served.go @@ -149,5 +149,11 @@ func SameSpelled(sent, served string) bool { // serving another model than asked (莫 on Discord: group/auto-… answered // by deepseek/deepseek-v4.1-flash, marked a swap). func GroupRouted(sent, served string) bool { - return strings.TrimSpace(served) != "" && strings.HasPrefix(strings.TrimSpace(sent), provider.GroupPrefix) + return strings.TrimSpace(served) != "" && remoteGroup(strings.TrimSpace(sent)) +} + +// remoteGroup reports whether id is a routing group's id as a magpie +// gives it: group/, or auto/ for a group it found. +func remoteGroup(id string) bool { + return strings.HasPrefix(id, provider.GroupPrefix) || strings.HasPrefix(id, provider.AutoPrefix) } diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 7bfc5b609..c3f26802a 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -999,18 +999,24 @@ type Via struct { // Vias is what the gateway sent each session's calls to since a time, by // agent id and the session's id ("codex|"), the most calls first. -func Vias(since time.Time) map[string][]Via { +func Vias(since time.Time) ViaIndex { return cachedVias(since) } -func buildVias(snapshot *logSnapshot, since time.Time) map[string][]Via { +func buildVias(snapshot *logSnapshot, since time.Time) *viaLists { out := map[string][]Via{} + first := map[string]time.Time{} + keep := keptStrings{} snapshot.visit(since, func(r Record) { if r.IsRejected() || r.IsReported() || r.Session == "" || r.Model == "" { return } + r.Provider, r.Model, r.Effort = keep.of(r.Provider), keep.of(r.Model), keep.of(r.Effort) k := ReportedAs(r.Agent) + "|" + r.Session vs := out[k] + if t, seen := first[k]; !seen || r.Time.Before(t) { + first[k] = r.Time + } i := slices.IndexFunc(vs, func(v Via) bool { return v.Provider == r.Provider && v.Model == r.Model && v.Effort == r.Effort }) if i < 0 { vs, i = append(vs, Via{Provider: r.Provider, Model: r.Model, Effort: r.Effort}), len(vs) @@ -1029,7 +1035,7 @@ func buildVias(snapshot *logSnapshot, since time.Time) map[string][]Via { for _, vs := range out { sort.SliceStable(vs, func(i, j int) bool { return vs[i].Calls > vs[j].Calls }) } - return out + return &viaLists{m: out, first: first} } // Saw notes a request from an agent arriving now. diff --git a/internal/usage/vias_cache.go b/internal/usage/vias_cache.go index de63bd367..656019703 100644 --- a/internal/usage/vias_cache.go +++ b/internal/usage/vias_cache.go @@ -6,29 +6,105 @@ import ( "time" ) +// viaLists is what the gateway sent each session's calls to, and when each +// session's first call was: a list counted from any time at or before that +// first call is the same list. +type viaLists struct { + m map[string][]Via + first map[string]time.Time +} + +// viasCache keeps one index of the whole log, which answers every since a +// session's calls all came after, and one window for a session that had +// calls before its since. The Sessions list, each agent's manage page and +// a session's detail each ask from a since of their own; one kept since +// was built again from the whole log at almost every ask, ~280 MB a time +// over ~720k calls, on every poll of an open page (#2776). var viasCache struct { sync.Mutex version uint64 - since time.Time clients string // the clients counted as agents (#1958) - value map[string][]Via + all *viaLists + window struct { + version uint64 + clients string + since time.Time + m map[string][]Via + } } -func cachedVias(since time.Time) map[string][]Via { +// ViaIndex is Vias' answer: the one copy every caller shares, handed out +// whole and read only through Of, which gives each session's list as a +// copy of its own. Each ask cloned every session's list, ~66 MB a time +// over ~720k calls, where a page reads the few sessions it lists (#2776). +type ViaIndex struct { + all *viaLists + since time.Time + snapshot *logSnapshot + clients string +} + +// Of is what the gateway sent one session's calls to ("agent|id") since +// the index's time, the most calls first; nil for a session it sent none +// of. +func (x ViaIndex) Of(key string) []Via { + vs, ok := x.all.m[key] + if !ok { + return nil + } + if x.since.IsZero() || !x.all.first[key].Before(x.since) { + return slices.Clone(vs) + } + return slices.Clone(x.window()[key]) +} + +// Len is how many sessions have a list. +func (x ViaIndex) Len() int { + if x.since.IsZero() { + return len(x.all.m) + } + n := 0 + for _, vs := range x.all.m { + if slices.ContainsFunc(vs, func(v Via) bool { return !v.Last.Before(x.since) }) { + n++ + } + } + return n +} + +// window is the lists counted from the index's since, for a session that +// had calls before it. +func (x ViaIndex) window() map[string][]Via { + viasCache.Lock() + defer viasCache.Unlock() + w := &viasCache.window + if w.m != nil && w.version == x.snapshot.version && w.clients == x.clients && w.since.Equal(x.since) { + return w.m + } + m := buildVias(x.snapshot, x.since).m + if x.snapshot.complete() { + w.version, w.clients, w.since, w.m = x.snapshot.version, x.clients, x.since, m + } + return m +} + +func cachedVias(since time.Time) ViaIndex { snapshot := readLogSnapshot() clients := clientAgentsKey() viasCache.Lock() defer viasCache.Unlock() - value := viasCache.value - if value == nil || viasCache.version != snapshot.version || !viasCache.since.Equal(since) || viasCache.clients != clients { - value = buildVias(snapshot, since) - if snapshot.info != nil && snapshot.off == snapshot.info.Size() { - viasCache.version, viasCache.since, viasCache.value, viasCache.clients = snapshot.version, since, value, clients + all := viasCache.all + if all == nil || viasCache.version != snapshot.version || viasCache.clients != clients { + all = buildVias(snapshot, time.Time{}) + if snapshot.complete() { + viasCache.version, viasCache.clients, viasCache.all = snapshot.version, clients, all } } - out := make(map[string][]Via, len(value)) - for k, vs := range value { - out[k] = slices.Clone(vs) - } - return out + return ViaIndex{all: all, since: since, snapshot: snapshot, clients: clients} +} + +// complete is whether the snapshot reached the end of the log, so what is +// built from it can be kept for its version. +func (s *logSnapshot) complete() bool { + return s.info != nil && s.off == s.info.Size() } diff --git a/internal/usage/vias_cache_test.go b/internal/usage/vias_cache_test.go new file mode 100644 index 000000000..9a8f0a551 --- /dev/null +++ b/internal/usage/vias_cache_test.go @@ -0,0 +1,61 @@ +package usage + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "time" +) + +// Vias hands every caller the one copy it keeps, not a clone of every +// session's list: a Sessions page reads the few sessions it lists, and +// each ask cloned all of them, ~66 MB a time over ~720k calls (#2776). +// A list read through Of is still the caller's own. +func TestViasHandOutTheKeptCopy(t *testing.T) { + pageHome(t) + settleLogClock(t) + const sessionCount = 20000 + if err := os.MkdirAll(filepath.Dir(Path()), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(Path()) + if err != nil { + t.Fatal(err) + } + enc := json.NewEncoder(f) + now := Clock() + for i := range sessionCount { + if err := enc.Encode(Record{Time: now.Add(-time.Duration(i) * time.Second), Agent: "pi", Session: fmt.Sprintf("s%d", i), Provider: "p", Model: "m", Input: 10, Status: 200}); err != nil { + t.Fatal(err) + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + vias := Vias(time.Time{}) + if vias.Len() != sessionCount { + t.Fatalf("%d sessions, want %d", vias.Len(), sessionCount) + } + vias.Of("pi|s1")[0].Calls = 999 + if got := Vias(time.Time{}).Of("pi|s1")[0].Calls; got != 1 { + t.Fatalf("a caller changed the kept copy: %d calls", got) + } + const asks = 20 + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for range asks { + Vias(time.Time{}).Of("pi|s7") + } + runtime.ReadMemStats(&after) + // a clone of 20000 lists is a few MB; the log's check and one list + // are tens of KB + per := (after.TotalAlloc - before.TotalAlloc) / asks + t.Logf("an ask allocated %d bytes", per) + if per > 256<<10 { + t.Fatalf("an ask allocated %d bytes", per) + } +} diff --git a/internal/usage/vias_since_test.go b/internal/usage/vias_since_test.go new file mode 100644 index 000000000..c1ad8b7ed --- /dev/null +++ b/internal/usage/vias_since_test.go @@ -0,0 +1,86 @@ +package usage + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "time" +) + +// The Sessions list, each agent's manage page and a session's detail each +// ask Vias from a since of their own. One kept since was built again from +// the whole log at almost every ask, ~280 MB a time over ~720k calls, on +// every poll of an open page (#2776). One index now answers every since a +// session's calls all came after, and a session with calls before its +// since still counts only those after it. +func TestViasAnswerEverySinceFromOneIndex(t *testing.T) { + pageHome(t) + settleLogClock(t) + const sessionCount = 20000 + if err := os.MkdirAll(filepath.Dir(Path()), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(Path()) + if err != nil { + t.Fatal(err) + } + enc := json.NewEncoder(f) + now := Clock() + write := func(r Record) { + if err := enc.Encode(r); err != nil { + t.Fatal(err) + } + } + for i := range sessionCount { + write(Record{Time: now.Add(-time.Duration(sessionCount-i) * time.Second), Agent: "pi", Session: fmt.Sprintf("s%d", i), Provider: "p", Model: "m", Input: 10, Status: 200}) + } + // one session with a call on each side of a since + write(Record{Time: now.Add(-time.Hour), Agent: "pi", Session: "both", Provider: "p", Model: "m", Input: 10, Status: 200}) + write(Record{Time: now, Agent: "pi", Session: "both", Provider: "p", Model: "m", Input: 10, Status: 200}) + if err := f.Close(); err != nil { + t.Fatal(err) + } + if got := Vias(now.Add(-time.Minute)).Of("pi|both"); len(got) != 1 || got[0].Calls != 1 { + t.Fatalf("since a minute ago: %+v, want the one call after it", got) + } + if got := Vias(time.Time{}).Of("pi|both"); len(got) != 1 || got[0].Calls != 2 { + t.Fatalf("since ever: %+v, want both calls", got) + } + // the last 60 sessions, a second apart up to a second ago, and "both" + if n := Vias(now.Add(-time.Minute)).Len(); n != 61 { + t.Fatalf("%d sessions with calls since a minute ago, want 61", n) + } + if n := Vias(time.Time{}).Len(); n != sessionCount+1 { + t.Fatalf("%d sessions, want %d", n, sessionCount+1) + } + // the list, a manage page and a detail, asking in turn + sinces := []time.Time{ + now.Add(-(sessionCount + 60) * time.Second), + now.Add(-(sessionCount/2 + 60) * time.Second), + now.Add(-(sessionCount - 10 + 60) * time.Second), + } + key := fmt.Sprintf("pi|s%d", sessionCount-10) + for _, since := range sinces { + if got := Vias(since).Of(key); len(got) != 1 || got[0].Calls != 1 { + t.Fatalf("since %v: %+v", since, got) + } + } + const asks = 30 + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for i := range asks { + Vias(sinces[i%len(sinces)]).Of(key) + } + runtime.ReadMemStats(&after) + // building the lists of 20000 sessions is several MB; the log's check + // and one list are tens of KB + per := (after.TotalAlloc - before.TotalAlloc) / asks + t.Logf("an ask allocated %d bytes", per) + if per > 256<<10 { + t.Fatalf("an ask allocated %d bytes: the lists were built again", per) + } +} diff --git a/internal/webview2env/webview2env.go b/internal/webview2env/webview2env.go new file mode 100644 index 000000000..d0d75b93b --- /dev/null +++ b/internal/webview2env/webview2env.go @@ -0,0 +1,19 @@ +// Package webview2env keeps WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS as magpie +// was started with. Wails' WebView2 loader blanks the variable in its own +// init (webviewloader.preventEnvAndRegistryOverrides, so neither it nor the +// registry's policy can change the browser's arguments), before magpie's +// code runs, and a user's --disable-features=RendererCodeIntegrity never +// reached the renderer (#2753). This package reads it first. Go +// initializes, at each step, the first package by import path whose +// imports are all done. This one imports only syscall, so it is ready as +// soon as syscall is, and it sorts before "os"; the loader needs os, so +// os, and the loader after it, can't start while this one waits. +package webview2env + +import "syscall" + +// Name is the variable WebView2 reads extra browser arguments from. +const Name = "WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS" + +// Args is the variable's value when magpie started, "" when it wasn't set. +var Args, _ = syscall.Getenv(Name) diff --git a/site/public/docs/docker.html b/site/public/docs/docker.html index 9269ebdea..defe1d07a 100644 --- a/site/public/docs/docker.html +++ b/site/public/docs/docker.html @@ -93,7 +93,7 @@ Volume/config: providers, keys, sign-ins, plugins and usage Usernonroot (uid 65532) -

The image holds magpie’s terminal-only build on distroless, with bash and busybox for a terminal in the container. It runs magpie serve (the gateway alone) unless given another command. The container finds no agents to wire, so magpie in it is a gateway: the agents that use it run elsewhere.

+

The image holds magpie’s terminal-only build on Debian 12 slim, with bash for a terminal in the container and curl for the installers of the CLIs some subscriptions sign in with (Cursor, Devin, Grok Build). It runs magpie serve (the gateway alone) unless given another command. The container finds no agents to wire, so magpie in it is a gateway: the agents that use it run elsewhere.

Run it

Run it with the browser UI, a key for that page you keep across restarts, and both ports on the host’s loopback only:

diff --git a/site/public/docs/integrate.html b/site/public/docs/integrate.html index e34b9c2da..1ff43e88a 100644 --- a/site/public/docs/integrate.html +++ b/site/public/docs/integrate.html @@ -108,6 +108,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"/v1/messages, /v1/messages/count_tokensAnthropic Messages /v1beta/models/{model}:generateContent (and :streamGenerateContent)Google Gemini /v1/modelsthe catalog + /api/version, /api/tags, /api/showthe catalog as an Ollama server lists it, for a client that takes only an Ollama endpoint (Copilot in Visual Studio and VS Code: enter http://127.0.0.1:<port> as the Ollama URL; it chats on /v1/chat/completions, and /api/chat isn’t served)

The key names your app

diff --git a/site/public/docs/ja/docker.html b/site/public/docs/ja/docker.html index 43302c61c..550632cb8 100644 --- a/site/public/docs/ja/docker.html +++ b/site/public/docs/ja/docker.html @@ -93,7 +93,7 @@ ボリューム/config:プロバイダ、キー、サインイン、プラグイン、使用量 ユーザーnonroot(uid 65532) -

イメージに入っているのはターミナル専用ビルドの magpie で、distroless をベースに、コンテナ内でターミナルを使うための bash と busybox を含みます。コマンドを指定しなければ magpie serve(ゲートウェイのみ)を実行します。コンテナ内には設定するエージェントがないので、ここでの magpie はゲートウェイです。それを使うエージェントはほかのマシンで動きます。

+

イメージに入っているのはターミナル専用ビルドの magpie で、Debian 12 slim をベースに、コンテナ内でターミナルを使うための bash と、一部のサブスクリプションのサインインに必要な CLI(Cursor、Devin、Grok Build)をインストールするための curl を含みます。コマンドを指定しなければ magpie serve(ゲートウェイのみ)を実行します。コンテナ内には設定するエージェントがないので、ここでの magpie はゲートウェイです。それを使うエージェントはほかのマシンで動きます。

起動する

ブラウザ UI 付きで、再起動しても変わらないページ用のキーを渡し、両方のポートをホストのループバックだけに公開して起動します。

diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index 3d1df78f8..3819f7be1 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -168,7 +168,7 @@

1 つのモデルを複数のプロバイダで

グループとは、1 つまたは複数のプロバイダのモデルを、エージェントが 1 つとして選べるようにまとめたものです。ピッカーの Routing groups の下に group/<id> として表示されます。2 つのプロバイダが同じ名前で提供しているモデルは、それだけでグループになります。Routing タブの New group では、好きなモデルを組み合わせてグループを作れます。グループで何ができるかは、最初のモデルが基準になります。

-
何もしなくてもできるグループ。 すでに持っているモデルを提供する 2 つ目のプロバイダを追加すると(Claude サブスクリプションと Copilot の Claude Opus、DeepSeek 自身の API と OpenRouter の DeepSeek など)、magpie はそれを提供するすべてのプロバイダにまたがるグループ group/auto-<model> を自動で作ります。名前はベンダーごとの表記の違い(deepseek/deepseek-chat、deepseek-chat)を吸収して照合されます。エージェントにこれを選ぶとリクエストがすべてに分散されます。不要なものは magpie group rm で非表示にできます。
+
何もしなくてもできるグループ。 すでに持っているモデルを提供する 2 つ目のプロバイダを追加すると(Claude サブスクリプションと Copilot の Claude Opus、DeepSeek 自身の API と OpenRouter の DeepSeek など)、magpie はそれを提供するすべてのプロバイダにまたがるグループ auto/<model>(モデル自身の ID。例: auto/claude-opus-4.6。以前の group/auto-… も引き続き使えます)を自動で作ります。名前はベンダーごとの表記の違い(deepseek/deepseek-chat、deepseek-chat)を吸収して照合されます。エージェントにこれを選ぶとリクエストがすべてに分散されます。不要なものは magpie group rm で非表示にできます。
diff --git a/site/public/docs/start.html b/site/public/docs/start.html index 88730bddd..2a1bfff0d 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -168,7 +168,7 @@

One model over several providers

A group is several models, from one provider or many, that an agent picks as one: group/<id>, under Routing groups in the picker. A model two of your providers serve under the same name becomes a group on its own; New group in the Routing tab makes one of any models you like. The first model answers for what the group can do.

-
Groups you get without doing anything. Add a second provider that serves a model you already have — Claude Opus from your Claude subscription and from Copilot, DeepSeek from its own API and from OpenRouter — and magpie makes it a group by itself, group/auto-<model>, over every provider that serves it. The name is matched however each vendor spells it (deepseek/deepseek-chat, deepseek-chat). Pick it for an agent to spread its requests over all of them; magpie group rm hides one you don’t want.
+
Groups you get without doing anything. Add a second provider that serves a model you already have — Claude Opus from your Claude subscription and from Copilot, DeepSeek from its own API and from OpenRouter — and magpie makes it a group by itself, auto/<model> (the model's own id, as in auto/claude-opus-4.6; the older group/auto-… id still works), over every provider that serves it. The name is matched however each vendor spells it (deepseek/deepseek-chat, deepseek-chat). Pick it for an agent to spread its requests over all of them; magpie group rm hides one you don’t want.
ルーティング先に使われるもの
スマート smartデフォルトです。メンバーのアカウントとキーをまとめて扱い(グループ内のグループは 1 つとして扱います。下記参照)、クォータに余裕のあるサブスクリプションのうち、利用枠が最も早く更新されるもの。基準は週の枠です。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は 5 時間枠で判断されるため、それより後に週の枠が更新されるものすべてより先になります。リセットのないクレジット(WorkBuddy のパッケージはそれぞれの日に失効します)は、残りのうち最も早く失効する時点で判断されるため、クレジットが最も早く失効する WorkBuddy アカウントが先になります。失敗後に休止中のものは最後に回ります。
diff --git a/site/public/docs/zh/docker.html b/site/public/docs/zh/docker.html index 5ac2be38f..9d12a9787 100644 --- a/site/public/docs/zh/docker.html +++ b/site/public/docs/zh/docker.html @@ -93,7 +93,7 @@
RoutingWhat goes first
Smart smartThe default. Over the members’ accounts and keys together (a group in the group as one, see below): of the subscriptions with quota to spare, the one whose allowance renews soonest. The week decides; an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later. Credits with no reset (WorkBuddy’s packages, each ending on its own day) count as renewing when the soonest of those left run out, so the WorkBuddy account whose credits end first goes first. One resting after a failure goes last.
数据卷/config:供应商、密钥、登录、插件和用量
用户nonroot(uid 65532)
-

镜像里是 magpie 的纯终端版本,基于 distroless,并带了 bash 和 busybox,方便在容器里开终端。不指定命令时运行 magpie serve(只有网关)。容器里找不到需要配置的 Agent,所以这里的 magpie 是一个网关:用它的 Agent 运行在别的机器上。

+

镜像里是 magpie 的纯终端版本,基于 Debian 12 slim,带 bash,方便在容器里开终端,也带 curl,用来安装部分订阅登录时需要的 CLI(Cursor、Devin、Grok Build)。不指定命令时运行 magpie serve(只有网关)。容器里找不到需要配置的 Agent,所以这里的 magpie 是一个网关:用它的 Agent 运行在别的机器上。

运行

带 Web 界面运行,给页面一个重启后不变的 key,两个端口都只发布在宿主机的回环地址上:

diff --git a/site/public/docs/zh/integrate.html b/site/public/docs/zh/integrate.html index 3b1e1db81..4ea3cae2f 100644 --- a/site/public/docs/zh/integrate.html +++ b/site/public/docs/zh/integrate.html @@ -108,6 +108,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"/v1/messages、/v1/messages/count_tokensAnthropic Messages /v1beta/models/{model}:generateContent(以及 :streamGenerateContent)Google Gemini /v1/models模型目录 + /api/version、/api/tags、/api/show以 Ollama 服务器的格式列出模型目录,供只接受 Ollama 端点的客户端使用(Visual Studio 和 VS Code 里的 Copilot:Ollama 地址填 http://127.0.0.1:<端口>;对话走 /v1/chat/completions,不提供 /api/chat)

用 key 标明你的应用

diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index f03cecadb..8a9b8b8d1 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -168,7 +168,7 @@

跨供应商的同一个模型

路由组是几个模型(来自一个或多个供应商),Agent 把它当作一个来选:group/<id>,在选择列表的 路由组 下面。两个供应商用同一个名字提供的模型会自动成组;在 路由 标签页点 新建组 可以把任意模型组到一起。排第一的模型决定这个组对外的能力。

-
不用手动建的组。再加一个供应商,只要它提供的模型和已有的同名(比如 Claude 订阅和 Copilot 都有 Claude Opus,DeepSeek 官方 API 和 OpenRouter 都有 DeepSeek),magpie 就会自动把它们组成一个路由组:group/auto-<模型>,包含所有提供这个模型的供应商。名字按各家不同的写法匹配(deepseek/deepseek-chat 和 deepseek-chat 算同一个)。给 Agent 选这个组,请求就会分摊到这些供应商上;不想要的可以用 magpie group rm 隐藏。
+
不用手动建的组。再加一个供应商,只要它提供的模型和已有的同名(比如 Claude 订阅和 Copilot 都有 Claude Opus,DeepSeek 官方 API 和 OpenRouter 都有 DeepSeek),magpie 就会自动把它们组成一个路由组:auto/<模型>(模型自己的 id,比如 auto/claude-opus-4.6;以前的 group/auto-… 也照样能用),包含所有提供这个模型的供应商。名字按各家不同的写法匹配(deepseek/deepseek-chat 和 deepseek-chat 算同一个)。给 Agent 选这个组,请求就会分摊到这些供应商上;不想要的可以用 magpie group rm 隐藏。
路由谁排在前面
智能 smart默认。把成员的账号和 Key 放在一起排(组里的路由组算一个,见下文):还有余量的订阅里,额度最先重置的排第一。看周额度的重置时间;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)看它的 5 小时重置,所以排在所有更晚重置的周额度前面。没有重置时间的积分(WorkBuddy 的积分包,各自到期)按剩余积分最早过期的时间算,所以积分最先过期的 WorkBuddy 账号排第一。失败后在休息的排最后。