kiro 0.1.16: a reply with no token counts says its cache is unknown, not 0 (zeewell on X)

zeewell on X: every Kiro request in magpie's Routing page shows cache 0%
(Claude Code through group/wf-coding-*, claude-sonnet-5.5 and
claude-opus-5.5, 150-180k tokens, consecutive calls seconds apart).

Cause, from real requests (Google sign-in through kiro-cli, 2026-10-24):
Kiro caches, but reports no token counts at all. A
generateAssistantResponse reply ends with metadataEvent {stopReason},
contextUsageEvent {contextUsagePercentage} and meteringEvent {credits};
no tokenUsage. The same 9k-token prompt sent twice was billed 0.091
then 0.048 credits, the same with or without cachePoints and with a
fresh or a fixed conversationId. kiro-cli 2.32's own trace log
(KIRO_LOG_LEVEL=trace) shows its MetadataEvent with total_tokens,
uncached_input_tokens, cache_read_input_tokens and
cache_write_input_tokens all None, and kiro-cli sends no cachePoint.
So nothing the plugin sends or drops keeps Kiro from caching (#110's
reading that only cachePoints make it cache was wrong); the plugin said
cache_read_input_tokens 0 for a number Kiro never gave.

Now, with no tokenUsage, the reply's usage leaves both cache fields out
and says magpie_cache_unknown: true, which magpie reads as no hit rate
instead of 0%. A tokenUsage, if Kiro sends one, is told as before.
cache-points.test.mjs's comment is corrected; the marks stay.

