diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index d298b6012..d31562456 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -106,7 +106,7 @@ recorded as a prediction failure (`noPrediction`). - An agent's fast pick (`settings.FastPicks`, the bolt in its picker, #954) may also be in `settings.UltraPicks` (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (`provider.CanUltra`, `UltraModels`). `fastPick` marks its candidates `ultra`; a try of one goes with `service_tier: "ultrafast"` on Chat and Responses, and an agent on Messages carries it in the context (`withUltra`) to `forwardTranslated`, which sets `Request.Ultrafast` for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (`tierMate`), or, with none left, sent `priority`. A Chat body's own `service_tier: "ultrafast"` is parsed as Ultrafast too (`chat.go`). `TestUltraPickSentUltrafast`. - A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`. - A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes. -- A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Devin, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. +- A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A 2xx from Zhipu or Z.ai holding the platform's refusal envelope (`{"code":1000,"msg":…,"success":false}`, which their Responses API at `/api/v1` answers a refused key) is the refusal it stands for (`provider.ZhipuEnveloped` in `forwardOnce`): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. `TestZhipuResponsesRefusalIsRefusal`. - A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`; whatever a relayed stream gets appended, that error or a filled-in `finish_reason`, begins after a blank line, two newlines when the upstream's last write stopped inside a line, so it is an event of its own rather than more of the half-written one, #2446, `TestPassthroughStreamCutMidLine`, `TestGeminiCompatFinishAfterPartialLine`), and a Chat one from Gemini's OpenAI-compatible API (`geminiCompat`) with no `finish_reason`, relayed or translated (`saysItsEnd`; Linka on Discord: the upstream hung up between a whole function call and its `finish_reason`, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the `finish_reason` was lost and it is filled in, `tool_calls` after a call and `stop` otherwise, as a relayed chunk before `[DONE]` or a translated reply's end, and the reply counts as whole (`chatTail`); only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A reply passed through in its own protocol isn't read this way. - A vendor's error keeps its `code` and `param` on its way to an OpenAI-shaped client (`writeVendorError`), where `writeError` used to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream's `error` event or failed response whose error is of type `invalid_request_error` is the request at fault (`requestRefused`, read by its type, not its words): its `Event` carries status 400 and the vendor's error (`Event.Said`), so a client answered whole gets the vendor's 400 with its code and param (the whole-translated path wrote 502 `api_error`), a reply cut by it isn't resumed (`continuation.again`), and a translated stream's error says the vendor's type, code and param (`saidError`), so `holdWriter` reads it as the 400 it is. Before, the hold read magpie's `api_error` as a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answers `access_programs` naming a program the workspace hasn't got with a 200 stream whose error is `access_program_not_enabled`). Asked once, nobody rests ([`codex_access_programs_test.go`](../../internal/gateway/codex_access_programs_test.go)). @@ -153,8 +153,8 @@ recorded as a prediction failure (`noPrediction`). - A Messages upstream that wants a turn's thinking back (`anthropicReplaysThinking` in [`anthropic.go`](../../internal/gateway/anthropic.go): a host or a model with `deepseek` in it, never `api.anthropic.com` or a Claude model) gets a thinking block on every assistant message with a `tool_use` or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (`withThinkingOnToolTurns` in `passthrough`) or translated (`build`, which also keeps unsigned thinking as its text there). DeepSeek's `/anthropic/v1/messages`, thinking (its default, or asked for), turns the whole request away with 400 "The `content[].thinking` in the thinking mode must be passed back to the API" when such a message has none, and answers any `redacted_thinking` with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (`noReasoning`) first; Claude's `redacted_thinking` becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. - A Grok model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last `/` segment beginning with `grok` (`grokModel`, `grokServed`), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: `2500.0` becomes `2500`, `-3.00` becomes `-3`. Strings, keys, other fractions (`2.5`, `2.50`) and exponents (`1.0e3`) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (`wholeNums`), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in `passthrough` by `intTidy`: Responses' function_call items, argument deltas and done events and the completed response; Chat's `tool_calls` deltas and messages; Messages' `tool_use` input and `input_json_delta`, streamed or whole. Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`) when `Request.Grok` is set. Any other model's reply is relayed byte for byte ([`grok_integral.go`](../../internal/gateway/grok_integral.go)). - A tool call a model writes into its reply's text, when the request offered tools, is made the call it is ([`textcalls.go`](../../internal/gateway/textcalls.go), #823): Hermes' `{…}`, DeepSeek's DSML (`<|DSML|invoke name=…>` with its parameters; its mark found as the parse regexes read it, by `dsmlMark`, not from a list of spellings: any run of pipes, ASCII or full-width or mixed, spaces after `<` and around `/`, `<||DSML||` too, #2623), DeepSeek's half-Hermes `` form (#917) and GLM's ``/`` (#906), read by `parseTextCalls`. Each block must name an offered tool and have arguments that can be read; else the text goes on as it came. The text before the first block is kept, what is left of the tags goes, and the reply ends as one that called tools (`finish_reason` `tool_calls`, `stop_reason` `tool_use`). A reply whose model made a call itself is left alone. Every route reads it the same way: a relayed Chat stream (`textCallTidy`), a relayed Chat reply that came whole, JSON or under `text/plain` or no type (`chatWhole` with `wholeTextCalls`, #1845: a `stream:false` request kept the markup and `finish_reason` `stop`), which also covers a vendor that answered a streamed request whole (`wholeAsStream`), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses or Messages upstream's text is not read for calls. Covered by `TestTextWritten*`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`. -- Structured output is carried across every translation (`Format`, [`format.go`](../../internal/gateway/format.go)). It is read from Responses' `text.format`, Chat's `response_format`, Anthropic's `output_config.format` and Gemini's `responseMimeType` with `responseJsonSchema`/`responseSchema`: `json_schema` with its name, description, schema and strict, or `json_object`. Each upstream is asked in its own field: `text.format` on Responses, `response_format` on Chat, `output_config.format` on Messages, and `generationConfig.responseMimeType`/`responseJsonSchema` on Gemini and Code Assist. An API with no name for it gets `response`. Messages and the Claude subscription's `--json-schema` take a schema only, so `json_object` is told in the system prompt there (`inSystem`). The bridges to a vendor's own API (Cursor, Devin, Kiro, Qoder, Command Code) are always told in the system prompt. A 400 or 422 that names the field (`refusesFormat`: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (`formatRefused`), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. A model may still wrap its JSON answer in a Markdown code fence; a client that asked for structured output, in a field or told in the system prompt (`wantsJSON`), gets the JSON inside a single unlabelled or json-labelled fence when that content is a complete valid JSON value, streamed (`fenceEncoder`) or whole (`unfencedResult`), in [`format_fence.go`](../../internal/gateway/format_fence.go). Invalid or truncated JSON, other fence languages, text outside the fence, and answers to plain-text clients reach the client as they came. This normalization applies to translated replies; native protocol passthrough stays byte-preserving. -- A tool's images reach the model on every translation (`toolOutput` in [`ir.go`](../../internal/gateway/ir.go) reads them from Anthropic's `tool_result`, Responses' `function_call_output`, such as Codex's `view_image` output `[{"type":"input_image","image_url":"data:…"}]`, and a Chat tool message). Anthropic's Messages keeps them in the `tool_result`. Chat, Qoder and Cursor (`cursorImage`) put them in a user message right after the results, and the result says they follow. Command Code puts them in the user's turn after the results, Gemini and Code Assist after the function's response, and Devin in its tool message. Kiro's results hold text alone, so Kiro (the built-in, and its plugin from 0.1.9 on) sends them with the message that answers the call, and only the latest images go again (#369, #1861). `TestCodexToolImageReachesAnthropicPlugin`, `TestCodexToolImageKiro`, `TestCodexToolImageCursor`, and the plugin's `tool-images.test.mjs`. +- Structured output is carried across every translation (`Format`, [`format.go`](../../internal/gateway/format.go)). It is read from Responses' `text.format`, Chat's `response_format`, Anthropic's `output_config.format` and Gemini's `responseMimeType` with `responseJsonSchema`/`responseSchema`: `json_schema` with its name, description, schema and strict, or `json_object`. Each upstream is asked in its own field: `text.format` on Responses, `response_format` on Chat, `output_config.format` on Messages, and `generationConfig.responseMimeType`/`responseJsonSchema` on Gemini and Code Assist. An API with no name for it gets `response`. Messages and the Claude subscription's `--json-schema` take a schema only, so `json_object` is told in the system prompt there (`inSystem`). The bridges to a vendor's own API (Cursor, Kiro, Qoder, Command Code) are always told in the system prompt. A 400 or 422 that names the field (`refusesFormat`: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (`formatRefused`), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. A model may still wrap its JSON answer in a Markdown code fence; a client that asked for structured output, in a field or told in the system prompt (`wantsJSON`), gets the JSON inside a single unlabelled or json-labelled fence when that content is a complete valid JSON value, streamed (`fenceEncoder`) or whole (`unfencedResult`), in [`format_fence.go`](../../internal/gateway/format_fence.go). Invalid or truncated JSON, other fence languages, text outside the fence, and answers to plain-text clients reach the client as they came. This normalization applies to translated replies; native protocol passthrough stays byte-preserving. +- A tool's images reach the model on every translation (`toolOutput` in [`ir.go`](../../internal/gateway/ir.go) reads them from Anthropic's `tool_result`, Responses' `function_call_output`, such as Codex's `view_image` output `[{"type":"input_image","image_url":"data:…"}]`, and a Chat tool message). Anthropic's Messages keeps them in the `tool_result`. Chat, Qoder and Cursor (`cursorImage`) put them in a user message right after the results, and the result says they follow. Command Code puts them in the user's turn after the results, Gemini and Code Assist after the function's response. Kiro's results hold text alone, so Kiro (the built-in, and its plugin from 0.1.9 on) sends them with the message that answers the call, and only the latest images go again (#369, #1861). `TestCodexToolImageReachesAnthropicPlugin`, `TestCodexToolImageKiro`, `TestCodexToolImageCursor`, and the plugin's `tool-images.test.mjs`. - Group members are `provider/model[:effort]`. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671). - A group offers agents the reasoning levels its members have in common (`groupEntries` in [`group.go`](../../internal/provider/group.go)), or the ones it names (`Group.Levels`, #295). A member that doesn't follow the agent's effort is left out of that: one fixed at an effort, one whose levels nothing knows (#597), one that thinks with no levels, one the user made reasonless, and one known not to think (`Entry.Quiet`), which the gateway sends no reasoning ask (`withoutReasoningAsk`, [`quiet.go`](../../internal/gateway/quiet.go)). A quiet member used to empty the group's levels, so Codex got its entry with no `supported_reasoning_levels`, showed no effort control and ran at its own medium (#2127, `TestGroupQuietMemberKeepsCodexEffortControl`). - An agent whose config can't carry an effort has one picked in magpie (`provider.AgentEffort`, settings' `agentEfforts`; Cursor Private Inference's row, #1003). It is asked for on that agent's requests to a model that reasons (`Provider.Thinks`), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then the effort the rule that put the member first sets (`Rule.UseEffort`), then a model's `:effort` suffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor. @@ -166,7 +166,7 @@ recorded as a prediction failure (`noPrediction`). - A model the user ticked no levels of (`ModelReasonless` in [settings](../../internal/settings/settings.go), `SetModelReasonless`; the provider editor's Names & levels, or `magpie model efforts off`) is sent no reasoning field on any route, whatever the agent asks: the candidate loop strips the body with `withoutAnyReasoning` ([`quiet.go`](../../internal/gateway/quiet.go): Chat's `reasoning_effort`, `reasoning`, `thinking`, `enable_thinking` and `include`'s `reasoning.encrypted_content`, Responses' `reasoning`, Anthropic's `thinking` of any type and `output_config.effort`, Gemini's `thinkingConfig`), the Anthropic relay doesn't add `thinking:{type:disabled}` for it, and `forwardTranslated` clears `Effort`, `ThinkOff` and `Thinking` for its other callers. It offers no levels (`Efforts`, `entryFor`), is `Quiet`, and as a routing-group member doesn't take the group's levels away. The learned refusals above cover only reasoning *off* and Gemini levels; a vendor that answers a plain `reasoning_effort` with 422 (yuexian7 on Discord) is not learned, so this is the user's switch. `TestReasonlessModelSentNoReasoning`, `TestReasonlessAnthropicRelay`, `TestGroupReasonlessMemberKeepsLevels`, `model-reasonless.test.cjs`. - A request to an Anthropic endpoint with `temperature`, `top_p` or `top_k` reaches a model that refuses them without them (`samplingAsTaken`, beside `thinkingOffAsTaken` in `forwardOnce`): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "`temperature` is deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (`samplingDeprecated`), is asked again without them, once — a Chat or Responses client's request translated to Messages (`forwardTranslated`) as much as a relayed one. - Claude Code's auto mode asks the API to review each action ([`automode.go`](../../internal/gateway/automode.go), Anthropic's [auto-mode-classifier-billing](https://code.claude.com/docs/en/auto-mode-classifier-billing)): the `dangerous-tool-use-…` beta, a `safeguards` field, and `safeguard_results` in the reply (a stream's in its `message_delta`). Only Anthropic runs that classifier, so they reach only a route it answers on (`AutoModeReviewed`): the Claude subscription (the bridge hands them to Claude Code's own binary), a Claude model under any vendor's spelling on a provider with a key (Anthropic's API, a relay, Bedrock, Vertex), and anything on `api.anthropic.com`. Another subscription's or a plugin's Claude model (Copilot, Kiro, Cursor…) is that vendor's service and isn't reviewed by its name: Copilot turns `safeguards` away (#1756), the others translate the request, so neither the beta nor `safeguards` is sent there (`TestAutoModeReviewedRoutes`, `TestAutoModeReviewLeftOffOtherSubscriptions`). There the beta, `safeguards` and the results pass as sent, a whole reply's results moved into a stream's `message_delta` (`anthropicWholeEvents`), tool-use ids unchanged. To any other model they are taken off (`serverReview`; a translation never carries them), and magpie never answers a result on Anthropic's behalf. Claude Code then classifies locally and names the gateway in a notice; the wiring turns the review off in its settings while no model it can reach through magpie is reviewed (`claudeReviewEnv`, [agent wiring](agent-wiring.md)), which is the page's remedy for a gateway that can't run the checks (1EFLOPS on X: Codex's model behind magpie). -- Claude Code's billing line (`x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;`, its own first system block, `cch` changing every turn) goes on only to a Claude model asked on Anthropic's Messages API (`keepsBillingLine` in [`billing_line.go`](../../internal/gateway/billing_line.go): Anthropic's, a relay's, Bedrock's), as Claude Code sent it. Anywhere else it is left out, the rest of the system as sent (`withoutBillingLine`): a vendor's model relayed on Messages (`passthrough`), every translation to Chat, Responses or Gemini (`forwardTranslated`, Claude models too), and the subscriptions asked through their own clients' APIs (Cursor, Devin, Kiro, Qoder, Command Code's Go plan, in `attempt`). Kept, a vendor read it as the prompt's first words and its prefix cache missed from byte 0 every turn (#1600, justrun1983: 4% read from DeepSeek's cache behind Command Code's plan). The Claude subscription's run sends its own (`withoutBillingHeader`), another magpie decides for the provider it picks, and Code Assist (Antigravity, Gemini CLI) is sent it as before, which `antigravityTurnsAway` reads (#666). Once Antigravity has turned such a request away, for `agForeseeing` (6 hours) after, a candidate loop with someone left after an Antigravity account skips it for a request that carries the line, without asking it (`antigravityForeseen`, #2156: each Claude Desktop turn waited about a second on the same refusal before the next member). The skip goes in `Fallback` with the hint, nothing rests, and the agent is told the refusal if nobody after it answers but with a quota. The last one left is still asked, and an old refusal foresees nothing, so a block Google lifts is noticed (`TestAntigravityTurnedAwayIsForeseen`). +- Claude Code's billing line (`x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;`, its own first system block, `cch` changing every turn) goes on only to a Claude model asked on Anthropic's Messages API (`keepsBillingLine` in [`billing_line.go`](../../internal/gateway/billing_line.go): Anthropic's, a relay's, Bedrock's), as Claude Code sent it. Anywhere else it is left out, the rest of the system as sent (`withoutBillingLine`): a vendor's model relayed on Messages (`passthrough`), every translation to Chat, Responses or Gemini (`forwardTranslated`, Claude models too), and the subscriptions asked through their own clients' APIs (Cursor, Kiro, Qoder, Command Code's Go plan, in `attempt`). Kept, a vendor read it as the prompt's first words and its prefix cache missed from byte 0 every turn (#1600, justrun1983: 4% read from DeepSeek's cache behind Command Code's plan). The Claude subscription's run sends its own (`withoutBillingHeader`), another magpie decides for the provider it picks, and Code Assist (Antigravity, Gemini CLI) is sent it as before, which `antigravityTurnsAway` reads (#666). Once Antigravity has turned such a request away, for `agForeseeing` (6 hours) after, a candidate loop with someone left after an Antigravity account skips it for a request that carries the line, without asking it (`antigravityForeseen`, #2156: each Claude Desktop turn waited about a second on the same refusal before the next member). The skip goes in `Fallback` with the hint, nothing rests, and the agent is told the refusal if nobody after it answers but with a quota. The last one left is still asked, and an old refusal foresees nothing, so a block Google lifts is noticed (`TestAntigravityTurnedAwayIsForeseen`). - Claude Code's advisor (`/advisor`, `--advisor`) is Anthropic's server tool `advisor_20260301`, its `model` named as Claude Code names its own: on magpie, by magpie's id (the tier an alias like `opus` is on), which no vendor knows, so the request was turned away whole (JackChou on Discord). Relayed on Messages (`passthrough`), the advisor's model goes as the upstream's own name for it when it is the same provider's Claude model, or a Claude id naming no provider (`advisorTools` in [`advisor.go`](../../internal/gateway/advisor.go)); one it can't run there (another provider's, a group, not Claude's) is left out, as is every advisor when the request's own model isn't a Claude model (a vendor's Messages API knows no such tool), and the turn is answered without one. A translation drops it with every other server tool. Claude Code (2.1.300) also puts the advisor in the conversation: a `{role: "system"}` message whose text ends in its instructions ("# Advisor Tool … call advisor BEFORE substantive work") and a `tool_addition` naming it. Where the advisor is left out, that `tool_addition` goes too (and a message it leaves empty), and the instructions become Claude Code's own "The advisor tool is no longer available; disregard the earlier advisor instructions." (`withoutAdvisor` on Messages, `advisorGoneIn` in `parseAnthropic` for a translation): left there, the model called `advisor()` as one of the agent's tools and Claude Code answered "No such tool available: advisor" (JackChou on Discord). The Claude subscription's run declares only magpie's tools, so it never has one. `TestAdvisorModelAsTheUpstreamNamesIt`, `TestAdvisorLeftOutOnTranslation`. - Kiro is told where to cache the prompt (plugins#110: a Kiro subscription read 0 from its cache). Its API takes Bedrock's `cachePoint: {"type":"default"}` on a `userInputMessage`, an `assistantResponseMessage` or as a tool entry. The built-in (`buildKiro` in [`kiro.go`](../../internal/gateway/kiro.go)) marks the first message when there is a system prompt, which it folds into that message, and the current message, as `buildAnthropic` marks Anthropic's. A moved Kiro's plugin (opencode-kiro-auth 0.1.10, the mover's `min`) turns each `cache_control` in the Anthropic body it is handed into one, at most 4, the last kept. - A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (`buildCodeAssistSent`: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, `continueText`, or `compactLastText` when an agent is compacting with its ask in the system prompt (`modelLastAsk`), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's `functionResponse` with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (`hasResponse`), except for a Claude model on Antigravity, whose tool_result turn holds both. diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index d322d5c05..cc0cf0e30 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -36,7 +36,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Codex's credential store | Codex 0.162 keeps its ChatGPT sign-in where `cli_auth_credentials_store` in `$CODEX_HOME/config.toml` says (`codex-rs/login/src/auth/storage.rs`): `file` (default) is `auth.json`; `keyring` the system keychain alone; `auto` the keychain, else `auth.json`, on read and on save; `ephemeral` Codex's memory. Saved to the keychain, Codex removes `auth.json` (#2312, #2367, Dony2050). On macOS magpie reads that item through `security`, as it reads Claude Code's: service `Codex Auth`, account `cli|` + the first 16 hex digits of SHA-256 of the canonical CODEX_HOME (`codexKeychainAccount`), the value auth.json's JSON on one line. `readCodexLogin` is the one reader: `codexAccount`, `codexToken`, `liveLogin`, `CodexAPIKeySignedIn`, `codexLoginAuth`, the usage card's `codexUntil`, session identities and the agent's wiring (`provider.CodexSignIn`: `codexChatGPT`, `Agent.Source`) go through it. `keyring` with no item is signed out; `auto` with no item, or one the keychain wouldn't give, is `auth.json`, as Codex does. An item the keychain wouldn't give under `keyring` is not known (`codexStoreError`), never signed out. With `[features] secret_auth_storage` on (Codex's default on Windows) keyring and auto mean Codex's encrypted auth storage, which magpie doesn't read; nor does it read the Linux or Windows keychain. There `keyring` and `ephemeral` are not known, `auto` is `auth.json` when Codex left one, and the saved accounts' reason says to set `file` (`codexSignedOutWhy`). Requirements an admin manages (`requirements.cli_auth_credentials_store`) aren't read. Reading the secret can put up to two macOS prompts in front of the user, who may type their password, so one read per item is in flight at a time and waits up to 2 minutes for them (`keychainAsk`, `askCodexKeychain`), outside the cache's lock. A reader waits at most 5s from when that ask started (`keychainHold`) and is otherwise told magpie is waiting for an answer (`errKeychainWaiting`); no request or page waits out the prompt. `security` exit 44 is no item; 51 (errSecAuthFailed) or 128 (errSecUserCanceled) is denied or cancelled (`errKeychainRefused`); the 2 minutes running out is no answer (`errKeychainNoAnswer`); anything else is `errKeychainUnread`. Each says so in the saved accounts' reason, and none of them is signed out. A read the keychain gave is kept while the item is unchanged: after 10s a reader asks only the item's modification date (`Stat`, `find-generic-password` without `-w`, which shows no prompt) and reads the secret again only when Codex or magpie changed it (#2367: with "Allow" once, background polls asked again every ~30s). A refusal or no answer is kept 10 minutes (#2408). magpie's own writes (`codexStore.write`, `keepCodexKeychain`) keep the date of what they wrote; a switch, sign-out or refresh forgets a read (`forgetCodexKeychain`) so the next one checks the date, but keeps a refusal; switching and refreshing read afresh. Beside a refusal, no answer or waiting, the saved accounts' line has Try again (`Exclusion.Retry`, `keychain-retry`, `RetryCodexKeychain`), which reads once past the refusal, and the reason says "Always Allow" lets `/usr/bin/security` read the item, so macOS stops asking each time Codex changes it. A switch or a first sign-in (`saveCodexLogin`) writes the store Codex reads, and refuses when that store couldn't be read, when config.toml doesn't parse, or when it is one magpie doesn't read; it leaves an `auth.json` beside the item to Codex. Signing the last account out (`deleteCodexLogin`) removes the item, then `auth.json`, as `codex logout`. Not tried against an item Codex itself wrote: macOS may ask whether magpie can read it, and Codex whether it can read one magpie rewrote. | [`codex_store.go`](../../internal/provider/codex_store.go), [`codex_store_test.go`](../../internal/provider/codex_store_test.go), [`codex_keychain_ask_unix_test.go`](../../internal/provider/codex_keychain_ask_unix_test.go) | | A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, or served a request (`ServedSignIn`), it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) | | Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go) | -| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`), or with the sign-in's while one asks it. | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) | +| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) | | Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, `email_address`, in `credentials` or `extra`, and keeps its `scope`, `account_uuid` and `org_uuid` as Claude Code's scopes, `accountUuid` and `organizationUuid` (#1975); a file with no email is refused, as Claude Code's own `.credentials.json` is. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go) | | Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. | [`codex_switch.go`](../../internal/provider/codex_switch.go) | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | diff --git a/internal/gateway/anthropic_call_ids_test.go b/internal/gateway/anthropic_call_ids_test.go index d76b69eb4..ba273acab 100644 --- a/internal/gateway/anthropic_call_ids_test.go +++ b/internal/gateway/anthropic_call_ids_test.go @@ -5,6 +5,7 @@ import ( "io" "net/http" "net/http/httptest" + "regexp" "strings" "sync" "testing" @@ -12,6 +13,14 @@ import ( "github.com/yetone/magpie/internal/provider" ) +// devinRawID is the call id Devin's SWE-2 gave in #1304 (StarMoonCity's +// capture). Claude Code takes a tool_use id only of [A-Za-z0-9_-] and +// dropped the call: "The model's tool call could not be parsed (retry also +// failed)". +const devinRawID = "Bash:0#a65b6a5e02194b87bbc796c4428c946d" + +var anthropicSafeID = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) + // chatCallUpstream is a Chat upstream (a plugin's provider, a relay) that // answers every request with one Bash call under id, and keeps the bodies // it was sent. @@ -156,7 +165,7 @@ func TestAnthropicCallIDsSafeBothWays(t *testing.T) { // prompt caching and every upstream that works today see no change; // Devin's "dv_…" ids are not encoded a second time. func TestAnthropicSafeCallIDsUnchanged(t *testing.T) { - for _, id := range []string{"toolu_01A09q90qw90lq917835lq9", "call_abc-123", "dv_QmFzaDowI2E2NWI2YTVl", devinOutID(devinRawID)} { + for _, id := range []string{"toolu_01A09q90qw90lq917835lq9", "call_abc-123", "dv_QmFzaDowI2E2NWI2YTVl", safeCallID("dv_", devinRawID)} { if got := anthropicOutID(id); got != id { t.Errorf("anthropicOutID(%q) = %q, want it as it came", id, got) } diff --git a/internal/gateway/connect_pb.go b/internal/gateway/connect_pb.go new file mode 100644 index 000000000..47c9d9740 --- /dev/null +++ b/internal/gateway/connect_pb.go @@ -0,0 +1,126 @@ +package gateway + +// Protobuf and Connect frames, by hand, for Cursor's API (cursor.go). They +// were written for the retired Devin built-in, whose API is a Connect RPC +// in protobuf too; Devin is served by its plugin now. + +import ( + "bufio" + "bytes" + "compress/gzip" + "encoding/binary" + "errors" + "io" + "math" +) + +// ---- protobuf, by hand --------------------------------------------------- + +// pb builds a protobuf message field by field. +type pb []byte + +func (b pb) tag(num, wire int) pb { return binary.AppendUvarint(b, uint64(num<<3|wire)) } + +func (b pb) varint(num int, v uint64) pb { return binary.AppendUvarint(b.tag(num, 0), v) } + +func (b pb) bytes(num int, v []byte) pb { + return append(binary.AppendUvarint(b.tag(num, 2), uint64(len(v))), v...) +} + +func (b pb) str(num int, v string) pb { return b.bytes(num, []byte(v)) } + +func (b pb) double(num int, v float64) pb { + return binary.LittleEndian.AppendUint64(b.tag(num, 1), math.Float64bits(v)) +} + +// pbField is one field of a message being read. +type pbField struct { + num int + wire int + n uint64 // a varint or fixed value + data []byte // a length-delimited one +} + +// pbFields reads a message's fields; a malformed tail is dropped. +func pbFields(b []byte) []pbField { + var out []pbField + for len(b) > 0 { + key, n := binary.Uvarint(b) + if n <= 0 { + break + } + b = b[n:] + f := pbField{num: int(key >> 3), wire: int(key & 7)} + switch f.wire { + case 0: + v, n := binary.Uvarint(b) + if n <= 0 { + return out + } + f.n, b = v, b[n:] + case 1: + if len(b) < 8 { + return out + } + f.n, b = binary.LittleEndian.Uint64(b), b[8:] + case 2: + l, n := binary.Uvarint(b) + if n <= 0 || uint64(len(b)-n) < l { + return out + } + f.data, b = b[n:n+int(l)], b[n+int(l):] + case 5: + if len(b) < 4 { + return out + } + f.n, b = uint64(binary.LittleEndian.Uint32(b)), b[4:] + default: + return out + } + out = append(out, f) + } + return out +} + +// connectFrame wraps a message as the one frame of a Connect stream. +func connectFrame(msg []byte) []byte { + out := make([]byte, 5, 5+len(msg)) + binary.BigEndian.PutUint32(out[1:], uint32(len(msg))) + return append(out, msg...) +} + +// connectMsg is one frame of a Connect stream: a message, or the stream's +// end with its JSON. +type connectMsg struct { + end bool + data []byte +} + +func readConnectFrame(r *bufio.Reader) (connectMsg, error) { + var head [5]byte + if _, err := io.ReadFull(r, head[:]); err != nil { + return connectMsg{}, err + } + n := binary.BigEndian.Uint32(head[1:]) + if n > 64<<20 { + return connectMsg{}, errors.New("a malformed stream") + } + data := make([]byte, n) + if _, err := io.ReadFull(r, data); err != nil { + return connectMsg{}, err + } + if head[0]&1 != 0 { + zr, err := gzip.NewReader(bytes.NewReader(data)) + if err != nil { + return connectMsg{}, err + } + if data, err = io.ReadAll(io.LimitReader(zr, 64<<20)); err != nil { + return connectMsg{}, err + } + } + return connectMsg{end: head[0]&2 != 0, data: data}, nil +} + +// devinNoResult answers a call the conversation never answered, in the +// words Devin's CLI used. +const devinNoResult = "Tool use was interrupted and did not produce a result." diff --git a/internal/gateway/devin.go b/internal/gateway/devin.go deleted file mode 100644 index a266d1739..000000000 --- a/internal/gateway/devin.go +++ /dev/null @@ -1,836 +0,0 @@ -package gateway - -// PLUGIN-SERVED (see AGENTS.md): Devin ("devin") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-devin-auth, -// once moved onto it (provider.Moved; the default for a new sign-in). A -// moved one's sign-ins, models, requests and usage are all the plugin's, -// never this code's (only the move, in migrate*.go, still reads its -// accounts). A fix here alone doesn't reach those users; fix the plugin -// (github.com/magpie-community/plugins, packages/devin) and raise the -// mover's min in internal/provider/migrate_side.go. - -// A Devin subscription is served through the API the devin CLI talks to — -// Windsurf's GetChatMessage, a Connect RPC in protobuf — the way a Kiro one -// is (kiro.go): each request goes whole, the conversation with the caller's -// tools, and the reply streams back as Connect frames, decoded here into -// events. The sign-in is the CLI's credentials.toml (provider/devin.go). - -import ( - "bufio" - "bytes" - "compress/gzip" - "context" - "encoding/binary" - "encoding/json" - "errors" - "io" - "math" - "net/http" - "runtime" - "slices" - "strings" - - "github.com/yetone/magpie/internal/provider" -) - -// devinAuth and devinVariant are the sign-in and the model the API is -// asked for; vars so tests can stand in for them. -var ( - devinAuth = provider.DevinAuthAt - devinVariant = provider.DevinVariant -) - -// devinCLIVersion is the CLI the requests say they come from. -const devinCLIVersion = "3000.11.3" - -// serveDevin answers a request through Devin's API, as the account signed -// in in home ("" for the CLI's own). -func (s *Server) serveDevin(w http.ResponseWriter, r *http.Request, from provider.Protocol, home, model string, body []byte, usage *Usage) (int, string) { - req, err := parse(from, body) - if err != nil { - return writeError(w, from, 400, err.Error()), err.Error() - } - // the vendor's own API is told the answer's format in words - req = req.inSystem() - req.Model = model - ask := s.askDevin(home, model) - if req.WebSearch && !searching(r.Context()) { - if canSearch() { - return s.searchReply(w, r, from, "Devin", req, usage, ask) - } - } - ctx, cancel := context.WithCancel(r.Context()) - defer cancel() - events, status, msg := ask(ctx, req) - if events == nil { - return writeError(w, from, status, msg), msg - } - return relay(w, r, from, "Devin", req, events, usage, cancel, nil, func(string, string, bool) {}) -} - -// askDevin is a round for Devin's API. -func (s *Server) askDevin(home, model string) round { - return func(ctx context.Context, req *Request) (<-chan Event, int, string) { - key, server, err := devinAuth(home) - if err != nil { - return nil, 401, "Devin: " + err.Error() - } - uid := devinVariant(ctx, model, req.Effort) - hr, err := http.NewRequestWithContext(ctx, http.MethodPost, server+"/exa.api_server_pb.ApiServerService/GetChatMessage", - bytes.NewReader(connectFrame(buildDevin(req, uid, key)))) - if err != nil { - return nil, 500, "Devin: " + err.Error() - } - hr.Header.Set("Content-Type", "application/connect+proto") - hr.Header.Set("Connect-Protocol-Version", "1") - hr.Header.Set("Authorization", "Basic "+key) - res, err := s.client.Do(hr) - if err != nil { - return nil, 502, "Devin: " + err.Error() - } - res = notAnAPIReply(res, "") // a web page served 200 (#1012) - if res.StatusCode/100 != 2 { - b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) - res.Body.Close() - status, msg := devinFailure(res.StatusCode, b) - return nil, status, "Devin: " + msg - } - // an error comes as the stream's end, before anything else: read - // that far so it is answered with its own status - br := bufio.NewReaderSize(res.Body, 64<<10) - first, err := readConnectFrame(br) - if err != nil { - res.Body.Close() - return nil, 502, "Devin: the reply broke off: " + err.Error() - } - if first.end { - res.Body.Close() - status, msg := devinFailure(200, first.data) - if status/100 == 2 { - status, msg = 502, "an empty reply" - } - return nil, status, "Devin: " + msg - } - events := make(chan Event, 16) - go func() { - defer res.Body.Close() - decodeDevin(ctx, first, br, events, model) - }() - return events, 0, "" - } -} - -// devinFailure is the status and message for a Connect error: -// {"code": "...", "message": "..."}, or at a stream's end -// {"error": {"code": "...", "message": "..."}}. -func devinFailure(status int, body []byte) (int, string) { - var e struct { - Code string `json:"code"` - Message string `json:"message"` - Error *struct { - Code string `json:"code"` - Message string `json:"message"` - } `json:"error"` - } - msg := strings.TrimSpace(string(body)) - code := "" - if json.Unmarshal(body, &e) == nil { - if e.Error != nil { - code, msg = e.Error.Code, e.Error.Message - } else if e.Code != "" { - code, msg = e.Code, e.Message - } - if msg == "" { - msg = code - } - } - if msg == "" { - msg = http.StatusText(status) - } - lower := strings.ToLower(msg) - switch { - case code == "unauthenticated": - return 401, msg + " — sign in to Devin again" - case code == "resource_exhausted" || strings.Contains(lower, "quota") || strings.Contains(lower, "rate limit"): - return 429, "usage limit reached: " + msg - case strings.Contains(lower, "content policy"): - // Devin turns away some system prompts outright; sent again, the - // same one is turned away again - return 400, msg - case strings.Contains(lower, "too long") || strings.Contains(lower, "context length") || strings.Contains(lower, "too many tokens"): - return 400, "input is too long for the model's context: " + msg - case code == "invalid_argument": - return 400, msg - case code == "unavailable": - return 503, msg - case code != "": - return 502, msg - } - return status, msg -} - -// ---- protobuf, by hand --------------------------------------------------- - -// pb builds a protobuf message field by field. -type pb []byte - -func (b pb) tag(num, wire int) pb { return binary.AppendUvarint(b, uint64(num<<3|wire)) } - -func (b pb) varint(num int, v uint64) pb { return binary.AppendUvarint(b.tag(num, 0), v) } - -func (b pb) bytes(num int, v []byte) pb { - return append(binary.AppendUvarint(b.tag(num, 2), uint64(len(v))), v...) -} - -func (b pb) str(num int, v string) pb { return b.bytes(num, []byte(v)) } - -func (b pb) double(num int, v float64) pb { - return binary.LittleEndian.AppendUint64(b.tag(num, 1), math.Float64bits(v)) -} - -// pbField is one field of a message being read. -type pbField struct { - num int - wire int - n uint64 // a varint or fixed value - data []byte // a length-delimited one -} - -// pbFields reads a message's fields; a malformed tail is dropped. -func pbFields(b []byte) []pbField { - var out []pbField - for len(b) > 0 { - key, n := binary.Uvarint(b) - if n <= 0 { - break - } - b = b[n:] - f := pbField{num: int(key >> 3), wire: int(key & 7)} - switch f.wire { - case 0: - v, n := binary.Uvarint(b) - if n <= 0 { - return out - } - f.n, b = v, b[n:] - case 1: - if len(b) < 8 { - return out - } - f.n, b = binary.LittleEndian.Uint64(b), b[8:] - case 2: - l, n := binary.Uvarint(b) - if n <= 0 || uint64(len(b)-n) < l { - return out - } - f.data, b = b[n:n+int(l)], b[n+int(l):] - case 5: - if len(b) < 4 { - return out - } - f.n, b = uint64(binary.LittleEndian.Uint32(b)), b[4:] - default: - return out - } - out = append(out, f) - } - return out -} - -// connectFrame wraps a message as the one frame of a Connect stream. -func connectFrame(msg []byte) []byte { - out := make([]byte, 5, 5+len(msg)) - binary.BigEndian.PutUint32(out[1:], uint32(len(msg))) - return append(out, msg...) -} - -// connectMsg is one frame of a Connect stream: a message, or the stream's -// end with its JSON. -type connectMsg struct { - end bool - data []byte -} - -func readConnectFrame(r *bufio.Reader) (connectMsg, error) { - var head [5]byte - if _, err := io.ReadFull(r, head[:]); err != nil { - return connectMsg{}, err - } - n := binary.BigEndian.Uint32(head[1:]) - if n > 64<<20 { - return connectMsg{}, errors.New("a malformed stream") - } - data := make([]byte, n) - if _, err := io.ReadFull(r, data); err != nil { - return connectMsg{}, err - } - if head[0]&1 != 0 { - zr, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - return connectMsg{}, err - } - if data, err = io.ReadAll(io.LimitReader(zr, 64<<20)); err != nil { - return connectMsg{}, err - } - } - return connectMsg{end: head[0]&2 != 0, data: data}, nil -} - -// ---- the request --------------------------------------------------------- - -// Devin's roles for a message. -const ( - devinUser = 1 - devinAssistant = 2 - devinTool = 4 -) - -// devinNoResult answers a call the conversation never answered. -const devinNoResult = "Tool use was interrupted and did not produce a result." - -// devinMsg is a message of the conversation, before it is encoded. -type devinMsg struct { - role int - text string - calls []Part - callID string // what a tool result answers - images []Part - thinking []Part // with Devin's own signatures -} - -// inlineImages is the images that carry their bytes: Devin takes no URL. -func inlineImages(ims []Part) []Part { - var out []Part - for _, im := range ims { - if im.Data != "" { - out = append(out, im) - } - } - return out -} - -// Devin names a call after its tool and turn (Bash:0#a65b6a5e…), and -// Claude Code takes a tool_use id only of [A-Za-z0-9_-]: it drops a call -// whose id has the ':' or '#', and the turn fails "could not be parsed" -// (#1304). Such an id goes out as "dv_" and its base64url, and comes back -// to Devin as it was, so its result still answers its call. An id that is -// already safe goes out as it came, unless it begins "dv_". The Devin -// plugin (packages/devin, outID and inID) maps the same way. -func devinOutID(id string) string { return safeCallID("dv_", id) } - -func devinInID(id string) string { return rawCallID("dv_", id) } - -// buildDevin is the GetChatMessage request for r, to the model uid. -func buildDevin(r *Request, uid, key string) []byte { - var msgs []devinMsg - var pending []Part // calls the last reply made, not yet answered - answer := func() { - for _, c := range pending { - msgs = append(msgs, devinMsg{role: devinTool, callID: c.ID, text: devinNoResult}) - } - pending = nil - } - for _, m := range joinSplitCalls(r.Messages) { - if m.Role == "assistant" { - a := devinMsg{role: devinAssistant} - var texts []string - for _, p := range m.Parts { - switch p.Kind { - case Text: - if p.Text != "" { - texts = append(texts, p.Text) - } - case ToolCall: - p.ID = devinInID(p.ID) - a.calls = append(a.calls, p) - case Thinking: - if strings.HasPrefix(p.Signature, "sealed.") { - a.thinking = append(a.thinking, p) - } - } - } - a.text = strings.Join(texts, "\n\n") - if a.text == "" && len(a.calls) == 0 { - continue // a turn that only thought, or failed - } - answer() - msgs = append(msgs, a) - pending = a.calls - continue - } - u := devinMsg{role: devinUser} - var texts []string - for _, p := range m.Parts { - switch p.Kind { - case Text: - if p.Text != "" { - texts = append(texts, p.Text) - } - case File: - texts = append(texts, attachmentText(p)) - case Image: - if p.Data != "" { - u.images = append(u.images, p) - } - case ToolResult: - // only a call just made is answered, and only once - for i, c := range pending { - if c.ID != devinInID(p.CallID) { - continue - } - out := p.Text - if out == "" { - out = "(no output)" - } - if p.IsError { - out = "Error: " + out - } - msgs = append(msgs, devinMsg{role: devinTool, callID: c.ID, text: out, images: inlineImages(p.Images)}) - pending = append(pending[:i:i], pending[i+1:]...) - break - } - } - } - u.text = strings.Join(texts, "\n\n") - if u.text == "" && len(u.images) == 0 { - continue - } - answer() - msgs = append(msgs, u) - } - answer() - if len(msgs) == 0 || msgs[len(msgs)-1].role == devinAssistant && len(msgs[len(msgs)-1].calls) == 0 { - msgs = append(msgs, devinMsg{role: devinUser, text: "Please proceed with the task."}) - } - - // the instructions go at the head of the first message, as Kiro's do: - // Devin turns away some agents' own in its system field (Claude Code's - // "You are a Claude agent, built on Anthropic's Claude Agent SDK"). The - // tools' descriptions go there too, each tool sent with only a pointer - // to its own: Devin answers "an internal error occurred" to some agents' - // tools as they describe themselves (WorkBuddy's Read, "Reads a file - // from the local filesystem. You can access any file directly by using - // this tool."), and the same words in a message go through - tools := r.Tools - if r.ToolChoice == "none" { - tools = nil - } - instructions := r.System - if described := devinToolDescriptions(tools); described != "" { - instructions = joinNonEmpty(instructions, described) - } - if instructions != "" { - at := slices.IndexFunc(msgs, func(m devinMsg) bool { return m.role == devinUser }) - if at < 0 { - msgs = slices.Insert(msgs, 0, devinMsg{role: devinUser}) - at = 0 - } - msgs[at].text = joinNonEmpty(instructions, msgs[at].text) - } - - meta := pb{}.str(1, "devin-cli").str(2, devinCLIVersion).str(3, key).str(4, "en"). - str(5, runtime.GOOS).str(7, devinCLIVersion).str(12, "chisel").str(28, "chisel") - out := pb{}.bytes(1, meta) - for _, m := range msgs { - out = out.bytes(3, encodeDevinMsg(m)) - } - out = out.varint(7, 5) - max := r.MaxTokens - if max <= 0 { - max = 128000 // the server holds it to the model's own - } - // Devin answers "an internal error occurred" to a temperature or top_p - // of exactly 0, on every model, where 1e-6 goes through: a 0 is sent - // as that, as near greedy as Devin takes (plugins #50) - above0 := func(v float64) float64 { - if v == 0 { - return 1e-6 - } - return v - } - topP := 0.95 - if r.TopP != nil { - topP = above0(*r.TopP) - } - temp := 1.0 - if r.Temp != nil { - temp = above0(*r.Temp) - } - out = out.bytes(8, pb{}.varint(1, 1).varint(2, uint64(max)).varint(3, 400).double(5, temp).varint(7, 40).double(8, topP)) - - // the caller's tools, and any the conversation used that it no longer - // offers - offered := map[string]bool{} - gemini := strings.Contains(strings.ToLower(uid), "gemini") - tool := func(name, desc string, schema json.RawMessage) { - if len(bytes.TrimSpace(schema)) == 0 || string(bytes.TrimSpace(schema)) == "null" { - schema = json.RawMessage(`{"type":"object","properties":{}}`) - } - if desc == "" { - desc = name - } - offered[name] = true - // Devin's Claude models answer 502 "There is an issue with this - // request" to a tool whose parameters have a root anyOf, oneOf or - // allOf (#1196: Codex desktop's automation_update), as Anthropic - // does behind Factory (#646) - schema = objectSchema(schema) - if gemini { - schema = devinGeminiSchema(schema) - } - out = out.bytes(10, pb{}.str(1, name).str(2, desc).bytes(3, schema)) - } - for _, t := range tools { - desc := t.Description - if desc != "" { - desc = "Described under in , in the instructions." - } - tool(t.Name, desc, t.Schema) - } - for _, m := range msgs { - for _, c := range m.calls { - if !offered[c.Name] { - tool(c.Name, "Tool", nil) - } - } - } - return out.str(21, uid) -} - -// devinGeminiSchema is a tool's parameters as Devin's Gemini models take -// them. Devin answers "There is an issue with this request, please try a -// different model" (invalid_argument) to a Gemini model offered a tool -// whose schema, at any depth, has a type that is a list (["string","null"], -// as zod-to-json-schema writes a nullable field), an array with no items, -// items that are a list or true, or properties or an enum with no type -// (7eleven on Discord, ZCode on gemini-4-argon); its Claude models and -// swe-2 take all of them, so only a Gemini uid gets this. A list type -// becomes its one type, nullable when it had "null", or anyOf of each; such -// an array's items become {} (a one-schema list, that schema); a schema -// with properties, or the root, is an object; an enum's type comes from its -// values, and an enum of mixed values goes. A schema needing none of it is -// sent as it came. The plugin does the same (geminiSchema, devin 0.1.17). -func devinGeminiSchema(schema json.RawMessage) json.RawMessage { - d := json.NewDecoder(bytes.NewReader(schema)) - d.UseNumber() - var m map[string]any - if d.Decode(&m) != nil || m == nil { - return schema - } - changed := false - if _, ok := m["type"]; !ok { - m["type"], changed = "object", true - if _, ok := m["properties"]; !ok { - m["properties"] = map[string]any{} - } - } - if !geminiSchemaIn(m, 0) && !changed { - return schema - } - b, err := json.Marshal(m) - if err != nil { - return schema - } - return b -} - -// geminiSchemaIn rewrites s in place as devinGeminiSchema says, and -// whether it changed anything. -func geminiSchemaIn(s map[string]any, depth int) bool { - if depth > 32 { - return false - } - changed := false - sub := func(v any) { - if m, ok := v.(map[string]any); ok && geminiSchemaIn(m, depth+1) { - changed = true - } - } - for _, k := range []string{"properties", "patternProperties", "$defs", "definitions", "dependentSchemas"} { - if m, ok := s[k].(map[string]any); ok { - for _, v := range m { - sub(v) - } - } - } - for _, k := range []string{"anyOf", "oneOf", "allOf", "prefixItems"} { - if l, ok := s[k].([]any); ok { - for _, v := range l { - sub(v) - } - } - } - for _, k := range []string{"additionalProperties", "not", "if", "then", "else", "contains"} { - sub(s[k]) - } - if list, ok := s["type"].([]any); ok { - changed = true - var some []string - null := false - seen := map[string]bool{} - for _, t := range list { - ts, _ := t.(string) - if ts == "" || seen[ts] { - continue - } - seen[ts] = true - if ts == "null" { - null = true - } else { - some = append(some, ts) - } - } - if null && len(some) > 0 { - s["nullable"] = true - } - switch { - case len(some) == 1: - s["type"] = some[0] - case len(some) == 0 && null: - s["type"] = "null" - case len(some) == 0: - delete(s, "type") - default: - delete(s, "type") - branches, _ := s["anyOf"].([]any) - for _, t := range some { - b := map[string]any{"type": t} - if t == "array" { - b["items"] = map[string]any{} - } - branches = append(branches, b) - } - s["anyOf"] = branches - } - } - _, typed := s["type"] - if vals, ok := s["enum"].([]any); ok && !typed { - changed = true - kinds := map[string]bool{} - var kept []any - for _, v := range vals { - switch x := v.(type) { - case nil: - s["nullable"] = true - continue - case string: - kinds["string"] = true - case bool: - kinds["boolean"] = true - case json.Number: - if strings.ContainsAny(x.String(), ".eE") { - kinds["number"] = true - } else { - kinds["integer"] = true - } - default: - kinds["other"] = true - } - kept = append(kept, v) - } - one := "" - if len(kinds) == 1 { - for k := range kinds { - one = k - } - } else if len(kinds) == 2 && kinds["integer"] && kinds["number"] { - one = "number" - } - if one != "" && one != "other" { - s["type"], s["enum"], typed = one, kept, true - } else { - delete(s, "enum") - } - } - if _, ok := s["properties"].(map[string]any); ok && !typed { - s["type"], typed, changed = "object", true, true - } - _, hasItems := s["items"] - if s["type"] == "array" || (!typed && hasItems) { - switch it := s["items"].(type) { - case map[string]any: - sub(it) - case []any: - changed = true - s["items"] = map[string]any{} - if len(it) == 1 { - if m, ok := it[0].(map[string]any); ok { - geminiSchemaIn(m, depth+1) - s["items"] = m - } - } - default: - changed = true - s["items"] = map[string]any{} - } - if s["type"] != "array" { - s["type"], changed = "array", true - } - } - return changed -} - -// devinToolDescriptions is what each tool says of itself, for the -// instructions. -func devinToolDescriptions(tools []Tool) string { - var b strings.Builder - for _, t := range tools { - if t.Description == "" { - continue - } - if b.Len() == 0 { - b.WriteString("\n") - } - b.WriteString("\n" + strings.TrimSpace(t.Description) + "\n\n") - } - if b.Len() == 0 { - return "" - } - return b.String() + "" -} - -func encodeDevinMsg(m devinMsg) []byte { - b := pb{}.str(1, newUUID()).varint(2, uint64(m.role)) - if m.text != "" { - b = b.str(3, m.text) - } - for _, c := range m.calls { - b = b.bytes(6, pb{}.str(1, c.ID).str(2, c.Name).bytes(3, argsOf(c))) - } - if m.callID != "" { - b = b.str(7, m.callID) - } - for _, p := range m.images { - mt := p.MediaType - if mt == "" { - mt = "image/png" - } - b = b.bytes(10, pb{}.str(1, p.Data).str(2, mt)) - } - for _, t := range m.thinking { - b = b.str(11, t.Text).str(12, t.Signature).str(18, "sealed") - } - return b -} - -// ---- the reply ----------------------------------------------------------- - -// decodeDevin turns Devin's reply, from its first frame on, into events. -func decodeDevin(ctx context.Context, first connectMsg, br *bufio.Reader, out chan<- Event, model string) { - defer close(out) - send := func(ev Event) bool { - select { - case out <- ev: - return true - case <-ctx.Done(): - return false - } - } - if !send(Event{Kind: KStart, MsgID: "msg_" + randomToken()[:24], Model: model}) { - return - } - var d devinDecoder - var failed string - for f := first; ; { - if f.end { - if status, msg := devinFailure(200, f.data); status/100 != 2 { - failed = msg - } - break - } - for _, ev := range d.frame(f.data) { - if !send(ev) { - return - } - } - var err error - if f, err = readConnectFrame(br); err != nil { - if !errors.Is(err, io.EOF) && ctx.Err() == nil { - failed = "the reply broke off: " + err.Error() - } - break - } - } - if failed != "" { - send(Event{Kind: KError, Text: failed}) - return - } - u := d.usage - if u.Output == 0 { - u.Output = (d.said + 3) / 4 - } - send(Event{Kind: KUsage, Usage: u}) - stop := "stop" - switch { - case d.tools > 0 || d.stop == 10: - stop = "tool" - case d.stop == 3: - stop = "length" - } - send(Event{Kind: KStop, Stop: stop}) -} - -// devinDecoder follows a reply: its text and thinking in pieces, its tool -// calls — each opened with its id and name, the arguments in pieces after -// — why it stopped, and what it used. -type devinDecoder struct { - tools int - stop uint64 - usage Usage - said int -} - -func (d *devinDecoder) frame(b []byte) []Event { - var evs []Event - for _, f := range pbFields(b) { - switch { - case f.num == 3 && f.wire == 2 && len(f.data) > 0: - d.said += len(f.data) - evs = append(evs, Event{Kind: KText, Text: string(f.data)}) - case f.num == 9 && f.wire == 2 && len(f.data) > 0: - d.said += len(f.data) - evs = append(evs, Event{Kind: KThink, Text: string(f.data)}) - case f.num == 6 && f.wire == 2: - var id, name, args string - for _, g := range pbFields(f.data) { - switch g.num { - case 1: - id = string(g.data) - case 2: - name = string(g.data) - case 3: - args += string(g.data) - } - } - if name != "" { - d.tools++ - if id == "" { - id = "call_" + randomToken()[:24] - } - evs = append(evs, Event{Kind: KToolStart, ID: devinOutID(id), Name: name}) - } - if args != "" { - evs = append(evs, Event{Kind: KToolArgs, Text: args}) - } - case f.num == 5 && f.wire == 0: - d.stop = f.n - case f.num == 7 && f.wire == 2: - for _, g := range pbFields(f.data) { - if g.wire != 0 || g.n == 0 { - continue - } - switch g.num { - case 2: - d.usage.Input = int(g.n) - case 3: - d.usage.Output = int(g.n) - case 4: - d.usage.CacheWrite = int(g.n) - case 5: - d.usage.CacheRead = int(g.n) - } - } - } - } - return evs -} diff --git a/internal/gateway/devin_gemini_schema_test.go b/internal/gateway/devin_gemini_schema_test.go deleted file mode 100644 index d6a40e816..000000000 --- a/internal/gateway/devin_gemini_schema_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package gateway - -import ( - "encoding/json" - "fmt" - "reflect" - "testing" -) - -// devinGeminiRefused are tool schemas Devin's gemini-4-argon refused on a -// real account, each on its own, with invalid_argument "There is an issue -// with this request, please try a different model" (7eleven on Discord, -// ZCode). Each went through once rewritten as devinGeminiSchema does; -// claude-sonnet-4-6 and swe-2 took every one as it was. -var devinGeminiRefused = map[string]string{ - "typeList": `{"type":"object","properties":{"a":{"type":["string","null"]}}}`, - "typeListOne": `{"type":"object","properties":{"a":{"type":["string"]}}}`, - "typeListTwo": `{"type":"object","properties":{"a":{"type":["string","number"]}}}`, - "noItems": `{"type":"object","properties":{"a":{"type":"array"}}}`, - "itemsTrue": `{"type":"object","properties":{"a":{"type":"array","items":true}}}`, - "itemsList": `{"type":"object","properties":{"a":{"type":"array","items":[{"type":"string"}]}}}`, - "deepNoItems": `{"type":"object","properties":{"a":{"type":"object","properties":{"b":{"type":"array"}}}}}`, - "unionNoItems": `{"type":"object","properties":{"a":{"anyOf":[{"type":"array"},{"type":"null"}]}}}`, - "propsNoType": `{"type":"object","properties":{"a":{"properties":{"b":{"type":"string"}}}}}`, - "enumNoType": `{"type":"object","properties":{"a":{"enum":["x","y"]}}}`, - "rootNoType": `{"properties":{"a":{"type":"string"}}}`, - "emptyRoot": `{}`, -} - -// devinGeminiFaults is what in s Devin's Gemini models refuse. -func devinGeminiFaults(s any, at string) []string { - m, ok := s.(map[string]any) - if !ok { - return nil - } - var out []string - if _, list := m["type"].([]any); list { - out = append(out, at+" list type") - } - _, typed := m["type"] - if !typed && (m["properties"] != nil || m["enum"] != nil) { - out = append(out, at+" no type") - } - if m["type"] == "array" { - if _, ok := m["items"].(map[string]any); !ok { - out = append(out, at+" items") - } - } - props, _ := m["properties"].(map[string]any) - for k, v := range props { - out = append(out, devinGeminiFaults(v, at+"."+k)...) - } - for _, k := range []string{"anyOf", "oneOf", "allOf"} { - l, _ := m[k].([]any) - for i, v := range l { - out = append(out, devinGeminiFaults(v, fmt.Sprintf("%s.%s[%d]", at, k, i))...) - } - } - return append(out, devinGeminiFaults(m["items"], at+"[]")...) -} - -func devinSentSchema(t *testing.T, schema, uid string) string { - t.Helper() - d := decodeDevinRequest(t, buildDevin(&Request{ - Tools: []Tool{{Name: "t", Description: "t", Schema: json.RawMessage(schema)}}, - Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "ok"}}}}, - }, uid, "k")) - if len(d.schemas) != 1 { - t.Fatalf("schemas %q", d.schemas) - } - return d.schemas[0] -} - -func TestBuildDevinGeminiSchema(t *testing.T) { - for name, schema := range devinGeminiRefused { - got := devinSentSchema(t, schema, "gemini-4-argon-medium") - var m map[string]any - if err := json.Unmarshal([]byte(got), &m); err != nil { - t.Fatalf("%s: %v", name, err) - } - if m["type"] != "object" { - t.Errorf("%s: root not an object: %s", name, got) - } - if f := devinGeminiFaults(m, "$"); len(f) > 0 { - t.Errorf("%s: Gemini refuses %v in %s", name, f, got) - } - // Claude models and swe-2 take every one as it came - if name == "rootNoType" || name == "emptyRoot" { - continue - } - for _, uid := range []string{"claude-opus-5-5-high", "swe-2-high"} { - if got := devinSentSchema(t, schema, uid); got != schema { - t.Errorf("%s: %s got %s", name, uid, got) - } - } - } -} - -func TestDevinGeminiSchemaKeepsWhatItAllowed(t *testing.T) { - for in, want := range map[string]string{ - `{"type":["string","null"],"description":"d"}`: `{"description":"d","nullable":true,"type":"string"}`, - `{"type":["string","number","null"]}`: `{"anyOf":[{"type":"string"},{"type":"number"}],"nullable":true}`, - `{"type":["array","null"]}`: `{"items":{},"nullable":true,"type":"array"}`, - `{"type":"array","items":[{"type":"string"}]}`: `{"items":{"type":"string"},"type":"array"}`, - `{"enum":[1,2]}`: `{"enum":[1,2],"type":"integer"}`, - `{"enum":["x",null]}`: `{"enum":["x"],"nullable":true,"type":"string"}`, - } { - // a schema at a property, as a tool's parameters hold it - got := devinGeminiSchema(json.RawMessage(`{"type":"object","properties":{"a":` + in + `}}`)) - var g, w map[string]any - json.Unmarshal(got, &g) - json.Unmarshal([]byte(want), &w) - if a := g["properties"].(map[string]any)["a"]; !reflect.DeepEqual(a, w) { - t.Errorf("%s: got %v, want %v", in, a, w) - } - } - // a schema Gemini takes is sent byte for byte - ok := `{"type":"object","properties":{"a":{"anyOf":[{"type":"string"},{"type":"null"}]},"b":{"type":"array","items":{"type":"string","enum":["x"]}},"c":{"$ref":"#/$defs/x"},"d":{"const":"k"}},"$defs":{"x":{"type":"object","properties":{"y":{"type":"integer"}}}},"required":["a"]}` - if got := devinSentSchema(t, ok, "gemini-4-argon-medium"); got != ok { - t.Errorf("a schema Gemini takes was changed: %s", got) - } -} diff --git a/internal/gateway/devin_sampling_test.go b/internal/gateway/devin_sampling_test.go deleted file mode 100644 index de8281e42..000000000 --- a/internal/gateway/devin_sampling_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package gateway - -import ( - "math" - "testing" -) - -// devinSampling is the temperature and top_p a GetChatMessage request -// carries in its field 8. -func devinSampling(t *testing.T, r *Request) (temp, topP float64) { - t.Helper() - for _, f := range pbFields(buildDevin(r, "swe-2", "k")) { - if f.num != 8 { - continue - } - for _, g := range pbFields(f.data) { - switch g.num { - case 5: - temp = math.Float64frombits(g.n) - case 8: - topP = math.Float64frombits(g.n) - } - } - } - return -} - -// Devin answers 400 "an internal error occurred" to a temperature or -// top_p of exactly 0 (Hermes Agent's command approvals send temperature -// 0): a 0 goes as 1e-6, any other value as it came, none as Devin's -// defaults (plugins #50). -func TestDevinSamplingZero(t *testing.T) { - f := func(v float64) *float64 { return &v } - say := []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}} - for _, c := range []struct { - name string - temp, topP *float64 - wantT, wantTopP float64 - }{ - {"none", nil, nil, 1, 0.95}, - {"temperature 0", f(0), nil, 1e-6, 0.95}, - {"top_p 0", nil, f(0), 1, 1e-6}, - {"both -0", f(math.Copysign(0, -1)), f(0), 1e-6, 1e-6}, - {"others as they came", f(0.2), f(1), 0.2, 1}, - {"1e-6 as it came", f(1e-6), nil, 1e-6, 0.95}, - } { - temp, topP := devinSampling(t, &Request{Temp: c.temp, TopP: c.topP, Messages: say}) - if temp != c.wantT || topP != c.wantTopP { - t.Errorf("%s: temperature %v top_p %v, want %v %v", c.name, temp, topP, c.wantT, c.wantTopP) - } - } -} diff --git a/internal/gateway/devin_test.go b/internal/gateway/devin_test.go deleted file mode 100644 index 3f04b9ad6..000000000 --- a/internal/gateway/devin_test.go +++ /dev/null @@ -1,373 +0,0 @@ -package gateway - -import ( - "bufio" - "bytes" - "compress/gzip" - "context" - "encoding/binary" - "encoding/json" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/yetone/magpie/internal/provider" -) - -// devinFrame is one frame of a Connect stream, gzipped when zip. -func devinFrame(flag byte, msg []byte, zip bool) []byte { - if zip { - var b bytes.Buffer - zw := gzip.NewWriter(&b) - zw.Write(msg) - zw.Close() - msg, flag = b.Bytes(), flag|1 - } - out := []byte{flag, 0, 0, 0, 0} - binary.BigEndian.PutUint32(out[1:], uint32(len(msg))) - return append(out, msg...) -} - -func devinEvents(t *testing.T, frames ...[]byte) []Event { - t.Helper() - br := bufio.NewReader(bytes.NewReader(bytes.Join(frames, nil))) - first, err := readConnectFrame(br) - if err != nil { - t.Fatal(err) - } - out := make(chan Event, 256) - decodeDevin(context.Background(), first, br, out, "swe-2") - var evs []Event - for ev := range out { - evs = append(evs, ev) - } - return evs -} - -func TestDevinDecodesTextThinkingAndCalls(t *testing.T) { - evs := devinEvents(t, - devinFrame(0, pb{}.str(1, "bot-1").str(9, "Hmm."), false), - devinFrame(0, pb{}.str(3, "Let me ").varint(4, 1), true), - devinFrame(0, pb{}.str(3, "look."), false), - devinFrame(0, pb{}.bytes(6, pb{}.str(1, "toolu_1").str(2, "read")), false), - devinFrame(0, pb{}.bytes(6, pb{}.str(3, `{"pa`)), false), - devinFrame(0, pb{}.bytes(6, pb{}.str(3, `th":"a"}`)), false), - devinFrame(0, pb{}.str(10, "sealed.v1xyz").varint(5, 10), false), - devinFrame(0, pb{}.bytes(7, pb{}.varint(2, 120).varint(3, 30).varint(5, 7).varint(6, 30).str(7, "id")), false), - devinFrame(2, []byte("{}"), false), - ) - if got, want := said(evs), `|think:Hmm.|text:Let me look.|call:toolu_1/read|args:{"path":"a"}|stop:tool`; got != want { - t.Fatalf("got %s\nwant %s", got, want) - } - var u Usage - for _, ev := range evs { - if ev.Kind == KUsage { - u = ev.Usage - } - } - if u.Input != 120 || u.Output != 30 || u.CacheRead != 7 { - t.Fatalf("usage = %+v", u) - } -} - -func TestDevinStopsAndFails(t *testing.T) { - evs := devinEvents(t, devinFrame(0, pb{}.str(3, "abcd").varint(5, 3), false)) - if got := said(evs); got != "|text:abcd|stop:length" { - t.Fatal(got) - } - evs = devinEvents(t, - devinFrame(0, pb{}.str(3, "ab"), false), - devinFrame(2, []byte(`{"error":{"code":"internal","message":"boom"}}`), false)) - if got := said(evs); got != "|text:ab|error:boom" { - t.Fatal(got) - } -} - -// devinDecoded is a GetChatMessage request, read back. -type devinDecoded struct { - system string - model string - msgs [][]pbField - tools []string - descs []string - // schemas are the tools' parameters, as sent - schemas []string - max uint64 -} - -func decodeDevinRequest(t *testing.T, b []byte) devinDecoded { - t.Helper() - var d devinDecoded - for _, f := range pbFields(b) { - switch f.num { - case 2: - d.system = string(f.data) - case 21: - d.model = string(f.data) - case 3: - d.msgs = append(d.msgs, pbFields(f.data)) - case 10: - fs := pbFields(f.data) - d.tools = append(d.tools, string(fs[0].data)) - d.descs = append(d.descs, string(fs[1].data)) - d.schemas = append(d.schemas, string(fs[2].data)) - case 8: - for _, g := range pbFields(f.data) { - if g.num == 2 { - d.max = g.n - } - } - } - } - return d -} - -// devinSummary is a message as role:text[extras]. -func devinSummary(m []pbField) string { - var role uint64 - var text, extra string - for _, f := range m { - switch f.num { - case 2: - role = f.n - case 3: - text = string(f.data) - case 6: - fs := pbFields(f.data) - extra += " call " + string(fs[0].data) + "/" + string(fs[1].data) + " " + string(fs[2].data) - case 7: - extra += " for " + string(f.data) - case 10: - extra += " image " + string(pbFields(f.data)[1].data) - case 12: - extra += " signed" - } - } - return string(rune('0'+role)) + ":" + text + extra -} - -func TestBuildDevin(t *testing.T) { - r := &Request{ - System: "Be brief.", - Tools: []Tool{{Name: "read", Description: "Read a file", Schema: json.RawMessage(`{"type":"object"}`)}}, - Messages: []Message{ - {Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "orphan", Text: "x"}, {Kind: Text, Text: "look at a"}}}, - {Role: "assistant", Parts: []Part{ - {Kind: Thinking, Text: "ok", Signature: "sealed.v1abc"}, - {Kind: Thinking, Text: "other", Signature: "EqQBCkY"}, - {Kind: Text, Text: "Reading."}, - {Kind: ToolCall, ID: "c1", Name: "read", Args: json.RawMessage(`{"p":"a"}`)}, - {Kind: ToolCall, ID: "c2", Name: "gone", Args: nil}, - }}, - {Role: "user", Parts: []Part{ - {Kind: ToolResult, CallID: "c1", Text: "A", IsError: true}, - {Kind: ToolResult, CallID: "c1", Text: "again"}, - {Kind: Image, MediaType: "image/jpeg", Data: "AAAA"}, - {Kind: Text, Text: "and this"}, - }}, - }, - } - d := decodeDevinRequest(t, buildDevin(r, "swe-2-high", "k")) - if d.system != "" || d.model != "swe-2-high" || d.max != 128000 { - t.Fatalf("%+v", d) - } - var got []string - for _, m := range d.msgs { - got = append(got, devinSummary(m)) - } - want := []string{ - "1:Be brief.\n\n\n\nRead a file\n\n\n\nlook at a", - `2:Reading. call c1/read {"p":"a"} call c2/gone {} signed`, - "4:Error: A for c1", - "4:" + devinNoResult + " for c2", - "1:and this image image/jpeg", - } - if strings.Join(got, "\n") != strings.Join(want, "\n") { - t.Fatalf("got\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) - } - if strings.Join(d.tools, ",") != "read,gone" { - t.Fatalf("tools = %v", d.tools) - } - // a tool is sent with a pointer to its description, which is in the - // instructions: Devin answers "an internal error occurred" to some - // agents' tools as they describe themselves (silenx on X: WorkBuddy - // on Devin, 502 every time) - if d.descs[0] != `Described under in , in the instructions.` || d.descs[1] != "Tool" { - t.Fatalf("descriptions = %q", d.descs) - } - - // none to be called: no tools, nor their descriptions - d = decodeDevinRequest(t, buildDevin(&Request{ToolChoice: "none", Tools: r.Tools, Messages: []Message{ - {Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}, - }}, "m", "k")) - if len(d.tools) != 0 || devinSummary(d.msgs[0]) != "1:hi" { - t.Fatalf("%+v", d) - } - - // a conversation ending on a reply goes on with a nudge - d = decodeDevinRequest(t, buildDevin(&Request{MaxTokens: 50, Messages: []Message{ - {Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}, - {Role: "assistant", Parts: []Part{{Kind: Text, Text: "yo"}}}, - }}, "m", "k")) - if n := len(d.msgs); n != 3 || devinSummary(d.msgs[2]) != "1:Please proceed with the task." || d.max != 50 { - t.Fatalf("%d %+v", n, d) - } -} - -// TestBuildDevinObjectRoot offers #1196's tool, whose parameters have a root -// oneOf, anyOf or allOf: Devin's Claude models answered 502 to every request -// with one, so each goes as a plain object; a plain object goes as it came. -func TestBuildDevinObjectRoot(t *testing.T) { - for _, k := range []string{"oneOf", "anyOf", "allOf"} { - schema := `{ - "type": "object", - "properties": {"a": {"type": "string"}}, - "` + k + `": [{"properties": {"a": {"type": "string"}}}, {"properties": {"b": {"type": "string"}}}] - }` - plain := `{"type":"object","properties":{"x":{"type":"string"}},"required":["x"]}` - d := decodeDevinRequest(t, buildDevin(&Request{ - Tools: []Tool{ - {Name: "t", Description: "t", Schema: json.RawMessage(schema)}, - {Name: "plain", Description: "p", Schema: json.RawMessage(plain)}, - }, - Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "ok"}}}}, - }, "claude-opus-5-5", "k")) - if len(d.schemas) != 2 { - t.Fatalf("%s: schemas %q", k, d.schemas) - } - var p map[string]any - if err := json.Unmarshal([]byte(d.schemas[0]), &p); err != nil { - t.Fatal(err) - } - props, _ := p["properties"].(map[string]any) - if p["type"] != "object" || p["anyOf"] != nil || p["oneOf"] != nil || p["allOf"] != nil || props["a"] == nil || props["b"] == nil { - t.Fatalf("%s: sent %s", k, d.schemas[0]) - } - if d.schemas[1] != plain { - t.Fatalf("%s: a plain object was changed: %s", k, d.schemas[1]) - } - } -} - -func TestBuildDevinKeepsImagesAToolReturned(t *testing.T) { - r := &Request{Messages: []Message{ - {Role: "user", Parts: []Part{{Kind: Text, Text: "look at it"}}}, - {Role: "assistant", Parts: []Part{ - {Kind: ToolCall, ID: "c1", Name: "read", Args: json.RawMessage(`{"p":"a.png"}`)}, - {Kind: ToolCall, ID: "c2", Name: "read", Args: json.RawMessage(`{"p":"b.png"}`)}, - }}, - {Role: "user", Parts: []Part{ - // Read gives a picture back with no text beside it - {Kind: ToolResult, CallID: "c1", Images: []Part{ - {Kind: Image, MediaType: "image/png", Data: "AAAA"}, - {Kind: Image, URL: "https://example.com/x.png"}, // Devin takes no URL - }}, - {Kind: ToolResult, CallID: "c2", Text: "B", Images: []Part{{Kind: Image, MediaType: "image/jpeg", Data: "BBBB"}}}, - }}, - }} - d := decodeDevinRequest(t, buildDevin(r, "swe-2", "k")) - var got []string - for _, m := range d.msgs { - got = append(got, devinSummary(m)) - } - want := []string{ - "1:look at it", - "2: call c1/read {\"p\":\"a.png\"} call c2/read {\"p\":\"b.png\"}", - "4:(no output) for c1 image image/png", - "4:B for c2 image image/jpeg", - } - if strings.Join(got, "\n") != strings.Join(want, "\n") { - t.Fatalf("got\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) - } -} - -func devinUpstream(t *testing.T, reply []byte) func() { - t.Helper() - up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, _ := io.ReadAll(r.Body) - if r.URL.Path != "/exa.api_server_pb.ApiServerService/GetChatMessage" || r.Header.Get("Authorization") != "Basic devin-session-token$k" || - r.Header.Get("Content-Type") != "application/connect+proto" || len(body) < 5 { - http.Error(w, `{"code":"unauthenticated","message":"no"}`, 401) - return - } - if m := decodeDevinRequest(t, body[5:]).model; m != "swe-2-high" { - t.Errorf("model = %q", m) - } - w.Header().Set("Content-Type", "application/connect+proto") - w.Write(reply) - })) - auth, variant := devinAuth, devinVariant - devinAuth = func(string) (string, string, error) { return "devin-session-token$k", up.URL, nil } - devinVariant = func(ctx context.Context, model, effort string) string { return model + "-high" } - return func() { up.Close(); devinAuth, devinVariant = auth, variant } -} - -func serveDevinOnce(t *testing.T, from provider.Protocol, body string) *httptest.ResponseRecorder { - t.Helper() - s := New() - w := httptest.NewRecorder() - r := httptest.NewRequest("POST", "/", strings.NewReader(body)) - var u Usage - s.serveDevin(w, r, from, "", "swe-2", []byte(body), &u) - return w -} - -func TestServeDevin(t *testing.T) { - t.Setenv("XDG_CONFIG_HOME", t.TempDir()) - t.Setenv("XDG_CACHE_HOME", t.TempDir()) - done := devinUpstream(t, bytes.Join([][]byte{ - devinFrame(0, pb{}.str(3, "Hello"), false), - devinFrame(0, pb{}.bytes(6, pb{}.str(1, "t1").str(2, "read").str(3, `{"p":1}`)), false), - devinFrame(0, pb{}.varint(5, 10).bytes(7, pb{}.varint(2, 9).varint(3, 3)), false), - devinFrame(2, []byte("{}"), false), - }, nil)) - defer done() - - w := serveDevinOnce(t, provider.Anthropic, `{"model":"x","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`) - var msg struct { - Content []struct { - Text string `json:"text"` - ID string `json:"id"` - Input json.RawMessage `json:"input"` - } `json:"content"` - StopReason string `json:"stop_reason"` - Usage struct { - In int `json:"input_tokens"` - Out int `json:"output_tokens"` - } `json:"usage"` - } - json.Unmarshal(w.Body.Bytes(), &msg) - if w.Code != 200 || len(msg.Content) != 2 || msg.Content[0].Text != "Hello" || msg.Content[1].ID != "t1" || string(msg.Content[1].Input) != `{"p":1}` || - msg.StopReason != "tool_use" || msg.Usage.In != 9 || msg.Usage.Out != 3 { - t.Fatalf("%d %s", w.Code, w.Body) - } - - w = serveDevinOnce(t, provider.Chat, `{"model":"x","stream":true,"messages":[{"role":"user","content":"hi"}]}`) - out := w.Body.String() - if w.Code != 200 || !strings.Contains(out, `"content":"Hello"`) || !strings.Contains(out, `"finish_reason":"tool_calls"`) { - t.Fatalf("%d %s", w.Code, out) - } -} - -// An error at the stream's head is answered with its own status. -func TestServeDevinFailures(t *testing.T) { - t.Setenv("XDG_CONFIG_HOME", t.TempDir()) - t.Setenv("XDG_CACHE_HOME", t.TempDir()) - for _, c := range []struct { - end string - status int - }{ - {`{"error":{"code":"resource_exhausted","message":"out of credits"}}`, 429}, - {`{"error":{"code":"permission_denied","message":"internal error"}}`, 502}, - {`{"error":{"code":"unauthenticated","message":"expired"}}`, 401}, - } { - done := devinUpstream(t, devinFrame(2, []byte(c.end), false)) - w := serveDevinOnce(t, provider.Anthropic, `{"model":"x","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`) - done() - if w.Code != c.status { - t.Errorf("%s: %d %s", c.end, w.Code, w.Body) - } - } -} diff --git a/internal/gateway/devin_tool_ids_test.go b/internal/gateway/devin_tool_ids_test.go deleted file mode 100644 index a8e7566ce..000000000 --- a/internal/gateway/devin_tool_ids_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package gateway - -import ( - "bytes" - "encoding/json" - "regexp" - "strings" - "testing" - - "github.com/yetone/magpie/internal/provider" -) - -// devinRawID is the call id SWE-2 gave in #1304 (StarMoonCity's capture). -// Claude Code takes a tool_use id only of [A-Za-z0-9_-] and dropped the -// call: "The model's tool call could not be parsed (retry also failed)". -const devinRawID = "Bash:0#a65b6a5e02194b87bbc796c4428c946d" - -var anthropicSafeID = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) - -// devinCallReply is Devin's reply making that call. -func devinCallReply() []byte { - return bytes.Join([][]byte{ - devinFrame(0, pb{}.bytes(6, pb{}.str(1, devinRawID).str(2, "Bash").str(3, `{"command":"date"}`)), false), - devinFrame(0, pb{}.varint(5, 10), false), - devinFrame(2, []byte("{}"), false), - }, nil) -} - -// devinIDsSent is the ids of the calls and of the results the request for r -// gives Devin. -func devinIDsSent(t *testing.T, r *Request) (calls, answers []string) { - t.Helper() - for _, m := range decodeDevinRequest(t, buildDevin(r, "swe-2-high", "k")).msgs { - for _, f := range m { - switch f.num { - case 6: - calls = append(calls, string(pbFields(f.data)[0].data)) - case 7: - answers = append(answers, string(f.data)) - } - } - } - return -} - -// On each protocol the call's id reaches the agent of [A-Za-z0-9_-] only, -// and the agent's next request, answering it under that id, gives Devin -// the call and its result under the id Devin gave. -func TestDevinCallIDsSafeBothWays(t *testing.T) { - t.Setenv("XDG_CONFIG_HOME", t.TempDir()) - t.Setenv("XDG_CACHE_HOME", t.TempDir()) - done := devinUpstream(t, devinCallReply()) - defer done() - - for _, c := range []struct { - from provider.Protocol - ask string - id func(body []byte) string - next func(id string) string - parse func([]byte) (*Request, error) - }{ - {provider.Anthropic, `{"model":"x","max_tokens":10,"messages":[{"role":"user","content":"用 Bash 跑一下 date"}]}`, - func(b []byte) string { - var m struct{ Content []struct{ Type, ID string } } - json.Unmarshal(b, &m) - for _, p := range m.Content { - if p.Type == "tool_use" { - return p.ID - } - } - return "" - }, - func(id string) string { - return `{"model":"x","max_tokens":10,"messages":[{"role":"user","content":"用 Bash 跑一下 date"}, - {"role":"assistant","content":[{"type":"tool_use","id":"` + id + `","name":"Bash","input":{"command":"date"}}]}, - {"role":"user","content":[{"type":"tool_result","tool_use_id":"` + id + `","content":"Thu Oct 8 10:00:00 CST 2026"}]}]}` - }, parseAnthropic}, - {provider.Chat, `{"model":"x","messages":[{"role":"user","content":"用 Bash 跑一下 date"}]}`, - func(b []byte) string { - var m struct { - Choices []struct { - Message struct { - ToolCalls []struct{ ID string } `json:"tool_calls"` - } - } - } - json.Unmarshal(b, &m) - if len(m.Choices) == 0 || len(m.Choices[0].Message.ToolCalls) == 0 { - return "" - } - return m.Choices[0].Message.ToolCalls[0].ID - }, - func(id string) string { - return `{"model":"x","messages":[{"role":"user","content":"用 Bash 跑一下 date"}, - {"role":"assistant","content":null,"tool_calls":[{"id":"` + id + `","type":"function","function":{"name":"Bash","arguments":"{\"command\":\"date\"}"}}]}, - {"role":"tool","tool_call_id":"` + id + `","content":"Thu Oct 8 10:00:00 CST 2026"}]}` - }, parseChat}, - {provider.Responses, `{"model":"x","input":"用 Bash 跑一下 date"}`, - func(b []byte) string { - var m struct { - Output []struct { - Type string - CallID string `json:"call_id"` - } - } - json.Unmarshal(b, &m) - for _, o := range m.Output { - if o.Type == "function_call" { - return o.CallID - } - } - return "" - }, - func(id string) string { - return `{"model":"x","input":[{"role":"user","content":"用 Bash 跑一下 date"}, - {"type":"function_call","call_id":"` + id + `","name":"Bash","arguments":"{\"command\":\"date\"}"}, - {"type":"function_call_output","call_id":"` + id + `","output":"Thu Oct 8 10:00:00 CST 2026"}]}` - }, parseResponses}, - } { - w := serveDevinOnce(t, c.from, c.ask) - id := c.id(w.Body.Bytes()) - if w.Code != 200 || !anthropicSafeID.MatchString(id) { - t.Fatalf("%s: call id %q, want one of [A-Za-z0-9_-] only (%d %s)", c.from, id, w.Code, w.Body) - } - r, err := c.parse([]byte(c.next(id))) - if err != nil { - t.Fatalf("%s: %v", c.from, err) - } - calls, answers := devinIDsSent(t, r) - if strings.Join(calls, ",") != devinRawID || strings.Join(answers, ",") != devinRawID { - t.Fatalf("%s: Devin got calls %q, results for %q, want both %q", c.from, calls, answers, devinRawID) - } - } - - // streamed to Claude Code too - w := serveDevinOnce(t, provider.Anthropic, `{"model":"x","max_tokens":10,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) - if out := w.Body.String(); strings.Contains(out, devinRawID) || !strings.Contains(out, `"id":"`+devinOutID(devinRawID)+`"`) { - t.Fatalf("streamed: %s", out) - } -} - -// An id that is already safe goes both ways as it came; one of the -// caller's own that begins dv_ (no id devinOutID makes) does too. -func TestDevinSafeCallIDsUnchanged(t *testing.T) { - for _, id := range []string{"toolu_01AbC", "call_abc-123", "t1", "dv_", "dv_abc"} { - if got := devinInID(devinOutID(id)); got != id { - t.Errorf("%q round-trips to %q", id, got) - } - if got := devinInID(id); got != id { - t.Errorf("%q from the agent reaches Devin as %q", id, got) - } - } - for _, id := range []string{"toolu_01AbC", "call_abc-123"} { - if got := devinOutID(id); got != id { - t.Errorf("%q goes out as %q", id, got) - } - } -} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 1e59f03d8..93f5240d3 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3474,12 +3474,6 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P if from == provider.Anthropic { own = withoutBillingLine(body) } - // Devin's through the API its CLI talks to, with the CLI's sign-in or - // one magpie keeps beside it - if p.Account != nil && p.Account.Agent == "devin" { - call.To = from - return s.serveDevin(w, r, from, p.Account.Home, model, own, &call.Usage) - } // Command Code's Go plan has no Provider API: it is asked where the // CLI asks, in the CLI's own format; its other plans go on as keys do if p.Account != nil && p.Account.Agent == provider.CommandCodePlanID { diff --git a/internal/gateway/required_tools_test.go b/internal/gateway/required_tools_test.go index e1d967be9..412ab4305 100644 --- a/internal/gateway/required_tools_test.go +++ b/internal/gateway/required_tools_test.go @@ -132,9 +132,6 @@ func TestEmptyGeminiAllowlistRejectedBySubscriptionPaths(t *testing.T) { name string call func(*Server, http.ResponseWriter, *http.Request, *Usage) (int, string) }{ - {"Devin", func(s *Server, w http.ResponseWriter, r *http.Request, u *Usage) (int, string) { - return s.serveDevin(w, r, provider.Gemini, "", "m", []byte(body), u) - }}, {"Claude subscription", func(s *Server, w http.ResponseWriter, r *http.Request, u *Usage) (int, string) { return s.serveClaudeSubscription(w, r, provider.Gemini, provider.Provider{ID: "claude"}, "m", []byte(body), u) }}, diff --git a/internal/gateway/split_calls_test.go b/internal/gateway/split_calls_test.go index 35781b615..4b0c7c5dd 100644 --- a/internal/gateway/split_calls_test.go +++ b/internal/gateway/split_calls_test.go @@ -118,22 +118,3 @@ func TestResponsesSplitParallelCallsKeepTheirResults(t *testing.T) { t.Fatalf("input = %s\nwant %s", strings.Join(got, " "), want) } } - -// Devin's answers a reply's calls at the next assistant message, as -// Chat did. -func TestDevinSplitParallelCallsKeepTheirResults(t *testing.T) { - d := decodeDevinRequest(t, buildDevin(parseSplit(t, splitCalls), "swe-2-high", "k")) - var got []string - for _, m := range d.msgs { - got = append(got, devinSummary(m)) - } - want := []string{ - "1:read a and b", - `2: call toolu_a/read {"path":"a"} call toolu_b/read {"path":"b"}`, - "4:A! for toolu_a", - "4:B! for toolu_b", - } - if strings.Join(got, "\n") != strings.Join(want, "\n") { - t.Fatalf("got\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) - } -} diff --git a/internal/provider/account.go b/internal/provider/account.go index c084cb87d..54f5bede0 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -853,9 +853,6 @@ func Accounts() []Provider { if p, ok := copilotAccount(cfg); ok { out = append(out, p) } - if p, ok := devinAccount(); ok { - out = append(out, p) - } if p, ok := commandCodeAccount(); ok { out = append(out, p) } diff --git a/internal/provider/account_test.go b/internal/provider/account_test.go index 859aee545..3230a4d2c 100644 --- a/internal/provider/account_test.go +++ b/internal/provider/account_test.go @@ -78,7 +78,7 @@ func isolate(t *testing.T) { DevinExecutable = func() string { return "" } forgetClaudeCredential() forgetClaudeStatus() - forgetDevinStatus() + devinStatus.forget() // nor Codex's keychain item (#2367): a test's has nothing in it, // whatever the system oldCodexKeychain, oldCodexHere := codexKeychain, codexKeychainHere @@ -109,7 +109,7 @@ func isolate(t *testing.T) { resetCodexKeychain() forgetClaudeCredential() forgetClaudeStatus() - forgetDevinStatus() + devinStatus.forget() }) } diff --git a/internal/provider/cli_identity.go b/internal/provider/cli_identity.go index 2e5fa0d07..a5e4d3f04 100644 --- a/internal/provider/cli_identity.go +++ b/internal/provider/cli_identity.go @@ -181,8 +181,12 @@ func (c *cliIdentity) refresh() chan struct{} { return done } -// cliIdentities are the CLIs asked who is signed in. -func cliIdentities() []*cliIdentity { return []*cliIdentity{cursorStatus, devinStatus} } +// cliIdentities are the CLIs a look at the accounts asks who is signed in. +// Devin's (devinStatus) isn't: its built-in is retired, and only the move +// onto its plugin asks it, waiting itself. Listed here, never asked by a +// look, it stayed unsettled, and every page was told lists were on their +// way. +func cliIdentities() []*cliIdentity { return []*cliIdentity{cursorStatus} } // awaitIdentities waits, at most timeout, for each CLI being asked who is // signed in for the first time: waited, if one was, and unknown, if one diff --git a/internal/provider/devin.go b/internal/provider/devin.go index 8a5530a6b..14d74c0fa 100644 --- a/internal/provider/devin.go +++ b/internal/provider/devin.go @@ -1,18 +1,17 @@ package provider -// PLUGIN-SERVED (see AGENTS.md): Devin ("devin") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-devin-auth, -// once moved onto it (provider.Moved; the default for a new sign-in). A -// moved one's sign-ins, models, requests and usage are all the plugin's, -// never this code's (only the move, in migrate*.go, still reads its -// accounts). A fix here alone doesn't reach those users; fix the plugin -// (github.com/magpie-community/plugins, packages/devin) and raise the -// mover's min in internal/provider/migrate_side.go. +// PLUGIN-SERVED (see AGENTS.md): Devin ("devin") is a retired built-in +// subscription, served by its plugin alone, +// @magpie-community/opencode-devin-auth (provider.BuiltinRetired). Its +// sign-in, requests and usage are the plugin's; what is left here reads +// the accounts signed in to the built-in for the move onto the plugin +// (migrate_side.go), installs and runs the Devin CLI the plugin and the +// devin agent use, and shapes the models listed under "devin" (families, +// variants, contexts, images). A fix belongs in the plugin +// (github.com/magpie-community/plugins, packages/devin), with the mover's +// min raised in internal/provider/migrate_side.go. -// A Devin subscription is served through the API the devin CLI talks to -// (gateway/devin.go), with the key the CLI signed in with; here is who that -// account is, the models it offers, and the sign-in, which is `devin auth -// login`'s. +// Here is who the devin CLI's account is and the models it offers. import ( "context" @@ -75,8 +74,6 @@ func devinIdentity() (user, plan string, ok bool) { return devinStatus.get() } -func forgetDevinStatus() { devinStatus.forget() } - // devinIdentityTimeout is how long `devin auth status` is given: it asks // Devin's servers, and on a real one took 3 to 11 seconds — the 10 seconds // it had dropped the account now and then. @@ -91,14 +88,6 @@ func askDevinStatus() (user, plan string, ok bool, err error) { return askDevinStatusAt(context.Background(), "") } -// askDevinIdentityAt is who the CLI says is signed in in home ("" for its -// own), sure or not: a sign-in has just written the credentials and has to -// name the account. -func askDevinIdentityAt(ctx context.Context, home string) (user, plan string, ok bool) { - u, p, ok, _ := askDevinStatusAt(ctx, home) - return u, p, ok -} - // askDevinStatusAt asks the CLI who is signed in in home ("" for its own), // through the proxy ctx names, else the account's (devinCommand). func askDevinStatusAt(ctx context.Context, home string) (user, plan string, ok bool, err error) { @@ -185,42 +174,6 @@ func parseDevinStatus(out string) (user, plan string, ok bool) { return user, plan, true } -// devinAccount is the Devin account in use first. -func devinAccount() (Provider, bool) { - ls := devinLogins() - if len(ls) == 0 { - return Provider{}, false - } - return devinProvider(ls[0]), true -} - -// devinProvider is one of the Devin accounts; the CLI's own has the plan -// the CLI says now. -func devinProvider(l devinLogin) Provider { - home, plan := l.Home, l.Plan - if home == "" { - if _, p, ok := devinIdentity(); ok { - plan = p - } - } - acct := &Account{Agent: "devin", User: l.User, Plan: plan, Home: home} - acct.models = func() []catalog.Model { - // what a fetch or a picker visit last asked the CLI — never spawn - // one here: Available() runs on every gateway request - return devinModels(devinCached()) - } - acct.fetch = func(ctx context.Context) ([]catalog.Model, error) { - families, err := askDevinFamiliesAt(ctx, home) - if err != nil { - return nil, err - } - ms := devinModels(families) - devinFamiliesCached(families) - return ms, catalog.SaveLive("devin", "", ms) - } - return Provider{ID: "devin", Name: "Devin", Icon: "devin", Website: "https://devin.ai", Account: acct} -} - // DevinFamily is one entry of `devin models list`: a name that follows the // family's newest model, and the pinned variants under it. type DevinFamily struct { @@ -512,13 +465,6 @@ func devinCached() []DevinFamily { return devinFamiliesCache.families } -func devinFamiliesCached(families []DevinFamily) { - devinFamiliesCache.Lock() - devinFamiliesCache.families, devinFamiliesCache.at = families, time.Now() - devinFamiliesCache.failed, devinFamiliesCache.err = time.Time{}, nil - devinFamiliesCache.Unlock() -} - // askDevinFamilies is the model list as the accounts signed in give it, the // one in use first: an account magpie signed in is asked in its own home, // not the CLI's, which may be signed out (蓝猫 on Discord: with only a @@ -623,67 +569,6 @@ func parseDevinModels(b []byte) []DevinFamily { // would write — a var so tests can point it elsewhere. const devinAPIServer = "https://server.codeium.com" -var devinExchangeURL = devinAPIServer + "/exa.seat_management_pb.SeatManagementService/ExchangeDevinCLIPKCECode" - -// devinExchange trades the code for the credentials file `devin auth login` -// writes, then asks the CLI who signed in. The CLI's own login makes the same -// Connect call: the answer's sessionToken — already shaped -// "devin-session-token$" — is the windsurf_api_key the file wants. -func devinExchange(ctx context.Context, code, verifier, redirect string) (savedLogin, error) { - body, _ := json.Marshal(map[string]string{"code": code, - "code_verifier": verifier, "redirect_uri": redirect}) - var res struct { - SessionToken string `json:"sessionToken"` - SessionTokenAlt string `json:"session_token"` - DevinWebappHost string `json:"devinWebappHost"` - DevinAPIURL string `json:"devinApiUrl"` - } - if err := postToken(ctx, devinExchangeURL, "application/json", body, &res); err != nil { - return savedLogin{}, err - } - key := res.SessionToken - if key == "" { - key = res.SessionTokenAlt - } - if key == "" { - return savedLogin{}, errors.New("Devin's exchange returned no session token") - } - creds := devinCredentials(key, devinAPIServer, res.DevinWebappHost, res.DevinAPIURL) - if _, _, err := DevinAuth(); err == nil { - // the CLI is signed in already: this account signs in in a home of - // magpie's, beside it - home, err := newDevinHome() - if err != nil { - return savedLogin{}, err - } - if err := writePrivate(devinCredentialsAt(home), creds); err != nil { - removeDevinHome(home) - return savedLogin{}, err - } - user, plan, err := addDevinLogin(ctx, home) - if err != nil { - removeDevinHome(home) - return savedLogin{}, err - } - forgetAccountCaches() - return savedLogin{Agent: "devin", User: user, Plan: plan, Home: home}, nil - } - // the CLI has no account: writing its file is signing it in, and puts - // the file where `devin auth status` reads it - if err := keepLogin(ctx, func() error { return writePrivate(DevinCredentialsPath(), creds) }); err != nil { - return savedLogin{}, err - } - forgetDevinStatus() - forgetAccountCaches() - user, plan, ok := askDevinIdentityAt(ctx, "") - if !ok { - // the account is only ever seen through the CLI: without it - // answering, magpie has nothing to show and nothing to run - return savedLogin{}, errors.New("signed in, but `devin auth status` doesn't show the account; run it in a terminal to see why") - } - return savedLogin{Agent: "devin", User: user, Plan: plan}, nil -} - // devinCredentials formats credentials.toml the way `devin auth login` // writes it, with the hosts the exchange left out defaulted. func devinCredentials(key, server, webapp, api string) []byte { diff --git a/internal/provider/devin_accounts.go b/internal/provider/devin_accounts.go index 8abe3686e..8b6dedd65 100644 --- a/internal/provider/devin_accounts.go +++ b/internal/provider/devin_accounts.go @@ -1,17 +1,19 @@ package provider -// PLUGIN-SERVED (see AGENTS.md): Devin ("devin") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-devin-auth, -// once moved onto it (provider.Moved; the default for a new sign-in). A -// moved one's sign-ins, models, requests and usage are all the plugin's, -// never this code's (only the move, in migrate*.go, still reads its -// accounts). A fix here alone doesn't reach those users; fix the plugin -// (github.com/magpie-community/plugins, packages/devin) and raise the -// mover's min in internal/provider/migrate_side.go. +// PLUGIN-SERVED (see AGENTS.md): Devin ("devin") is a retired built-in +// subscription, served by its plugin alone, +// @magpie-community/opencode-devin-auth (provider.BuiltinRetired). Its +// sign-in, requests and usage are the plugin's; what is left here reads +// the accounts signed in to the built-in for the move onto the plugin +// (migrate_side.go), installs and runs the Devin CLI the plugin and the +// devin agent use, and shapes the models listed under "devin" (families, +// variants, contexts, images). A fix belongs in the plugin +// (github.com/magpie-community/plugins, packages/devin), with the mover's +// min raised in internal/provider/migrate_side.go. // Several Devin subscriptions. The devin CLI keeps one account, in its -// credentials.toml; magpie signs the CLI in when it has none, and reads it -// after. Each further account gets a home of magpie's own, laid out as the +// credentials.toml. Each further account the built-in signed in got a home +// of magpie's own, laid out as the // CLI's data folder, so the CLI itself answers for it (`devin auth status` // and `devin models list` run with that home as their data folder) and the // CLI's own sign-in is never touched. logins.json names those homes; the @@ -20,7 +22,6 @@ package provider import ( "context" - "errors" "os" "os/exec" "path/filepath" @@ -109,70 +110,8 @@ func devinLogins() []devinLogin { return out } -func devinSide() []sideLogin { - var out []sideLogin - for _, d := range devinLogins() { - out = append(out, sideLogin{Login: d.Login}) - } - return out -} - -// devinLoginList is the Devin accounts as Logins lists them. -func devinLoginList() []Login { return loginsOf(devinSide()) } - -// switchDevinLogin puts a Devin account first. The CLI's own sign-in stays -// as it is: magpie only changes which account its gateway uses first. -func switchDevinLogin(user string) error { return switchSideLogin("devin", user, devinSide()) } - -func setDevinLoginOn(user string, on bool) error { - return setSideLoginOn("devin", user, on, devinSide()) -} - -// forgetDevinLogin drops an account magpie signed in, with its home. The -// CLI's own is only hidden (forgetSideLogin). -func forgetDevinLogin(user string) error { - return forgetSideLogin("devin", user, devinSide(), - func(l savedLogin) { removeDevinHome(l.Home) }) -} - // newDevinHome makes the home a further Devin account is signed in in. func newDevinHome() (string, error) { home := filepath.Join(devinAccountsDir(), strings.ToLower(strings.NewReplacer("-", "", "_", "").Replace(randomToken(9)))) return home, os.MkdirAll(filepath.Join(home, "devin"), 0o700) } - -// removeDevinHome deletes a home magpie made, and nothing else. -func removeDevinHome(home string) { - if rel, err := filepath.Rel(devinAccountsDir(), home); err == nil && rel != "." && !strings.HasPrefix(rel, "..") { - _ = os.RemoveAll(home) - } -} - -// addDevinLogin keeps the account just signed in in home, in use beside -// the others, once the CLI says whose it is. Signed in again, an account -// keeps the newer home. -func addDevinLogin(ctx context.Context, home string) (user, plan string, err error) { - user, plan, ok := askDevinIdentityAt(ctx, home) - if !ok || user == "" { - return "", "", errors.New("signed in, but `devin auth status` doesn't show the account; run it in a terminal to see why") - } - own, _, ownOK := devinIdentity() - if !ownOK { - own = "" - } - return user, plan, keepLogin(ctx, func() error { - return addSideLogin(savedLogin{Agent: "devin", User: user, Plan: plan, Home: home}, own, - func(l savedLogin) { removeDevinHome(l.Home) }) - }) -} - -// devinAlsoOn is the Devin accounts in use behind the first. -func devinAlsoOn() []Provider { - var out []Provider - for _, d := range devinLogins() { - if !d.Active && d.On { - out = append(out, devinProvider(d)) - } - } - return out -} diff --git a/internal/provider/devin_cli_signed_out_test.go b/internal/provider/devin_cli_signed_out_test.go deleted file mode 100644 index 97c38822a..000000000 --- a/internal/provider/devin_cli_signed_out_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package provider - -import ( - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "testing" - - "github.com/yetone/magpie/internal/testenv" -) - -// TestDevinSignedInOnlyInMagpie is 蓝猫's Devin on Discord: the CLI kept a -// sign-in Devin no longer took, so magpie signed the account in in a home -// of its own. Every request failed until `devin auth login`: the model -// list, which turns a family (claude-sonnet-5-5) into the variant Devin's -// API takes, was asked of the CLI's own sign-in only. And once the CLI -// signed in to the same account, it was listed twice. -func TestDevinSignedInOnlyInMagpie(t *testing.T) { - home := claudeHome(t) - data := filepath.Join(home, "data") - t.Setenv("XDG_DATA_HOME", data) - os.MkdirAll(filepath.Join(data, "devin"), 0o700) - cliSignIn := func(key string) { - t.Helper() - if err := os.WriteFile(filepath.Join(data, "devin", "credentials.toml"), devinCredentials(key, "", "", ""), 0o600); err != nil { - t.Fatal(err) - } - forgetDevinStatus() - } - - // a CLI that answers for the key in its data folder's credentials.toml: - // an old account's, one Devin refused, or the account signed in (by - // magpie, or by `devin auth login` after) - exe := filepath.Join(home, "devin") - testenv.Program(t, exe, `#!/bin/sh -f="$XDG_DATA_HOME/devin/credentials.toml" -[ -f "$f" ] || { echo "Not logged in"; exit 1; } -if grep -q refused "$f"; then - if [ "$1" = models ]; then echo "Authentication required: Invalid token" >&2; exit 1; fi - `+devinKeyRefused+` - exit 0 -fi -if [ "$1" = models ]; then - echo '{"families":[{"family_uid":"claude-sonnet-5-5","family_label":"Claude Sonnet 5.5","variants":[{"model_uid":"claude-sonnet-5-5-medium"},{"model_uid":"claude-sonnet-5-5-high"}]}]}' - exit 0 -fi -if grep -q old "$f"; then who=old@example.com; else who=dev@example.com; fi -printf 'Logged in (via Devin).\n\nUser:\n Email: %s\n\nAccount:\n Tier: Devin Pro\n' "$who" -`) - fakeDevin(t, exe) - devinFamiliesCached(nil) - t.Cleanup(func() { devinFamiliesCached(nil) }) - - // the CLI was signed in to another account once, remembered as its own - cliSignIn("devin-session-token$old") - if ls := devinLogins(); len(ls) != 1 || ls[0].User != "old@example.com" || ls[0].Home != "" { - t.Fatalf("CLI's own %+v", ls) - } - // then Devin refused its key: nobody is signed in there - cliSignIn("devin-session-token$refused") - if ls := devinLogins(); len(ls) != 0 { - t.Fatalf("refused %+v", ls) - } - - fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - json.NewEncoder(w).Encode(map[string]any{"sessionToken": "devin-session-token$magpie"}) - })) - defer fake.Close() - oldTok := devinExchangeURL - devinExchangeURL = fake.URL - t.Cleanup(func() { devinExchangeURL = oldTok }) - st, err := StartSignIn("devin") - if err != nil { - t.Fatal(err) - } - finishInBrowser(t, st, "dv-code") - if st = waitDone(t, st.ID); st.State != "done" || st.User != "dev@example.com" || !st.Using { - t.Fatalf("state %+v", st) - } - ls := devinLogins() - if len(ls) != 1 || ls[0].User != "dev@example.com" || ls[0].Home == "" { - t.Fatalf("signed in in magpie %+v", ls) - } - - // a request for the family goes to Devin as its variant at the effort, - // read from the account magpie signed in - if got := DevinVariant(context.Background(), "claude-sonnet-5-5", "high"); got != "claude-sonnet-5-5-high" { - t.Fatalf("variant %q, want claude-sonnet-5-5-high", got) - } - - // `devin auth login` to the same account: still one account - cliSignIn("devin-session-token$cli") - if ls := Logins("devin"); len(ls) != 1 || ls[0].User != "dev@example.com" || !ls[0].Active { - t.Fatalf("after the CLI signed in %+v", ls) - } - if p, ok := devinAccount(); !ok || p.Account.User != "dev@example.com" || p.AlsoOn() != nil { - t.Fatalf("account %+v also %+v", p.Account, p.AlsoOn()) - } -} diff --git a/internal/provider/devin_images.go b/internal/provider/devin_images.go index 3079266c6..48616f5df 100644 --- a/internal/provider/devin_images.go +++ b/internal/provider/devin_images.go @@ -1,13 +1,15 @@ package provider -// PLUGIN-SERVED (see AGENTS.md): Devin ("devin") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-devin-auth, -// once moved onto it (provider.Moved; the default for a new sign-in). A -// moved one's sign-ins, models, requests and usage are all the plugin's, -// never this code's (only the move, in migrate*.go, still reads its -// accounts). A fix here alone doesn't reach those users; fix the plugin -// (github.com/magpie-community/plugins, packages/devin) and raise the -// mover's min in internal/provider/migrate_side.go. +// PLUGIN-SERVED (see AGENTS.md): Devin ("devin") is a retired built-in +// subscription, served by its plugin alone, +// @magpie-community/opencode-devin-auth (provider.BuiltinRetired). Its +// sign-in, requests and usage are the plugin's; what is left here reads +// the accounts signed in to the built-in for the move onto the plugin +// (migrate_side.go), installs and runs the Devin CLI the plugin and the +// devin agent use, and shapes the models listed under "devin" (families, +// variants, contexts, images). A fix belongs in the plugin +// (github.com/magpie-community/plugins, packages/devin), with the mover's +// min raised in internal/provider/migrate_side.go. // Which of Devin's models take images, as Devin tells its CLI: `devin models // list` leaves it out, and models.dev doesn't know Devin's own ids (swe-2, @@ -25,6 +27,9 @@ import ( "time" ) +// devinUsageVersion is the CLI version Devin's API is asked as. +const devinUsageVersion = "3000.11.3" + var devinImagesClient = &http.Client{Timeout: 15 * time.Second} const devinModelConfigsRPC = "/exa.api_server_pb.ApiServerService/GetCliModelConfigs" @@ -39,7 +44,7 @@ var devinImagesAt = func(ctx context.Context, home string) map[string]bool { } ctx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() - // the metadata the gateway's chats send (gateway/devin.go), which the + // the metadata the retired built-in's chats sent, which the // CLI's own requests carry: with the CLI's ide and extension names // alone Devin lists one model meta := devinPB{}.str(1, "devin-cli").str(2, devinUsageVersion).str(3, key).str(4, "en"). diff --git a/internal/provider/devin_models_test.go b/internal/provider/devin_models_test.go index 8aef83054..430e247fc 100644 --- a/internal/provider/devin_models_test.go +++ b/internal/provider/devin_models_test.go @@ -4,6 +4,7 @@ import ( "path/filepath" "strings" "testing" + "time" "github.com/yetone/magpie/internal/catalog" ) @@ -204,3 +205,11 @@ func TestDevinTiers(t *testing.T) { t.Errorf("offered to the agent: %s", got) } } + +// devinFamiliesCached stands in for a model list read from the CLI. +func devinFamiliesCached(families []DevinFamily) { + devinFamiliesCache.Lock() + devinFamiliesCache.families, devinFamiliesCache.at = families, time.Now() + devinFamiliesCache.failed, devinFamiliesCache.err = time.Time{}, nil + devinFamiliesCache.Unlock() +} diff --git a/internal/provider/devin_test.go b/internal/provider/devin_test.go index 8218dfe20..183c02570 100644 --- a/internal/provider/devin_test.go +++ b/internal/provider/devin_test.go @@ -1,18 +1,15 @@ package provider import ( - "encoding/json" - "github.com/yetone/magpie/internal/catalog" - "github.com/yetone/magpie/internal/testenv" - "net/http" - "net/http/httptest" - "net/url" "os" "path/filepath" "runtime" "strings" "testing" "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/testenv" ) func TestParseDevinStatus(t *testing.T) { @@ -175,183 +172,6 @@ func TestDevinCredentials(t *testing.T) { } } -func TestDevinSignIn(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("the fake devin is a shell script") - } - home := claudeHome(t) - t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data")) - - // a CLI that answers `auth status` once the exchange wrote its file - exe := filepath.Join(home, "devin") - testenv.Program(t, exe, "#!/bin/sh\ncat <<'X'\nLogged in (via Devin).\n\nUser:\n Email: dev@example.com\n\nAccount:\n Tier: Devin Pro\nX\n") - oldExe := DevinExecutable - DevinExecutable = func() string { return exe } - t.Cleanup(func() { DevinExecutable = oldExe }) - - var gotCode, gotVerifier, gotRedirect string - fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var body map[string]string - json.NewDecoder(r.Body).Decode(&body) - gotCode, gotVerifier, gotRedirect = body["code"], body["code_verifier"], body["redirect_uri"] - json.NewEncoder(w).Encode(map[string]any{ - "sessionToken": "devin-session-token$sk-test", - "devinWebappHost": "app.devin.ai", "devinApiUrl": "https://api.devin.ai", - }) - })) - defer fake.Close() - oldTok := devinExchangeURL - devinExchangeURL = fake.URL - t.Cleanup(func() { devinExchangeURL = oldTok }) - - st, err := StartSignIn("devin") - if err != nil { - t.Fatal(err) - } - u, _ := url.Parse(st.URL) - if u.Host != "app.devin.ai" || u.Path != "/auth/cli/continue" { - t.Fatalf("url %s", st.URL) - } - q := u.Query() - if q.Get("prompt") != "select_account" || q.Get("code_challenge") == "" || - q.Get("code_challenge_method") != "S256" || q.Get("redirect_uri") == "" || q.Get("state") == "" { - t.Fatalf("params %s", st.URL) - } - page := finishInBrowser(t, st, "dv-code") - if !strings.Contains(page, "signed in") { - t.Fatalf("page %s", page) - } - if st = waitDone(t, st.ID); st.State != "done" || st.User != "dev@example.com" || st.Plan != "Devin Pro" || !st.Using { - t.Fatalf("state %+v", st) - } - if gotCode != "dv-code" || gotVerifier == "" || gotRedirect == "" { - t.Fatalf("exchange code=%q verifier=%q redirect=%q", gotCode, gotVerifier, gotRedirect) - } - // credentials.toml as `devin auth login` would write it - b, err := os.ReadFile(DevinCredentialsPath()) - if err != nil { - t.Fatal(err) - } - for _, want := range []string{`windsurf_api_key = "devin-session-token$sk-test"`, `api_server_url = "https://server.codeium.com"`} { - if !strings.Contains(string(b), want) { - t.Fatalf("credentials %s", b) - } - } - // the CLI's own account, the one in use - if ls := Logins("devin"); len(ls) != 1 || ls[0].User != "dev@example.com" || !ls[0].Active { - t.Fatalf("logins %v", ls) - } -} - -// TestDevinSeveralAccounts signs a second Devin account in beside the CLI's -// own: it gets a home of magpie's, the CLI's file is left alone, and the -// gateway can use either. -func TestDevinSeveralAccounts(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("the fake devin is a shell script") - } - home := claudeHome(t) - data := filepath.Join(home, "data") - t.Setenv("XDG_DATA_HOME", data) - os.MkdirAll(filepath.Join(data, "devin"), 0o700) - own := string(devinCredentials("devin-session-token$own", "", "", "")) - os.WriteFile(filepath.Join(data, "devin", "credentials.toml"), []byte(own), 0o600) - - // a CLI that says whose key is in the credentials.toml of its data folder - exe := filepath.Join(home, "devin") - testenv.Program(t, exe, `#!/bin/sh -f="$XDG_DATA_HOME/devin/credentials.toml" -[ -f "$f" ] || { echo "Not logged in"; exit 1; } -if grep -q own "$f"; then who=dev@example.com; tier="Devin Pro"; else who=two@example.com; tier="Devin Max"; fi -printf 'Logged in (via Devin). - -User: - Email: %s - -Account: - Tier: %s -' "$who" "$tier" -`) - oldExe := DevinExecutable - DevinExecutable = func() string { return exe } - t.Cleanup(func() { DevinExecutable = oldExe }) - forgetDevinStatus() - t.Cleanup(forgetDevinStatus) - - fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - json.NewEncoder(w).Encode(map[string]any{ - "sessionToken": "devin-session-token$two", - "devinWebappHost": "app.devin.ai", "devinApiUrl": "https://api.devin.ai", - }) - })) - defer fake.Close() - oldTok := devinExchangeURL - devinExchangeURL = fake.URL - t.Cleanup(func() { devinExchangeURL = oldTok }) - - signIn := func() SignInState { - st, err := StartSignIn("devin") - if err != nil { - t.Fatal(err) - } - finishInBrowser(t, st, "dv-code") - return waitDone(t, st.ID) - } - if st := signIn(); st.State != "done" || st.User != "two@example.com" || st.Plan != "Devin Max" || st.Using { - t.Fatalf("state %+v", st) - } - // the CLI's own sign-in is as it was - if b, _ := os.ReadFile(DevinCredentialsPath()); string(b) != own { - t.Fatalf("CLI credentials %s", b) - } - ls := devinLogins() - if len(ls) != 2 || ls[0].User != "dev@example.com" || ls[0].Home != "" || !ls[0].Active || - ls[1].User != "two@example.com" || ls[1].Home == "" || !ls[1].On { - t.Fatalf("logins %+v", ls) - } - if key, _, err := DevinAuthAt(ls[1].Home); err != nil || key != "devin-session-token$two" { - t.Fatalf("second key %q %v", key, err) - } - p, ok := devinAccount() - if !ok || p.Account.User != "dev@example.com" || p.Account.Plan != "Devin Pro" { - t.Fatalf("account %+v", p.Account) - } - also := p.AlsoOn() - if len(also) != 1 || also[0].Account.User != "two@example.com" || also[0].Account.Home != ls[1].Home { - t.Fatalf("also on %+v", also) - } - - // signed in again, it is still the one account, in its newer home - first := ls[1].Home - signIn() - if ls = devinLogins(); len(ls) != 2 || ls[1].Home == first { - t.Fatalf("again %+v", ls) - } - if _, err := os.Stat(first); !os.IsNotExist(err) { - t.Fatalf("old home kept: %v", err) - } - - // switched, the gateway uses it first - if err := SwitchLogin("devin", "two@example.com"); err != nil { - t.Fatal(err) - } - if p, _ := devinAccount(); p.Account.User != "two@example.com" || p.Account.Home != ls[1].Home { - t.Fatalf("switched %+v", p.Account) - } - if err := SwitchLogin("devin", "dev@example.com"); err != nil { - t.Fatal(err) - } - if err := ForgetLogin("devin", "two@example.com"); err != nil { - t.Fatal(err) - } - if _, err := os.Stat(ls[1].Home); !os.IsNotExist(err) { - t.Fatalf("home kept: %v", err) - } - if ls = devinLogins(); len(ls) != 1 || ls[0].User != "dev@example.com" { - t.Fatalf("after forget %+v", ls) - } -} - // devinSigned is the CLI's own report, as `devin auth status` prints it. const devinSigned = `printf 'Logged in (via Devin).\n\nUser:\n Email: dev@example.com\n\nAccount:\n Tier: Devin Pro\n'` @@ -387,7 +207,7 @@ func fakeDevin(t *testing.T, exe string) { devinStatus.Lock() devinStatus.user, devinStatus.plan, devinStatus.ok = "", "", false devinStatus.Unlock() - forgetDevinStatus() + devinStatus.forget() }) } diff --git a/internal/provider/devin_usage.go b/internal/provider/devin_usage.go deleted file mode 100644 index 0f4dfec89..000000000 --- a/internal/provider/devin_usage.go +++ /dev/null @@ -1,182 +0,0 @@ -package provider - -// PLUGIN-SERVED (see AGENTS.md): Devin ("devin") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-devin-auth, -// once moved onto it (provider.Moved; the default for a new sign-in). A -// moved one's sign-ins, models, requests and usage are all the plugin's, -// never this code's (only the move, in migrate*.go, still reads its -// accounts). A fix here alone doesn't reach those users; fix the plugin -// (github.com/magpie-community/plugins, packages/devin) and raise the -// mover's min in internal/provider/migrate_side.go. - -// How much of a Devin plan an account has used, as GetUserStatus (what the -// CLI's /usage reads) tells it: the plan's end, the daily and weekly quotas -// a quota-billed plan has (the share left of each, and when it comes back), -// the ACUs a plan with a limit has used this cycle, and the extra usage -// balance. The Devin plugin reads the same. - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "math" - "net/http" - "runtime" - "strconv" - "strings" - "time" -) - -var devinUsageClient = &http.Client{Timeout: 20 * time.Second} - -// devinUsageVersion is the CLI version GetUserStatus is asked as, the one -// the gateway's chats name. -const devinUsageVersion = "3000.11.3" - -// devinNum reads a number JSON gives as a number or a string (int64s are -// strings in proto JSON); ok is false when it is left out. -func devinNum(raw json.RawMessage) (float64, bool) { - if len(raw) == 0 || string(raw) == "null" { - return 0, false - } - var s string - if json.Unmarshal(raw, &s) == nil { - f, err := strconv.ParseFloat(strings.TrimSpace(s), 64) - return f, err == nil - } - var f float64 - return f, json.Unmarshal(raw, &f) == nil -} - -type devinPlanStatus struct { - PlanInfo struct { - HideDaily bool `json:"hideDailyQuota"` - HideWeekly bool `json:"hideWeeklyQuota"` - Billing string `json:"billingStrategy"` - } `json:"planInfo"` - PlanEnd string `json:"planEnd"` - DailyLeft json.RawMessage `json:"dailyQuotaRemainingPercent"` - DailyReset json.RawMessage `json:"dailyQuotaResetAtUnix"` - WeeklyLeft json.RawMessage `json:"weeklyQuotaRemainingPercent"` - WeeklyReset json.RawMessage `json:"weeklyQuotaResetAtUnix"` - ACULimit json.RawMessage `json:"acuLimit"` - ACUUsed json.RawMessage `json:"acuConsumed"` - Overage json.RawMessage `json:"overageBalanceMicros"` -} - -// devinQuota fills q from a plan's status. JSON leaves a 0 out, so on a -// quota-billed plan a quota with a reset and no share left is used up: a -// week at 0% left came as no weeklyQuotaRemainingPercent beside the day's -// 100, and the day alone was shown, at 0% (面条 on magpie's Discord). -// Billed otherwise, a share left out is no quota. -func devinQuota(q *SubscriptionQuota, st devinPlanStatus) { - var end *time.Time - if t, err := time.Parse(time.RFC3339Nano, st.PlanEnd); err == nil { - end = &t - q.Until = &t - } - quota := st.PlanInfo.Billing == "BILLING_STRATEGY_QUOTA" - for _, w := range []struct { - name string - span time.Duration - left, reset json.RawMessage - hide bool - }{ - {"1 day", 24 * time.Hour, st.DailyLeft, st.DailyReset, st.PlanInfo.HideDaily}, - {"7 days", 7 * 24 * time.Hour, st.WeeklyLeft, st.WeeklyReset, st.PlanInfo.HideWeekly}, - } { - left, ok := devinNum(w.left) - at, _ := devinNum(w.reset) - if w.hide || !ok && !(quota && at > 0) { - continue - } - x := QuotaWindow{Name: w.name, Used: min(100, max(0, 100-left)), Span: w.span} - if at > 0 { - t := time.Unix(int64(at), 0).UTC() - x.ResetsAt = &t - } - q.Windows = append(q.Windows, x) - } - if limit, _ := devinNum(st.ACULimit); limit > 0 { - used, _ := devinNum(st.ACUUsed) - q.Windows = append(q.Windows, QuotaWindow{Name: "ACUs", Used: min(100, 100*used/limit), - Display: devinACUs(used) + " / " + devinACUs(limit) + " ACUs", ResetsAt: end, Aside: true}) - } - if extra, _ := devinNum(st.Overage); extra > 0 { - q.Balance = fmt.Sprintf("$%.2f", extra/1e6) - } -} - -// devinACUs writes an ACU count as the plugin does: to two decimals, none -// trailing. -func devinACUs(f float64) string { - return strconv.FormatFloat(math.Round(f*100)/100, 'f', -1, 64) -} - -func devinLoginQuota(ctx context.Context, l Login) SubscriptionQuota { - q := SubscriptionQuota{Provider: "devin", Name: "Devin", Icon: "devin", Plan: l.Plan, User: l.User, Windows: []QuotaWindow{}} - home, found := "", false - for _, d := range devinLogins() { - if d.User == l.User { - home, found = d.Home, true - break - } - } - if !found { - q.Error = "no such Devin account" - return q - } - key, server, err := DevinAuthAt(home) - if err != nil { - q.Error = err.Error() - return q - } - ctx, cancel := context.WithTimeout(ctx, 15*time.Second) - defer cancel() - st, err := devinUserStatus(ctx, key, server) - if err != nil { - q.Error = err.Error() - return q - } - devinQuota(&q, st) - return q -} - -var errDevinUsageSignIn = errors.New("Devin's sign-in has expired — sign in again") - -func devinUserStatus(ctx context.Context, key, server string) (devinPlanStatus, error) { - body, _ := json.Marshal(map[string]any{"metadata": map[string]any{ - "ideName": "devin-cli", "ideVersion": devinUsageVersion, "extensionName": "devin-cli", - "extensionVersion": devinUsageVersion, "apiKey": key, "locale": "en", "os": runtime.GOOS, - }}) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, server+"/exa.seat_management_pb.SeatManagementService/GetUserStatus", bytes.NewReader(body)) - if err != nil { - return devinPlanStatus{}, err - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Connect-Protocol-Version", "1") - res, err := devinUsageClient.Do(req) - if err != nil { - return devinPlanStatus{}, err - } - defer res.Body.Close() - b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20)) - var env struct { - Code string `json:"code"` - Message string `json:"message"` - UserStatus struct { - PlanStatus devinPlanStatus `json:"planStatus"` - } `json:"userStatus"` - } - _ = json.Unmarshal(b, &env) - if res.StatusCode == http.StatusUnauthorized || env.Code == "unauthenticated" { - return devinPlanStatus{}, errDevinUsageSignIn - } - if res.StatusCode != http.StatusOK { - return devinPlanStatus{}, fmt.Errorf("Devin: %s", APIError(b, res.Status)) - } - return env.UserStatus.PlanStatus, nil -} diff --git a/internal/provider/devin_usage_test.go b/internal/provider/devin_usage_test.go deleted file mode 100644 index 6739bf915..000000000 --- a/internal/provider/devin_usage_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package provider - -import ( - "context" - "encoding/json" - "io" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/yetone/magpie/internal/testenv" -) - -// TestDevinUsage: magpie's built-in Devin account showed no usage while the -// Devin plugin showed its day, week and ACU windows; both read -// GetUserStatus now, and a key Devin refuses says to sign in again. The -// CLI's own account had no plan either, where the plugin's said its tier. -func TestDevinUsage(t *testing.T) { - home := claudeHome(t) - data := filepath.Join(home, "data") - t.Setenv("XDG_DATA_HOME", data) - os.MkdirAll(filepath.Join(data, "devin"), 0o700) - os.WriteFile(filepath.Join(data, "devin", "credentials.toml"), devinCredentials("devin-session-token$good", "", "", ""), 0o600) - exe := filepath.Join(home, "devin") - testenv.Program(t, exe, `#!/bin/sh -printf 'Logged in (via Devin).\n\nUser:\n Email: dev@example.com\n\nAccount:\n Tier: Devin Pro\n' -`) - fakeDevin(t, exe) - forgetDevinStatus() - old := firstAsk - firstAsk = time.Minute // a loaded machine's shell takes longer than a look's first wait - t.Cleanup(func() { firstAsk = old }) - - var asked map[string]any - fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/exa.seat_management_pb.SeatManagementService/GetUserStatus" || r.Header.Get("Connect-Protocol-Version") != "1" { - http.NotFound(w, r) - return - } - b, _ := io.ReadAll(r.Body) - json.Unmarshal(b, &asked) - if strings.Contains(string(b), "refused") { - w.WriteHeader(http.StatusUnauthorized) - io.WriteString(w, `{"code":"unauthenticated","message":"bad key"}`) - return - } - io.WriteString(w, `{"userStatus":{"planStatus":{"planInfo":{"planName":"Pro"},"planEnd":"2026-11-01T00:00:00Z", - "dailyQuotaRemainingPercent":75,"dailyQuotaResetAtUnix":"1790000000", - "weeklyQuotaRemainingPercent":"40","weeklyQuotaResetAtUnix":"1790500000", - "acuLimit":"250","acuConsumed":12.345,"overageBalanceMicros":"5000000"}}}`) - })) - defer fake.Close() - t.Setenv("WINDSURF_API_SERVER_URL", fake.URL) - - ls, ok := builtinLogins("devin") - // the CLI's own account is named by its tier, as the plugin names it - if !ok || len(ls) != 1 || ls[0].User != "dev@example.com" || ls[0].Plan != "Devin Pro" { - t.Fatalf("logins %+v %v", ls, ok) - } - q := loginQuota(context.Background(), ls[0]) - if q.Error != "" { - t.Fatal(q.Error) - } - if md, _ := asked["metadata"].(map[string]any); md["apiKey"] != "devin-session-token$good" || md["ideName"] != "devin-cli" { - t.Fatalf("asked %v", asked) - } - if len(q.Windows) != 3 { - t.Fatalf("windows %+v", q.Windows) - } - day, week, acu := q.Windows[0], q.Windows[1], q.Windows[2] - if day.Name != "1 day" || day.Used != 25 || day.ResetsAt == nil || day.ResetsAt.Unix() != 1790000000 { - t.Fatalf("day %+v", day) - } - if week.Name != "7 days" || week.Used != 60 || week.Span != 7*24*time.Hour { - t.Fatalf("week %+v", week) - } - if acu.Name != "ACUs" || !acu.Aside || acu.Display != "12.35 / 250 ACUs" || acu.ResetsAt == nil { - t.Fatalf("acu %+v", acu) - } - if q.Until == nil || q.Until.Format("2006-01-02") != "2026-11-01" || q.Balance != "$5.00" { - t.Fatalf("plan %+v", q) - } - - os.WriteFile(filepath.Join(data, "devin", "credentials.toml"), devinCredentials("devin-session-token$refused", "", "", ""), 0o600) - if q := loginQuota(context.Background(), ls[0]); q.Error != "Devin's sign-in has expired — sign in again" { - t.Fatalf("refused %+v", q) - } -} - -// TestDevinWeekUsedUpHolds: 面条 on magpie's Discord — Devin has a daily -// and a weekly quota, and with the week used up only the day showed, at -// 0%, while routing kept sending to the account. JSON leaves a 0 out, so -// the week came as no weeklyQuotaRemainingPercent beside the day's 100 -// (the rest as the owner's real Teams account answers GetUserStatus). -func TestDevinWeekUsedUpHolds(t *testing.T) { - const status = `{"planInfo":{"teamsTier":"TEAMS_TIER_DEVIN_TEAMS_V2","planName":"Teams","monthlyPromptCredits":-1,"isTeams":true,"isDevin":true,"billingStrategy":"BILLING_STRATEGY_QUOTA"}, - "planStart":"2026-09-26T21:45:55Z","planEnd":"2026-10-26T21:45:55Z","availablePromptCredits":-1, - "dailyQuotaRemainingPercent":100,"overageBalanceMicros":"46807746", - "dailyQuotaResetAtUnix":"1791705600","weeklyQuotaResetAtUnix":"1792051200"}` - var st devinPlanStatus - if err := json.Unmarshal([]byte(status), &st); err != nil { - t.Fatal(err) - } - var q SubscriptionQuota - devinQuota(&q, st) - if len(q.Windows) != 2 || q.Windows[0].Name != "1 day" || q.Windows[0].Used != 0 || - q.Windows[1].Name != "7 days" || q.Windows[1].Used != 100 || q.Windows[1].ResetsAt == nil || q.Windows[1].ResetsAt.Unix() != 1792051200 { - t.Fatalf("windows %+v", q.Windows) - } - now := time.Unix(1791700000, 0) - if till := allowanceOf(q.Windows, now).Full("swe-2", 100, now); till.Unix() != 1792051200 { - t.Fatalf("held till %v, want the week's reset", till) - } - - // billed otherwise, a share left out is no quota - var credits devinPlanStatus - json.Unmarshal([]byte(strings.Replace(status, "BILLING_STRATEGY_QUOTA", "BILLING_STRATEGY_CREDITS", 1)), &credits) - var c SubscriptionQuota - devinQuota(&c, credits) - if len(c.Windows) != 1 || c.Windows[0].Name != "1 day" { - t.Fatalf("credits windows %+v", c.Windows) - } -} diff --git a/internal/provider/fetching_new_test.go b/internal/provider/fetching_new_test.go index 021eca555..2f25deda4 100644 --- a/internal/provider/fetching_new_test.go +++ b/internal/provider/fetching_new_test.go @@ -166,18 +166,18 @@ func TestFetchingNewOnceStarted(t *testing.T) { // waiting on it, which the page doesn't (#541); the fetch lists them // and waits behind the page, which is told lists are on their way until // it has (yetone on #1147, #1789) - wasDevin, wasFirst := devinStatus, firstAsk - defer func() { devinStatus, firstAsk = wasDevin, wasFirst }() + wasCursor, wasFirst := cursorStatus, firstAsk + defer func() { cursorStatus, firstAsk = wasCursor, wasFirst }() firstAsk = 5 * time.Second // long, to tell a look's wait from none for _, asked := range []bool{false, true} { answer := make(chan struct{}) - devinStatus = &cliIdentity{name: "devin-test", exe: func() string { return "" }, read: true, + cursorStatus = &cliIdentity{name: "cursor-test", exe: func() string { return "" }, read: true, ask: func() (string, string, bool, error) { <-answer; return "", "", false, nil }} if asked { - devinStatus.Lock() - devinStatus.waited = true // its look gave up already - devinStatus.refresh() - devinStatus.Unlock() + cursorStatus.Lock() + cursorStatus.waited = true // its look gave up already + cursorStatus.refresh() + cursorStatus.Unlock() } start = time.Now() FetchNewBehind(5 * time.Second) @@ -199,7 +199,7 @@ func TestFetchingNewOnceStarted(t *testing.T) { // way, not that none is due. The forget is that listing's own, and the CLI // answers only once the page was told: a read another test left running // (a usage refresh reads Grok's account, then Cursor's) took the first -// GrokExecutable call, forgot Cursor before the listing read it, and +// GrokExecutable call (the hook is Kiro's kiro-cli lookup now), forgot Cursor before the listing read it, and // Cursor answered nobody at once, so nothing was left to wait on and // nothing was due (#2390, red on ubuntu CI). func TestFetchingNewForgottenWhileListed(t *testing.T) { @@ -216,11 +216,11 @@ func TestFetchingNewForgottenWhileListed(t *testing.T) { ForgetAccounts() answer := make(chan struct{}) answered := sync.OnceFunc(func() { close(answer) }) - wasCursor, wasDevin, wasGrok := cursorStatus, devinStatus, GrokExecutable + wasCursor, wasDB := cursorStatus, kiroCLIDB t.Cleanup(func() { answered() waitFetchingNew(t) - cursorStatus, devinStatus, GrokExecutable = wasCursor, wasDevin, wasGrok + cursorStatus, kiroCLIDB = wasCursor, wasDB ForgetAccounts() }) nobody := func() (string, string, bool, error) { return "", "", false, nil } @@ -229,16 +229,15 @@ func TestFetchingNewForgottenWhileListed(t *testing.T) { cursor := &cliIdentity{name: "cursor-test", exe: func() string { return "" }, read: true, at: now, ask: func() (string, string, bool, error) { <-answer; return nobody() }} cursorStatus = cursor - devinStatus = &cliIdentity{name: "devin-test", exe: func() string { return "" }, read: true, at: now, ask: nobody} - // Grok's account is read after Cursor's: the sign-in lands there, in + // Kiro's account is read after Cursor's: the sign-in lands there, in // the page's own listing, not in anything else reading the accounts var once sync.Once - GrokExecutable = func() string { + kiroCLIDB = func() string { b := make([]byte, 64<<10) if strings.Contains(string(b[:runtime.Stack(b, false)]), "provider.FetchNewBehind(") { once.Do(cursor.forget) } - return "" + return wasDB() } FetchNewBehind(5 * time.Second) diff --git a/internal/provider/install_test.go b/internal/provider/install_test.go index d438e6e0e..d0460c5a6 100644 --- a/internal/provider/install_test.go +++ b/internal/provider/install_test.go @@ -3,9 +3,6 @@ package provider import ( "context" "errors" - "net/http" - "net/http/httptest" - "os" "os/exec" "path/filepath" "runtime" @@ -16,75 +13,8 @@ import ( "github.com/yetone/magpie/internal/testenv" ) -// a sign-in that needs a CLI this machine lacks installs it, then goes on -func TestSignInInstallsMissingCLI(t *testing.T) { - if os.PathSeparator != '/' { - t.Skip("the fake devin is a shell script") - } - home := claudeHome(t) - t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data")) - exe := filepath.Join(home, "bin", "devin") - oldExe := DevinExecutable - DevinExecutable = func() string { - if isFile(exe) { - return exe - } - return "" - } - t.Cleanup(func() { DevinExecutable = oldExe }) - // an early failure ends the test with the install still held: the - // fake then gives up without touching the test that has gone - release, ended := make(chan struct{}), make(chan struct{}) - t.Cleanup(func() { close(ended) }) - var ran string - oldRun := runInstaller - runInstaller = func(ctx context.Context, c agentCLI) ([]byte, error) { - ran = c.sh - select { - case <-release: - case <-ended: - return nil, errors.New("the test ended") - } - os.MkdirAll(filepath.Dir(exe), 0o755) - // not testenv.Program: this runs on the sign-in's goroutine, which a - // failed test can leave behind - if err := testenv.WriteProgram(exe, "#!/bin/sh\nprintf 'Logged in (via Devin).\\n Email: dev@example.com\\n Tier: Devin Pro\\n'\n"); err != nil { - return nil, err - } - // as Devin's does: `devin setup` gives up on its sign-in without a terminal - return []byte("Installed devin\nError: Login canceled\n"), errors.New("exit status 1") - } - t.Cleanup(func() { runInstaller = oldRun }) - fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"sessionToken":"devin-session-token$sk-test"}`)) - })) - defer fake.Close() - oldTok := devinExchangeURL - devinExchangeURL = fake.URL - t.Cleanup(func() { devinExchangeURL = oldTok }) - - st, err := StartSignIn("devin") - if err != nil { - t.Fatal(err) - } - if st.State != "installing" || st.Installing != "Devin CLI" || st.URL != "" { - t.Fatalf("started %+v", st) - } - close(release) - st = waitPast(t, st.ID, "installing") - if st.State != "waiting" || !strings.HasPrefix(st.URL, devinAuthorizeURL) || st.Installing != "" { - t.Fatalf("after install %+v", st) - } - if !strings.Contains(ran, "cli.devin.ai/install.sh") { - t.Fatalf("installer %q", ran) - } - finishInBrowser(t, st, "dv-code") - if st = waitDone(t, st.ID); st.State != "done" || st.User != "dev@example.com" { - t.Fatalf("state %+v", st) - } -} - -// an installer that fails says so, and how to install it by hand +// an installer that fails says so, and how to install it by hand: Devin's +// plugin signs in through the CLI, which is installed first func TestSignInInstallFails(t *testing.T) { claudeHome(t) oldExe := DevinExecutable @@ -96,7 +26,7 @@ func TestSignInInstallFails(t *testing.T) { } t.Cleanup(func() { runInstaller = oldRun }) - st, err := StartSignIn("devin") + st, err := StartPluginSignIn("devin", 0, nil) if err != nil { t.Fatal(err) } @@ -145,7 +75,7 @@ func TestSignInCanceledWhileInstalling(t *testing.T) { } t.Cleanup(func() { runInstaller = oldRun }) - st, _ := StartSignIn("devin") + st, _ := StartPluginSignIn("devin", 0, nil) CancelSignIn(st.ID) select { case <-stopped: @@ -157,36 +87,6 @@ func TestSignInCanceledWhileInstalling(t *testing.T) { } } -// signed in, but the CLI can't see it: a failure, not "done" with no one -func TestDevinSignInUnseen(t *testing.T) { - if os.PathSeparator != '/' { - t.Skip("the fake devin is a shell script") - } - home := claudeHome(t) - t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data")) - exe := filepath.Join(home, "devin") - testenv.Program(t, exe, "#!/bin/sh\necho 'Not logged in.'\n") - oldExe := DevinExecutable - DevinExecutable = func() string { return exe } - t.Cleanup(func() { DevinExecutable = oldExe }) - fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"sessionToken":"devin-session-token$sk-test"}`)) - })) - defer fake.Close() - oldTok := devinExchangeURL - devinExchangeURL = fake.URL - t.Cleanup(func() { devinExchangeURL = oldTok }) - - st, err := StartSignIn("devin") - if err != nil { - t.Fatal(err) - } - finishInBrowser(t, st, "dv-code") - if st = waitDone(t, st.ID); st.State != "failed" || !strings.Contains(st.Error, "devin auth status") { - t.Fatalf("state %+v", st) - } -} - func waitPast(t *testing.T, id, state string) SignInState { t.Helper() for end := time.Now().Add(signInDeadline); time.Now().Before(end); time.Sleep(20 * time.Millisecond) { diff --git a/internal/provider/left_alone_test.go b/internal/provider/left_alone_test.go index 150810cb0..954c736ee 100644 --- a/internal/provider/left_alone_test.go +++ b/internal/provider/left_alone_test.go @@ -36,8 +36,7 @@ func TestLeftAloneRunsNoCLI(t *testing.T) { // the real lookups, which find them on PATH claudeExecutable, DevinExecutable = claudecode.Find, findDevin forgetClaudeStatus() - forgetDevinStatus() - t.Cleanup(func() { forgetClaudeStatus(); forgetDevinStatus() }) + t.Cleanup(forgetClaudeStatus) runs := func() []string { b, _ := os.ReadFile(log) @@ -92,11 +91,12 @@ func TestLeftAloneRunsNoCLI(t *testing.T) { t.Fatalf("claude switched off: %+v %v", p, ok) } - // switched on, the same loop asks them: the fakes are the ones found + // switched on, the same loop asks them: the fakes are the ones found. + // Devin's built-in is retired, so nothing here asks its CLI either way. save(false, false) loop() got := strings.Join(runs(), " ") - for _, want := range []string{"claude_auth_status_--json", "devin_auth_status"} { + for _, want := range []string{"claude_auth_status_--json"} { if !strings.Contains(got, want) { t.Errorf("switched on, no %s among %s", want, got) } diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index 78e267b3b..47b017c1b 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -265,8 +265,6 @@ func builtinLogins(agent string) (logins []Login, ok bool) { logins = copilotLoginList() case CommandCodePlanID: logins = cmdLoginList() - case "devin": - logins = devinLoginList() case ChatGPTAPIID: logins = siwcLoginList() case "gemini", "antigravity": @@ -292,9 +290,6 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota { if strings.HasPrefix(l.Agent, "plugin:") { return pluginLoginQuota(ctx, l) } - if l.Agent == "devin" { - return devinLoginQuota(ctx, l) - } if l.Agent == "gemini" || l.Agent == "antigravity" { return googleLoginQuota(ctx, l) } diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 0cab3a756..079a8c94f 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -807,8 +807,6 @@ func Logins(agent string) []Login { switch agent { case "copilot": return copilotLoginList() - case "devin": - return devinLoginList() case CommandCodePlanID: return cmdLoginList() case ChatGPTAPIID: @@ -834,7 +832,7 @@ func Logins(agent string) []Login { list func() []Login }{ {"grok", nil}, {"copilot", copilotLoginList}, {"zcode", nil}, {"kiro", nil}, - {"devin", devinLoginList}, {"workbuddy", nil}, {WorkBuddyAIID, nil}, {CommandCodePlanID, cmdLoginList}, + {"devin", nil}, {"workbuddy", nil}, {WorkBuddyAIID, nil}, {CommandCodePlanID, cmdLoginList}, {"qoder", nil}, {QoderCNID, nil}, {"zed", nil}, {"factory", nil}, {MiMoID, nil}, {ChatGPTAPIID, siwcLoginList}, {"gemini", func() []Login { return googleLoginList("gemini") }}, {"antigravity", func() []Login { return googleLoginList("antigravity") }}, @@ -1032,8 +1030,6 @@ func switchLogin(agent, user string) error { switch agent { case "copilot": return switchCopilotLogin(user) - case "devin": - return switchDevinLogin(user) case CommandCodePlanID: return switchCommandCodeLogin(user) case ChatGPTAPIID: @@ -1210,8 +1206,6 @@ func ForgetLogin(agent, user string) error { switch agent { case "copilot": return forgetCopilotLogin(user) - case "devin": - return forgetDevinLogin(user) case CommandCodePlanID: return forgetCommandCodeLogin(user) case ChatGPTAPIID: diff --git a/internal/provider/logins_on.go b/internal/provider/logins_on.go index ba13175f7..e8d6e9576 100644 --- a/internal/provider/logins_on.go +++ b/internal/provider/logins_on.go @@ -37,8 +37,6 @@ func SetLoginOn(agent, user string, on bool) error { switch agent { case "copilot": return setCopilotLoginOn(user, on) - case "devin": - return setDevinLoginOn(user, on) case CommandCodePlanID: return setCommandCodeLoginOn(user, on) case ChatGPTAPIID: @@ -139,9 +137,6 @@ func (p Provider) alsoOn() []Provider { if p.Account != nil && p.Account.Agent == "copilot" { return copilotAlsoOn() } - if p.Account != nil && p.Account.Agent == "devin" { - return devinAlsoOn() - } if p.Account != nil && p.Account.Agent == CommandCodePlanID { return commandCodeAlsoOn() } diff --git a/internal/provider/migrate.go b/internal/provider/migrate.go index 596fad348..52416324e 100644 --- a/internal/provider/migrate.go +++ b/internal/provider/migrate.go @@ -275,6 +275,7 @@ var retiredBuiltins = map[string]bool{ "zcode": true, "factory": true, "grok": true, + "devin": true, } // PluginServes is whether the built-in id's subscription is its plugin's to diff --git a/internal/provider/migrate_parity_test.go b/internal/provider/migrate_parity_test.go index 970b92a14..e303263fd 100644 --- a/internal/provider/migrate_parity_test.go +++ b/internal/provider/migrate_parity_test.go @@ -83,7 +83,7 @@ func TestDevinOwnMovesWithPlan(t *testing.T) { devinStatus.Lock() devinStatus.user, devinStatus.plan, devinStatus.ok, devinStatus.at = "dev@example.com", "Devin Pro", true, time.Now() devinStatus.Unlock() - t.Cleanup(forgetDevinStatus) + t.Cleanup(devinStatus.forget) own := movingOf(t, "devin")["dev@example.com"] md, _ := own.Auth["metadata"].(map[string]any) if !own.Own || own.Plan != "Devin Pro" || md["plan"] != "Devin Pro" { diff --git a/internal/provider/modelprefs.go b/internal/provider/modelprefs.go index f5fb4c24f..e8f2ce2b9 100644 --- a/internal/provider/modelprefs.go +++ b/internal/provider/modelprefs.go @@ -1265,7 +1265,7 @@ func (p Provider) asksOwnBackend() bool { return false } switch p.Account.Agent { - case "claude", "devin", CommandCodePlanID: + case "claude", CommandCodePlanID: return true } return false diff --git a/internal/provider/signin.go b/internal/provider/signin.go index 229b46fbe..d0b549444 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -374,24 +374,6 @@ func (s *signInFlow) begin() error { s.mu.Lock() s.st.URL = siwcAuthorize(s.redirect, s.state, s.nonce, challenge, s.hostID) s.mu.Unlock() - case "devin": - // `devin auth login` is a TUI over this same PKCE + localhost - // callback, so magpie runs the round itself - if ln, err = net.Listen("tcp", "127.0.0.1:0"); err != nil { - return err - } - s.redirect = fmt.Sprintf("http://127.0.0.1:%d/callback", ln.Addr().(*net.TCPAddr).Port) - q.Set("redirect_uri", s.redirect) - q.Set("state", s.state) - q.Set("prompt", "select_account") - q.Set("code_challenge", challenge) - q.Set("code_challenge_method", "S256") - q.Set("cli_pkce_marker", "1") - // set with the lock: the window follows a sign-in that installed - // devin first while this runs - s.mu.Lock() - s.st.URL = devinAuthorizeURL + "?" + q.Encode() - s.mu.Unlock() case "copilot": // GitHub's device code, as Copilot's editors sign in if err := startCopilotSignIn(s); err != nil { @@ -733,18 +715,6 @@ func (s *signInFlow) callback(w http.ResponseWriter, r *http.Request) { return } l, err := s.exchange(ctx, q.Get("code")) - if err == nil && s.st.Agent == "devin" { - // the exchange kept it already: the CLI's own, or one beside it - using := false - for _, d := range devinLogins() { - if strings.EqualFold(d.User, l.User) { - using = d.Active - } - } - s.finish(SignInState{State: "done", User: l.User, Plan: l.Plan, Using: using}) - signInPage(w, true, "You're signed in", fmt.Sprintf("%s is added to magpie. You can close this tab.", l.User)) - return - } if err == nil { var using bool if err = keepLogin(ctx, func() (err error) { using, err = addLogin(l); return err }); err == nil { @@ -779,11 +749,7 @@ func (s *signInFlow) googleDone(ctx context.Context, w http.ResponseWriter, app // exchange trades the code for tokens and makes them into a login. func (s *signInFlow) exchange(ctx context.Context, code string) (savedLogin, error) { - switch s.st.Agent { - case "codex": - return codexExchange(ctx, code, s.verifier, s.redirect) - } - return devinExchange(ctx, code, s.verifier, s.redirect) + return codexExchange(ctx, code, s.verifier, s.redirect) } func postToken(ctx context.Context, tokenURL, ctype string, body []byte, out any) error { diff --git a/internal/provider/signin_proxy_test.go b/internal/provider/signin_proxy_test.go index 8dbc765f9..c8fa97e60 100644 --- a/internal/provider/signin_proxy_test.go +++ b/internal/provider/signin_proxy_test.go @@ -342,8 +342,9 @@ func TestChatGPTSignOutGoesThroughItsProxy(t *testing.T) { } // Devin's CLI, asked who is signed in and for its models, runs with the -// account's own proxy, and while a sign-in asks it, with the proxy the -// sign-in goes through, where it always had the global one (#1663). +// account's own proxy, where it always had the global one (#1663). The +// built-in's sign-in is retired; the plugin's goes through its proxy in +// TestPluginSignInGoesThroughItsProxy. func TestDevinCLIGoesThroughItsProxy(t *testing.T) { shellFakes(t) home := claudeHome(t) @@ -373,15 +374,15 @@ Account: ' "$who" `) fakeDevin(t, exe) - exchange := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - json.NewEncoder(w).Encode(map[string]any{"sessionToken": "devin-session-token$two"}) - })) - t.Cleanup(exchange.Close) - oldTok := devinExchangeURL - devinExchangeURL = exchange.URL - t.Cleanup(func() { devinExchangeURL = oldTok }) const sub, mine, picked = "http://127.0.0.1:7001", "http://127.0.0.1:7002", "http://127.0.0.1:7003" - setProxies(t, "devin", sub, map[string]string{"dev@example.com": mine}) + setProxies(t, "devin", sub, map[string]string{"dev@example.com": mine, "two@example.com": picked}) + // the CLI's own account, and a second one in a home of magpie's + two, _ := newDevinHome() + os.WriteFile(devinCredentialsAt(two), devinCredentials("devin-session-token$two", "", "", ""), 0o600) + writeLogins([]savedLogin{ + {Agent: "devin", User: "dev@example.com", On: true, First: true}, + {Agent: "devin", User: "two@example.com", Home: two, On: true}, + }) ran := func() []string { b, _ := os.ReadFile(runs) os.Remove(runs) @@ -393,35 +394,10 @@ Account: } return out } - forgetDevinStatus() + devinStatus.forget() ran() - // a second account, signed in through a proxy picked for it: the CLI - // asked whose it is runs with that proxy - p := picked - st, err := StartSignInWith("devin", SignInOptions{Proxy: &p}) - if err != nil { - t.Fatal(err) - } - finishInBrowser(t, st, "dv-code") - if st = waitDone(t, st.ID); st.State != "done" || st.User != "two@example.com" { - t.Fatalf("state %+v", st) - } - if got := ran(); !slices.Contains(got, "two@example.com auth "+picked) || - slices.ContainsFunc(got, func(l string) bool { return strings.HasPrefix(l, "two@") && !strings.HasSuffix(l, " "+picked) }) { - t.Fatalf("the sign-in ran the CLI as %q", got) - } - - // later, each account's CLI runs with that account's own proxy - var homeOf = map[string]string{} - for _, l := range devinLogins() { - homeOf[l.User] = l.Home - } - two, ok := homeOf["two@example.com"] - if !ok || two == "" { - t.Fatalf("logins %v", homeOf) - } - ran() + // each account's CLI runs with that account's own proxy if _, err := askDevinFamiliesAt(context.Background(), two); err != nil && !strings.Contains(err.Error(), "no models") { t.Logf("models: %v", err) } diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index d61a6d0e9..f8e6cd82f 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -470,9 +470,6 @@ func fetchSubscriptionUsage(ctx context.Context) []SubscriptionQuota { if !moved(CommandCodePlanID) && !hidden[CommandCodePlanID] { fetches = append(fetches, perLogin(via(CommandCodePlanID), cmdLoginList(), accountCard(CommandCodePlanID))...) } - if !moved("devin") && !hidden["devin"] { - fetches = append(fetches, perLogin(via("devin"), devinLoginList(), accountCard("devin"))...) - } for _, agent := range []string{"gemini", "antigravity"} { if hidden[agent] { continue