From 37c1bc043bf2a2e9dce90ff59d8b534930a5abe3 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 6 Nov 2026 18:02:03 +0800 Subject: [PATCH] agent: a group whose members all serve Responses, one best there, is asked on Responses zyh6036 on X: several subscriptions that all serve the Responses API were asked on Chat once they were put in a routing group. Pi, OmO, omp, StepCode, droid, dsh, Hermes, Grok CLI and the live agents ask each model on the one API catalog.Model.APIs names, and a group had Responses only when every member's Native was Responses (allResponses, #1594). A relay that serves Chat and Responses, best on Chat (no Base URL API given, not OpenAI's own host), counts as Chat there, so one such member put the whole group on Chat, and the gateway then translated Chat to Responses for the ChatGPT, Copilot GPT or Responses-relay members. Found groups (auto-) hit this without the user doing anything: a new relay that also lists gpt-5.5 moved auto/gpt-5.5 from openai-responses to Chat (pi_api_test shows it). provider.GroupAPI now gives Responses when one member is best on Responses and every other takes a Responses request as it is (Responses among the APIs it relays), or translates every request anyway (a Claude Code subscription). So no member is translated that Chat would have relayed, and the ones best on Responses are relayed, not translated from Chat. The gateway already relays a /v1/responses request to each member that serves it (usable), so nothing changes there. Mixed groups: a member that Responses doesn't reach (a Chat-only key, a Messages-only Claude) keeps the group on Chat, where that member is relayed; picking Responses there would translate it on every turn. A Messages-only group stays on Chat as before (#1594's reason: a Claude member's thinking is known by its own model id, not the group's). An agent plugin's connect is told a group's native_endpoints now (provider.GroupEndpoints: the APIs every member relays), where it had none. /v1/models still leaves them out for a group: TestRemoteMagpieNativeAPI holds that a remote magpie sends a group's request on in the client's API for the other side to pick per member. No setting added: the group's API follows from its members. Run (mote, through mote-run): - go test ./... -timeout 45m at 65780f04f on 49c9491b7, under the shared lock: every package ok except three reds, all filed and not in this change's path: internal/gateway TestBurstTellsNoSpeed/ responses_from_chat_burst (passes 3 of 3 alone; #2719, commented), internal/gui TestMainWindowCorners/macOS_26_SDK (#3949), internal/provider TestRenewLoginsKeepsClaudeReading (red alone too; #5481, on main). - After rebasing on fcc0daa23: go test ./internal/agent ./internal/catalog, ./internal/provider -run 'TestGroupAPI|TestNative|Group', ./internal/gateway -run 'Group|RemoteMagpie'; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...; gofmt -l empty. - Broken by hand: GroupAPI put back to "every member best on Responses": TestGroupAPI red (one best there plus one serving it too; the same second), TestPiModelsAskedOnTheirNativeAPI red (group/subs, and auto/gpt-5.5 once a Chat-first relay serves gpt-5.5). - New: TestGroupAPI (provider), TestGroupOfResponsesServersRelaysOnResponses (gateway: the Chat-first member is asked on /responses, relayed). Not tried: the reporter's own providers (not known: which subscriptions, which agent); a real Pi or dsh run against a real mixed-API group; the GUI (unchanged). --- docs/subsystems/agent-wiring.md | 4 +- internal/agent/agents.go | 2 +- internal/agent/pi_api_test.go | 19 +++- internal/agent/pi_group_effort_test.go | 2 +- internal/agent/route.go | 30 +++---- internal/catalog/catalog.go | 5 +- .../gateway/group_responses_relay_test.go | 39 +++++++++ internal/provider/group_api_test.go | 63 ++++++++++++++ internal/provider/native_endpoints.go | 87 +++++++++++++++++-- 9 files changed, 214 insertions(+), 37 deletions(-) create mode 100644 internal/provider/group_api_test.go diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 090213f10..03da1916c 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -31,7 +31,7 @@ something else shows up as drift. | WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `@wsl:`, edited through `\\wsl.localhost\`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) | | WSL folders that are links | Through `\\wsl.localhost` Windows can't follow a link the distro has: with `~/.codex` a link to `/mnt/c/Users//.codex`, a mkdir of it says it exists and nothing below it can be made, written, read or listed (#4502, linusxiong). The probe asks `readlink -f` there where each agent folder, its `skills` and the folders beside them lead (`wslLinkPaths`, `distro.Links`; a `$HOME` that is itself through a link is left as it was) and which drive each Windows mount is (`distro.Drives`). `distro.open` opens a path at or below a link where it leads: on a Windows drive the drive's own path (`C:\Users\\.codex`), elsewhere in the distro through its root again; `native` spells such a path back through the link for the agent. A link `readlink -f` couldn't resolve is never guessed at: its agent is unreached (`Agent.Unreached`), says why in its notice and refuses each change and sync. Every writer goes through it: the agents' own files (`place.join`, `place.open`), the library's targets (`wslOpen`, a `wsl` problem per agent), RTK (`rtkAt`, `agent.WSLOpen`), the Sessions page's reads (`sessions.WSLHome.Open`) and the Copilot CLI's sign-in (`provider.CopilotWSLDirs`). Links deeper than the probed paths aren't resolved (`TestWSLOpenThroughLinks`, `TestWSLAgentFolderIsALink`, `TestWSLAgentFolderLinkUnresolved`, `TestWSLProbeLinks`, `TestWSLFolderIsALinkToC`, `TestRTKWSLFolderIsALink`). | [`wsl.go`](../../internal/agent/wsl.go), [`targets.go`](../../internal/library/targets.go), [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) | | Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings..autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) | -| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. One whose agent keeps the model a new session starts on in a file apart from its provider list says so with `startup` (`config`, `format`, `model`, and `keys` written beside the model as they are) and has no `model`: PiG keeps its providers in `models.json` and `defaultProvider`/`defaultModel` in `settings.json` (str_ on Discord: its row only listed models, where Pi's picks the one it starts on). Its field is `model` again; picking one of magpie's writes `connect`'s keys into `config` and the model and `startup.keys` into `startup.config`, each file stashed under its own `plugin::` (the startup one marked by its first string key, so a model picked in the agent among magpie's, with `defaultProvider` still `magpie`, reads as magpie's). A model of the agent's own picked in it while `connect`'s keys are still in `config` is `Beside`: connected, not drift, and Disconnect leaves that pick and takes the rest out. A magpie without `startup` reads the same module as connect only (`TestPluggedStartupModel`, `TestPluggedStartupOwnPickKept`, `TestPluggedStartupRestoreGone`). `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`, carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) | +| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. One whose agent keeps the model a new session starts on in a file apart from its provider list says so with `startup` (`config`, `format`, `model`, and `keys` written beside the model as they are) and has no `model`: PiG keeps its providers in `models.json` and `defaultProvider`/`defaultModel` in `settings.json` (str_ on Discord: its row only listed models, where Pi's picks the one it starts on). Its field is `model` again; picking one of magpie's writes `connect`'s keys into `config` and the model and `startup.keys` into `startup.config`, each file stashed under its own `plugin::` (the startup one marked by its first string key, so a model picked in the agent among magpie's, with `defaultProvider` still `magpie`, reads as magpie's). A model of the agent's own picked in it while `connect`'s keys are still in `config` is `Beside`: connected, not drift, and Disconnect leaves that pick and takes the rest out. A magpie without `startup` reads the same module as connect only (`TestPluggedStartupModel`, `TestPluggedStartupOwnPickKept`, `TestPluggedStartupRestoreGone`). `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`; a routing group's, `provider.GroupEndpoints`, the APIs every member relays as it is; carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) | | Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL` and `--model` (no `--model` when the user gives one) while settings.json's model is still magpie's, and unchanged otherwise. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models by id with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) | | Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer), each minute while magpie serves; it never stops one running. `Check` reads the daemon's `operon.lock`, not `status` (seconds for a 130 MB Bun program), and calls a daemon with another pid drift: the app's window, opened while none ran, starts its own without the variable. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). | [`claudescience.go`](../../internal/agent/claudescience.go), [`science.go`](../../internal/gateway/science.go) | | Claude Code beside its own account | `claude-magpie` (baranwang on X) starts Claude Code through magpie while a plain `claude` stays on the user's own account, nothing switched back and forth. `magpie claude run [args…]` writes `/claude-launch/settings.json` as `claude#launch`, an agent `claudeIn` makes at that folder (`place.dir`) and lists nowhere, so the Agents page, Check and Notice see only the user's settings.json: connected the first time as Connect would (`ConnectHow`), set again when the gateway's address or key moved (`claudeLaunchStale`, the LAN key included), synced after that, with `ANTHROPIC_API_KEY` and the cloud switches (`agentenv.ClaudeProviders`) blanked. It then runs `claude --settings args…` as a child (not exec, so it can tidy after): Claude Code puts a --settings file's env and model over the user's settings.json, a claude.ai sign-in and the shell (tried on 2.1.318). `/model` saves to the user's settings.json, never the --settings file, so `ClaudeLaunchAfter` moves a magpie model picked there into the launch file and gives the user's file its model back while magpie isn't wired into it; it also undoes Claude Code's own one-time `opus` → `opus[1m]` rewrite (`migration_opus_to_opus1m`), which the launch file's 1M opus tier sets off. A Claude alias picked (`sonnet`) stays. On Unix a stopped child stops magpie too (^Z, fg), and its exit code is magpie's; on Windows magpie ignores Ctrl+C while claude runs. The command `claude-magpie` is a launcher beside the `magpie` command (`update.Launchers`): a `#!/bin/sh` `exec` of `Program()`, or on Windows a `.cmd` running `"%~dp0magpie"`. `AddCLI` writes it, and `magpie claude launcher add` puts it there for a command added before; a file by that name without `written by magpie` is never written over. StandIn falls back to the launch file's tiers. | [`claude_launch.go`](../../internal/agent/claude_launch.go), [`claude_launch_cli.go`](../../internal/cli/claude_launch_cli.go), [`claude_run_unix.go`](../../internal/cli/claude_run_unix.go), [`launcher.go`](../../internal/update/launcher.go) | @@ -78,7 +78,7 @@ something else shows up as drift. - The YAML ones go through `yamlKept` and `mergeKept` in [`sync.go`](../../internal/agent/sync.go). Each is tested by a `TestKeepsTheUsersSettings`. - Copilot in JetBrains IDEs keeps its Bring Your Own Key providers in the Copilot language server's `byok.json`, shared with Xcode's and Eclipse's Copilot (`copilotJetBrains` in [`copilotjetbrains.go`](../../internal/agent/copilotjetbrains.go)). magpie writes its own three keys there, `magpie-provider-config`, `magpie-api-key` and `magpie-models-config`, in the bytes the server itself writes, and only when they differ; the user's providers and keys stay. A magpie model the user hid in Manage Models (`isRegistered: false`) stays hidden through a sync. A new file is made 0600 in a 0700 folder, as the server makes it. - The Copilot CLI (1.0.105 tried) takes its own model providers from `providers.json` (BYOK; `copilot help providers`, [GitHub's docs](https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/use-byok-models)): `$COPILOT_PROVIDERS_CONFIG`, else beside `settings.json` in `$COPILOT_HOME` or `~/.copilot`. It needs no GitHub sign-in, and a model is picked as `/` in settings.json's `model`. Picking a magpie model writes the provider `magpie` (type `openai`, chat completions, the gateway's `/v1`, the agent's own key) and one `models` entry per model of magpie's, each with its name and limits (`copilotWrite` in [`copilot_byok.go`](../../internal/agent/copilot_byok.go)), then `model` as `magpie/`. Only the entries naming `magpie` are magpie's: the user's providers, models and any other key stay through connect, `Sync` (which follows the catalog while the file has the provider) and Disconnect, and a file that doesn't parse is left as it is with an error (`TestCopilotKeepsTheUsersOwn`, `TestCopilotUnreadableProvidersJSONIsNotWrittenOver`). Copilot's own models stay in the field's list beside magpie's. `COPILOT_PROVIDER_BASE_URL` in the environment, or an organization policy that forces a GitHub sign-in (`forceLoginOrgs`), takes over from the file; magpie sets neither. The multi-provider file is marked experimental in Copilot's SDK types (tony9759 on Discord). -- 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` or `AdaptiveWithEffort`, so Max reaches GLM-5.3 as max) 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. For a custom provider with more than one URL that is the API its Base URL was given as (`BaseAPI`), after the vendor rules (an OpenAI model on OpenAI's API, a Claude where Messages is served): a relay set to Responses whose Chat URL Detect found beside it had its GPTs on dsh's Chat route (nb5p on Discord, `TestDshCustomResponsesProvider`). dsh's bundled pi-ai (`@earendil-works/pi-ai`, dsh 0.2.1-rc.2) takes `openai-responses` as a route's `api`. 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. A model of a route whose api stands as `openai-responses` carries `compat.supportsStrictMode` (#3055): OpenAI's Responses API takes a function tool whose `strict` is left out as a strict-mode one, every property required, so a tool's optional parameters come back filled; pi-ai says `strict: false` on an ordinary tool only when the compat says so, by the api the route has, not by its name. 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. A start on a model by an id magpie lists it by no longer, a found group's `group/auto-` (now `auto/`, `provider.PublicRef`) or a renamed provider's (`provider.RenamedRef`), moves onto the id its route lists, in every profile and the home layer: dsh finds the start by that id, and the desktop app showed no model picked while its patch list held every route (zyh6036 on X, `TestDshStartOnAFoundGroupsOldIdMovesOntoItsId`). `renameFoundGroups` moves only a value applied.json records, and the start dsh read was not one (none on the owner's install either), nor is a pick made in dsh. 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. +- 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` or `AdaptiveWithEffort`, so Max reaches GLM-5.3 as max) 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. For a custom provider with more than one URL that is the API its Base URL was given as (`BaseAPI`), after the vendor rules (an OpenAI model on OpenAI's API, a Claude where Messages is served): a relay set to Responses whose Chat URL Detect found beside it had its GPTs on dsh's Chat route (nb5p on Discord, `TestDshCustomResponsesProvider`). dsh's bundled pi-ai (`@earendil-works/pi-ai`, dsh 0.2.1-rc.2) takes `openai-responses` as a route's `api`. A routing group has `responses` when a member is best on Responses and every other member takes a Responses request as it is too, or translates every request anyway (`provider.GroupAPI`, #1594; zyh6036 on X: a group of subscriptions that all serve Responses, not all best there, was asked on Chat), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, so a member only Chat reaches keeps being relayed, and a Messages-only group stays there 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. A model of a route whose api stands as `openai-responses` carries `compat.supportsStrictMode` (#3055): OpenAI's Responses API takes a function tool whose `strict` is left out as a strict-mode one, every property required, so a tool's optional parameters come back filled; pi-ai says `strict: false` on an ordinary tool only when the compat says so, by the api the route has, not by its name. 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. A start on a model by an id magpie lists it by no longer, a found group's `group/auto-` (now `auto/`, `provider.PublicRef`) or a renamed provider's (`provider.RenamedRef`), moves onto the id its route lists, in every profile and the home layer: dsh finds the start by that id, and the desktop app showed no model picked while its patch list held every route (zyh6036 on X, `TestDshStartOnAFoundGroupsOldIdMovesOntoItsId`). `renameFoundGroups` moves only a value applied.json records, and the start dsh read was not one (none on the owner's install either), nor is a pick made in dsh. 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. - The names every agent's model list gets are `provider.Labels`' ([`modelprefs.go`](../../internal/provider/modelprefs.go)). With Provider in model names off (or own, for names the user gave), a name stands alone unless another model in the same list reads the same, when both keep their provider's after it. A routing group named as anything else in the list keeps "· routing group", and the model it shares the name with stays plain: the group found for a model served by two providers, one of them hidden from the agent, had the shown model read "GPT-6.1 Terra · MyGateway" beside its provider's plain "GPT-6.1 Sol" (nb5p on Discord; `TestPlainNames`, `TestSuffixMode`, `TestPlainOwnNamesGroups`). - dsh takes a model's listed `maxTokens` as every request's output and reserves it, with 65536 of headroom, out of `contextWindow` before deciding when to compact (compaction-basic's `resolveCompactSpec`: the smaller of 80% of the window and window − maxTokens − 65536). A vendor's reply limit near its window had dsh compact at 41248 of a 500000 group (#2823) or fail with no budget (524288/524288, LoKi on Discord; 131072/65536), so magpie lists it held to what leaves dsh half the window to compact in (window/2 − 65536), or to a quarter of the window where that is more (every window under 262144, as VS Code and Copilot in JetBrains hold it), on every route and in the older `llm-deepseek` entry (`dshMaxTokens`). A quarter alone cut DeepSeek's 393216 on its 1000000 window to 250000 (#3298); now it keeps all of it and dsh compacts at 541248, while 500000/393216 is held to 184464 and compacts at 250000. A Max output the user set stays as they set it (`outputOr`), even one that leaves dsh no budget. `TestDshOutputLeavesCompactionRoom`. - Each of magpie's routes has `streamIdleTimeoutMs: 600000` (`dshIdleWait`), the gateway's own wait for a reply's headers (`upstreamHeaderWait`, 10 minutes). llm-pi-ai gives a turn up after 5 minutes without a pi-ai event (`DEFAULT_STREAM_IDLE_TIMEOUT_MS`, 0.1.5 to 0.2.2), and the gateway's `: keepalive` comments (`keepQueued`, `keepQuiet`) are not events: real dsh 0.2.1-rc.2 timed out at a route's 3000ms with comments every second. A turn queued behind dsh's own title request on a plugin serving one request at a time (magpie-gemini-web, `maxConcurrency: 1`) was cut while the gateway and the plugin still waited, and recorded as 499 (tim on Discord). A value already on the route, set in dsh or by hand, stays (`TestDshRoutesWaitAsLongAsTheGateway`, `TestDshRouteKeepsTheUsersIdleWait`). Codex's comment-blind limit is met in the gateway instead (`agentQuietMost`). diff --git a/internal/agent/agents.go b/internal/agent/agents.go index fb0ded69a..ba7bddd96 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -860,7 +860,7 @@ func piModelJSON(m catalog.Model, gw string, native bool) map[string]any { e["promptCache"] = c } else if native && e["api"] == nil { // a routing group has no api of its own (a Messages-only group stays - // on Chat, allResponses), and went out with no promptCache, which + // on Chat, provider.GroupAPI), and went out with no promptCache, which // stops Pi's cacheWarming with "cache lifetime unavailable" (#5037) // — while whatever Claude member it picks has the gateway's own // translation marking the request ephemeral for five minutes diff --git a/internal/agent/pi_api_test.go b/internal/agent/pi_api_test.go index 5c73aa864..81c98b00e 100644 --- a/internal/agent/pi_api_test.go +++ b/internal/agent/pi_api_test.go @@ -13,8 +13,9 @@ import ( // relays the request as it is: a Responses-only provider's models and GPT // on OpenAI's API go on openai-responses; a Messages-only provider's on // anthropic-messages at the gateway; a Chat provider's stay on the -// provider's openai-completions. A group whose members are all best on -// Responses goes there too (#1594); any other group stays on Chat. +// provider's openai-completions. A group goes on Responses when a member +// is best there and every other serves it too (#1594, zyh6036 on X); any +// other group stays on Chat. func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { home := syncHome(t) for _, p := range []provider.Provider{ @@ -23,6 +24,8 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { {ID: "anth", Name: "Anth", Key: "k", Anthropic: "http://127.0.0.1:1", Models: []string{"claude-sonnet-5", "kimi-k3"}}, {ID: "gem", Name: "Gemini", Key: "k", Gemini: "http://127.0.0.1:1/v1beta", Models: []string{"gemini-3-flash"}}, {ID: "hybrid", Name: "Hybrid", Key: "k", Chat: "http://127.0.0.1:1/v1", Gemini: "http://127.0.0.1:1/v1beta", Models: []string{"gemini-3-flash", "gemini-2.5-pro"}}, + // a relay serving Chat and Responses, best on Chat + {ID: "both", Name: "Both", Key: "k", Chat: "http://127.0.0.1:1/v1", Responses: "http://127.0.0.1:1/v1", Models: []string{"gpt-5.5"}}, } { if err := provider.Save(p); err != nil { t.Fatal(err) @@ -31,14 +34,19 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { if err := provider.SetModelAPI("hybrid/gemini-3-flash", "gemini"); err != nil { t.Fatal(err) } - // a group goes on Responses only when every member is best served there - // (#1594): one with a Chat member, or of Messages ones, stays on Chat + // a group goes on Responses when a member is best served there and + // every other serves it too (#1594): one with a Chat-only member, or of + // Messages ones, stays on Chat for _, g := range []provider.Group{ {ID: "gpts", Name: "GPTs", Members: []string{"resp/gpt-5.5", "openai/gpt-5.5", "resp/grok-5"}}, {ID: "mixed", Name: "Mixed", Members: []string{"resp/grok-5", "relay/glm-4.6"}}, {ID: "claudes", Name: "Claudes", Members: []string{"anth/claude-sonnet-5", "anth/kimi-k3"}}, {ID: "outer", Name: "Outer", Members: []string{"group/gpts", "openai/gpt-5.5"}}, {ID: "geminis", Name: "Geminis", Members: []string{"gem/gemini-3-flash"}}, + // zyh6036 on X: every member serves Responses, one is best there + {ID: "subs", Name: "Subs", Members: []string{"both/gpt-5.5", "resp/gpt-5.5"}}, + // none is best there: each stays relayed on Chat + {ID: "chatfirst", Name: "Chat first", Members: []string{"both/gpt-5.5"}}, } { if err := provider.SaveGroup(g); err != nil { t.Fatal(err) @@ -80,6 +88,9 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { "group/mixed": nil, "group/claudes": nil, "group/geminis": nil, + "both/gpt-5.5": nil, + "group/subs": "openai-responses", + "group/chatfirst": nil, } { got, ok := apis[id] if !ok { diff --git a/internal/agent/pi_group_effort_test.go b/internal/agent/pi_group_effort_test.go index c751b24bb..2881e4805 100644 --- a/internal/agent/pi_group_effort_test.go +++ b/internal/agent/pi_group_effort_test.go @@ -98,7 +98,7 @@ func TestPiGroupThinkingIsWhatPiRuns(t *testing.T) { } // #5037: a routing group has no api of its own — a Messages-only group -// stays on Chat (allResponses) — so its entry went out with no promptCache +// stays on Chat (provider.GroupAPI) — so its entry went out with no promptCache // and Pi's cacheWarming stopped with "cache lifetime unavailable". Whatever // Claude member the group picks, the gateway's own translation marks the // request ephemeral for five minutes, so the group declares that short diff --git a/internal/agent/route.go b/internal/agent/route.go index ff114fb69..6271f7309 100644 --- a/internal/agent/route.go +++ b/internal/agent/route.go @@ -371,8 +371,9 @@ func buildModels(agent string) []catalog.Model { m.ImageInput = &yes } // APIs is the preferred client protocol, preserving the vendor's - // own content where possible. A group's members may differ, so a group has - // one only when every member is served best on Responses (#1594, + // own content where possible. A group's members may differ, so a + // group has Responses when one member is best there and every + // other takes it as it is too (provider.GroupAPI; #1594, // ObsidianArch02): Pi, omp, droid and dsh then ask it there, and a // GPT group's tool-call arguments stream as the member sends them // instead of being held for a Chat answer @@ -390,8 +391,8 @@ func buildModels(agent string) []catalog.Model { } } } - } else if allResponses(members(e.ID)) { - m.APIs = []string{string(provider.Responses)} + } else if api := provider.GroupAPI(members(e.ID)); api != "" { + m.APIs = []string{string(api)} } // the service tiers Codex is offered on it, as the gateway's own // lists offer them: Fast in the Codex CLI magpie writes @@ -405,6 +406,13 @@ func buildModels(agent string) []catalog.Model { // the gateway paths it goes on untranslated, as /v1/models says // them: what an agent plugin's connect is told (cleary5779) m.Endpoints = provider.NativeEndpoints(e) + if e.Group != "" { + // a group's, the APIs every member relays as it is + // (provider.GroupEndpoints), which /v1/models leaves out: a + // remote magpie sends a group's request on in the client's + // API, for the other side to pick per member + m.Endpoints = provider.GroupEndpoints(members(e.ID)) + } // Codex's /fast on a ChatGPT account's own GPT model, which // OpenCode has no command for and takes as variants (#2379); a // group is sent fast as the group says, as a fast pick is @@ -431,20 +439,6 @@ func describedNow() bool { var builtSeen stampedLists[bool] -// allResponses reports whether a group's members are all served best on -// Responses, so the gateway relays a Responses request to whichever it -// picks. A group with none, or one member on another API, is false: a -// Messages-only group stays on Chat too, as the thinking a Claude member -// takes is known by its own model, not by the group's id. -func allResponses(ms []provider.Member) bool { - for _, m := range ms { - if m.Provider.Native(m.Model) != provider.Responses { - return false - } - } - return len(ms) > 0 -} - // maxTokens is the output limit an agent is handed for m, kept within the // context window it is handed with it: models.dev lists some models' output // above their window (deepseek-chat's 384000 against 128000). An unknown diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 5d407b9b3..5880d0996 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -48,8 +48,9 @@ type Model struct { APIs []string `json:",omitempty"` // Endpoints, in magpie's own models for an agent, are the gateway // paths a request for it is relayed on as it is - // (provider.NativeEndpoints, /v1/models' native_endpoints); none for a - // group or a model translated anyway. + // (provider.NativeEndpoints, /v1/models' native_endpoints); a group's + // are those every member relays (provider.GroupEndpoints), which + // /v1/models leaves out; none for a model translated anyway. Endpoints []string `json:"-"` // Images is set on a model that takes images as input. Images bool `json:",omitempty"` diff --git a/internal/gateway/group_responses_relay_test.go b/internal/gateway/group_responses_relay_test.go index cb68306a4..72e8de7e4 100644 --- a/internal/gateway/group_responses_relay_test.go +++ b/internal/gateway/group_responses_relay_test.go @@ -4,6 +4,7 @@ import ( "io" "net/http" "net/http/httptest" + "slices" "strings" "sync" "testing" @@ -63,3 +64,41 @@ func TestGroupOnResponsesRelaysArgumentDeltas(t *testing.T) { t.Fatalf("the member was asked on %v", paths) } } + +// A group of members that all serve Responses, one best there, is asked +// on Responses (provider.GroupAPI; zyh6036 on X), and the gateway relays +// it as it is to each: the relay best on Chat that serves Responses too is +// asked on /responses, not translated to Chat. +func TestGroupOfResponsesServersRelaysOnResponses(t *testing.T) { + fresh(t) + var mu sync.Mutex + var paths []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + mu.Lock() + paths = append(paths, r.URL.Path) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"r1","object":"response","model":"gpt-5.5","status":"completed","output":[{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"hello"}]}],"usage":{"input_tokens":3,"output_tokens":1}}`) + })) + defer up.Close() + for _, p := range []provider.Provider{ + {ID: "resp", Name: "Resp", Key: "k", Responses: up.URL + "/v1", Models: []string{"gpt-5.5"}}, + {ID: "both", Name: "Both", Key: "k", Chat: up.URL + "/v1", Responses: up.URL + "/v1", Models: []string{"gpt-5.5"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{ID: "subs", Name: "Subs", Members: []string{"both/gpt-5.5", "resp/gpt-5.5"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + // the member best on Chat, first in the group, is asked on /responses + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"group/subs","input":"hi"}`))) + mu.Lock() + defer mu.Unlock() + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hello") || !slices.Equal(paths, []string{"/v1/responses"}) { + t.Fatalf("the group was asked on %v: %d %s", paths, rec.Code, rec.Body) + } +} diff --git a/internal/provider/group_api_test.go b/internal/provider/group_api_test.go new file mode 100644 index 000000000..a1d20dda6 --- /dev/null +++ b/internal/provider/group_api_test.go @@ -0,0 +1,63 @@ +package provider + +import ( + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +// A routing group is asked on Responses when one member is best there and +// every other takes a Responses request as it is too, or translates every +// request anyway (zyh6036 on X: subscriptions that all serve Responses +// were asked on Chat in a group, as only a group all of whose members were +// best on Responses went there, #1594). A member Responses doesn't reach +// keeps the group on Chat, where it is relayed. +func TestGroupAPI(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + catalog.Reset() + t.Cleanup(catalog.Reset) + resp := Provider{ID: "resp", Responses: "http://127.0.0.1:1/v1"} // best on Responses + both := Provider{ID: "both", Chat: "http://127.0.0.1:1/v1", Responses: "http://127.0.0.1:1/v1"} // Chat first, Responses too + chat := Provider{ID: "chat", Chat: "http://127.0.0.1:1/v1"} + anth := Provider{ID: "anth", Anthropic: "http://127.0.0.1:1"} + claude := Provider{ID: "claude", Anthropic: "http://127.0.0.1:1", Account: &Account{Agent: "claude"}} // translated anyway + of := func(ps ...Provider) []Member { + var ms []Member + for _, p := range ps { + ms = append(ms, Member{Provider: p, Model: "gpt-5.5"}) + } + return ms + } + if n := both.Native("gpt-5.5"); n != Chat { + t.Fatalf("the Chat-first relay's GPT is best on %q; the cases below assume Chat", n) + } + for _, c := range []struct { + name string + ms []Member + api Protocol + endpoints []string + }{ + {"all best on Responses", of(resp, resp), Responses, []string{"/v1/responses"}}, + {"one best there, one serving it too", of(resp, both), Responses, []string{"/v1/responses"}}, + {"the one best there second", of(both, resp), Responses, []string{"/v1/responses"}}, + {"with a subscription translated anyway", of(resp, claude), Responses, nil}, + {"none best on Responses", of(both, both), "", []string{"/v1/chat/completions", "/v1/responses"}}, + {"a Chat-only member", of(resp, chat), "", nil}, + {"a Messages-only member", of(resp, anth), "", nil}, + {"Messages-only", of(anth, anth), "", []string{"/v1/messages"}}, + {"no members", nil, "", nil}, + } { + if got := GroupAPI(c.ms); got != c.api { + t.Errorf("%s: API %q, want %q", c.name, got, c.api) + } + if got := GroupEndpoints(c.ms); !slices.Equal(got, c.endpoints) { + t.Errorf("%s: endpoints %v, want %v", c.name, got, c.endpoints) + } + } +} diff --git a/internal/provider/native_endpoints.go b/internal/provider/native_endpoints.go index b9570527b..47ff92642 100644 --- a/internal/provider/native_endpoints.go +++ b/internal/provider/native_endpoints.go @@ -2,23 +2,92 @@ package provider import "slices" +// endpointOf is the gateway path a protocol is asked at. +var endpointOf = map[Protocol]string{Chat: "/v1/chat/completions", Responses: "/v1/responses", Anthropic: "/v1/messages"} + // NativeEndpoints are the paths a request for the model is relayed on to // its provider as it is (/v1/models' and an agent plugin's connect's -// "native_endpoints"): the APIs the provider serves it on. None for a -// routing group, whose members may speak any, or a model every request -// to is translated anyway (a subscription served through its agent's own -// API). +// "native_endpoints"): the APIs the provider serves it on. A routing +// group's are GroupEndpoints, which need its members; none here. None +// either for a model every request to is translated anyway (a +// subscription served through its agent's own API). func NativeEndpoints(e Entry) []string { - p := e.Provider - if e.Group != "" || p.Native(e.Model) == "" { + if e.Group != "" { return nil } - apis := p.APIs(e.Model) - var out []string + return endpointsOf(relayed(e.Provider, e.Model)) +} + +// relayed are the APIs p takes a request for model on as it is, in the +// order p speaks them: none for a model every request to is translated +// anyway. +func relayed(p Provider, model string) []Protocol { + if p.Native(model) == "" { + return nil + } + apis := p.APIs(model) + var out []Protocol for _, pr := range p.Speaks() { if slices.Contains(Protocols, pr) && (apis == nil || slices.Contains(apis, pr)) { - out = append(out, map[Protocol]string{Chat: "/v1/chat/completions", Responses: "/v1/responses", Anthropic: "/v1/messages"}[pr]) + out = append(out, pr) } } return out } + +func endpointsOf(prs []Protocol) []string { + var out []string + for _, pr := range prs { + out = append(out, endpointOf[pr]) + } + return out +} + +// GroupEndpoints are the paths a request for a routing group is relayed +// on as it is to whichever of its members ms answers it: the APIs every +// member takes it on. None when a member translates every request anyway, +// or the members share no API. +func GroupEndpoints(ms []Member) []string { + var common []Protocol + for i, m := range ms { + r := relayed(m.Provider, m.Model) + if i == 0 { + common = r + continue + } + common = slices.DeleteFunc(common, func(pr Protocol) bool { return !slices.Contains(r, pr) }) + } + return endpointsOf(common) +} + +// GroupAPI is the API an agent that asks each model on one API is wired +// to ask a routing group on, "" for Chat. It is Responses when a member +// is served best there (a ChatGPT sign-in, GPT on OpenAI's API or +// Copilot's, a relay given as a Responses URL) and every other member +// takes a Responses request as it is too, or translates every request +// anyway (a Claude Code subscription): no member is then translated that +// Chat would have relayed, and the ones best on Responses are relayed +// instead of translated from Chat (zyh6036 on X: a group of +// subscriptions that all serve Responses was asked on Chat, as only a +// group whose members were all best there went on Responses, #1594). A +// group with a member Responses doesn't reach (a Chat-only key, a +// Messages-only Claude) stays on Chat, so that member keeps being +// relayed; a Messages-only group stays on Chat too, as the thinking a +// Claude member takes is known by its own model, not by the group's id. +func GroupAPI(ms []Member) Protocol { + best := false + for _, m := range ms { + n := m.Provider.Native(m.Model) + if n == "" { + continue + } + if !slices.Contains(relayed(m.Provider, m.Model), Responses) { + return "" + } + best = best || n == Responses + } + if best { + return Responses + } + return "" +}