Run: cache-unknown.test.mjs (the real reply's events, streamed and not)
fails on 0.1.15's index.mjs (1 fail) and passes; bun test in
packages/kiro 57 pass under a scratch HOME/TMPDIR; scripts/check.mjs
kiro ok. The patched loader's fetch against real Kiro (source "kiro",
claude-sonnet-4.5, twice): 200, message_delta usage
{"output_tokens":1,"magpie_cache_unknown":true}. Not tried: an IDE or
Builder ID sign-in, other models' replies.
This commit is contained in:
yetone
2026-10-24 17:03:48 +08:00
parent a41a8d3a57
commit 9f6c4e8861
4 changed files with 117 additions and 10 deletions
+5 -2
View File
@@ -4,8 +4,11 @@
// and as an entry of the tools (the CodeWhisperer streaming model's
// UserInputMessage.cachePoint, AssistantResponseMessage.cachePoint and
// Tool::CachePoint; Kiro CLI 2.27's model list tells
// supportsPromptCaching and maximumCacheCheckpointsPerRequest). The plugin
// dropped every cache_control, so Kiro was never asked to cache.
// supportsPromptCaching and maximumCacheCheckpointsPerRequest). Tried
// with a real account on 2026-10-24, Kiro caches a repeated prompt without
// them too (the second call billed about half the credits, marked or not,
// and kiro-cli 2.32 sends none); the marks stay as the caller's intent.
// Why magpie showed 0% is cache-unknown.test.mjs: Kiro reports no tokens.
import { expect, test } from "bun:test"
import { _internal } from "./index.mjs"
+95
View File
@@ -0,0 +1,95 @@
// Kiro caches but says nothing of it (X, zeewell: "kiro 代理的模型缓存每次都是 0%").
// A real reply to claude-sonnet-4.5 (2026-10-24, a 9k-token prompt sent
// twice) ends with these events and no others: no tokenUsage in the
// metadataEvent, so no input, output or cache counts at all, while the
// second call was billed 0.048 credits to the first's 0.091. kiro-cli
// 2.32's own trace log shows the same reply as MetadataEvent { total_tokens:
// None, uncached_input_tokens: None, …, cache_read_input_tokens: None }.
// The plugin said cache_read_input_tokens 0, and magpie showed "cache 0%"
// on every Kiro request; it now says the cache is unknown.
import { test, expect } from "bun:test"
import { _internal } from "./index.mjs"
const { events, reply } = _internal
// frame is one AWS event-stream message with string headers.
function frame(headers, payload) {
const enc = new TextEncoder()
const hs = []
for (const [k, v] of Object.entries(headers)) {
const name = enc.encode(k)
const val = enc.encode(v)
const h = new Uint8Array(1 + name.length + 1 + 2 + val.length)
h[0] = name.length
h.set(name, 1)
h[1 + name.length] = 7
new DataView(h.buffer).setUint16(2 + name.length, val.length)
h.set(val, 4 + name.length)
hs.push(h)
}
const hlen = hs.reduce((n, h) => n + h.length, 0)
const body = enc.encode(JSON.stringify(payload))
const total = 12 + hlen + body.length + 4
const out = new Uint8Array(total)
const v = new DataView(out.buffer)
v.setUint32(0, total)
v.setUint32(4, hlen)
let i = 12
for (const h of hs) {
out.set(h, i)
i += h.length
}
out.set(body, i)
return out
}
const stream = (...fs) =>
new ReadableStream({
start(c) {
for (const f of fs) c.enqueue(f)
c.close()
},
})
const ev = (type, payload) => frame({ ":message-type": "event", ":event-type": type }, payload)
// the events of the real reply, as Kiro sent them
const kiroReply = () =>
stream(
ev("assistantResponseEvent", { content: "OK" }),
ev("metadataEvent", { stopReason: "END_TURN" }),
ev("contextUsageEvent", { contextUsagePercentage: 11.032500267028809 }),
ev("meteringEvent", { unit: "credit", unitPlural: "credits", usage: 0.09107998018242124 }),
)
const ask = (body, streaming) => reply(events(body, "claude-sonnet-4.5", 0), "claude-sonnet-4.5", streaming)
async function finalUsage(res, streaming) {
if (!streaming) return (await res.json()).usage
let last
for (const line of (await res.text()).split("\n"))
if (line.startsWith("data: ")) {
const d = JSON.parse(line.slice(6))
if (d.type === "message_delta") last = d.usage
}
return last
}
test("a reply with no token counts says its cache is unknown, not 0", async () => {
for (const s of [false, true]) {
const u = await finalUsage(await ask(kiroReply(), s), s)
expect(u.magpie_cache_unknown).toBe(true)
expect(u).not.toHaveProperty("cache_read_input_tokens")
expect(u).not.toHaveProperty("cache_creation_input_tokens")
expect(u.output_tokens).toBeGreaterThan(0)
}
})
test("a reply whose metadataEvent counts tokens tells them, cache included", async () => {
for (const s of [false, true]) {
const body = stream(
ev("assistantResponseEvent", { content: "OK" }),
ev("metadataEvent", { stopReason: "END_TURN", tokenUsage: { uncachedInputTokens: 120, outputTokens: 3, cacheReadInputTokens: 9000, cacheWriteInputTokens: 0, totalTokens: 9123 } }),
)
const u = await finalUsage(await ask(body, s), s)
expect(u).toEqual({ input_tokens: 120, output_tokens: 3, cache_read_input_tokens: 9000, cache_creation_input_tokens: 0 })
}
})
+16 -7
View File
@@ -1097,7 +1097,12 @@ async function* events(body, model, budget) {
let tool = ""
let tools = 0
let stop = ""
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
// reported: Kiro sent a tokenUsage. It doesn't today: a reply has a
// contextUsageEvent and a meteringEvent (credits) and nothing more, and
// kiro-cli 2.32's own trace log shows its MetadataEvent with every token
// count None, while a repeated prompt is billed about half the credits,
// so Kiro does cache and doesn't say how much
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reported: false }
let pct = 0
let said = 0
let failed = ""
@@ -1147,6 +1152,7 @@ async function* events(body, model, budget) {
if (m.stopReason) stop = m.stopReason
const tu = m.tokenUsage
if (tu && typeof tu === "object") {
usage.reported = true
usage.input += tu.uncachedInputTokens || tu.inputTokens || 0
usage.output += tu.outputTokens || 0
usage.cacheRead += tu.cacheReadInputTokens || 0
@@ -1192,12 +1198,15 @@ function finished(content) {
return content
}
const anthropicUsage = (u) => ({
input_tokens: u.input,
output_tokens: u.output,
cache_read_input_tokens: u.cacheRead,
cache_creation_input_tokens: u.cacheWrite,
})
// anthropicUsage is the usage in Messages' words. With no tokenUsage from
// Kiro the input is reckoned from how full the context is, and what of it
// Kiro read from its cache is unknown, not 0: the cache fields are left
// out and magpie is told so (magpie_cache_unknown), so it shows no hit
// rate rather than 0%.
const anthropicUsage = (u) =>
u.reported
? { input_tokens: u.input, output_tokens: u.output, cache_read_input_tokens: u.cacheRead, cache_creation_input_tokens: u.cacheWrite }
: { input_tokens: u.input, output_tokens: u.output, magpie_cache_unknown: true }
// quotaWords are magpie's (internal/gateway/fallback.go): how a vendor says
// "out of quota" or "slow down".
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-kiro-auth",
"version": "0.1.15",
"version": "0.1.16",
"description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
"type": "module",
"main": "./index.mjs",