Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

routing: a request whose vendor counts no cache tokens shows no hit rate, not 0% (zeewell on X)

yetone436bcc946d6c
diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md
index 3ca3c3a48..8f1430fcb 100644
--- a/docs/subsystems/provider-plugins.md
+++ b/docs/subsystems/provider-plugins.md
@@ -38,6 +38,10 @@ A plugin that learns a step's usage only after the step has ended reports it wit
The gateway parses the field into `Usage.Deferred` ([`cUsage`](../../internal/gateway/chat.go)) and adds it only where it bills: the usage records, the OTel attempt spans and route pricing, which prices it as a tier before the request's own ([`routeUsage`](../../internal/gateway/trace.go), [`Usage.billed`](../../internal/gateway/ir.go)). What a client is told stays the request's own, because agents read `prompt_tokens` as how full their context is: the passthrough forwards the plugin's bytes as they are, whose standard fields are the step's own, and a translated reply is encoded from the own count alone. `promptCounted` also reads the request's own. A reply without the field is handled as before. With an older magpie the field is ignored and the owed step goes unbilled in the ledger. [`deferred_usage_test.go`](../../internal/gateway/deferred_usage_test.go) covers the passthrough, the translated reply, the ledger, the OTel span and the pricing tiers.
+## Cache a vendor doesn't count
+
+A plugin whose vendor counts no cache tokens says so with `usage.magpie_cache_unknown: true` in its Anthropic usage, and leaves the cache fields out. Kiro does this: it caches on its side (a repeated prompt costs about half the credits), but its replies carry credits and a context share, never tokens (opencode-kiro-auth 0.1.16, zeewell on X). The gateway reads the field in [`aUsage`](../../internal/gateway/anthropic.go) into `Usage.cacheUnknown`, ORed across a reply's usage events. [`routeUsage`](../../internal/gateway/trace.go) then sets `RouteUsage.CacheUnknown` on a try that counted no cache read or write. The Routing page's `promptOf` (`plugins/routing/client.js`) leaves such a try out of the hit rate, so the request shows none, not 0%. The field is never told to a client: `Usage.anthropic()` leaves it out, and a passthrough forwards the plugin's bytes as they are. The usage ledger doesn't carry it yet ([#3464](https://github.com/yetone/magpie/issues/3464)). [`cache_unknown_test.go`](../../internal/gateway/cache_unknown_test.go) covers the passthrough and translated replies, both whole and streamed.
+
## A plugin's daily check-in
A plugin can press its vendor's daily check-in (签到) itself: its `auth` hook gains `checkin(getAuth, provider)`, beside `usage`. The host lists the provider with `checkin: true` (`plugin.Provider.Checkin`) and answers `checkin({provider, account})` (`plugin.AccountCheckin`) by refreshing the account as `usage` does and calling the hook with the account's auth.
diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go
index a5d7e17cb..0bd150611 100644
--- a/internal/gateway/anthropic.go
+++ b/internal/gateway/anthropic.go
@@ -1299,6 +1299,11 @@ type aUsage struct {
// which Anthropic bills apart: 1.25× input for 5 minutes, 2× for an
// hour
CacheCreation *aCacheCreation `json:"cache_creation,omitempty"`
+ // CacheUnknown: a plugin's usage saying its vendor gave no cache
+ // counts (magpie_cache_unknown), so the zero above is not a miss:
+ // Kiro caches but tells only credits, never tokens (zeewell on X).
+ // It is read, never told: anthropic() leaves it false.
+ CacheUnknown bool `json:"magpie_cache_unknown,omitempty"`
}
type aCacheCreation struct {
@@ -1307,7 +1312,7 @@ type aCacheCreation struct {
}
func (u aUsage) usage() Usage {
- out := Usage{Input: u.InputTokens, Output: u.OutputTokens, CacheRead: u.CacheReadInputTokens, CacheWrite: u.CacheCreationInputTokens}
+ out := Usage{Input: u.InputTokens, Output: u.OutputTokens, CacheRead: u.CacheReadInputTokens, CacheWrite: u.CacheCreationInputTokens, cacheUnknown: u.CacheUnknown}
if c := u.CacheCreation; c != nil {
out.cacheCreationReported = true
out.cacheCreationHasCounts = c.Ephemeral5m+c.Ephemeral1h > 0
diff --git a/internal/gateway/cache_unknown_test.go b/internal/gateway/cache_unknown_test.go
new file mode 100644
index 000000000..6f5ef8f13
--- /dev/null
+++ b/internal/gateway/cache_unknown_test.go
@@ -0,0 +1,85 @@
+package gateway
+
+import (
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// The Kiro plugin's real replies (opencode-kiro-auth 0.1.16 against
+// Kiro, 10-24): Kiro caches but counts no tokens, cache included, so the
+// plugin says magpie_cache_unknown and the Routing page shows no hit rate
+// where it showed 0% (zeewell on X).
+const (
+ kiroStream = "event: message_start\n" +
+ `data: {"type":"message_start","message":{"id":"msg_6eb0d1cc14c9126db4218f61","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}` + "\n\n" +
+ "event: content_block_start\n" +
+ `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}` + "\n\n" +
+ "event: content_block_delta\n" +
+ `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"OK"}}` + "\n\n" +
+ "event: content_block_stop\n" +
+ `data: {"type":"content_block_stop","index":0}` + "\n\n" +
+ "event: message_delta\n" +
+ `data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"input_tokens":0,"output_tokens":19,"magpie_cache_unknown":true}}` + "\n\n" +
+ "event: message_stop\n" +
+ `data: {"type":"message_stop"}` + "\n\n"
+ kiroJSON = `{"id":"msg_e6ad400ac6ed0f3febe5125d","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[{"type":"text","text":"OK."}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":1,"magpie_cache_unknown":true}}`
+ // a vendor that counts its cache and read none of it: a real 0%
+ missJSON = `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"OK."}],"stop_reason":"end_turn","usage":{"input_tokens":1200,"output_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}`
+)
+
+func TestCacheUnknownReachesTheRoute(t *testing.T) {
+ messages := `{"model":"fake/m1","max_tokens":20,"messages":[{"role":"user","content":"Say just OK."}]}`
+ streamed := `{"model":"fake/m1","max_tokens":20,"stream":true,"messages":[{"role":"user","content":"Say just OK."}]}`
+ chat := `{"model":"fake/m1","messages":[{"role":"user","content":"Say just OK."}]}`
+ for _, c := range []struct {
+ name, ctype, reply, path, request string
+ unknown bool
+ }{
+ {"Claude Code, whole", "application/json", kiroJSON, "/v1/messages", messages, true},
+ {"Claude Code, streamed", "", kiroStream, "/v1/messages", streamed, true},
+ // a translated request is always streamed from the vendor
+ {"translated for a Chat client", "", kiroStream, "/v1/chat/completions", chat, true},
+ {"translated, streamed", "", kiroStream, "/v1/chat/completions", strings.Replace(chat, `"messages"`, `"stream":true,"messages"`, 1), true},
+ {"a counted miss stays 0%", "application/json", missJSON, "/v1/messages", messages, false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ setup(t, provider.Anthropic, &fake{ctype: c.ctype, reply: c.reply})
+ s := New()
+ rec := httptest.NewRecorder()
+ s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", c.path, strings.NewReader(c.request)))
+ if rec.Code != 200 {
+ t.Fatalf("gateway: %d %s", rec.Code, rec.Body)
+ }
+ r := lastRoute(s)
+ if len(r.Usage) != 1 {
+ t.Fatalf("route usage %+v", r.Usage)
+ }
+ if got := r.Usage[0].CacheUnknown; got != c.unknown {
+ t.Fatalf("cache unknown %v, want %v: %+v", got, c.unknown, r.Usage[0])
+ }
+ })
+ }
+}
+
+// a try whose vendor did count cache tokens is known, whatever another
+// part of the reply said
+func TestCacheCountedIsNotUnknown(t *testing.T) {
+ var u Usage
+ u.add(aUsage{OutputTokens: 1, CacheUnknown: true}.usage())
+ u.add(aUsage{InputTokens: 10, OutputTokens: 2, CacheReadInputTokens: 90}.usage())
+ if rs := routeUsage("p", "m", u); len(rs) != 1 || rs[0].CacheUnknown {
+ t.Fatalf("%+v", rs)
+ }
+}
+
+// what Claude Code is told is Anthropic's usage: magpie never adds the
+// field to a reply it writes itself
+func TestCacheUnknownNotTold(t *testing.T) {
+ u := aUsage{InputTokens: 5, OutputTokens: 1, CacheUnknown: true}.usage()
+ if u.anthropic().CacheUnknown {
+ t.Fatal("told")
+ }
+}
diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go
index 7359d837f..722818edf 100644
--- a/internal/gateway/ir.go
+++ b/internal/gateway/ir.go
@@ -365,6 +365,9 @@ type Usage struct {
// cacheCreationHasCounts describes the parsed update's own split.
// It is never accumulated from earlier usage.
cacheCreationHasCounts bool
+ // cacheUnknown: the reply said its vendor counts no cache tokens
+ // (a plugin's magpie_cache_unknown), so a CacheRead of 0 is not a miss
+ cacheUnknown bool
Reasoning int `json:"reasoning"`
// Served: the model the vendor's reply says answered, when it named
@@ -436,6 +439,7 @@ func (u *Usage) add(v Usage) {
u.CacheWrite1h = v.CacheWrite1h
}
u.cacheCreationReported = u.cacheCreationReported || v.cacheCreationReported
+ u.cacheUnknown = u.cacheUnknown || v.cacheUnknown
if v.Reasoning > 0 {
u.Reasoning = v.Reasoning
}
diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go
index cca8e69d0..2ab57eded 100644
--- a/internal/gateway/trace.go
+++ b/internal/gateway/trace.go
@@ -153,6 +153,9 @@ type RouteUsage struct {
CacheRead int `json:"cache_read,omitempty"`
CacheWrite int `json:"cache_write,omitempty"`
Reasoning int `json:"reasoning,omitempty"`
+ // CacheUnknown: the vendor counted no cache tokens, so the Routing
+ // page shows no hit rate rather than 0% (Kiro, zeewell on X)
+ CacheUnknown bool `json:"cache_unknown,omitempty"`
}
// PricingRecord lets the routing view reuse the ledger's effective prices.
@@ -886,5 +889,6 @@ func routeUsage(id, model string, u Usage) []RouteUsage {
return out
}
return append(out, RouteUsage{Provider: id, Model: model, Input: u.Input, Output: u.Output,
- CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.Reasoning})
+ CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.Reasoning,
+ CacheUnknown: u.cacheUnknown && u.CacheRead+u.CacheWrite == 0})
}
diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js
index 85f77b2b2..9aed852ee 100644
--- a/internal/gui/assets/plugins/routing/client.js
+++ b/internal/gui/assets/plugins/routing/client.js
@@ -370,7 +370,10 @@ function routingPage(part) {
// Input excludes both cache tiers. Include writes in the denominator,
// and every billable try, as the request's cost does. Older history
// without the tiers cannot tell a hit rate, even when it has tokens.
+ // A vendor that counts no cache tokens (cache_unknown: Kiro tells
+ // credits only) has no hit rate, not 0%.
for (const u of r.usage || []) {
+ if (u.cache_unknown) continue;
read += u.cache_read || 0;
prompt += (u.in || 0) + (u.cache_read || 0) + (u.cache_write || 0);
}
diff --git a/internal/gui/tests/routing-request-metrics.test.cjs b/internal/gui/tests/routing-request-metrics.test.cjs
index a382cbba4..09d05e099 100644
--- a/internal/gui/tests/routing-request-metrics.test.cjs
+++ b/internal/gui/tests/routing-request-metrics.test.cjs
@@ -39,6 +39,9 @@ const fixtures = [
req(2, [tier(1000, 3000, 1000)], { out: 0 }),
req(1, [tier(1000, 3000, 1000)], { tries: [{ id: seat.id, start: now.toISOString(), done: true, status: 200, fail: "other", ms: 11000, ttft: 7000 }] }),
req(0, undefined, { session: "unknown-metrics", tokens: 0, out: 0, ms: 0, ttft: 0, priced: false, cost: 0 }),
+ // Kiro caches but counts no cache tokens: its tier says so, and the row
+ // shows no hit rate, never 0% (zeewell on X)
+ req(-1, [{ ...tier(148000, 0, 0, 19), cache_unknown: true }], { session: "kiro-metrics", tokens: 148019, out: 19 }),
];
function serve(lang, feed) {
@@ -89,6 +92,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.match(await rows.nth(8).locator(".cache-hit").textContent(), /60%$/, "sum the billable prompt tiers across retries");
assert.match(await rows.nth(8).locator(".speed .v").textContent(), /^100 /, "retry wait and earlier output do not change decode speed");
assert.equal(await rows.nth(9).locator(".cache-hit").count(), 0, "a request still underway has no final rate");
+ assert.equal(await rows.nth(13).locator(".cache-hit").count(), 0, "a vendor that counts no cache tokens has no hit rate, not 0%");
assert.equal(await rows.nth(12).locator(".meta").isVisible(), false, "a row with no available metrics has no empty band");
assert.equal(await rows.locator(".rt-metric").filter({ hasText: "—" }).count(), 0, "unavailable metrics leave no dash placeholders");
assert.equal(await rows.nth(0).locator(".ttft .k").textContent(), lang === "zh" ? "首字耗时" : "First token");
@@ -112,6 +116,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const unknown = page.locator("button.rt-session").filter({ hasText: "unknown-metrics" });
assert.equal(await unknown.locator(".rt-metric").count(), 0, "a session with no measured cache or speed omits both");
assert.equal(await unknown.locator(".cost").isVisible(), false, "a session with unknown cost omits it");
+ assert.equal(await page.locator("button.rt-session").filter({ hasText: "kiro-metrics" }).locator(".cache-hit").count(), 0, "a session of uncounted cache has no hit rate");
assert.doesNotMatch(await unknown.locator(".summary").textContent(), /token|—/, "a session without token counts has no fake zero or dash");
assert.equal(await group.locator(".cache-hit .v").textContent(), "63%", "cache average is weighted by prompt tokens, not by request count");
assert.match(await group.locator(".speed .v").textContent(), /^133 /, "speed is output divided by summed decode windows, not the mean of individual speeds");