Merge remote-tracking branch 'origin/main' into pf/serve
# Conflicts: # internal/gui/core_budget_test.go
This commit is contained in:
+16
-22
@@ -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
|
||||
|
||||
|
||||
@@ -14,8 +14,7 @@ and when a quota runs out, it quietly moves on to the next account.
|
||||
    
|
||||
|
||||
<sub>Sponsors</sub><br>
|
||||
<a href="https://usemagpie.ai/go/apinebula/readme"><picture><source media="(prefers-color-scheme: dark)" srcset="site/public/img/sponsor-apinebula-dark.svg"><img src="site/public/img/sponsor-apinebula.svg" height="36" alt="APINEBULA"></picture></a>
|
||||
<a href="https://usemagpie.ai/go/zerotoken/readme"><picture><source media="(prefers-color-scheme: dark)" srcset="site/public/img/sponsor-zerotoken-dark.svg"><img src="site/public/img/sponsor-zerotoken.svg" height="36" alt="零词元"></picture></a>
|
||||
<a href="https://usemagpie.ai/go/apinebula/readme"><picture><source media="(prefers-color-scheme: dark)" srcset="site/public/img/sponsor-apinebula-dark.svg"><img src="site/public/img/sponsor-apinebula.svg" height="36" alt="APINEBULA"></picture></a>  <a href="https://usemagpie.ai/go/zerotoken/readme"><picture><source media="(prefers-color-scheme: dark)" srcset="site/public/img/sponsor-zerotoken-dark.svg"><img src="site/public/img/sponsor-zerotoken.svg" height="36" alt="零词元"></picture></a>
|
||||
|
||||
**[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)
|
||||
|
||||
|
||||
+1
-2
@@ -14,8 +14,7 @@
|
||||
    
|
||||
|
||||
<sub>赞助商</sub><br>
|
||||
<a href="https://usemagpie.ai/go/apinebula/readme"><picture><source media="(prefers-color-scheme: dark)" srcset="site/public/img/sponsor-apinebula-dark.svg"><img src="site/public/img/sponsor-apinebula.svg" height="36" alt="APINEBULA"></picture></a>
|
||||
<a href="https://usemagpie.ai/go/zerotoken/readme"><picture><source media="(prefers-color-scheme: dark)" srcset="site/public/img/sponsor-zerotoken-dark.svg"><img src="site/public/img/sponsor-zerotoken.svg" height="36" alt="零词元"></picture></a>
|
||||
<a href="https://usemagpie.ai/go/apinebula/readme"><picture><source media="(prefers-color-scheme: dark)" srcset="site/public/img/sponsor-apinebula-dark.svg"><img src="site/public/img/sponsor-apinebula.svg" height="36" alt="APINEBULA"></picture></a>  <a href="https://usemagpie.ai/go/zerotoken/readme"><picture><source media="(prefers-color-scheme: dark)" srcset="site/public/img/sponsor-zerotoken-dark.svg"><img src="site/public/img/sponsor-zerotoken.svg" height="36" alt="零词元"></picture></a>
|
||||
|
||||
**[下载](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) · **简体中文**
|
||||
|
||||
|
||||
+16
-4
@@ -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_<publisher>\LocalCache\Local`, or `AnthropicPBC.Claude_<publisher>` 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
|
||||
|
||||
@@ -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 `Test<Agent>KeepsTheUsersSettings`.
|
||||
- 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.<var>`, 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)): `<model>=effort[,xhigh_effort][,max_effort]` for those it is shown, and, while Claude Desktop is on magpie, for Desktop's `mythos-magpie-<number>` 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/<model>`. 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/<name>/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:<distro>.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-<n>.anthropic.<model>`, 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-<n>`, an unknown model, and Haiku 4.5 got an effort Copilot refuses, #1819); a request for it is served by `<n>` 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-<n>.anthropic.<model>`, 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-<n>`, an unknown model, and Haiku 4.5 got an effort Copilot refuses, #1819); a request for it is served by `<n>` 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/<id>`, 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/<id>`, 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-<number>.anthropic.<model>` 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/<name>.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 <agent> …` is refused (`help_cli.go`; `TestHelpOnEveryCommandDoesNothing` walks `run`'s switch and every agent).
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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-<model>`) stay the
|
||||
groups magpie finds (a model two providers serve, `auto/<model>`) 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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 <id> 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 <id> 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 <id> 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 <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> '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://<host>/v1/projects/<project>/locations/<location>`, 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 <id>` 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
|
||||
`<id>.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
|
||||
`<id>.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
|
||||
|
||||
@@ -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-<slug>) is its auto/<model>
|
||||
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)) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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/<model> (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/<model> and group/auto-<slug> are one group
|
||||
}
|
||||
g, _ := provider.GroupFor(v)
|
||||
return g
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A group magpie found is listed as auto/<model> (provider.Group.Ref); it
|
||||
// was group/auto-<slug>, 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-<slug>, 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/<model> 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-<slug> onto the group's auto/<model>, 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-<slug> in it as the group's auto/<model>: 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
|
||||
}
|
||||
@@ -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-<slug>,
|
||||
// is moved onto the group's auto/<model> 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)
|
||||
}
|
||||
}
|
||||
+117
-13
@@ -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
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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" {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
+109
-5
@@ -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.")
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 ""
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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/<model> 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, "/")
|
||||
|
||||
@@ -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/<model>
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+107
-2
@@ -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 {
|
||||
|
||||
@@ -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})
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+12
-12
@@ -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/<model> as group/auto-<slug>;: 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 {
|
||||
// <id> +<model>` 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)
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 <id> family=%s makes one)",
|
||||
n, orNone(provider.Families()), n)
|
||||
|
||||
@@ -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/<model>
|
||||
// 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",
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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/<model> (ZeroClover on X), and
|
||||
// served by that id and by its old group/auto-<slug> 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/<model>, as the lists now give it, for an agent left on the
|
||||
// old id, and one naming the old id, or group/*, for auto/<model>. 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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\" \\ é 😀 <a>&\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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+55
-13
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}{
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+137
-11
@@ -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/<model> as group/auto-<slug>, 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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"}]}`)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
+27
-2
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 <b> & c"}`,
|
||||
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"a <b> & 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)
|
||||
}
|
||||
}
|
||||
@@ -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, "<provider>/<model>", whatever the agent
|
||||
// called it. A routing group passes when the key names it, "group/<id>"
|
||||
// (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/<model>
|
||||
// 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/<model> (as the model lists give it, any spelling of the
|
||||
// model) may use group/auto-<slug>, the id the gateway routes it by, and
|
||||
// one held to group/auto-<slug> or group/* the auto/<model> an agent asks
|
||||
// for, which the gateway takes back to that id (validateModel). A pattern
|
||||
// of auto/ ids ("auto/*") holds to the groups' auto/<model>.
|
||||
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
|
||||
|
||||
+302
-13
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"},
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
// "<general.architecture>.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})
|
||||
}
|
||||
@@ -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
|
||||
// <endpoint>/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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user