diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a5a5cd39c..19180dbc9 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -447,6 +447,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`). - Antigravity answers a system instruction holding one of a few lines with a 429 "Resource has been exhausted" whatever quota is left, on every model (`agTurnedAway` in [`codeassist.go`](../../internal/gateway/codeassist.go)): Claude Code's billing line, the Claude Agent SDK's identity line, Codex's identity lines for its GPT-5 models (which a Codex thread begun on a GPT model keeps after a switch), Hermes Agent's earlier default persona, and oh-my-pi's RFC 2119 line; since the evening of 11-14 also "You are Hermes Agent" (Hermes' current persona), "You are OpenCode", Codex CLI's "You are a coding agent running in the Codex CLI" (its prompt for models it has none of its own for) and pi's "a coding assistant running inside pi". Codex's GPT-6 prompt, Claude Code's own line, Gemini CLI, Qwen Code, Cline, Kilo, goose, Amp, Droid, Kimi, Aider and Cursor pass as written (real account, 11-14). An Antigravity account's system instruction goes with each such line reworded with the same meaning (`antigravityCloak`, `agSaidAs`, in `codeAssistBody`): the billing line left out, "built on the Claude Agent SDK by Anthropic", Codex's "built on GPT-5", Hermes' "built by Nous Research", oh-my-pi's "RFC 2119 key words", "You're" for Hermes', OpenCode's and Codex CLI's "You are", and pi's "running within pi". The refusal's hint names the agent (`antigravityHint`: Codex, Codex CLI, Hermes, OpenCode, pi, RFC), word for word as the antigravity and agy-cli plugins and the Routing page's `HINTS` have it. Until 11-14 they went broken up by zero-width spaces; since then Google's check reads past invisible characters and turned every broken-up line away 5 of 5 on a real account, so a line is also matched with invisible characters inside it and a copy an older magpie or middleware broke up is reworded too. Every other provider, Gemini CLI's sign-in on the same envelope included, is sent the prompt as written. `magpie provider set antigravity prompt=as-written` (`Provider.PromptAsWritten`) turns it off. The refusal is still told against the system prompt as the agent wrote it (`antigravityTurnedAway`): a 400 with the hint for that prompt, the account not rested, and a group skipping Antigravity for that prompt for 6 hours after a refusal (`antigravityForeseen`). - 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)). The model Claude Code names is first taken to the id magpie serves, as a request's own model is (`advisorID`): a dotted Claude id is given to Claude Code with dashes, and the advisor came back so, so `relay/claude-fable-5-2` on a provider listing `claude-fable-5.2` went upstream as `claude-fable-5-2`, a name the relay doesn't know (Refeccd on Discord); one it can't run there (another provider's, a group, not Claude's) is run by magpie when magpie serves it (below) and otherwise 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 bridge runs it as magpie does on a translation (below, and [claude-subscription-bridge.md](claude-subscription-bridge.md)). `TestAdvisorModelAsTheUpstreamNamesIt`, `TestAdvisorLeftOutOnTranslation`. - magpie runs Claude Code's advisor itself where the upstream can't and the advisor's model is one magpie serves (`provider.Resolve` takes it; `advisedHere` in [`advisor_serve.go`](../../internal/gateway/advisor_serve.go), Awad_Yoo on X). Claude Code sends the advisor for any model only with `CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL` set (2.1.316), which the Claude Code advisor field writes (agent-wiring.md). Such a request is translated, a relay on Messages too (`ownAPI`): the server tool becomes `Request.Advisor`, and the model is offered a function tool `advisor` with no parameters (`advisorToolDef`, a neutral description naming neither magpie nor a vendor), Claude Code's instructions and `tool_addition` kept as written. A call of it is answered inside the reply's rounds, beside web search's (`searchRounds`, `adviceRound`): the advisor model is asked through the gateway (`advise`, User-Agent `magpie-advisor/1`, the executor's system prompt and conversation, what the model said before the call, its tools offered with `tool_choice` none, no reasoning, and a short ask appended to the last user message, `adviceFor`; Claude Code's advisor instructions are cut from its system prompt and messages, `advisorCut`, since with them, or `advisorGone` in their place, the advisor answered as the executor that it had no advisor, #6804), and the reply goes on with the advice as the call's result. Claude Code is told as Anthropic's server tells it: a `server_tool_use` (`srvtoolu_…`, empty input) and an `advisor_tool_result` with `{type: advisor_result, text}`, or `{type: advisor_tool_result_error, error_code}` (`unavailable`, `too_many_requests`, `overloaded`, `prompt_too_long`, `execution_time_exceeded`, or `max_uses_exceeded` past three calls a reply). Claude Code echoes both blocks in the next turn's assistant message; `readAdvised` reads them back as the model's call and its result, splitting the message around them (`adviceApart`). Not handled: a round that calls the advisor beside an agent tool keeps the agent's tool call only, as with web search. `TestAdvisorServedForAVendorModel`, `TestAdvisorHistoryGoesBackAsACall`, `TestAdvisorFailureIsAnErrorCode`, `TestAdvisedHere`. +- An advisor Anthropic's server runs (the request relayed on Messages, `advisorTools` above) bills apart from the request's model: the reply's top-level `usage` is the executor's alone, and each call is an `advisor_message` entry of `usage.iterations`, with its `model` and token counts, billed at the advisor model's rates and in no top-level total (Anthropic's advisor tool page, "Usage and billing"). The ledger had the executor's row only, so an Opus advisor beside a Sonnet executor was in no row (#6977, Refeccd on Discord). `aUsage.Iterations` is read (whole, and from a stream's `message_delta`, whose list holds every call so far and replaces the one before: `Usage.advised`), and each advisor call is a usage row of its own (`advisorRows` in [`advisor_usage.go`](../../internal/gateway/advisor_usage.go), written by `appendAdvised` beside every row of a try that reached a provider, and on the native route): under the advisor's model by magpie's id (`advisorKeyModel` of the request's advisor tool, `advisedAs` in `passthrough`; else the vendor's name), its `Served` the vendor's, `Kind` `advisor` (`usage.KindAdvisor`, named Advisor on Usage's Requests and filters), the request's route, agent, account and session, status 200, no timing. It counts as a request of its own, as an advisor call magpie runs itself does (below). The executor's row is as the reply said; nothing is taken from it. Routing prices the calls too, before the request's own usage (`advisorRouteUsage`), so the prompt is still read from the last. Not captured from a real reply: the fixture is Anthropic's documented example word for word. `TestAdvisorIterationsRead`, `TestAdvisorCallHasItsOwnRow`. - 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. - The cache marks `buildAnthropic` adds for a Responses client (Codex) to a Claude model last an hour (`addedMark`, `Request.hourMarks`; 7eleven on Discord): Codex's turns are often more than five minutes apart, and Codex's own vendor keeps a thread cached an hour (`chatGPTCold`). A 1h write costs 2x the input price where Anthropic's default 5m costs 1.25x and a read 0.1x or less, so one turn read after a 5 to 60 minute pause, which a 5m mark would have written again, pays for the dearer writes of dozens of turns in quick succession. Every mark it adds has the same ttl, since Anthropic refuses a 1h mark after a 5m one. The client's `prompt_cache_retention: "in_memory"` keeps them at 5m. A Chat client's marks, a model that isn't Claude's, and marks a client placed itself (an Anthropic client's, relayed as sent) are unchanged. An upstream that answers 400 naming `cache_control` and `ttl` (a relay that knows no ttl) is asked again at 5m and remembered in `unfit` (`hourMarksRefused`) until magpie restarts. A Claude subscription is served by Claude Code, which asks 1h unless the user picked 5m ([Claude subscription bridge](claude-subscription-bridge.md)). `TestResponsesToClaudeMarksLastAnHour`, `TestHourMarksRefused`. - 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/internal/gateway/advisor_usage.go b/internal/gateway/advisor_usage.go new file mode 100644 index 000000000..88cfbdf62 --- /dev/null +++ b/internal/gateway/advisor_usage.go @@ -0,0 +1,65 @@ +package gateway + +import ( + "cmp" + "net/http" + + "github.com/yetone/magpie/internal/usage" +) + +// advisorRows are the usage rows of the advisor calls a reply says its +// vendor made (Anthropic's advisor tool, run at the vendor on a request +// that goes as it is: advisorTools), one a call, beside rec, the +// executor's own row. Anthropic's top-level usage is the executor's alone +// and bills each advisor_message iteration at the advisor model's rates, +// so a row of the request's model held only part of what was spent: an +// Opus advisor's tokens beside a Sonnet executor were in no row at all +// (#6977, Refeccd on Discord). Each row is under the advisor's model, by +// magpie's id the request named it by (advisedAs), else the vendor's name +// for it, its Served the vendor's; nothing is taken from rec. It is its +// own request, as an advisor call magpie runs itself is (advise): Kind +// says it is the advisor's, and it has the request's route, agent, +// account and session. It has no timing of its own (the vendor's stream +// tells none), and its status is the call's, which the reply listed as +// done, not the executor's. +func advisorRows(rec usage.Record, u Usage) []usage.Record { + a := u.advised + if a == nil { + return nil + } + out := make([]usage.Record, 0, len(a.calls)) + for _, c := range a.calls { + b := c.use + if b.Input+b.Output+b.CacheRead+b.CacheWrite == 0 { + continue + } + model := cmp.Or(a.model, c.served) + out = append(out, usage.Record{RouteID: rec.RouteID, Time: rec.Time, Agent: rec.Agent, Via: rec.Via, Provider: rec.Provider, Host: rec.Host, + ProviderKeyID: rec.ProviderKeyID, ProviderKeyName: rec.ProviderKeyName, ProviderAccount: rec.ProviderAccount, + Model: model, Requested: model, Served: c.served, + Input: b.Input, Output: b.Output, CacheRead: b.CacheRead, CacheWrite: b.CacheWrite, CacheWrite1h: b.CacheWrite1h, Reasoning: b.Reasoning, + Status: http.StatusOK, Session: rec.Session, NativeSession: rec.NativeSession, Kind: usage.KindAdvisor, Endpoint: rec.Endpoint}) + } + return out +} + +// appendAdvised writes rec, then the rows of the advisor calls u says its +// reply made (advisorRows). +func appendAdvised(r *http.Request, rec usage.Record, u Usage) { + appendUsage(r, rec) + for _, a := range advisorRows(rec, u) { + appendUsage(r, a) + } +} + +// advisorRouteUsage is the Routing page's pricing of the advisor calls u +// says its reply made, under provider id, before the request's own (which +// stays last: promptCounted reads the prompt from it). +func advisorRouteUsage(id string, u Usage) []RouteUsage { + var out []RouteUsage + for _, a := range advisorRows(usage.Record{Provider: id}, u) { + out = append(out, RouteUsage{Provider: id, Model: a.Model, Input: a.Input, Output: a.Output, + CacheRead: a.CacheRead, CacheWrite: a.CacheWrite, Reasoning: a.Reasoning}) + } + return out +} diff --git a/internal/gateway/advisor_usage_test.go b/internal/gateway/advisor_usage_test.go new file mode 100644 index 000000000..f6d4bc02e --- /dev/null +++ b/internal/gateway/advisor_usage_test.go @@ -0,0 +1,173 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// advisedUsage is the usage of a reply whose advisor ran once, word for +// word Anthropic's example on its advisor tool page ("Usage and billing", +// platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool): +// no real reply with an advisor call was captured. The top-level counts +// are the executor's alone; the advisor_message iteration is the +// advisor's, at its own model's rates (#6977). +const advisedUsage = `{"input_tokens":1760,"cache_read_input_tokens":412,"cache_creation_input_tokens":0,"output_tokens":531,"iterations":[{"type":"message","input_tokens":412,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":89},{"type":"advisor_message","model":"claude-opus-5-5","input_tokens":823,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":1612},{"type":"message","input_tokens":1348,"cache_read_input_tokens":412,"cache_creation_input_tokens":0,"output_tokens":442}]}` + +// advisedReply is a reply to a turn whose advisor ran at the vendor, its +// usage advisedUsage: whole, or streamed with the iterations on its +// message_delta, as Anthropic's page says a stream tells them. +func advisedReply(stream bool) string { + if !stream { + return `{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":` + advisedUsage + `}` + } + return sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[],"usage":{"input_tokens":1760,"cache_read_input_tokens":412,"cache_creation_input_tokens":0,"output_tokens":1}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":`+advisedUsage+`}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`) +} + +// The usage a reply's advisor calls ran up is read beside the executor's, +// whole and streamed, and the executor's counts are the top-level ones as +// they came: nothing is taken from them or added to them. +func TestAdvisorIterationsRead(t *testing.T) { + for _, stream := range []bool{false, true} { + ct := "application/json" + if stream { + ct = "text/event-stream" + } + s := newSniffer(provider.Anthropic, ct) + s.write([]byte(advisedReply(stream))) + u := s.usage() + if u.Input != 1760 || u.Output != 531 || u.CacheRead != 412 || u.CacheWrite != 0 { + t.Errorf("stream=%v: the executor's usage %+v, want 1760 in, 531 out, 412 read", stream, u) + } + if u.advised == nil || len(u.advised.calls) != 1 { + t.Fatalf("stream=%v: advisor calls %+v, want one", stream, u.advised) + } + c := u.advised.calls[0] + if c.served != "claude-opus-5-5" || c.use.Input != 823 || c.use.Output != 1612 || c.use.CacheRead+c.use.CacheWrite != 0 { + t.Errorf("stream=%v: the advisor's call %+v", stream, c) + } + } + // a stream's later message_delta lists the earlier calls again: it + // stands for the reply's, never added to the one before + var u Usage + for range 2 { + var a aUsage + if err := json.Unmarshal([]byte(advisedUsage), &a); err != nil { + t.Fatal(err) + } + u.add(a.usage()) + } + if len(u.advised.calls) != 1 { + t.Fatalf("the same iterations told twice made %d calls", len(u.advised.calls)) + } + // iterations with no advisor call in them (Copilot's message_delta) + // leave the usage as it was + var a aUsage + if err := json.Unmarshal([]byte(`{"input_tokens":5,"output_tokens":2,"iterations":[{"type":"message","input_tokens":5,"output_tokens":2}]}`), &a); err != nil { + t.Fatal(err) + } + if got := a.usage(); got != (Usage{Input: 5, Output: 2}) { + t.Fatalf("no advisor call: %+v", got) + } +} + +// A Claude Code turn with its advisor on, sent as it is to a provider's +// Messages API, where Anthropic's server runs the advisor: its call is a +// usage row of its own under the advisor's model, by magpie's id (here +// claude-opus-5.5, which Claude Code names claude-opus-5-5 and the +// iteration names as the vendor does), priced as that model, and the +// request's own row is the executor's usage as the reply said it (Refeccd +// on Discord: the advisor's Opus tokens were in no row). The Routing page +// prices it too. +func TestAdvisorCallHasItsOwnRow(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + if stream { + w.Header().Set("Content-Type", "text/event-stream") + } else { + w.Header().Set("Content-Type", "application/json") + } + io.WriteString(w, advisedReply(stream)) + })) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: srv.URL, Models: []string{"claude-opus-5.5", "claude-sonnet-5-5"}}); err != nil { + t.Fatal(err) + } + body := advisorTurn("relay/claude-sonnet-5-5", "relay/claude-opus-5-5") + if !stream { + body = strings.Replace(body, `"stream":true`, `"stream":false`, 1) + } + s := New() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader(body)) + req.Header.Set("User-Agent", "claude-cli/2.1.300 (external, cli)") + req.Header.Set("Authorization", "Bearer "+Token) + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + route := lastRoute(s) + var rows []usage.Record + deadline := time.Now().Add(10 * time.Second) + for { + rows = rows[:0] + for _, u := range usage.Load(time.Time{}) { + if u.RouteID == route.ID { + rows = append(rows, u) + } + } + if len(rows) >= 2 || time.Now().After(deadline) { + break + } + time.Sleep(20 * time.Millisecond) + } + var own, advised []usage.Record + for _, r := range rows { + if r.Kind == usage.KindAdvisor { + advised = append(advised, r) + } else { + own = append(own, r) + } + } + if len(own) != 1 || own[0].Model != "claude-sonnet-5-5" || own[0].Input != 1760 || own[0].Output != 531 || own[0].CacheRead != 412 { + t.Fatalf("the request's own row: %+v", own) + } + if len(advised) != 1 { + t.Fatalf("advisor rows: %+v (every row %+v)", advised, rows) + } + a := advised[0] + if a.Provider != "relay" || a.Model != "claude-opus-5.5" || a.Served != "claude-opus-5-5" || a.Input != 823 || a.Output != 1612 || + a.CacheRead+a.CacheWrite != 0 || a.Status != 200 || a.HandedOn || a.Session != own[0].Session || a.Agent != own[0].Agent { + t.Fatalf("the advisor's row: %+v", a) + } + var models []string + for _, u := range route.Usage { + models = append(models, fmt.Sprintf("%s:%d/%d", u.Model, u.Input, u.Output)) + } + if got := strings.Join(models, ","); got != "claude-opus-5.5:823/1612,claude-sonnet-5-5:1760/531" { + t.Fatalf("Routing's usage %s", got) + } + if promptCounted(route.Usage) != 1760+412 { + t.Fatalf("the prompt read from the advisor's usage: %d", promptCounted(route.Usage)) + } + }) + } +} diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index 49c5c3f7e..17a5b6dc8 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -1537,6 +1537,25 @@ type aUsage struct { // reads from Claude Code. A vendor that leaves it out is told by its // stream (hidesReasoning, #4545) OutputTokensDetails *aOutputDetails `json:"output_tokens_details,omitempty"` + // Iterations lists the reply's sampling steps when a server-side tool + // ran one of its own: Anthropic's advisor tool. The counts above are + // the executor's alone; an advisor_message entry is the advisor + // model's call, billed at its rates and in no total above (#6977). + // It is read, never told: anthropic() leaves it out. + Iterations []aIteration `json:"iterations,omitempty"` +} + +// aIteration is one entry of usage.iterations: "message" for the +// executor's own sampling, "advisor_message" for an advisor call, with +// the model that ran it. +type aIteration struct { + Type string `json:"type"` + Model string `json:"model,omitempty"` + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` + CacheReadInputTokens int `json:"cache_read_input_tokens"` + CacheCreationInputTokens int `json:"cache_creation_input_tokens"` + CacheCreation *aCacheCreation `json:"cache_creation,omitempty"` } type aCacheCreation struct { @@ -1559,6 +1578,22 @@ func (u aUsage) usage() Usage { if d := u.OutputTokensDetails; d != nil { out.Reasoning = d.ThinkingTokens } + // the list is cumulative, so one with no advisor call in it says + // nothing that replaces an earlier one's + if len(u.Iterations) > 0 { + a := &advisedUse{} + for _, it := range u.Iterations { + if it.Type != "advisor_message" { + continue + } + use := aUsage{InputTokens: it.InputTokens, OutputTokens: it.OutputTokens, CacheReadInputTokens: it.CacheReadInputTokens, + CacheCreationInputTokens: it.CacheCreationInputTokens, CacheCreation: it.CacheCreation}.usage() + a.calls = append(a.calls, advisorCall{served: it.Model, use: use}) + } + if len(a.calls) > 0 { + out.advised = a + } + } return out } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 204a3cc55..e206a6e61 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4696,7 +4696,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro failed.wholeIn, failed.wholeOut = call.wholeIn, hw.errBody() } withBodies(&rec, failed) - appendUsage(r, rec) + appendAdvised(r, rec, call.Usage) } sentMs, ownMs, retriedMs, queuedMs = 0, 0, 0, 0 if at := wrote.Load(); at > 0 && call.TTFT > 0 { @@ -4943,7 +4943,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro refusal.wholeIn, refusal.wholeOut = call.wholeIn, hw.errBody() } withBodies(&rec, refusal) - appendUsage(r, rec) + appendAdvised(r, rec, call.Usage) } failedRow = nil // its row is written continue @@ -4988,7 +4988,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro refusal.wholeIn, refusal.wholeOut = call.wholeIn, hw.errBody() } withBodies(&rec, refusal) - appendUsage(r, rec) + appendAdvised(r, rec, call.Usage) } failedRow = nil // its row is written continue @@ -5887,7 +5887,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) withBodies(&rec, &call) - appendUsage(r, rec) + appendAdvised(r, rec, call.Usage) if call.Status < 400 { // what its model searched with its provider's own tool logNativeSearches(r.Context(), call.Usage.searches, start, call.Agent, call.Provider, where, model) @@ -6864,6 +6864,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. searchFn := false // Codex's tool search sent as a function geminiWhole := false // a Gemini client's generateContent var toolSeen map[string]bool // the call ids the client holds (tool_use_ids.go) + advisor := "" // magpie's id of the advisor model asked for // a model that wants its reasoning text back (#388, #1104) replay := proto == provider.Responses && (replaysReasoning(model, p.VendorHost()) || replaysReasoning(upstream, p.VendorHost())) switch proto { @@ -7025,7 +7026,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. // Anthropic turns the whole request away for, and every later // one of the conversation with it (tool_blocks_paired.go) body = toolBlocksPaired(body) - // Claude Code's advisor, named by magpie's id (advisor.go) + // Claude Code's advisor, named by magpie's id (advisor.go); its + // calls' usage rows go by that id (advisorRows) + advisor = advisorKeyModel(advisorAsked(provider.Anthropic, body)) body = advisorTools(body, p, upstream, wiresOf(r.Context()), keyAllows(r, p)) if p.IsBedrock() { // Claude Code's metadata.user_id, a JSON string these days, is @@ -7667,7 +7670,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. } f, _ := w.(http.Flusher) sniff := newSniffer(proto, res.Header.Get("Content-Type")) - defer func() { u.add(sniff.usage()) }() + defer func() { u.add(sniff.usage().advisedAs(advisor)) }() var tidy *chatTidy if proto == provider.Chat && sse { tidy = &chatTidy{} diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index ba8b99c10..e472a6b95 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -585,6 +585,39 @@ type Usage struct { // credits, nil when it said none: WorkBuddy's usage.credit, the // figure its app shows on each reply as "Credits Consumed" (#2512) Credits *float64 `json:"credits,omitempty"` + // advised is what the reply says its server-side advisor's calls cost + // (Anthropic's usage.iterations, advisor_message entries): billed at + // the advisor model's rates and never in the counts above, so each is + // a usage row of its own (advisorRows, #6977). A pointer, so Usage is + // still compared as a value; nil when the reply listed no iterations. + advised *advisedUse +} + +// advisedUse is the advisor calls one reply reported, in the order its +// iterations listed them. +type advisedUse struct { + // model is magpie's id of the advisor model the request named, which + // its rows are priced by; "" until the route names it (advisedAs) + model string + calls []advisorCall +} + +// advisorCall is one advisor_message iteration: the model the vendor +// says ran it and its own token counts. +type advisorCall struct { + served string + use Usage +} + +// advisedAs is u with its advisor calls named by magpie's id of the +// advisor model the request asked for: the iterations name the vendor's. +func (u Usage) advisedAs(model string) Usage { + if u.advised != nil && model != "" { + a := *u.advised + a.model = model + u.advised = &a + } + return u } // billed is what the request is billed for: its own count, and what it @@ -668,6 +701,11 @@ func (u *Usage) add(v Usage) { if v.Credits != nil { u.Credits = v.Credits } + // a stream's message_delta lists every iteration so far, the earlier + // ones again: the latest list stands for the reply's + if v.advised != nil { + u.advised = v.advised + } } // Result is a whole reply, for non-streaming clients. diff --git a/internal/gateway/native.go b/internal/gateway/native.go index e91e47899..ce6280e7f 100644 --- a/internal/gateway/native.go +++ b/internal/gateway/native.go @@ -497,8 +497,8 @@ func (s *Server) nativeAny(w http.ResponseWriter, r *http.Request, p provider.Pr } call.Usage = u s.record(*call) - appendUsage(r, usage.Record{Operation: "native", Time: start, Agent: call.Agent, Via: call.Via, Provider: p.ID, Host: p.Where(), Model: call.Model, Requested: call.Model, Served: u.Served, Upstream: u.Upstream, + appendAdvised(r, usage.Record{Operation: "native", Time: start, Agent: call.Agent, Via: call.Via, Provider: p.ID, Host: p.Where(), Model: call.Model, Requested: call.Model, Served: u.Served, Upstream: u.Upstream, ProviderKeyID: provider.KeyID(p.Key), ProviderKeyName: p.KeyName, Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, CacheWrite1h: u.CacheWrite1h, Reasoning: u.Reasoning, - Millis: call.Millis, Status: call.Status, Session: sessionOf(r.Header)}) + Millis: call.Millis, Status: call.Status, Session: sessionOf(r.Header)}, u) } diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 4a5b4f4f6..d0d9a034d 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -1172,9 +1172,11 @@ func swapped(sent, served string) bool { return usage.Swapped(sent, served) } // request's metadata. Unknown token counts have no price, including failures. // What the reply counted of earlier requests (Deferred) is priced as a tier // of its own before the request's, which stays last: the prompt is read -// from the last (promptCounted), and is the request's own. +// from the last (promptCounted), and is the request's own. So are the +// calls its advisor made at the vendor, under the advisor's model +// (advisorRouteUsage, #6977). func routeUsage(id, model string, u Usage) []RouteUsage { - var out []RouteUsage + out := advisorRouteUsage(id, u) if d := u.Deferred; d != nil && d.Input+d.Output+d.CacheRead+d.CacheWrite > 0 { out = append(out, RouteUsage{Provider: id, Model: model, Input: d.Input, Output: d.Output, CacheRead: d.CacheRead, CacheWrite: d.CacheWrite, Reasoning: d.Reasoning}) diff --git a/internal/gui/assets/purposes.js b/internal/gui/assets/purposes.js index e1cc0131c..09f8ba04c 100644 --- a/internal/gui/assets/purposes.js +++ b/internal/gui/assets/purposes.js @@ -1,2 +1,2 @@ // Code generated by go generate ./internal/usage; DO NOT EDIT. -const REQUEST_KINDS = {"agent_job":{"purpose":"kind:collab_spawn","name":"Subagent"},"agent_summary":{"purpose":"kind:agent_summary","name":"Progress summary"},"agent_summary_inferred":{"purpose":"kind:agent_summary","name":"Progress summary (inferred)"},"ambient_suggestion_safety":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"ambient_suggestions":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"api_detect":{"purpose":"kind:api_detect","name":"Detect APIs"},"auto_mode_check":{"purpose":"kind:auto_mode_check","name":"Auto mode check"},"auto_mode_check_inferred":{"purpose":"kind:auto_mode_check","name":"Auto mode check (inferred)"},"auto_review":{"purpose":"kind:guardian","name":"Approval check"},"cache_keepalive":{"purpose":"kind:cache_keepalive","name":"Cache keep-alive"},"collab_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"compact":{"purpose":"kind:compact","name":"Compaction"},"composer_predictions":{"purpose":"kind:composer_predictions","name":"Prediction"},"connection_check":{"purpose":"kind:connection_check","name":"Connection check"},"guardian":{"purpose":"kind:guardian","name":"Approval check"},"guardian_review":{"purpose":"kind:guardian","name":"Approval check"},"luna_reserve":{"purpose":"kind:luna_reserve","name":"Luna Reserve"},"mcp":{"purpose":"kind:mcp","name":"MCP tool"},"memgen":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory_consolidation":{"purpose":"kind:memory_consolidation","name":"Memory"},"model_list":{"purpose":"kind:model_list","name":"Model list"},"provider_test":{"purpose":"kind:provider_test","name":"Test"},"review":{"purpose":"kind:review","name":"Review"},"routing":{"purpose":"kind:routing","name":"Routing classifier"},"thread_description":{"purpose":"kind:thread_description","name":"Description"},"thread_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"thread_title":{"purpose":"kind:thread_title","name":"Title"},"thread_title_reconsideration":{"purpose":"kind:thread_title","name":"Title"},"title":{"purpose":"kind:thread_title","name":"Title"},"title_generation":{"purpose":"kind:thread_title","name":"Title"},"vision":{"purpose":"kind:vision","name":"Image description"},"web_search":{"purpose":"kind:web_search","name":"Web search"}}; +const REQUEST_KINDS = {"advisor":{"purpose":"kind:advisor","name":"Advisor"},"agent_job":{"purpose":"kind:collab_spawn","name":"Subagent"},"agent_summary":{"purpose":"kind:agent_summary","name":"Progress summary"},"agent_summary_inferred":{"purpose":"kind:agent_summary","name":"Progress summary (inferred)"},"ambient_suggestion_safety":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"ambient_suggestions":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"api_detect":{"purpose":"kind:api_detect","name":"Detect APIs"},"auto_mode_check":{"purpose":"kind:auto_mode_check","name":"Auto mode check"},"auto_mode_check_inferred":{"purpose":"kind:auto_mode_check","name":"Auto mode check (inferred)"},"auto_review":{"purpose":"kind:guardian","name":"Approval check"},"cache_keepalive":{"purpose":"kind:cache_keepalive","name":"Cache keep-alive"},"collab_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"compact":{"purpose":"kind:compact","name":"Compaction"},"composer_predictions":{"purpose":"kind:composer_predictions","name":"Prediction"},"connection_check":{"purpose":"kind:connection_check","name":"Connection check"},"guardian":{"purpose":"kind:guardian","name":"Approval check"},"guardian_review":{"purpose":"kind:guardian","name":"Approval check"},"luna_reserve":{"purpose":"kind:luna_reserve","name":"Luna Reserve"},"mcp":{"purpose":"kind:mcp","name":"MCP tool"},"memgen":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory_consolidation":{"purpose":"kind:memory_consolidation","name":"Memory"},"model_list":{"purpose":"kind:model_list","name":"Model list"},"provider_test":{"purpose":"kind:provider_test","name":"Test"},"review":{"purpose":"kind:review","name":"Review"},"routing":{"purpose":"kind:routing","name":"Routing classifier"},"thread_description":{"purpose":"kind:thread_description","name":"Description"},"thread_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"thread_title":{"purpose":"kind:thread_title","name":"Title"},"thread_title_reconsideration":{"purpose":"kind:thread_title","name":"Title"},"title":{"purpose":"kind:thread_title","name":"Title"},"title_generation":{"purpose":"kind:thread_title","name":"Title"},"vision":{"purpose":"kind:vision","name":"Image description"},"web_search":{"purpose":"kind:web_search","name":"Web search"}}; diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 2f865ad9a..7831769f0 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -18,7 +18,7 @@ import ( // `git log -L` of this file. const ( appScriptBudget = 1_088_196 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had; +123 for a sidebar list folded from its page's row (hkwok06 on X), its chevron and fold in navicons.js, imported with the first list; +57 for each account of a provider's Usage card in a card of its own (normalcoder_ on X), past the 24 of room left; +17 for an allowance card's wallet line under its rings (apple_test_src on X), the one filter shared with its text line; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to; +864 for Use on a Claude setup-token account, which switches Claude Code itself to it in its settings.json, and Use back on its signed-in account (liukaybee on X): one swUse helper shared by both buttons, packed to the shortest form; renderAccounts draws every account row, so there is no page to move it to; +1 for the classifier timeout's unset default, 15 and not 8 (ESern29751 on X): its second digit in the Settings row's fallback, which renderReplies draws, so there is no page to move it to; +457 for Kimi Code's subagent pool and its effort (XiaoLing_Arisa on X): the Subagents line and its pool menu in kimisub.js, imported before a Kimi Code row's Details first slides open so it measures the line, and what is left is that import, the line's place, the three fields kept out of the row's squares and the picker's note that Kimi's subagents run on the lead's model, packed to the shortest form; renderAgents draws every row, so there is no page to move it to; +354 for Images per request (#6849, Yuu_jiang_ on X): its field and parse are in maximages.js, imported as the editor draws Max output, and what stays is the import, the two saves' lines and the check that the editor is still open when it and keyrates.js land, no page to move them to; +499 for Speed beside Model and Effort in an agent's opened row (Tengs999 on X): the line, its menu and what decides the speed in agentspeed.js, imported before a fast model's Details first slides open so it measures the line, and what is left is that import and the line's place in the panel's and the window's rows, packed to one helper; renderAgents draws every row, so there is no page to move it to; -1,529: each ChatGPT account's own warm-up time (renderWarmAtOwn) moved into autoresetown.js, imported when its rows first draw, paying for a provider's editor opening Advanced when its warm-up or check-in is on (ChrisYagao on X), and the room left over given back; +103 for the sidebar foot that holds Settings' tabs marked by a class, not :has(), which Safari before 15.4 can't parse (#5919): no page's code small enough to move was left (modelInfo serves two plugins) - coreScriptBudget = 1_272_475 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to; +72 for Copy all keys (emilochen on X): its row in keyrates.js, imported when a provider with two or more keys opens through keyRateField, now told which of its parts to draw, and what is left is the one line that places it; +83 for the page saying it has gone from view, so what its Sessions and Usage pages keep goes in 30 s and not 7 minutes (P0 memory): folded into the visibilitychange listener every window has, packed to the shortest form, so there is no page to move it to; +270 for Providers' Select, to remove several at once (eiyuuzaki2333 on X): its rows, bar, removal and keys in pvpick.js, imported when Select is first clicked, and what is left is pvSel, the button's click and two lines in renderProviders, which draws the list, so there is no page to move it to; +81 for each account of a provider's Usage card in a card of its own (normalcoder_ on X): one line that makes the box, its brief look left to CSS, and renderQuotas, which draws every card, so there is no page to move it to; +17 for Kimi Code's booster balance under an allowance card's rings in the tray panel (apple_test_src on X): the card's text line and the wallet line share one filter, packed to the shortest form; panelQuotaCard draws every card, so there is no page to move it to; +51 for what a failed plugin install left in plugins/, listed under Installed with a Remove (CHENGJIAHEGOXIS on X): its section in plugininstalled.js as pmLeftovers, imported when Plugins first draws, and what is left is the one call after drawInstalled; draw is what draws the page, so there is no page to move it to; +123 for a sidebar list folded from its page's row (hkwok06 on X): the chevron, its click and the fold kept per page in navicons.js, imported with the first list, and what is left is the folded list read beside the hidden pages' (navList, which navMine now shares) and the two rows' clicks asking navFold first; navSubs draws every list, so there is no page to move it to; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to; +189 for Let magpie set it on a Codex card locked by config.toml's own compact limit or background threshold (sufeng1894 on X), and Undo for a background share taken over: the shared send posts it, packed to the shortest form; adviceRow draws every card, so there is no page to move it to; +864 for Use on a Claude setup-token account, which switches Claude Code itself to it in its settings.json, and Use back on its signed-in account (liukaybee on X): one swUse helper shared by both buttons, packed to the shortest form; renderAccounts draws every account row, so there is no page to move it to; +1 for the classifier timeout's unset default, 15 and not 8 (ESern29751 on X): its second digit in the Settings row's fallback, which renderReplies draws, so there is no page to move it to; +457 for Kimi Code's subagent pool and its effort (XiaoLing_Arisa on X): the Subagents line and its pool menu in kimisub.js, imported before a Kimi Code row's Details first slides open so it measures the line, and what is left is that import, the line's place, the three fields kept out of the row's squares and the picker's note that Kimi's subagents run on the lead's model, packed to the shortest form; renderAgents draws every row, so there is no page to move it to; +354 for Images per request (#6849, Yuu_jiang_ on X): its field and parse are in maximages.js, imported as the editor draws Max output, and what stays is the import, the two saves' lines and the check that the editor is still open when it and keyrates.js land, no page to move them to; +499 for Speed beside Model and Effort in an agent's opened row (Tengs999 on X): the line, its menu and what decides the speed in agentspeed.js, imported before a fast model's Details first slides open so it measures the line, and what is left is that import and the line's place in the panel's and the window's rows, packed to one helper; renderAgents draws every row, so there is no page to move it to; -1,529: each ChatGPT account's own warm-up time moved into autoresetown.js, paying for Advanced opening on a warm-up or check-in that is on (ChrisYagao on X), the room left over given back; +103 for the same .with-sub foot (#5919) + coreScriptBudget = 1_272_527 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to; +72 for Copy all keys (emilochen on X): its row in keyrates.js, imported when a provider with two or more keys opens through keyRateField, now told which of its parts to draw, and what is left is the one line that places it; +83 for the page saying it has gone from view, so what its Sessions and Usage pages keep goes in 30 s and not 7 minutes (P0 memory): folded into the visibilitychange listener every window has, packed to the shortest form, so there is no page to move it to; +270 for Providers' Select, to remove several at once (eiyuuzaki2333 on X): its rows, bar, removal and keys in pvpick.js, imported when Select is first clicked, and what is left is pvSel, the button's click and two lines in renderProviders, which draws the list, so there is no page to move it to; +81 for each account of a provider's Usage card in a card of its own (normalcoder_ on X): one line that makes the box, its brief look left to CSS, and renderQuotas, which draws every card, so there is no page to move it to; +17 for Kimi Code's booster balance under an allowance card's rings in the tray panel (apple_test_src on X): the card's text line and the wallet line share one filter, packed to the shortest form; panelQuotaCard draws every card, so there is no page to move it to; +51 for what a failed plugin install left in plugins/, listed under Installed with a Remove (CHENGJIAHEGOXIS on X): its section in plugininstalled.js as pmLeftovers, imported when Plugins first draws, and what is left is the one call after drawInstalled; draw is what draws the page, so there is no page to move it to; +123 for a sidebar list folded from its page's row (hkwok06 on X): the chevron, its click and the fold kept per page in navicons.js, imported with the first list, and what is left is the folded list read beside the hidden pages' (navList, which navMine now shares) and the two rows' clicks asking navFold first; navSubs draws every list, so there is no page to move it to; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to; +189 for Let magpie set it on a Codex card locked by config.toml's own compact limit or background threshold (sufeng1894 on X), and Undo for a background share taken over: the shared send posts it, packed to the shortest form; adviceRow draws every card, so there is no page to move it to; +864 for Use on a Claude setup-token account, which switches Claude Code itself to it in its settings.json, and Use back on its signed-in account (liukaybee on X): one swUse helper shared by both buttons, packed to the shortest form; renderAccounts draws every account row, so there is no page to move it to; +1 for the classifier timeout's unset default, 15 and not 8 (ESern29751 on X): its second digit in the Settings row's fallback, which renderReplies draws, so there is no page to move it to; +457 for Kimi Code's subagent pool and its effort (XiaoLing_Arisa on X): the Subagents line and its pool menu in kimisub.js, imported before a Kimi Code row's Details first slides open so it measures the line, and what is left is that import, the line's place, the three fields kept out of the row's squares and the picker's note that Kimi's subagents run on the lead's model, packed to the shortest form; renderAgents draws every row, so there is no page to move it to; +354 for Images per request (#6849, Yuu_jiang_ on X): its field and parse are in maximages.js, imported as the editor draws Max output, and what stays is the import, the two saves' lines and the check that the editor is still open when it and keyrates.js land, no page to move them to; +499 for Speed beside Model and Effort in an agent's opened row (Tengs999 on X): the line, its menu and what decides the speed in agentspeed.js, imported before a fast model's Details first slides open so it measures the line, and what is left is that import and the line's place in the panel's and the window's rows, packed to one helper; renderAgents draws every row, so there is no page to move it to; -1,529: each ChatGPT account's own warm-up time moved into autoresetown.js, paying for Advanced opening on a warm-up or check-in that is on (ChrisYagao on X), the room left over given back; +103 for the same .with-sub foot (#5919); +52 for the Advisor kind of an advisor call's own usage row (#6977, Refeccd on Discord): its entry in the generated purposes.js; the kinds are read wherever Usage and Routing draw a row, so there is no page to move it to ) // codeBytes is how many bytes of b are code: its blank lines, its lines diff --git a/internal/usage/purpose.go b/internal/usage/purpose.go index 69836a4e8..2d306db13 100644 --- a/internal/usage/purpose.go +++ b/internal/usage/purpose.go @@ -36,6 +36,7 @@ var purposeKinds = func() map[string]PurposeKind { add("Model list", "model_list") // probelog.KindList add("MCP tool", KindMCP) // an MCP tool call (SourceMCP) add("Cache keep-alive", KindKeepalive) // a plugin's own ping (plugin_calls.go) + add("Advisor", KindAdvisor) // an advisor call its vendor ran (gateway's advisorRows) // Claude Code names neither of these requests, so the gateway tells them // by their content: the *_inferred kinds. They share the purpose of the // plain kind (a client's own marker, were one sent), and say in their @@ -53,6 +54,10 @@ var purposeKinds = func() map[string]PurposeKind { // sub-agent progress summary and its auto mode classifier; InferredSuffix // follows one that was told by the request's content. const ( + // KindAdvisor is the kind of an advisor call's row: one Anthropic's + // server ran for a request's advisor tool, its usage listed in the + // reply's iterations (#6977) + KindAdvisor = "advisor" KindAgentSummary = "agent_summary" KindAutoMode = "auto_mode_check" InferredSuffix = "_inferred"