gateway: an advisor call Anthropic's server ran is a usage row of its own (#6977)
A Claude Code turn relayed on Messages with its advisor on has the advisor run at the vendor. The reply's top-level usage is the executor's alone; each advisor call is an advisor_message entry of usage.iterations, billed at the advisor model's rates (Anthropic's advisor tool page, "Usage and billing"). magpie read only the top level, so an Opus advisor beside a Sonnet executor was in no row and priced nowhere. aUsage reads iterations, whole and from a stream's message_delta (whose list is cumulative, so the latest stands for the reply). Each advisor call becomes its own row (advisorRows, written by appendAdvised at 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), Served as the vendor names it, Kind "advisor" (named Advisor in Usage's filters, already translated), the request's route, agent, account and session, status 200, counted as its own request as magpie's own advisor calls already are. The executor's row is unchanged. Routing prices the calls too, before the request's own usage so the prompt is still read from the last entry. Iterations with no advisor entry (Copilot) leave Usage as it was. The fixture is Anthropic's documented example word for word; no real reply with an advisor call was captured. The core script budget is raised by 52, the Advisor entry in the generated purposes.js (the base had no room; 1 byte less is red). The kinds are read wherever Usage and Routing draw a row, so there is no page to move it to. Run at this commit's tree onf1b0663f1, then onb1f044fc1(which changed core scripts only, i18n.js and syncfiles.js, so internal/gui and the GUI files were run again there): - mica: gofmt -l (nothing), go vet (darwin), GOOS=linux go vet -tags nogui, GOOS=windows go vet for internal/gateway, internal/usage, internal/gui: ok. - mica: go test -timeout 45m -count=1 ./internal/gateway ./internal/usage ./internal/gui: ok (916s, 64s, 161s). - mote: node --test purpose-filter, routing-purpose-state, usage-big-write, usage-ledger-mcp, usage-ledger-search, i18n-keys (Chromium and WebKit): 74 of 74 pass. - Onb1f044fc1, the pushed base: mica go test -timeout 45m -count=1 ./internal/gui ok (147s); mote the same six GUI files, 74 of 74 pass. - Before the rebase, atae94571d7, the same packages on mote were ok except TestCoreScriptBudget, which this commit's budget line answers. Broken by hand: - aUsage.usage never setting advised: TestAdvisorIterationsRead red ("stream=false: advisor calls <nil>, want one"), TestAdvisorCallHasItsOwnRow red in both subtests ("advisor rows: []"). - passthrough without advisedAs: TestAdvisorCallHasItsOwnRow red in both subtests, the row named claude-opus-5-5 and not magpie's claude-opus-5.5. Not tried: a real Anthropic reply with an advisor call (no account with the advisor beta at hand); Bedrock and Vertex passthrough with an advisor (they share the sniffer, not run); the Usage page with an advisor row in a real browser session beyond the GUI files above. Reported by Refeccd on Discord.
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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{}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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})
|
||||
|
||||
@@ -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"}};
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user