diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 8b7b6d746..2b37a0005 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -39,7 +39,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). A group with chat models beside its image or video ones is tried on those alone (`drawingTries`' `makes`: `drawsModel`, or `servesKind` for video), so a drawing never goes to a chat member, on its provider's images API or as a chat asked for an image (changqiu4890 on Discord: a group of three relay chat models, a DeepSeek one and the relay's gpt-image-2.5 drew on its first chat model; `TestMixedGroupDrawsOnItsImageMemberOnly`, `TestMixedGroupMakesVideoOnItsVideoMemberOnly`). Codex's image tool draws on the routing group its turn asked for when that group has an image member (`codexDrawingProvider` gives the turn's group, `GroupDraws`, then `resolveDrawing`), and only otherwise on the provider that served the turn or Settings' pick (`TestCodexDrawingTakesItsGroupsImageMember`). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. A group's Add a model picker offers each provider's image models, `/api/groups`' `drawers` (`gateway.Drawers` less hidden ones, apart from the chat `models`), said as such and with no reasoning level (jzw690 on X); such a member draws whether or not its provider's picks name it, as picks are of chat models (`provider.FindDrawingGroup`, used by `GroupDraws`, `resolveDrawing` and the image group's turns), and the group is no model agents are offered. A group named on `/v1/embeddings`, `/v1/rerank`, `/v1/audio/speech`, `/v1/audio/transcriptions` (and translations) or `/v1/videos` keeps the same way a member its provider's chat list doesn't have (`mediaMembers`: `provider.FindGroupAlso` with `offChatList`), and is tried from its first such member (`mediaGroupFirst`), so a hand-made group of embedding or speech models of providers with picks is served, not a 404 (XYenon on Discord); a chat model the user unticked stays out. `TestMediaGroupOfProvidersWithChatPicks`, `TestVideoGroupOfProvidersWithChatPicks`. The same models need no group made by hand (#5339): a fetched list keeps its models made for another API, each marked with it (`catalog.Model.Serves`, from the id: `catalog.ServesOf`; `LiveServing`), out of the chat models (`catalog.Chat`), so agents' lists, gateway keys and Routing's chat pickers never offer them, and a moderation model is still dropped. A model of one kind that more than one provider serves under exactly the same id (no other case, no other version) is a group of that kind made per request on its route (`provider.KindGroup`, `mediaMembers` and `servesKind` in [`media_group.go`](../../internal/gateway/media_group.go)): asked by the bare id there, or by `group/auto-:` (`KindGroupID`; a chat model's found group's id has no `:`), never on another kind's route, its members in the Providers order, none switched off and none the model is disabled on. It is in no list of groups (`Groups`), so no agent, key or picker offers it. Video is the kind `video` (`Videomakers`); images keep their own groups. A list saved before this is fetched again once a run, schedule or none (`refreshDueLists`, `catalog.LiveKinded`). Another magpie's list (`X-Magpie-Drawers`) is not marked; its models are found by their id (`ServesOf`). `TestKindGroupsServeEachAPIByRoute`, `TestVideoKindGroupByTheModelsID`, `TestKindGroupHoldsTheExactModel`, `TestKindlessListFetchedOnce`, `TestFetchKeepsModelsOfOtherAPIs`. `TestImageGroupOfUnpickedImageModelsDraws`, `TestGroupEditorOffersImageModels`, `group-pick-drawers.test.cjs`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | -| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`affinityID`, in `stickKey` and `ruleKey`): the agent's session header, else the caller's `X-Magpie-Session` (#5242: requests that each named a session of their own, and opened alike, were taken for one conversation and kept together; `TestMagpieSessionIsTheConversation`), else (`conversationID`, which is what Kilo and a plugin are sent as the conversation, so `X-Magpie-Session` never goes upstream) a hash of how the conversation opens, which every later turn repeats: its first user message, or, when the agent wrote that one alone (`userWords`: an `` block, Reasonix's ``, an instruction file), the user messages from it through the first that holds the user's own words, an image, a file or a recording (`conversationOpening`, `userOpens`). A system or developer message between them is passed over; a reply, a call or a tool's result ends the opening, and with none of the user's before it the first message is hashed alone. One message is hashed as the request has it; several are hashed without their cache marks and with a content of one text part read as that text (`writeOpening`), since an agent moves its mark on to each turn's newest message, some spelling a marked message as one part and an unmarked one as a string (`TestCacheMarkMovingOnKeepsTheID`). Before, the first message was always hashed alone, and every conversation an agent opened on the same message in one folder was one: kept under `session` on the account that answered the first, and never moved on by rotate (keeyangyy, #3938, `TestConversationsOnOneEnvironmentMessageAreApart`, `TestReasonixConversationsInOneWorkspaceAreApart`, `TestNewConversationsInOneFolderAreRoutedApart`). A conversation whose first user message is the user's own keeps the id it had, which the Context page and the Routing page's requests find dsh's sessions by (`dshConvs`, `convOwners`, `convSessions`): dsh's pi-ai routes send no session header. A Claude Code subagent's is kept apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | +| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`affinityID`, in `stickKey` and `ruleKey`): the agent's session header, else the caller's `X-Magpie-Session` (#5242: requests that each named a session of their own, and opened alike, were taken for one conversation and kept together; `TestMagpieSessionIsTheConversation`), else (`conversationID`, which is what Kilo and a plugin are sent as the conversation, so `X-Magpie-Session` never goes upstream) a hash of how the conversation opens, which every later turn repeats: its first user message, or, when the agent wrote that one alone (`userWords`: an `` block, Reasonix's ``, an instruction file), the user messages from it through the first that holds the user's own words, an image, a file or a recording (`conversationOpening`, `userOpens`). A system or developer message between them is passed over; a reply, a call or a tool's result ends the opening, and with none of the user's before it the first message is hashed alone. One message is hashed as the request has it; several are hashed without their cache marks and with a content of one text part read as that text (`writeOpening`), since an agent moves its mark on to each turn's newest message, some spelling a marked message as one part and an unmarked one as a string (`TestCacheMarkMovingOnKeepsTheID`). Before, the first message was always hashed alone, and every conversation an agent opened on the same message in one folder was one: kept under `session` on the account that answered the first, and never moved on by rotate (keeyangyy, #3938, `TestConversationsOnOneEnvironmentMessageAreApart`, `TestReasonixConversationsInOneWorkspaceAreApart`, `TestNewConversationsInOneFolderAreRoutedApart`). A conversation whose first user message is the user's own keeps the id it had, which the Context page and the Routing page's requests find dsh's sessions by (`dshConvs`, `routeOwners`, `routeSessions`): dsh's pi-ai routes send no session header. A dsh fork repeats its source's opening, so a finished request is named by the id of the reply its client was given (`Route.ResponseID`, set from `clientResponseID` as the route is marked done), which dsh writes down on that reply (`replayState.response.responseId`, read into `Session.ResponseIDs`: a fork's own replies after its `session/end-seed` only). Vendors' reply ids can repeat, so a reply's id names a session over the opening only when the opening is that session's own or that of a session it was forked from (`ForkOf`, from the fork's `parentSession`; `ownerOf`), and Routing reads the sessions again for a reply id it has not found only up to a minute after the request ended (`looseKeys`): a title call's id is never written down (#5491, Flandern1211). A request still running or failed, and one logged before Route had the id, keeps the opening's session. A Claude Code subagent's is kept apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | | One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)), and one held to HTTP/1.1 (`HTTP1`) is spoken it at those hosts alone. A TLS record error read on an HTTP/2 connection ("bad record MAC", "received record with version …": the bytes under the TLS were mangled, by the far side or a box between) drops that connection, as Go's transport does, and `netproxy.Dispatch` sends the requests to that host:port over HTTP/1.1 for 6 hours after (`markH2Broken`, `h2BrokenFor`; kepner_53726: a company gateway failed 124 turns in 3 days so, each a 200 with no output, until a restart; `TestH2RecordErrorMovesHostToHTTP1`). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL, from the editor's Save or `magpie model api`; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. It goes to the first API `usable` gives, Chat where the provider has a Chat URL too, except one that asks an image's size or shape (`generationConfig.imageConfig`), which only a Gemini API takes: that one is translated on the Gemini URL (#3820, `TestGeminiImageConfigGoesToTheGeminiAPIBesideChat`). | [`gateway.go`](../../internal/gateway/gateway.go) | | Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) A request outside the chat path gets a route of its own too ([`media_route.go`](../../internal/gateway/media_route.go), `sideRoute`): an image (`images`, each account `drawOnAccounts` asks a try), a video's start (`videosCreate`; its polls and download are the same video and add none) and an embedding, rerank, transcription or speech (`retrieve`). Each try's key or account is put in `Order` so the page finds its seat, the route's `Kind` stays empty, and the one usage row names it in `RouteID` (zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's requests and not on Routing; `TestVideoIsOnRoutingOnce`, `TestImageIsOnRouting`, `TestEmbeddingAndRerankAreOnRouting`). | | Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them, each inline picture's base64 swapped for a ref into `keptImages` (in memory, 128 MiB at most, least recently used first; `image_keep.go`), so a conversation of pictures, which DeepSeek's file ids let grow past 64 MiB (#5407), keeps its text and pictures (matrix0487 on Discord; the archive's copy is read the same way, `TestFileIDConversationStillShows`); for a model let have it unmasked, the body is kept as it went and masked when `PromptText` first reads it, so the request itself never waits on masking (#3973). `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`. Once a body is dropped, or magpie quits, the GUI reads the request archive's copy when the route names one (`Route.Archive`; wangbinyq on Discord): `ArchivedPromptText` parses it the same way and masks it as the body in memory is (`maskedCopy`), and the reply beside it comes from `ReplyBody` (the Recent calls' reply) or the archive's, read into pieces by `ReplyPieces` and masked alike (`prompt_reply.go`, served as `/api/context/reply`). A body or reply that can't be masked shows nothing, and one the archive cut short isn't parsed (`TestArchivedPromptTextIsMasked`, `TestReplyPiecesAreMasked`, `TestContextTextFromTheArchive`). It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) | diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index bf8ac782e..53f6ed78e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5036,6 +5036,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro tries := 0 // the request's tries, as its route lists them s.trace.update(tr, func(t *Route) { t.Done, t.Status, t.Error, t.Millis = true, call.Status, call.Error, call.Millis + // the id the agent reads beside the reply, so the session that + // keeps it can be found after the fact (dsh's replays) + t.ResponseID = call.Usage.ResponseID tries = len(t.Tries) + reasked if t.TitleLink != nil && isTitleKind(t.Kind) && call.Status < 400 && call.Error == "" && !call.ResponseTruncated { link := *t.TitleLink diff --git a/internal/gateway/response_id_test.go b/internal/gateway/response_id_test.go index 61b8038de..9170f379b 100644 --- a/internal/gateway/response_id_test.go +++ b/internal/gateway/response_id_test.go @@ -139,3 +139,40 @@ func TestGatewayPersistsTranslatedClientResponseID(t *testing.T) { }) } } + +// A done route keeps the id of the reply the client was given: the agent +// stores that id with the reply it keeps (dsh's replay state), so the +// session that made the request can be found again after the fact even +// when its conversation opening is one a fork copied. +func TestDoneRouteKeepsTheClientResponseID(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(map[bool]string{true: "stream", false: "json"}[stream], func(t *testing.T) { + fresh(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.Write([]byte("data: {\"id\":\"chatcmpl-upstream\",\"model\":\"model\",\"choices\":[{\"delta\":{\"content\":\"answer\"}}]}\n\ndata: {\"id\":\"chatcmpl-upstream\",\"choices\":[],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":2}}\n\ndata: [DONE]\n\n")) + })) + defer up.Close() + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Chat: up.URL + "/v1", Models: []string{"model"}}); err != nil { + t.Fatal(err) + } + body := `{"model":"fake/model","input":"hi","stream":` + map[bool]string{true: "true", false: "false"}[stream] + `}` + s := New() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + id := clientResponseID(t, provider.Responses, rec.Body.String(), stream) + s.trace.mu.Lock() + got := "" + if n := len(s.trace.routes); n > 0 { + got = s.trace.routes[n-1].ResponseID + } + s.trace.mu.Unlock() + if got == "" || got != id { + t.Fatalf("route's reply id %q, the client's %q", got, id) + } + }) + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index afc1cba76..cb80b6f7d 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -184,6 +184,12 @@ type Route struct { // Conv: the conversation a request without a session id is part of, // as a digest of its first user turn (conversationID) Conv string `json:"conv,omitempty"` + // ResponseID: the id of the reply object actually released to the + // client, as the client read it, set when the route is done. The agent + // stores that id with the reply (dsh's replay state), so a request + // whose agent keeps it can be found again after the fact even when its + // conversation opening is one a fork copied (dshConvs) + ResponseID string `json:"responseId,omitempty"` // Folder: the last two levels of the folder its agent says it works // in (shortFolder), never the whole path; a request that says none // takes its session's, as said last (#1068) diff --git a/internal/gui/context.go b/internal/gui/context.go index 8bf54b486..a98a307b5 100644 --- a/internal/gui/context.go +++ b/internal/gui/context.go @@ -175,6 +175,7 @@ type ctxRec struct { Time time.Time Agent, Model, Kind, Sub string Session, Parent, Conv string + ResponseID string Done, Failed bool Asked bool // it has a prompt of some tokens Tokens, Window, MCP, Cache int @@ -186,7 +187,7 @@ type ctxRec struct { // recOf is r as the tab reads it, its whole prompt kept when whole. func recOf(r gateway.Route, whole bool) ctxRec { c := ctxRec{ID: r.ID, Time: r.Time, Agent: r.Agent, Model: r.Model, Kind: r.Kind, Sub: r.Sub, - Session: r.Session, Parent: r.ParentSession, Conv: r.Conv, Done: r.Done, + Session: r.Session, Parent: r.ParentSession, Conv: r.Conv, ResponseID: r.ResponseID, Done: r.Done, Failed: r.Status >= 400 || r.Error != "", Cache: cacheOf(r), CacheKnown: cacheKnown(r)} if p := r.Prompt; p != nil { c.Asked = p.Tokens > 0 @@ -267,15 +268,18 @@ func sessionOfRec(r *ctxRec) string { } // joinConvs puts a route that names no session under the agent's session -// its conversation id was read from (sessions' Convs): dsh's -// chat-completions and messages routes send no session id, so the gateway -// keys each request by its first prompt's hash, and the page showed -// "magpie-a…" where the Sessions page shows the session's title (Kumo31 -// on Discord). An id two sessions share stays as it is. +// its reply or its conversation id was read from (sessions' ResponseIDs and +// Convs): dsh's chat-completions and messages routes send no session id, so +// the gateway keys each request by its first prompt's hash, and the page +// showed "magpie-a…" where the Sessions page shows the session's title +// (Kumo31 on Discord). A hash is the conversation's opening, which a fork +// copies, so the reply's own id is asked first: a fork's reply has one its +// source does not, and names the fork. An id two sessions share stays as it +// is. func joinConvs(routes []ctxRec, list func() []sessions.Session) { loose := false for _, r := range routes { - if r.Session == "" && r.Parent == "" && r.Conv != "" { + if r.Session == "" && r.Parent == "" && (r.ResponseID != "" || r.Conv != "") { loose = true break } @@ -283,29 +287,82 @@ func joinConvs(routes []ctxRec, list func() []sessions.Session) { if !loose { return } - of := convOwners(list()) + of := routeOwners(list()) for i, r := range routes { - if r.Session == "" && r.Parent == "" && r.Conv != "" { - if id := of[r.Agent+"\x00"+r.Conv]; id != "" { + if r.Session == "" && r.Parent == "" { + if id := ownerOf(r.Agent, r.ResponseID, r.Conv, of); id != "" { routes[i].Session = id } } } } -// convOwners is each agent's conversation id (agent, NUL, the gateway's -// id) and the session of that agent it was read from (sessions' Convs); -// "" for an id two sessions share, which stays as it is. -func convOwners(list []sessions.Session) map[string]string { +// ownerOf is the session an agent's route that names none belongs to: the +// one whose own replies carry the route's reply id, and, when no one's does, +// the one whose conversation the route opens. A reply id is the vendor's, +// which some give out again (Ollama's chatcmpl-<0-998>), so it names a +// session over the opening only where the two agree: the opening is no +// one's, or two sessions', or the reply's session's own, or one it was +// forked from (sessions' ForkOf). Another session's opening goes by the +// opening, as it did before reply ids were read. +func ownerOf(agent, responseID, conv string, of map[string]string) string { + opened := "" + if conv != "" { + opened = of[ownerKey(agent, ownerConv, conv)] + } + if responseID != "" { + if id := of[ownerKey(agent, ownerResponse, responseID)]; id != "" && (opened == "" || forkedFrom(agent, id, opened, of)) { + return id + } + } + return opened +} + +// forkedFrom says session id is from, or a fork of it, or of a fork of it. +func forkedFrom(agent, id, from string, of map[string]string) bool { + for n := 0; id != "" && n < 64; n++ { + if id == from { + return true + } + id = of[ownerKey(agent, ownerFork, id)] + } + return false +} + +// The kinds of id a route without a session id is named by: the reply it +// got, and the conversation it opens; and a session's source, for the +// session a fork's reply names (ForkOf). +const ( + ownerResponse = "response" + ownerConv = "conv" + ownerFork = "fork" +) + +func ownerKey(agent, kind, id string) string { return agent + "\x00" + kind + "\x00" + id } + +// routeOwners is each agent's reply ids and conversation ids (agent, NUL, +// kind, NUL, the id) and the session of that agent each was read from +// (sessions' ResponseIDs and Convs); "" for an id two sessions share, which +// stays as it is. A fork's session id is kept with the one it was forked +// from (ownerFork). +func routeOwners(list []sessions.Session) map[string]string { of := map[string]string{} + put := func(k, id string) { + if was, ok := of[k]; ok && was != id { + of[k] = "" + } else if !ok { + of[k] = id + } + } for _, s := range list { for _, c := range s.Convs { - k := s.Agent + "\x00" + c - if id, ok := of[k]; ok && id != s.ID { - of[k] = "" - } else if !ok { - of[k] = s.ID - } + put(ownerKey(s.Agent, ownerConv, c), s.ID) + } + for _, r := range s.ResponseIDs { + put(ownerKey(s.Agent, ownerResponse, r), s.ID) + } + if s.ForkOf != "" { + of[ownerKey(s.Agent, ownerFork, s.ID)] = s.ForkOf } } return of diff --git a/internal/gui/context_dsh_response_test.go b/internal/gui/context_dsh_response_test.go new file mode 100644 index 000000000..b81589075 --- /dev/null +++ b/internal/gui/context_dsh_response_test.go @@ -0,0 +1,80 @@ +package gui + +import ( + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/sessions" +) + +// The Context page names a dsh fork's requests as Routing does: by the reply +// each got (Route.ResponseID), where the conversation's opening is the +// source's. A request of the source's own still opens under the source. +func TestContextTellsAForkByItsReply(t *testing.T) { + sandboxHome(t) + home := t.TempDir() + t.Setenv("DSH_HOME", home) + sessions.Reset() + t.Cleanup(sessions.Reset) + + const opening = `{"type":"user/message","seq":1,"time":1000,"data":{"source":{"kind":"user"},"content":[{"type":"text","text":"same first prompt"}]}}` + const endSeed = `{"type":"session/end-seed","seq":2,"time":1000,"data":{"inherited":true}}` + reply := func(seq int, id string) string { + return `{"type":"assistant/message","seq":` + strconv.Itoa(seq) + `,"time":1000,"data":{"message":{"source":{"provider":"magpie","model":"group/flash","replayState":{"response":{"provider":"magpie","responseId":"` + id + `"}}}}}}` + } + write := func(name, header string, lines ...string) { + dir := filepath.Join(home, "sessions", "proj", name) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + b := header + "\n" + for _, l := range lines { + b += l + "\n" + } + if err := os.WriteFile(filepath.Join(dir, "session.v4.jsonl"), []byte(b), 0o600); err != nil { + t.Fatal(err) + } + } + write("session-source", `{"type":"session","version":4,"id":"session-source","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":false}`, + opening, reply(2, "reply-source")) + write("session-fork", `{"type":"session","version":4,"id":"session-fork","cwd":"/w","createdAt":1000,"delegationDepth":0,"parentSession":"session-source","isSeeded":true}`, + opening, reply(2, "reply-source"), endSeed, reply(4, "reply-fork")) + + var openingHash string + for _, s := range sessions.List(0) { + if s.ID == "session-source" && len(s.Convs) > 0 { + openingHash = s.Convs[0] + } + } + if openingHash == "" { + t.Fatal("the fixture session names no conversation id") + } + conv := func(id int64, c string) gateway.Route { + r := ctxRoute(id, "dsh", "", 20000, int(1000*id), 128000, 0) + r.Conv = c + return r + } + fork := conv(1, openingHash) + fork.ResponseID = "reply-fork" + source := conv(2, openingHash) + source.ResponseID = "reply-source" + loose := conv(3, openingHash) + out := contextOf([]gateway.Route{fork, source, loose}, 7) + keys := map[string]string{} + for _, s := range out.Sessions { + keys[s.Key] = s.Title + } + // the fork's own turn is the fork; the source's is the source; the + // opening alone is the source's, whose it is + for _, k := range []string{"session-fork", "session-source"} { + if _, ok := keys[k]; !ok { + t.Fatalf("no %s among %v", k, keys) + } + } + if len(keys) != 2 { + t.Fatalf("sessions %v, want the fork and its source", keys) + } +} diff --git a/internal/gui/dsh_fork_routes_test.go b/internal/gui/dsh_fork_routes_test.go new file mode 100644 index 000000000..d1593862a --- /dev/null +++ b/internal/gui/dsh_fork_routes_test.go @@ -0,0 +1,302 @@ +package gui + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/sessions" +) + +// #5491 (Flandern1211): a dsh fork's requests were listed under the session +// it was forked from. Here the requests are real dsh 0.2.0-rc.2's, captured +// on its chat-completions route (sessions' testdata/dsh-gateway), sent +// through the gateway twice, byte for byte the same as a fork's and its +// source's are. The vendor answers on the messages protocol and streams, so +// the id dsh reads is magpie's translation of the vendor's. The first reply +// is written into the source's file, the second into a fork of it made as +// dsh's buildForkSeed makes one: the source's events up to the boundary, a +// session/end-seed, then its own turn, under a header naming parentSession. +func TestDshForkNamedByTheReplyTheGatewayGave(t *testing.T) { + sandboxHome(t) + fixture := filepath.Join("..", "sessions", "testdata", "dsh-gateway") + const source = "session-508e7b0a-37c0-41f7-ac62-e48ab3146111" + const fork = "session-5e1c0f3a-8d2b-4c6e-9a71-2f4b6d8e0c13" + + var n atomic.Int32 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + if !strings.HasSuffix(r.URL.Path, "/messages") { + http.Error(w, "messages only", 404) + return + } + id := "msg_up" + string(rune('0'+n.Add(1))) + w.Header().Set("Content-Type", "text/event-stream") + for _, ev := range []string{ + `{"type":"message_start","message":{"id":"` + id + `","type":"message","role":"assistant","model":"m1","content":[],"usage":{"input_tokens":9,"output_tokens":0}}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Done."}}`, + `{"type":"content_block_stop","index":0}`, + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`, + `{"type":"message_stop"}`, + } { + var typ struct{ Type string } + json.Unmarshal([]byte(ev), &typ) + io.WriteString(w, "event: "+typ.Type+"\ndata: "+ev+"\n\n") + } + })) + defer up.Close() + if err := provider.Save(provider.Provider{ID: "fake", Name: "FAKE", Key: "k", Models: []string{"m1"}, Anthropic: up.URL}); err != nil { + t.Fatal(err) + } + + b, err := os.ReadFile(filepath.Join(fixture, "requests", "completions-turn.json")) + if err != nil { + t.Fatal(err) + } + head, body, _ := bytes.Cut(b, []byte("\n")) + var captured struct { + Path string `json:"path"` + Headers map[string]string `json:"headers"` + } + if err := json.Unmarshal(head, &captured); err != nil { + t.Fatal(err) + } + // only the model is changed, to one this gateway has + body = bytes.Replace(body, []byte(`"model":"group/flash"`), []byte(`"model":"fake/m1"`), 1) + s := gateway.New() + ask := func() string { + t.Helper() + r := httptest.NewRequest("POST", captured.Path, bytes.NewReader(body)) + for k, v := range captured.Headers { + r.Header.Set(k, v) + } + r.Header.Del("Content-Length") + r.Header.Del("Accept-Encoding") + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, r) + if w.Code != 200 { + t.Fatalf("%d %.300s", w.Code, w.Body) + } + // the id dsh reads: its chunks' (pi-ai's responseId) + sc := bufio.NewScanner(w.Body) + for sc.Scan() { + var c struct{ ID string } + if d, ok := strings.CutPrefix(sc.Text(), "data: "); ok && json.Unmarshal([]byte(d), &c) == nil && c.ID != "" { + return c.ID + } + } + t.Fatal("no reply id in the stream") + return "" + } + sourceReply, forkReply := ask(), ask() + if sourceReply == forkReply || strings.HasPrefix(sourceReply, "msg_") { + t.Fatalf("client ids %q, %q: not two chat-completions ids", sourceReply, forkReply) + } + routes := s.Trace(context.Background(), 0, 0).Routes + if len(routes) != 2 || routes[0].Conv == "" || routes[0].Conv != routes[1].Conv { + t.Fatalf("routes %+v: want two of one conversation", routes) + } + for _, r := range routes { + if r.Agent != "dsh" || r.Session != "" { + t.Fatalf("route %d: agent %q session %q", r.ID, r.Agent, r.Session) + } + if r.ResponseID != sourceReply && r.ResponseID != forkReply { + t.Fatalf("route %d keeps %q, the client read %q or %q", r.ID, r.ResponseID, sourceReply, forkReply) + } + } + + // dsh writes the replies down: the source's own, then the fork's + home := t.TempDir() + if err := os.CopyFS(filepath.Join(home, "sessions"), os.DirFS(filepath.Join(fixture, "sessions"))); err != nil { + t.Fatal(err) + } + t.Setenv("DSH_HOME", home) + srcPath := filepath.Join(home, "sessions", "--work-proj--", source, "session.v4.jsonl") + src, err := os.ReadFile(srcPath) + if err != nil { + t.Fatal(err) + } + src = bytes.Replace(src, []byte(`"responseId":"c1"`), []byte(`"responseId":"`+sourceReply+`"`), 1) + if err := os.WriteFile(srcPath, src, 0o600); err != nil { + t.Fatal(err) + } + writeDshFork(t, filepath.Join(home, "sessions", "--work-proj--", fork), fork, source, src, forkReply) + sessions.Reset() + t.Cleanup(sessions.Reset) + resetRouteConvs(t) + + // old history: a route from before reply ids were kept + old := routes[0] + old.ID, old.ResponseID = 99, "" + want := map[string]string{sourceReply: source, forkReply: fork, "": source} + priced := pricedRoutes(append(routes, old)) + for _, r := range priced { + if w := want[r.ResponseID]; r.Session != w { + t.Errorf("Routing: route %d (reply %q) under %q, want %q", r.ID, r.ResponseID, r.Session, w) + } + } + out := contextOf(append(routes, old), 7) + keys := map[string]bool{} + for _, s := range out.Sessions { + keys[s.Key] = true + } + if !keys[source] || !keys[fork] || len(keys) != 2 { + t.Errorf("Context: sessions %v, want %s and %s", keys, source, fork) + } +} + +// A reply id is the vendor's, and some vendors give one out again (Ollama's +// chatcmpl-<0-998>): a route that opens another session's conversation +// stays that session's though its reply's id is one a fork kept. +func TestDshReplyIDOfAnotherConversationNamesNoOne(t *testing.T) { + sandboxHome(t) + of := routeOwners([]sessions.Session{ + {Agent: "dsh", ID: "source", Convs: []string{"magpie-open"}, ResponseIDs: []string{"chatcmpl-1"}}, + {Agent: "dsh", ID: "fork", ForkOf: "source", ResponseIDs: []string{"chatcmpl-217"}}, + {Agent: "dsh", ID: "fork2", ForkOf: "fork", ResponseIDs: []string{"chatcmpl-5"}}, + {Agent: "dsh", ID: "other", Convs: []string{"magpie-other"}, ResponseIDs: []string{"chatcmpl-9"}}, + }) + for _, c := range []struct{ reply, conv, want string }{ + {"chatcmpl-217", "magpie-open", "fork"}, // the fork's own turn + {"chatcmpl-5", "magpie-open", "fork2"}, // a fork of the fork + {"chatcmpl-217", "magpie-other", "other"}, // another conversation's, the same id + {"chatcmpl-9", "magpie-open", "source"}, // another's id on the source's opening + {"chatcmpl-217", "magpie-unknown", "fork"}, + {"chatcmpl-unknown", "magpie-open", "source"}, + {"", "magpie-open", "source"}, + } { + if got := ownerOf("dsh", c.reply, c.conv, of); got != c.want { + t.Errorf("reply %s, conv %s: %q, want %q", c.reply, c.conv, got, c.want) + } + } +} + +// The Routing page polls every second or two. A dsh reply whose id dsh never +// writes down (a title call's, one that failed) is listed nowhere, and the +// sessions were listed again every convsFresh for as long as such a route +// was on the page; a route's reply is waited for only convsKept after it +// ended. +func TestRoutingWaitsForAReplyIDOnlyAWhile(t *testing.T) { + sandboxHome(t) + t.Setenv("DSH_HOME", t.TempDir()) + sessions.Reset() + t.Cleanup(sessions.Reset) + resetRouteConvs(t) + now := time.Now() + conv := ownerKey("dsh", ownerConv, "magpie-open") + built := now.Add(-3 * convsFresh) + routeConvs.Lock() + routeConvs.of, routeConvs.at = map[string]string{conv: "source"}, built + routeConvs.Unlock() + listed := func(r gateway.Route) bool { + routeSessions(true, looseKeys(r, now)) + routeConvs.Lock() + defer routeConvs.Unlock() + again := !routeConvs.at.Equal(built) + routeConvs.of, routeConvs.at = map[string]string{conv: "source"}, built + return again + } + old := gateway.Route{Agent: "dsh", Conv: "magpie-open", ResponseID: "chatcmpl-title", Done: true, Time: now.Add(-2 * convsKept), Millis: 900} + if listed(old) { + t.Fatal("a route ended long ago, whose reply id no session has, listed the sessions again") + } + recent := old + recent.Time = now.Add(-5 * time.Second) + if !listed(recent) { + t.Fatal("a route just ended, its reply not yet listed, did not list the sessions again") + } +} + +func resetRouteConvs(t *testing.T) { + reset := func() { + routeConvs.Lock() + routeConvs.of, routeConvs.at = nil, time.Time{} + routeConvs.Unlock() + } + reset() + t.Cleanup(reset) +} + +// writeDshFork writes a fork of the session file src as dsh does +// (buildForkSeed, api-session-controller's fork): every event of src, a +// session/end-seed after them at the last one's time, then a turn of its +// own whose reply has the id given, copied from src's own reply. +func writeDshFork(t *testing.T, dir, id, parent string, src []byte, reply string) { + t.Helper() + lines := bytes.Split(bytes.TrimSpace(src), []byte("\n")) + var out bytes.Buffer + out.WriteString(`{"type":"session","version":4,"id":"` + id + `","createdAt":1792664880000,"cwd":"/work/proj","parentSession":"` + parent + `","isSeeded":true}` + "\n") + var last struct { + Seq int `json:"seq"` + Time int64 `json:"time"` + } + var answer []byte + for _, l := range lines[1:] { + out.Write(l) + out.WriteByte('\n') + json.Unmarshal(l, &last) + if bytes.Contains(l, []byte(`"type":"assistant/message"`)) { + answer = l + } + } + if answer == nil { + t.Fatal("the source has no reply to copy") + } + seq, n := last.Seq+1, strconv.Itoa + out.WriteString(`{"type":"session/end-seed","seq":` + n(seq) + `,"time":` + strconv.FormatInt(last.Time, 10) + `,"data":{"inherited":true}}` + "\n") + seq++ + out.WriteString(`{"type":"user/message","seq":` + n(seq) + `,"time":` + strconv.FormatInt(last.Time+int64(seq), 10) + `,"data":{"content":[{"type":"text","text":"Now the tests"}],"source":{"kind":"user"},"role":"user","id":"0b7c1d2e-3f40-4a51-8b62-7c83d94ea5f6"},"surfaceOp":"append"}` + "\n") + seq++ + var at struct { + Seq int `json:"seq"` + Time int64 `json:"time"` + } + json.Unmarshal(answer, &at) + was := `"seq":` + n(at.Seq) + `,"time":` + strconv.FormatInt(at.Time, 10) + if !bytes.Contains(answer, []byte(was)) { + t.Fatalf("the source's reply has no %s", was) + } + own := bytes.Replace(answer, []byte(was), []byte(`"seq":`+n(seq)+`,"time":`+strconv.FormatInt(last.Time+int64(seq), 10)), 1) + // the reply's own id (replayState.response.responseId), wherever it sits + var ids struct { + Data struct { + Message struct { + Source struct { + ReplayState struct { + Response struct { + ResponseID string `json:"responseId"` + } `json:"response"` + } `json:"replayState"` + } `json:"source"` + } `json:"message"` + } `json:"data"` + } + json.Unmarshal(answer, &ids) + from := ids.Data.Message.Source.ReplayState.Response.ResponseID + if from == "" { + t.Fatal("the source's reply has no responseId") + } + own = bytes.ReplaceAll(own, []byte(`"responseId":"`+from+`"`), []byte(`"responseId":"`+reply+`"`)) + out.Write(own) + out.WriteByte('\n') + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "session.v4.jsonl"), out.Bytes(), 0o600); err != nil { + t.Fatal(err) + } +} diff --git a/internal/gui/trace.go b/internal/gui/trace.go index bf1bb76d7..796008e82 100644 --- a/internal/gui/trace.go +++ b/internal/gui/trace.go @@ -97,17 +97,19 @@ func pricedRoutes(routes []gateway.Route) []routeJSON { } titles := sessions.CodexTitles(ids) var loose []string + need, now := false, time.Now() for _, r := range routes { - if k := looseConv(r); k != "" { - loose = append(loose, k) - } + need = need || looseRoute(r) + loose = append(loose, looseKeys(r, now)...) } - owners := convSessions(loose) + owners := routeSessions(need, loose) pub := publicRefs() for _, r := range routes { r = publicRoute(r, pub) - if k := looseConv(r); k != "" && owners[k] != "" { - r.Session = owners[k] + if looseRoute(r) { + if id := ownerOf(r.Agent, r.ResponseID, r.Conv, owners); id != "" { + r.Session = id + } } r.Usage = cacheCounted(r.Usage) recs := make([]usage.Record, len(r.Usage)) @@ -131,25 +133,43 @@ func pricedRoutes(routes []gateway.Route) []routeJSON { } // convAgents are the agents whose own session files say which of the -// gateway's conversation ids are theirs (sessions' Convs): dsh's, whose -// chat-completions and messages routes send no session id -// (changqiu4890 on Discord: Routing put every dsh request under "No -// session ID"). +// gateway's reply and conversation ids are theirs (sessions' ResponseIDs +// and Convs): dsh's, whose chat-completions and messages routes send no +// session id (changqiu4890 on Discord: Routing put every dsh request under +// "No session ID"). var convAgents = map[string]bool{"dsh": true} -// looseConv is the agent and conversation id (convOwners' key) of a route -// of such an agent that names no session, "" for any other. -func looseConv(r gateway.Route) string { - if r.Session != "" || r.ParentSession != "" || r.Conv == "" || !convAgents[r.Agent] { - return "" +// looseKeys are the agent and ids (ownerKey's) a route of such an agent +// that names no session is to be found by, and whose absence from the +// listing means it is behind: its conversation's, and its reply's while +// dsh may still be writing the reply down — up to convsKept after the +// route ended. A reply dsh keeps no id of (a title call's, a refusal's) +// is never listed, and the page polls every second or two: past that it +// would list every agent's sessions again each convsFresh. None for any +// other route. +func looseKeys(r gateway.Route, now time.Time) []string { + if !looseRoute(r) { + return nil } - return r.Agent + "\x00" + r.Conv + var out []string + if r.ResponseID != "" && r.Done && now.Sub(r.Time.Add(time.Duration(r.Millis)*time.Millisecond)) < convsKept { + out = append(out, ownerKey(r.Agent, ownerResponse, r.ResponseID)) + } + if r.Conv != "" { + out = append(out, ownerKey(r.Agent, ownerConv, r.Conv)) + } + return out } -// routeConvs is convOwners of the sessions listed, for every trace the +// looseRoute says r is a route of such an agent that names no session. +func looseRoute(r gateway.Route) bool { + return r.Session == "" && r.ParentSession == "" && convAgents[r.Agent] && (r.ResponseID != "" || r.Conv != "") +} + +// routeConvs is routeOwners of the sessions listed, for every trace the // Routing page polls: listing the sessions reads every agent's folder, so // it is made again only when it is convsKept old, or convsFresh old and a -// route's conversation isn't in it (a session begun since). +// route's id isn't in it (a reply or a session begun since). var routeConvs struct { sync.Mutex at time.Time @@ -158,10 +178,11 @@ var routeConvs struct { var convsFresh, convsKept = 2 * time.Second, time.Minute -// convSessions is convOwners for keys (looseConv's), nil when there are -// none, so a page with no such route lists nothing. -func convSessions(keys []string) map[string]string { - if len(keys) == 0 { +// routeSessions is routeOwners for the routes of a page that has a route +// that names no session (need), nil for one with none, so it lists +// nothing; keys are looseKeys'. +func routeSessions(need bool, keys []string) map[string]string { + if !need { return nil } routeConvs.Lock() @@ -177,7 +198,7 @@ func convSessions(keys []string) map[string]string { } } if stale { - routeConvs.of, routeConvs.at = convOwners(sessions.List(0)), time.Now() + routeConvs.of, routeConvs.at = routeOwners(sessions.List(0)), time.Now() } return routeConvs.of } diff --git a/internal/gui/trace_dsh_response_test.go b/internal/gui/trace_dsh_response_test.go new file mode 100644 index 000000000..708995a86 --- /dev/null +++ b/internal/gui/trace_dsh_response_test.go @@ -0,0 +1,85 @@ +package gui + +import ( + "os" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/sessions" +) + +// A dsh fork copies its source's conversation, so the hash of the opening +// names both sessions and names neither: Routing showed the source for the +// fork's own requests too, or nothing at all. The reply's id is the fork's +// own — dsh keeps the one magpie's gateway put on it — and names it +// (Route.ResponseID, sessions' ResponseIDs). +func TestRoutingTellsAForkByItsReply(t *testing.T) { + sandboxHome(t) + home := t.TempDir() + t.Setenv("DSH_HOME", home) + sessions.Reset() + t.Cleanup(sessions.Reset) + resetRouteConvs := func() { + routeConvs.Lock() + routeConvs.of, routeConvs.at = nil, time.Time{} + routeConvs.Unlock() + } + resetRouteConvs() + t.Cleanup(resetRouteConvs) + defer func(f, k time.Duration) { convsFresh, convsKept = f, k }(convsFresh, convsKept) + convsFresh = 0 + + const opening = `{"type":"user/message","seq":1,"time":1000,"data":{"source":{"kind":"user"},"content":[{"type":"text","text":"same first prompt"}]}}` + const endSeed = `{"type":"session/end-seed","seq":2,"time":1000,"data":{"inherited":true}}` + reply := func(seq int, id string) string { + return `{"type":"assistant/message","seq":` + strconv.Itoa(seq) + `,"time":1000,"data":{"message":{"source":{"provider":"magpie","model":"group/flash","replayState":{"response":{"provider":"magpie","responseId":"` + id + `"}}}}}}` + } + write := func(name, header string, lines ...string) { + dir := filepath.Join(home, "sessions", "proj", name) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + b := header + "\n" + for _, l := range lines { + b += l + "\n" + } + if err := os.WriteFile(filepath.Join(dir, "session.v4.jsonl"), []byte(b), 0o600); err != nil { + t.Fatal(err) + } + } + write("session-source", `{"type":"session","version":4,"id":"session-source","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":false}`, + opening, reply(2, "reply-source")) + write("session-fork", `{"type":"session","version":4,"id":"session-fork","cwd":"/w","createdAt":1000,"delegationDepth":0,"parentSession":"session-source","isSeeded":true}`, + opening, reply(2, "reply-source"), endSeed, reply(4, "reply-fork")) + + var openingHash string + for _, s := range sessions.List(0) { + if s.ID == "session-source" && len(s.Convs) > 0 { + openingHash = s.Convs[0] + } + } + if openingHash == "" { + t.Fatal("the fixture session names no conversation id") + } + routes := []gateway.Route{ + {ID: 1, Agent: "dsh", Conv: openingHash, ResponseID: "reply-fork"}, // the fork's own turn + {ID: 2, Agent: "dsh", Conv: openingHash}, // the opening alone: its source's + {ID: 3, Agent: "dsh", Conv: openingHash, ResponseID: "reply-source"}, // the source's + {ID: 4, Agent: "dsh", ResponseID: "reply-fork"}, // the reply alone + } + got := map[int64]string{} + for _, r := range pricedRoutes(routes) { + got[r.ID] = r.Session + } + // 2 is the opening alone: the fork's inherited copy of it is its + // source's (the seed ends before its own turns), so it names the source + want := map[int64]string{1: "session-fork", 2: "session-source", 3: "session-source", 4: "session-fork"} + for id, w := range want { + if got[id] != w { + t.Errorf("route %d: session %q, want %q", id, got[id], w) + } + } +} diff --git a/internal/sessions/dsh.go b/internal/sessions/dsh.go index 7c8dc4016..799ecafcd 100644 --- a/internal/sessions/dsh.go +++ b/internal/sessions/dsh.go @@ -204,6 +204,10 @@ type dshResponse struct { Model string `json:"model"` Provider string `json:"provider"` ResponseModel string `json:"responseModel"` + // ResponseID is the id of the reply object the vendor's own response + // carried, as dsh read it: the same id magpie's gateway wrote on the + // route that served it (Route.ResponseID) + ResponseID string `json:"responseId"` } // dshReplay is a reply's replay state, where dsh keeps what the vendor's own @@ -374,6 +378,13 @@ func dshCount(s *state, h *dshHead, b []byte, main bool) { if h.Version < 2 && e.Seq != nil && *e.Seq < h.SeedLength { return } + if e.Type == "assistant/message" && main { + if src := e.Data.Message.Source; dshGatewayProvider(src) { + if id := src.ReplayState.Response.ResponseID; id != "" { + s.ResponseIDs = append(s.ResponseIDs, id) + } + } + } at := ms(e.Time) s.saw(at, main) switch { diff --git a/internal/sessions/dsh_response_id_test.go b/internal/sessions/dsh_response_id_test.go new file mode 100644 index 000000000..4740de272 --- /dev/null +++ b/internal/sessions/dsh_response_id_test.go @@ -0,0 +1,189 @@ +package sessions + +import ( + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" +) + +// dshReply is an assistant/message line holding a reply's replay state, as +// dsh writes it: the id is the one the gateway put on the reply. +func dshReplyWithID(seq int, id string) string { + return `{"type":"assistant/message","seq":` + strconv.Itoa(seq) + `,"time":1000,"data":{"message":{"source":{"provider":"magpie","model":"group/flash","replayState":{"response":{"kind":"pi-ai","version":2,"api":"openai-completions","provider":"magpie","model":"group/flash","responseId":"` + id + `","stopReason":"stop"}}}}}}` +} + +// dshSessionFile writes a session file with the lines given and parses it. +func dshSessionFile(t *testing.T, lines []string) *state { + t.Helper() + p := filepath.Join(t.TempDir(), "session.jsonl") + b := "" + for _, l := range lines { + b += l + "\n" + } + if err := os.WriteFile(p, []byte(b), 0o600); err != nil { + t.Fatal(err) + } + st, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + return parseDsh(file{agent: "dsh", path: p, main: true, size: st.Size(), mod: st.ModTime()}, nil) +} + +func TestDshResponseIDsSkipTheSeed(t *testing.T) { + head := `{"type":"session","version":4,"id":"session-child","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":true}` + s := dshSessionFile(t, []string{ + head, + dshReplyWithID(1, "inherited-1"), + dshReplyWithID(2, "inherited-2"), + `{"type":"session/end-seed","seq":3,"time":1000,"data":{"inherited":true}}`, + dshReplyWithID(4, "own-1"), + dshReplyWithID(5, "own-2"), + }) + if want := []string{"own-1", "own-2"}; !slices.Equal(s.ResponseIDs, want) { + t.Fatalf("fork's own replies: %v, want %v", s.ResponseIDs, want) + } +} + +// A file in the format before session/end-seed marks its inherited events by +// seq: those are its source's, not its own. +func TestDshResponseIDsSkipTheSeedLength(t *testing.T) { + head := `{"type":"session","version":1,"id":"session-old","cwd":"/w","createdAt":1000,"seedLength":2,"isSeeded":true}` + s := dshSessionFile(t, []string{ + head, + dshReplyWithID(0, "inherited"), + dshReplyWithID(1, "inherited-2"), + dshReplyWithID(2, "own"), + }) + if want := []string{"own"}; !slices.Equal(s.ResponseIDs, want) { + t.Fatalf("fork's own replies: %v, want %v", s.ResponseIDs, want) + } +} + +// A session that is no fork owns every reply of its own. +func TestDshResponseIDsOfASession(t *testing.T) { + head := `{"type":"session","version":4,"id":"session-plain","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":false}` + s := dshSessionFile(t, []string{ + head, + dshReplyWithID(1, "a"), + dshReplyWithID(2, "b"), + }) + if want := []string{"a", "b"}; !slices.Equal(s.ResponseIDs, want) { + t.Fatalf("replies: %v, want %v", s.ResponseIDs, want) + } +} + +// A reply dsh did not get from magpie's gateway is no route's to name: its id +// would match nothing, and is not kept. +func TestDshResponseIDsOnlyFromTheGateway(t *testing.T) { + head := `{"type":"session","version":4,"id":"session-plain","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":false}` + s := dshSessionFile(t, []string{ + head, + `{"type":"assistant/message","seq":1,"time":1000,"data":{"message":{"source":{"provider":"deepseek","model":"deepseek-v4","replayState":{"response":{"provider":"deepseek","responseId":"vendor-1"}}}}}}`, + dshReplyWithID(2, "gw-1"), + }) + if want := []string{"gw-1"}; !slices.Equal(s.ResponseIDs, want) { + t.Fatalf("replies: %v, want %v", s.ResponseIDs, want) + } +} + +// A fork read before its seed's end lets its source's replies stand for it +// for that read; the marker, arriving later, takes them back (TestDshCalls- +// EndSeedAcrossReads reads the calls the same way). +func TestDshResponseIDsEndSeedAcrossReads(t *testing.T) { + head := `{"type":"session","version":4,"id":"session-child","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":true}` + dir := t.TempDir() + p := filepath.Join(dir, "session.jsonl") + write := func(lines ...string) { + f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + t.Fatal(err) + } + defer f.Close() + for _, l := range lines { + if _, err := f.WriteString(l + "\n"); err != nil { + t.Fatal(err) + } + } + } + f := func() file { + st, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + return file{agent: "dsh", path: p, main: true, size: st.Size(), mod: st.ModTime()} + } + write(head, dshReplyWithID(1, "inherited")) + first := parseDsh(f(), nil) + if len(first.ResponseIDs) != 1 { + t.Fatalf("before the marker: %v", first.ResponseIDs) + } + write(`{"type":"session/end-seed","seq":2,"time":1000,"data":{"inherited":true}}`, dshReplyWithID(3, "own")) + next := parseDsh(f(), first) + if want := []string{"own"}; !slices.Equal(next.ResponseIDs, want) { + t.Fatalf("after the marker: %v, want %v", next.ResponseIDs, want) + } +} + +// A fork of a real dsh 0.2.0-rc.2 session (testdata/dsh-gateway), made as +// dsh's buildForkSeed makes one: the source's events, a session/end-seed, +// then its own turn, under a header naming the source (parentSession). The +// listing gives the fork its own reply only and the source its own, and +// names the source the fork was made from (ForkOf). +func TestDshForkOfARealSessionListsItsOwnReplies(t *testing.T) { + const source, fork = "session-508e7b0a-37c0-41f7-ac62-e48ab3146111", "session-5e1c0f3a-8d2b-4c6e-9a71-2f4b6d8e0c13" + manageSetup(t) + home := filepath.Join(t.TempDir(), "dsh") + if err := os.CopyFS(filepath.Join(home, "sessions"), os.DirFS(filepath.Join("testdata", "dsh-gateway", "sessions"))); err != nil { + t.Fatal(err) + } + src, err := os.ReadFile(filepath.Join(home, "sessions", "--work-proj--", source, "session.v4.jsonl")) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(string(src)), "\n") + answer := "" + for _, l := range lines { + if strings.Contains(l, `"type":"assistant/message"`) { + answer = l + } + } + // the source's last event is seq 17 at 1792664874100 + b := `{"type":"session","version":4,"id":"` + fork + `","createdAt":1792664880000,"cwd":"/work/proj","parentSession":"` + source + `","isSeeded":true}` + "\n" + + strings.Join(lines[1:], "\n") + "\n" + + `{"type":"session/end-seed","seq":18,"time":1792664874100,"data":{"inherited":true}}` + "\n" + + `{"type":"user/message","seq":19,"time":1792664880100,"data":{"content":[{"type":"text","text":"Now the tests"}],"source":{"kind":"user"},"role":"user","id":"0b7c1d2e-3f40-4a51-8b62-7c83d94ea5f6"},"surfaceOp":"append"}` + "\n" + + strings.NewReplacer(`"seq":14,"time":1792664874092`, `"seq":20,"time":1792664880200`, `"responseId":"c1"`, `"responseId":"chatcmpl-fork1"`).Replace(answer) + "\n" + if !strings.Contains(b, `"seq":20,`) || !strings.Contains(b, "chatcmpl-fork1") { + t.Fatal("the fixture's reply is not the one this fork copies") + } + dir := filepath.Join(home, "sessions", "--work-proj--", fork) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "session.v4.jsonl"), []byte(b), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("DSH_HOME", home) + ageDsh(home) + Reset() + byID := map[string]Session{} + for _, s := range List(0) { + if s.Agent == "dsh" { + byID[s.ID] = s + } + } + if got := byID[source].ResponseIDs; !slices.Equal(got, []string{"c1"}) { + t.Errorf("source's replies %v, want [c1]", got) + } + f := byID[fork] + if !slices.Equal(f.ResponseIDs, []string{"chatcmpl-fork1"}) || f.ForkOf != source || len(f.Convs) != 0 { + t.Errorf("fork's replies %v, forked from %q, convs %v; want its own reply, from %s, no opening of its own", f.ResponseIDs, f.ForkOf, f.Convs, source) + } + if byID[source].ForkOf != "" { + t.Errorf("the source is forked from %q", byID[source].ForkOf) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 8511d1d2e..091c7e837 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -156,6 +156,16 @@ type Session struct { // Convs are the ids magpie's gateway keys the session's requests by // when they carry no session id of their own (dshConvs) Convs []string `json:"-"` + // ResponseIDs are the ids of the replies the session's own requests + // got, as the gateway wrote them on its routes and the agent kept them + // with the reply (dsh's replay state): a fork's inherited replies are + // its source's, and are not counted here (Route.ResponseID) + ResponseIDs []string `json:"-"` + // ForkOf is the session a dsh fork was seeded from (its header's + // parentSession, isSeeded): the fork's requests open as that one's do, + // so a reply id that names the fork is taken over the opening only for + // a fork of the opening's session (gui's ownerOf) + ForkOf string `json:"-"` // Copies are the ids of the sessions that are copies of its // conversation, not listed apart from it (ccCopies) Copies []string `json:"-"` @@ -215,9 +225,14 @@ type state struct { Custom string `json:"custom,omitempty"` // the name the user gave it First string `json:"first,omitempty"` // the first message, when no prompt looked typed Convs []string `json:"convs,omitempty"` // the gateway's ids for its requests (dshConvs) - Start time.Time `json:"start"` - Last time.Time `json:"last"` - Models named[Tokens] `json:"models,omitempty"` + // ResponseIDs are the ids of the replies its own requests got, as the + // gateway wrote them on its routes and the agent kept them with the + // reply (dsh's replay state): they name a request after the fact, where + // a conversation id is only its opening (Route.ResponseID) + ResponseIDs []string `json:"response_ids,omitempty"` + Start time.Time `json:"start"` + Last time.Time `json:"last"` + Models named[Tokens] `json:"models,omitempty"` // Days is Models again, split by the local date each message was // written on: a session that runs past midnight counts on both days. Days named[*day] `json:"days,omitempty"` @@ -378,6 +393,7 @@ func (s *state) clone() *state { c.Total = &t } c.Convs = slices.Clone(s.Convs) + c.ResponseIDs = slices.Clone(s.ResponseIDs) c.CodexSpawnNames = maps.Clone(s.CodexSpawnNames) c.CodexSpawnConflicts = maps.Clone(s.CodexSpawnConflicts) c.CodexAgentIDs = maps.Clone(s.CodexAgentIDs) @@ -1143,7 +1159,10 @@ const cacheVersion = 29 // // codex 2: only a fork's copies are; its own calls after them are its own, // whatever their numbers. -var parseVersions = map[string]int{"codex": 3, "zcode": 1} +// +// dsh 1: the ids of the replies its own requests got (ResponseIDs), for +// the routes that carry no session id and an opening a fork copies. +var parseVersions = map[string]int{"codex": 3, "zcode": 1, "dsh": 1} type cacheFile struct { Version int `json:"version"` @@ -1853,6 +1872,10 @@ func assembleListed(fs []file, price func(string) *catalog.Price, codexTitle fun s.App = "claude-desktop" } s.Convs = append(s.Convs, st.Convs...) + s.ResponseIDs = append(s.ResponseIDs, st.ResponseIDs...) + if d := st.Dsh; d != nil && d.Head.IsSeeded && d.Head.DelegationDepth == 0 { + s.ForkOf = d.Head.ParentSession + } } if s.Agent == "codex" && st.CodexNickname != "" { s.Nickname = st.CodexNickname