From 01eaa6dda4ac880bcae02c81aabe9d5ab6abae72 Mon Sep 17 00:00:00 2001 From: tungloong Date: Thu, 12 Nov 2026 04:30:07 +0800 Subject: [PATCH] agy-cli 0.1.20: each step's usage from agy's own store, and 1.5.1+ inputTokens read as uncached (#983) agy 1.5.1+ reports ACP `inputTokens` as uncached prompt tokens only; `promptUsage()` tells the exclusive shape from the inclusive one by `totalTokens`, so cache reads are no longer clipped and the learned cache ratio no longer pins to 1.0. Each HTTP step of a multi-step tool loop is settled from agy's own per-call rows in `conversations/.db` (`gen_metadata` on 1.5.1+, `steps` type 15 on 1.4.x-1.5.0) when they reconcile with ACP's total; same-generation tool continuations settle at 0, a cancelled or fallen-back turn stops trusting the store, and a clipped cold-start replay bounds its fallback estimate. The reader (`step-usage.mjs`) never opens a store read-write. Under Bun it opens with `SQLITE_OPEN_READONLY | SQLITE_OPEN_URI` (Bun's SQLite on Linux and Windows parses `file:` URIs only with that flag), finalizes statements and waits on no busy timeout. A checkpointed WAL store with no `-wal`/`-shm` is read through `?immutable=1` and gains no side files; if `-wal` appears during that read it is read again live. Store paths are resolved to absolute first, and Windows `\\?\` and UNC paths get their own `file:` form. On an uncheckpointed store the only file a reader touches is SQLite's `-shm` WAL index. Reviewed head 9054f47295d51d6f83f8585dd550312ebff8448a (base dba24067; merges cleanly onto main 7c44d027). What ran at that head, Bun 1.4.2 everywhere, fresh temp HOME (and USERPROFILE on Windows): - macOS (mote): `bun test packages/agy-cli` 14/14; step-usage 10/10, usage-settlement 33/33; `node --test test/step-usage.mjs` (Node 22.22) 10/10; `bun scripts/check.mjs` ok. - Linux (WSL Ubuntu 24.04): `bun test packages/agy-cli` 14/14; step-usage 10/10, usage-settlement 33/33; Node 22.23 10/10; check.mjs ok. - Windows 11: step-usage 10/10 (the loopback UNC share was reachable, so its branch ran), usage-settlement 33/33, Node 10/10, check.mjs ok. `bun test packages/agy-cli` 13/14: smoke's one red is "no call to the loaded tool reaches agy's validator in the old prompt", the known #973 (1 of 334 checks), not touched here. - Root `bun test` on mica, merged onto origin/main 7c44d027, under suite.lock: 8407 pass, 20 skip, 0 fail across 593 files (fresh temp HOME). Broken by hand (restored after each): - Linux: SQLITE_OPEN_URI dropped -> step-usage 3 red, usage-settlement 2 red; `path.resolve` dropped -> the URI/relative-path test red (Bun and Node); the "no -wal after a failed immutable read returns null" guard dropped -> the mid-read test red (Bun and Node). - macOS: the re-read after `-wal` appears removed, and the failed-immutable-read path returning null outright -> the mid-read test red under Bun and Node (at 262145f4; the code is unchanged since). - Windows: the `\\` branch of `immutableUri` disabled -> the URI/UNC test red. Not tried: a real agy session or account (fake agy and fixture stores only); Bun versions other than 1.4.2; a remote (non-loopback) UNC share. Co-authored-by: tungloong <19512489+tungloong@users.noreply.github.com> --- packages/agy-cli/agy-cli.test.mjs | 1 + packages/agy-cli/index.mjs | 230 ++++++- packages/agy-cli/package.json | 3 +- packages/agy-cli/step-usage.mjs | 344 ++++++++++ packages/agy-cli/test/smoke.mjs | 12 +- packages/agy-cli/test/step-usage.mjs | 400 ++++++++++++ packages/agy-cli/test/testkit.mjs | 3 + packages/agy-cli/test/usage-settlement.mjs | 727 ++++++++++++++++++++- 8 files changed, 1694 insertions(+), 26 deletions(-) create mode 100644 packages/agy-cli/step-usage.mjs create mode 100644 packages/agy-cli/test/step-usage.mjs diff --git a/packages/agy-cli/agy-cli.test.mjs b/packages/agy-cli/agy-cli.test.mjs index 1a8f6e8..5628b28 100644 --- a/packages/agy-cli/agy-cli.test.mjs +++ b/packages/agy-cli/agy-cli.test.mjs @@ -20,6 +20,7 @@ for (const [name, mocks] of [ ["prefill.mjs", false], ["usage.mjs", true], ["catalog.mjs", false], + ["step-usage.mjs", false], ["usage-settlement.mjs", false], ["repeat-batch.mjs", false], ["conversation-key.mjs", false], diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index a21ffdf..abc6fae 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -12,6 +12,7 @@ import { sanitizePatternFields } from "./re2-pattern.mjs" import { startLogin } from "./login.mjs" import { ensureGeminiArrayItems } from "./array-items.mjs" import { cloak, hint, turnsAway } from "./cloak.mjs" +import { modelUsageCursor, modelUsageAfter, sessionDbPath } from "./step-usage.mjs" const PROVIDER_ID = "agy-cli" // Client tools reach the session through a private `nc` placed first on agy's @@ -92,6 +93,10 @@ const ACP_LINE_LIMIT = 64 * 1024 * 1024 const LOG_TAIL_BYTES = 256 * 1024 const NPM_ANTHROPIC = "@ai-sdk/anthropic" const PING_INTERVAL_MS = 15_000 +// agy commits a model call to its conversation store just after the call ends. +const STEP_USAGE_WAIT_MS = 1_000 +const STEP_USAGE_SAME_GEN_WAIT_MS = 75 +const STEP_USAGE_POLL_MS = 25 // agy reports an upstream failure as an ordinary message chunk followed by end_turn. const AGENT_ERROR_MARKER = "\n⚠ Agent execution terminated due to error.\n" const AGENT_ERROR_CORE = AGENT_ERROR_MARKER.trim() @@ -845,13 +850,15 @@ class Turn { this.rawAcpUsages = [] this.rawUsage = null this.accountedPrompts = new Set() + this.stepUsageReconciled = false + this.sawGenerationOutput = false let settle this.settled = new Promise((resolve) => { settle = resolve }) this.settle = settle } registerResponse(body) { - const estimate = estimateInputTokens(body) + const estimate = this.proc.estimatePromptTokens(body) const pending = this.pendingPromptStep const step = { body, @@ -884,7 +891,7 @@ class Turn { const results = extractToolResults(body) const alreadyInHistory = lateCalls?.length && lateCalls.every((call) => results.some((block) => block.tool_use_id === call.id)) - const estimate = estimateInputTokens({ + const estimate = this.proc.estimatePromptTokens({ ...body, messages: [ ...history, @@ -916,8 +923,8 @@ class Turn { // no usage of their own until it ends, so they take this ratio. Only a // final, uncancelled response used to teach it, so a fresh or cancelled // conversation reported every tool step as a full cache miss. - const input = tokenCount(usage?.inputTokens) - if (input > 0) this.proc.lastCacheRatio = Math.min(1, Math.min(input, tokenCount(usage.cachedReadTokens)) / input) + const parts = promptUsage(usage) + if (parts.promptInput > 0) this.proc.lastCacheRatio = Math.min(1, parts.read / parts.promptInput) } return this.rawUsage } @@ -1099,6 +1106,8 @@ class Proc { // Unset until recordPromptUsage or a final calibrated response teaches // it, including a recorded 0. Distinct from a calibrated miss. this.lastCacheRatio = undefined + this.omittedHistoryTokens = 0 + this.stepUsageTrusted = true this.configOptions = [] this.configMethodUnsupported = false this.currentSelectionKey = null @@ -1392,13 +1401,23 @@ class Proc { if (turn.cancelRequested) return if (update.sessionUpdate === "agent_message_chunk") { const text = update.content?.type === "text" ? update.content.text : "" - if (text) turn.pushText(text) + if (text) { + turn.sawGenerationOutput = true + turn.pushText(text) + } } else if (update.sessionUpdate === "agent_thought_chunk") { const text = update.content?.type === "text" ? update.content.text : "" - if (text) turn.push({ type: "thinking", text }) + if (text) { + turn.sawGenerationOutput = true + turn.push({ type: "thinking", text }) + } } } + estimatePromptTokens(body) { + return Math.max(1, estimateInputTokens(body) - this.omittedHistoryTokens) + } + startTurn(content, messages, model, selection) { if (this.dead) throw this.deadError if (this.retiring) throw new BusyError("agy bridge: this conversation's process is being retired") @@ -1491,6 +1510,11 @@ class Proc { try { turn.arm() if (model) await this.#setModel(model, selection) + const stepUsageEnabled = this.stepUsageTrusted && + !/^(?:0|false|off|no|disabled)$/i.test(process.env.AGY_BRIDGE_STEP_USAGE || "") + turn.stepsFile = stepUsageEnabled ? sessionDbPath(this.sessionId) : null + turn.stepCursor = turn.stepsFile ? modelUsageCursor(turn.stepsFile) : null + if (turn.stepsFile && turn.stepCursor === null) this.stepUsageTrusted = false // Content a cancelled turn never delivered still belongs to the session. let promptParts = mergePromptParts(this.unsentPrompt, toPromptParts(content)) this.unsentPrompt = null @@ -1768,6 +1792,9 @@ class Proc { finalizeTurn(turn) { if (turn.finalized) return turn.finalized = true + if (turn.stepsFile && turn.promptCount > 0 && !turn.stepUsageReconciled) { + this.stepUsageTrusted = false + } turn.detach() clearTimeout(turn.timer) for (const waiter of turn.waiters.splice(0)) { @@ -4178,18 +4205,45 @@ function tokenCount(value) { } // ACP usage accumulates the internal model calls of one session/prompt. -// Gemini includes read-cache input and excludes thought output in its totals. +// agy 1.5.1+ reports inputTokens as the uncached prompt tokens; cached reads and +// writes are separate and totalTokens includes all of them (measured: +// 2133 input + 4899 cache read + 6 output = 7038 total). Some earlier builds +// folded cached reads into inputTokens. totalTokens tells the two shapes apart, +// so both report the same uncached input and cache numbers. +function promptUsage(usage) { + if (!usage || typeof usage !== "object") usage = {} + const rawInput = tokenCount(usage.inputTokens) + const cacheRead = tokenCount(usage.cachedReadTokens) + const cacheWrite = tokenCount(usage.cachedWriteTokens) + const output = tokenCount(usage.outputTokens) + const thinking = tokenCount(usage.thoughtTokens) + const total = tokenCount(usage.totalTokens) + const inclusive = total > 0 + ? Math.abs(total - (rawInput + output + thinking)) < + Math.abs(total - (rawInput + cacheRead + cacheWrite + output + thinking)) + : cacheRead <= rawInput + // Prompt input excludes cache creation, which is reported separately. + const promptInput = inclusive ? rawInput : rawInput + cacheRead + const read = Math.min(cacheRead, promptInput) + return { + input: promptInput - read, + read, + write: cacheWrite, + output: output + thinking, + thinking, + promptInput, + } +} + function translateUsage(usage) { if (!usage || typeof usage !== "object") return null - const input = tokenCount(usage.inputTokens) - const cacheRead = Math.min(input, tokenCount(usage.cachedReadTokens)) - const thinking = tokenCount(usage.thoughtTokens) + const parts = promptUsage(usage) return { - input_tokens: input - cacheRead, - output_tokens: tokenCount(tokenCount(usage.outputTokens) + thinking), - cache_read_input_tokens: cacheRead, - cache_creation_input_tokens: tokenCount(usage.cachedWriteTokens), - ...(thinking > 0 ? { output_tokens_details: { thinking_tokens: thinking } } : {}), + input_tokens: parts.input, + output_tokens: parts.output, + cache_read_input_tokens: parts.read, + cache_creation_input_tokens: parts.write, + ...(parts.thinking > 0 ? { output_tokens_details: { thinking_tokens: parts.thinking } } : {}), } } @@ -4236,13 +4290,13 @@ function responseUsage(proc, turn, step, content, result) { if (final) { const sum = turn.stepInputEstimates.reduce((total, value) => total + value, 0) const weight = estimate / Math.max(estimate, sum) - const totalInput = tokenCount(result?.usage?.inputTokens) - const totalWrite = tokenCount(result?.usage?.cachedWriteTokens) - const read = Math.min(totalInput, tokenCount(result?.usage?.cachedReadTokens)) + const parts = promptUsage(result?.usage || {}) + const totalInput = parts.promptInput + const totalWrite = parts.write if (totalInput + totalWrite > 0) { input = tokenCount(totalInput * weight) write = tokenCount(totalWrite * weight) - cacheRatio = totalInput > 0 ? read / totalInput : 0 + cacheRatio = totalInput > 0 ? parts.read / totalInput : 0 } // The bound applies to the full window, including cache creation. Scale // both portions together before rounding, then split the exact integer. @@ -4292,6 +4346,111 @@ function responseUsage(proc, turn, step, content, result) { } } +// Usage of one HTTP response from agy's own per-call records (step-usage.mjs): +// the model calls since the last settled response. Its prompt buckets are the +// latest call's, which is how full the context is; output adds up all of them. +// Returns null, keeping the estimate, when the store has no new completed call +// in time or, at the end of a prompt, its calls don't yet add up to ACP's total. +async function measuredUsage(turn, step, content, result) { + if (step.settled || !turn.stepsFile || turn.stepCursor == null) return null + const final = result !== undefined + const acp = final && result?.usage ? promptUsage(result.usage) : null + const measured = turn.measured || { prompt: 0 } + const expected = acp ? acp.promptInput + acp.write : null + const promptOf = (steps) => steps.reduce((sum, item) => sum + item.input + item.read + item.write, measured.prompt) + const complete = (steps) => { + if (!steps?.length) return false + if (expected === null) return true + return promptOf(steps) >= expected + } + // agy has written the store by its first tool call; none means none kept here. + if (!fs.existsSync(turn.stepsFile)) return null + // When an earlier response in this turn already measured a generation and no + // new message/thought chunk arrived, agy may still be draining sequential MCP + // tool calls from that same generation without invoking the model again. Wait + // briefly unless a new row is pending; stop immediately if the store fails/locks. + const sawOutput = turn.sawGenerationOutput || + (Array.isArray(content) && content.some((block) => block?.type === "text" || block?.type === "thinking")) + const canShareGeneration = !final && !sawOutput && measured.prompt > 0 && turn.stepCursor.source !== null + const start = performance.now() + let batch = modelUsageAfter(turn.stepsFile, turn.stepCursor) + for (;;) { + if (!batch || complete(batch.steps)) break + const waitMs = canShareGeneration && !batch.pending + ? STEP_USAGE_SAME_GEN_WAIT_MS + : STEP_USAGE_WAIT_MS + if (performance.now() - start >= waitMs) break + await new Promise((resolve) => setTimeout(resolve, STEP_USAGE_POLL_MS)) + batch = modelUsageAfter(turn.stepsFile, turn.stepCursor) + } + if (!batch) return null + const steps = batch.steps + if (!complete(steps)) { + if (!batch.pending && !steps?.length && ( + canShareGeneration || + (final && expected !== null && measured.prompt > 0 && + measured.prompt >= expected && + measured.prompt <= expected + Math.max(16, Math.ceil(expected * 0.01))) + )) { + if (final) turn.stepUsageReconciled = true + step.usageKind = "agy_same_generation" + step.modelCalls = 0 + return { + input_tokens: 0, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, + output_tokens: 0, + } + } + return null + } + // agy's per-call prompts sum to ACP's total exactly. A large over-count means + // the store's layout or contents no longer match what ACP reported, so don't + // hand the client numbers we cannot reconcile. + const prompt = promptOf(steps) + if (expected !== null && prompt > expected + Math.max(16, Math.ceil(expected * 0.01))) return null + const last = steps.at(-1) + const output = steps.reduce((sum, item) => sum + item.output + item.thinking, 0) + const thinking = steps.reduce((sum, item) => sum + item.thinking, 0) + turn.stepCursor = { source: batch.source, idx: last.idx } + turn.measured = { prompt } + if (final) turn.stepUsageReconciled = true + step.usageKind = "agy_model_call" + step.modelCalls = steps.length + logBridgeEvent(turn.proc, turn, "model_usage", batch.source, {}, { + model: turn.proc.currentModel, effort: turn.proc.currentEffort, + model_calls: steps.length, + input_tokens: last.input, cache_read_tokens: last.read, cache_write_tokens: last.write, + output_tokens: output, thinking_tokens: thinking, + context_tokens: last.input + last.read + last.write, + local_context_estimate: last.context, + }) + return { + input_tokens: last.input, + cache_read_input_tokens: last.read, + cache_creation_input_tokens: last.write, + output_tokens: output, + ...(thinking > 0 ? { output_tokens_details: { thinking_tokens: thinking } } : {}), + } +} + +async function settleUsage(proc, turn, step, content, result) { + if (step.settled) return step.usage + try { + const measured = result?.stopReason === "cancelled" ? null : await measuredUsage(turn, step, content, result) + if (measured) return measured + // Any unconsumed generation from this turn (cancelled, timed out, locked, or + // an empty `.pb` / unreadable store) could land after the next turn reads + // MAX(idx) or keep costing 1s per turn. Stop trusting the store on this + // process and fall back to bounded window estimates. + turn.stepCursor = null + if (turn.stepsFile) proc.stepUsageTrusted = false + return responseUsage(proc, turn, step, content, result) + } finally { + turn.sawGenerationOutput = false + } +} + // agy's ACP stream carries thought summaries without the model's own signature. // Clients keep and replay a thinking block only with a signature, so the bridge // issues one: an HMAC over the session and text under a per-process key. It is @@ -4470,7 +4629,9 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist } if (performance.now() >= batchDeadline) break } - stopMessage("tool_use", responseUsage(proc, turn, step, responseContent)) + const usage = await settleUsage(proc, turn, step, responseContent) + if (finished) return + stopMessage("tool_use", usage, false, step.usageKind === "agy_model_call") proc.recordAssistantResponse(turn, responseContent) detach() controller.close() @@ -4479,7 +4640,8 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist if (event.type === "result") { closeBlock() turn.rawUsage = event.result.usage ?? turn.rawUsage - const usage = responseUsage(proc, turn, step, responseContent, event.result) + const usage = await settleUsage(proc, turn, step, responseContent, event.result) + if (finished) return stopMessage(STOP_REASONS[event.result.stopReason] || "end_turn", usage, true, event.result.stopReason !== "cancelled") proc.recordAssistantResponse(turn, responseContent) proc.finalizeTurn(turn) @@ -4577,6 +4739,16 @@ function estimateInputTokens(body) { return Math.max(1, total + images * 1600) } +function estimatePromptPartsTokens(parts) { + let total = 0 + let images = 0 + for (const part of parts || []) { + if (part?.type === "text" && part.text) total += estimateTextTokens(part.text) + else if (part?.type === "image") images++ + } + return total + images * 1600 +} + async function jsonResponseFromStream(stream, fallbackModel, fallbackId) { const reader = stream.getReader() const decoder = new TextDecoder() @@ -4691,7 +4863,8 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a const reminder = outputFormatReminder(body) const flattened = proc.pendingFlattenedTurn proc.pendingFlattenedTurn = null - const baseParts = proc.hasSentFirstTurn + const isFirstTurn = !proc.hasSentFirstTurn + const baseParts = !isFirstTurn ? renderContinuedTurnParts(flattened ? [flattened, ...body.messages.slice(1)] : withoutAnswered(body.messages.slice(history.length), answered)) @@ -4699,12 +4872,23 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a reminder.length ? promptTextBytes(reminder) + 2 : 0) const contentParts = mergePromptParts(baseParts, reminder) if (promptHasImage(contentParts) && !proc.supportsImages) { - if (!proc.hasSentFirstTurn) { + if (isFirstTurn) { dropFromPool(proc) await proc.stop().catch(() => {}) } throw new UnsupportedContent("image input with this agy ACP server; update to an image-capable agy version") } + if (isFirstTurn) { + const rawEstimate = estimateInputTokens(body) + const sessionOverhead = (proc.instructionsInSession && body.system + ? estimateInputTokens({ system: body.system, messages: [] }) + : 0) + (Array.isArray(body.tools) && body.tools.length ? estimateTextTokens(JSON.stringify(body.tools)) : 0) + const sentEstimate = Math.max(1, sessionOverhead + estimatePromptPartsTokens(contentParts)) + const clipThreshold = Math.min(HISTORY_BLOCK_CLIP_BYTES, maxInitialPromptBytes()) + const promptClipped = utf8Bytes(JSON.stringify(body.messages)) > clipThreshold && + rawEstimate > sentEstimate + 64 + proc.omittedHistoryTokens = promptClipped ? rawEstimate - sentEstimate : 0 + } return proc.startTurn(contentParts, body.messages, model, selection) } diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 55cf644..1edc524 100644 --- a/packages/agy-cli/package.json +++ b/packages/agy-cli/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.19", + "version": "0.1.20", "description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI", "type": "module", "main": "./opencode.mjs", @@ -14,6 +14,7 @@ "platform.mjs", "login.mjs", "mcp-server.mjs", + "step-usage.mjs", "usage.mjs", "README.md", "README.en.md", diff --git a/packages/agy-cli/step-usage.mjs b/packages/agy-cli/step-usage.mjs new file mode 100644 index 0000000..ee099ab --- /dev/null +++ b/packages/agy-cli/step-usage.mjs @@ -0,0 +1,344 @@ +// Per-model-call usage from agy's local conversation store. +// +// ACP reports usage once, accumulated over a whole session/prompt. Prefer +// `gen_metadata`, written when generation ends, before client tools return. +// Older stores record each completed model call in table `steps`, with +// step_type 15 and status 3 (done), the counts in Protobuf field 9 of +// `metadata` (2 uncached input, 3 output, 4 cache write, 5 cache read, +// 9 thinking). Summed over a prompt they equal the ACP total exactly. +// Protobuf layout first decoded by lili-luo/dsh-plugin-bundle +// (dsh-llm-antigravity-acp, MIT); SQLite reader adapted from +// DylanLIiii/opencode-antigravity-bridge (MIT). Any failure here returns null +// and the caller keeps its estimate. +import { createRequire } from "node:module" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { pathToFileURL } from "node:url" + +const MODEL_STEP = 15 +const STEP_DONE = 3 +const require = createRequire(import.meta.url) + +let opener + +// Prefer bun:sqlite under Bun (Bun's node:sqlite keeps an unfinalized statement's +// file handle open until GC, locking the store on Windows); fall back to +// node:sqlite on Node >= 22.5. Never open a read-write handle or wait on locks. +function loadOpener() { + if (opener !== undefined) return opener + opener = null + try { + const { Database, constants } = require("bun:sqlite") + if (typeof Database === "function") { + // Bun's bundled SQLite on Linux/Windows disables URI filenames unless SQLITE_OPEN_URI is passed. + const flags = constants.SQLITE_OPEN_READONLY | constants.SQLITE_OPEN_URI + opener = (target) => { + const db = new Database(target, flags) + return { + all: (sql, ...args) => { + const stmt = db.prepare(sql) + try { + return stmt.all(...args) + } finally { + stmt.finalize() + } + }, + close: () => db.close(), + } + } + return opener + } + } catch {} + try { + const { DatabaseSync } = require("node:sqlite") + if (typeof DatabaseSync === "function") { + // Only plain Node reaches this fallback; Node's DatabaseSync.close() finalizes prepared statements. + opener = (target) => { + const db = new DatabaseSync(target, { readOnly: true, timeout: 0 }) + return { + all: (sql, ...args) => db.prepare(sql).all(...args), + close: () => db.close(), + } + } + return opener + } + } catch {} + return opener +} + +export function conversationsDir(env = process.env) { + return env.AGY_BRIDGE_CONVERSATIONS_DIR || + path.join(os.homedir(), ".gemini", "antigravity-cli", "conversations") +} + +export function sessionDbPath(sessionId, env = process.env) { + if (!sessionId || !/^[A-Za-z0-9._-]+$/.test(String(sessionId))) return null + return path.join(conversationsDir(env), `${sessionId}.db`) +} + +function varint(buf, at) { + let value = 0 + let scale = 1 + for (let i = 0; i < 10; i++) { + const byte = buf[at + i] + if (byte === undefined) return null + value += (byte & 0x7f) * scale + if ((byte & 0x80) === 0) return { value, next: at + i + 1 } + scale *= 128 + } + return null +} + +// Calls fn(field, wire, value | bytes) for each field; false on malformed input. +function walk(buf, fn) { + let at = 0 + while (at < buf.length) { + const tag = varint(buf, at) + if (!tag || tag.value < 8) return false + at = tag.next + const field = Math.floor(tag.value / 8) + const wire = tag.value % 8 + if (wire === 0) { + const item = varint(buf, at) + if (!item) return false + at = item.next + fn(field, wire, item.value) + } else if (wire === 2) { + const len = varint(buf, at) + if (!len || len.next + len.value > buf.length) return false + fn(field, wire, buf.subarray(len.next, len.next + len.value)) + at = len.next + len.value + } else if (wire === 1 || wire === 5) { + at += wire === 1 ? 8 : 4 + if (at > buf.length) return false + } else { + return false + } + } + return true +} + +const count = (value) => Number.isSafeInteger(value) && value > 0 ? value : 0 + +function decodeUsage(buf) { + const usage = { input: 0, output: 0, write: 0, read: 0, thinking: 0 } + const ok = walk(buf, (field, wire, n) => { + if (wire !== 0) return + if (field === 2) usage.input = count(n) + else if (field === 3) usage.output = count(n) + else if (field === 4) usage.write = count(n) + else if (field === 5) usage.read = count(n) + else if (field === 9) usage.thinking = count(n) + }) + return ok ? usage : null +} + +export function decodeStepUsage(metadata) { + const buf = metadata instanceof Uint8Array ? metadata + : ArrayBuffer.isView(metadata) ? new Uint8Array(metadata.buffer, metadata.byteOffset, metadata.byteLength) + : null + if (!buf) return null + let stats = null + const ok = walk(buf, (field, wire, value) => { + if (field !== 9 || wire !== 2) return + stats = decodeUsage(value) + }) + return ok ? stats : null +} + +// gen_metadata.data contains the same usage message at field 1 -> 4. +// Its pre-send local context estimate is separate, at 1 -> 9 -> 10 -> 1. +// A context estimate alone is not a completed, billed model call. +export function decodeGenerationUsage(data) { + const buf = data instanceof Uint8Array ? data + : ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) + : null + if (!buf) return null + let stats = null + let context = null + let valid = true + const ok = walk(buf, (field, wire, chat) => { + if (field !== 1 || wire !== 2) return + valid = walk(chat, (sub, subWire, value) => { + if (subWire !== 2) return + if (sub === 4) { + stats = decodeUsage(value) + if (!stats) valid = false + } else if (sub === 9) { + if (!walk(value, (key, kind, start) => { + if (key !== 10 || kind !== 2) return + if (!walk(start, (k, w, n) => { + if (k === 1 && w === 0) context = count(n) + })) valid = false + })) valid = false + } + }) && valid + }) + return ok && valid && stats ? { ...stats, ...(context !== null ? { context } : {}) } : null +} + +function runReadOnly(open, target, fn) { + let db + try { + db = open(target) + return fn(db) + } finally { + try { db?.close() } catch {} + } +} + +function tableQuery(db, sql, ...args) { + try { + return db.all(sql, ...args) + } catch (error) { + if (/no such table|no such column/i.test(String(error?.message || ""))) return null + throw error + } +} + +function isCheckpointedWal(file) { + if (fs.existsSync(`${file}-wal`) || fs.existsSync(`${file}-shm`) || fs.existsSync(`${file}-journal`)) return false + let fd + try { + fd = fs.openSync(file, "r") + const header = new Uint8Array(20) + if (fs.readSync(fd, header, 0, 20, 0) < 20) return false + return header[18] === 2 && header[19] === 2 + } catch { + return false + } finally { + if (fd !== undefined) { + try { fs.closeSync(fd) } catch {} + } + } +} + +function resolveStorePath(file) { + if (typeof file !== "string" || !file || file.includes("\0")) return null + return path.resolve(file) +} + +// SQLite rejects non-localhost URI authorities (`file://server/share/...`) unless +// compiled with SQLITE_ALLOW_URI_AUTHORITY, strips `localhost` from `\\localhost\...`, +// and pathToFileURL rejects `\\?\...` extended paths. Prefixing Windows `\\...` paths +// directly after `file:` (with `%`, `?`, `#`, space percent-encoded) avoids any +// `//authority` segment so sqlite3ParseUri hands the exact `\\...` path to winOpen. +function immutableUri(resolved) { + if (process.platform === "win32" && resolved.startsWith("\\\\")) { + return `file:${resolved.replace(/[%?# ]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`)}?immutable=1` + } + return `${pathToFileURL(resolved).href}?immutable=1` +} + +// When a WAL-flagged store (header bytes 18..19 = 2, 2) has neither -wal nor +// -shm on disk, no writer holds it open, yet SQLITE_OPEN_READONLY fails with +// SQLITE_CANTOPEN under Apple's libsqlite3 on macOS and creates -wal/-shm +// sidecars under upstream SQLite. Opening with ?immutable=1 keeps that closed +// WAL read strictly side-effect-free; if -wal appears concurrently, re-read +// once against the resolved live file path (never a relative `file:...` string). +function withStore(file, fn) { + const resolved = resolveStorePath(file) + if (!resolved || !fs.existsSync(resolved)) return null + const open = loadOpener() + if (!open) return null + if (isCheckpointedWal(resolved)) { + try { + const result = runReadOnly(open, immutableUri(resolved), fn) + if (!fs.existsSync(`${resolved}-wal`)) return result + } catch { + if (!fs.existsSync(`${resolved}-wal`)) return null + } + } + try { + return runReadOnly(open, resolved, fn) + } catch { + return null + } +} + +function maxCompletedStep(db) { + const rows = tableQuery(db, + `SELECT COALESCE(MAX(idx), -1) AS idx FROM steps WHERE step_type = ${MODEL_STEP} AND status = ${STEP_DONE}`) + const idx = Number(rows?.[0]?.idx) + return Number.isSafeInteger(idx) ? idx : null +} + +function stepsAfter(db, afterIdx) { + const rows = tableQuery(db, + `SELECT idx, metadata FROM steps WHERE step_type = ${MODEL_STEP} AND status = ${STEP_DONE} AND idx > ? ORDER BY idx`, + afterIdx) + if (!rows) return null + const steps = [] + for (const row of rows) { + const idx = Number(row.idx) + const usage = decodeStepUsage(row.metadata) + if (!Number.isSafeInteger(idx) || !usage) continue + steps.push({ idx, ...usage }) + } + return steps +} + +// Highest completed model-call index, -1 for an empty or missing store, null +// when the store exists but cannot be read. +export function lastModelStep(file) { + const resolved = resolveStorePath(file) + if (!resolved) return null + if (!fs.existsSync(resolved)) return -1 + return withStore(resolved, (db) => maxCompletedStep(db)) +} + +// Completed model calls after `afterIdx`, oldest first: [{ idx, input, output, write, read, thinking }]. +export function modelStepsAfter(file, afterIdx) { + return withStore(file, (db) => stepsAfter(db, afterIdx)) +} + +// Pin a turn to one table. Reading both tables for a turn would bill the same +// generation twice. A new store is discovered after its first generation. +export function modelUsageCursor(file) { + const resolved = resolveStorePath(file) + if (!resolved) return null + if (!fs.existsSync(resolved)) return { source: null, idx: -1, generationIdx: -1 } + return withStore(resolved, (db) => { + const genRows = tableQuery(db, "SELECT COALESCE(MAX(idx), -1) AS idx FROM gen_metadata") + const generationIdx = Number(genRows?.[0]?.idx) + const step = maxCompletedStep(db) + if (Number.isSafeInteger(generationIdx)) { + return step === null ? { source: "gen_metadata", idx: generationIdx } + : { source: null, idx: step, generationIdx } + } + return step === null ? null : { source: "steps", idx: step } + }) +} + +export function modelUsageAfter(file, cursor) { + if (!cursor) return null + return withStore(file, (db) => { + if (cursor.source !== "steps") { + const after = cursor.source === "gen_metadata" ? cursor.idx : cursor.generationIdx + const rows = tableQuery(db, "SELECT idx, data FROM gen_metadata WHERE idx > ? ORDER BY idx", after) + if (rows) { + const steps = [] + let pending = false + for (const row of rows) { + const idx = Number(row.idx) + const usage = decodeGenerationUsage(row.data) + if (!Number.isSafeInteger(idx)) return null + // Failed generations and pre-send estimates carry no billing counters. + if (!usage || !(usage.input + usage.read + usage.write + usage.output + usage.thinking)) { + pending = true + continue + } + pending = false + steps.push({ idx, ...usage }) + } + if (steps.length || pending || cursor.source === "gen_metadata") { + return { source: "gen_metadata", steps, ...(pending ? { pending: true } : {}) } + } + } + if (cursor.source === "gen_metadata") return null + } + const steps = stepsAfter(db, cursor.idx) + return steps === null ? null : { source: "steps", steps } + }) +} diff --git a/packages/agy-cli/test/smoke.mjs b/packages/agy-cli/test/smoke.mjs index 7362085..8066162 100644 --- a/packages/agy-cli/test/smoke.mjs +++ b/packages/agy-cli/test/smoke.mjs @@ -178,10 +178,20 @@ async function invoke(name, args) { const textOf = result => (result.content || []).map(part => part.text || "").join("") function finish(reply, extra = {}) { + const cached = extra.cached || 0 + const thought = extra.thought || 0 + const input = extra.input ?? 10 log({ type: "result", convId: session.id, prompt: session.prompts, response: reply }) return { stopReason: "end_turn", - usage: { inputTokens: extra.input ?? 10 + (extra.cached || 0), outputTokens: reply.length, cachedReadTokens: extra.cached || 0, cachedWriteTokens: 0, thoughtTokens: extra.thought || 0, totalTokens: 10 + reply.length }, + usage: { + inputTokens: extra.exclusive ? input : input + cached, + outputTokens: reply.length, + cachedReadTokens: cached, + cachedWriteTokens: 0, + thoughtTokens: thought, + totalTokens: input + cached + reply.length + thought, + }, } } diff --git a/packages/agy-cli/test/step-usage.mjs b/packages/agy-cli/test/step-usage.mjs new file mode 100644 index 0000000..cad3ffb --- /dev/null +++ b/packages/agy-cli/test/step-usage.mjs @@ -0,0 +1,400 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { decodeStepUsage, decodeGenerationUsage, lastModelStep, modelStepsAfter, modelUsageCursor, modelUsageAfter, sessionDbPath } from "../step-usage.mjs" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { createRequire } from "node:module" + +const varint = (n) => { const out = []; while (n > 127) { out.push((n & 127) | 128); n = Math.floor(n / 128) } out.push(n); return out } +const usageStats = ({ input, output, write = 0, read, thinking }) => [0x08, ...varint(1418), 0x10, ...varint(input), 0x18, ...varint(output), + ...(write ? [0x20, ...varint(write)] : []), ...(read ? [0x28, ...varint(read)] : []), + 0x30, 24, 0x48, ...varint(thinking), 0x5a, 2, 0x41, 0x42] +const usageBlob = (usage) => { + const sub = usageStats(usage) + // Other metadata fields around field 9, as agy writes them. + return new Uint8Array([0x0a, 2, 0x08, 1, 0x18, 2, 0x4a, ...varint(sub.length), ...sub, 0x58, ...varint(1418)]) +} +const field = (n, bytes) => [n * 8 + 2, ...varint(bytes.length), ...bytes] +const generationBlob = (usage, context = 8100) => { + const stats = usageStats(usage) + return new Uint8Array(field(1, [ + ...field(4, stats), ...field(9, field(10, [8, ...varint(context)])), + ])) +} + +test("decodes the usage agy records for one model call", () => { + // Counts from a real agy 1.5.3 session: second call of a tool turn. + assert.deepEqual(decodeStepUsage(usageBlob({ input: 2205, output: 40, read: 4907, thinking: 7 })), + { input: 2205, output: 40, write: 0, read: 4907, thinking: 7 }) + assert.equal(decodeStepUsage(new Uint8Array([0x18, 2])), null) + assert.equal(decodeStepUsage(new Uint8Array([0x4a, 9, 1])), null) + assert.equal(decodeStepUsage("not bytes"), null) +}) + +test("a missing or unreadable store gives no measurement", () => { + const missing = path.join(os.tmpdir(), "agy-nonexistent-dir-983", "agy.db") + assert.equal(lastModelStep(missing), -1) + assert.equal(modelStepsAfter(missing, -1), null) + assert.equal(sessionDbPath("../escape"), null) + const customDir = path.join(os.tmpdir(), "agy-custom-convs") + assert.equal( + sessionDbPath("f6faf504-502b-4184-90da-aa6ff6105eb0", { AGY_BRIDGE_CONVERSATIONS_DIR: customDir }), + path.join(customDir, "f6faf504-502b-4184-90da-aa6ff6105eb0.db"), + ) +}) + +test("generation records separate billing from the local context estimate", () => { + const usage = { input: 2205, output: 40, write: 12, read: 4907, thinking: 7 } + assert.deepEqual(decodeGenerationUsage(generationBlob(usage)), { ...usage, context: 8100 }) + assert.equal(decodeGenerationUsage(new Uint8Array(field(1, field(9, field(10, [8, 100]))))), null) + assert.equal(decodeGenerationUsage(new Uint8Array([10, 90, 1])), null) + assert.equal(decodeGenerationUsage(new Uint8Array(field(1, field(4, [16, 128])))), null) + assert.equal(decodeGenerationUsage("not bytes"), null) +}) + +const require = createRequire(import.meta.url) +let openDatabase +try { + const { Database } = require("bun:sqlite") + openDatabase = (file) => { + const db = new Database(file) + return { + exec: (sql) => db.exec(sql), + run: (sql, ...args) => { + const stmt = db.prepare(sql) + try { + return stmt.run(...args) + } finally { + stmt.finalize() + } + }, + close: () => db.close(), + } + } +} catch { + try { + const { DatabaseSync } = require("node:sqlite") + openDatabase = (file) => { + const db = new DatabaseSync(file) + return { + exec: (sql) => db.exec(sql), + run: (sql, ...args) => db.prepare(sql).run(...args), + close: () => db.close(), + } + } + } catch {} +} + +test("usage cursors prefer generation billing, pin the source, mark pending rows and release handles immediately", { skip: !openDatabase }, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-generation-test-")) + const file = path.join(dir, "session.db") + const initial = modelUsageCursor(file) + const db = openDatabase(file) + let closed = false + const usage = { input: 2205, output: 40, write: 12, read: 4907, thinking: 7 } + try { + db.run("CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB)") + db.run("CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO steps VALUES (1, 15, 3, ?)", usageBlob(usage)) + db.run("INSERT INTO gen_metadata VALUES (1, ?)", generationBlob(usage)) + const first = modelUsageAfter(file, initial) + assert.equal(first.source, "gen_metadata") + assert.deepEqual(first.steps, [{ idx: 1, ...usage, context: 8100 }]) + const cursor = modelUsageCursor(file) + assert.deepEqual(modelUsageAfter(file, cursor)?.steps, []) + // Pre-send estimate row carries 0 billing counters -> pending: true. + db.run("INSERT INTO gen_metadata VALUES (2, ?)", generationBlob({ input: 0, output: 0, read: 0, thinking: 0 })) + const pendingBatch = modelUsageAfter(file, cursor) + assert.deepEqual(pendingBatch, { source: "gen_metadata", steps: [], pending: true }) + db.run("INSERT INTO gen_metadata VALUES (3, ?)", generationBlob({ ...usage, input: 100 })) + const completedBatch = modelUsageAfter(file, cursor) + assert.equal(completedBatch?.pending, undefined) + assert.equal(completedBatch?.steps[0]?.input, 100) + // Generation-source turns cannot bill a later legacy row again. + db.run("INSERT INTO steps VALUES (4, 15, 3, ?)", usageBlob(usage)) + assert.deepEqual(modelUsageAfter(file, { source: "gen_metadata", idx: 3 })?.steps, []) + // Conversely, a turn already reporting steps must not switch on a late gen row. + assert.deepEqual(modelUsageAfter(file, { source: "steps", idx: 4 })?.steps, []) + db.close() + closed = true + // Strict recursive remove (without `force: true`) verifies no handle leaked on Windows. + fs.rmSync(dir, { recursive: true }) + } finally { + if (!closed) { + try { db.close() } catch {} + fs.rmSync(dir, { recursive: true, force: true }) + } + } +}) + +test("stores with an absent or unused generation table retain step billing", { skip: !openDatabase }, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-legacy-test-")) + const file = path.join(dir, "session.db") + const db = openDatabase(file) + const usage = { input: 22, output: 4, write: 0, read: 0, thinking: 1 } + try { + db.run("CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB)") + const legacy = modelUsageCursor(file) + db.run("INSERT INTO steps VALUES (1, 15, 3, ?)", usageBlob(usage)) + assert.deepEqual(modelUsageAfter(file, legacy), { source: "steps", steps: [{ idx: 1, ...usage }] }) + db.run("CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + const empty = modelUsageCursor(file) + db.run("INSERT INTO steps VALUES (2, 15, 3, ?)", usageBlob(usage)) + assert.deepEqual(modelUsageAfter(file, empty), { source: "steps", steps: [{ idx: 2, ...usage }] }) + } finally { + db.close() + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +test("checkpointed WAL stores without -wal/-shm read cleanly without creating sidecar files", { skip: !openDatabase }, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-wal-clean-")) + const srcDir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-wal-src-")) + const src = path.join(srcDir, "writer.db") + const file = path.join(dir, "session.db") + const usage = { input: 31609, output: 1255, write: 0, read: 22528, thinking: 850 } + try { + const db = openDatabase(src) + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB)") + db.run("CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (0, ?)", generationBlob(usage, 65123)) + db.exec("PRAGMA wal_checkpoint(TRUNCATE)") + db.close() + fs.copyFileSync(src, file) + assert.deepEqual(fs.readdirSync(dir), ["session.db"]) + const initial = { source: null, idx: -1, generationIdx: -1 } + const batch = modelUsageAfter(file, initial) + assert.deepEqual(batch, { source: "gen_metadata", steps: [{ idx: 0, ...usage, context: 65123 }] }) + assert.deepEqual(modelUsageCursor(file), { source: null, idx: -1, generationIdx: 0 }) + // Must neither fail SQLITE_CANTOPEN (macOS libsqlite3) nor create -wal/-shm sidecars (upstream SQLite). + assert.deepEqual(fs.readdirSync(dir), ["session.db"]) + fs.rmSync(dir, { recursive: true }) + } finally { + fs.rmSync(srcDir, { recursive: true, force: true }) + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +test("re-reads against the live file when -wal appears mid-read during an immutable open", { skip: !openDatabase }, () => { + const srcDir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-wal-race-src-")) + const src = path.join(srcDir, "writer.db") + const first = { input: 100, output: 10, write: 0, read: 500, thinking: 2 } + const second = { input: 240, output: 25, write: 0, read: 600, thinking: 5 } + try { + const db = openDatabase(src) + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (0, ?)", generationBlob(first, 1000)) + db.exec("PRAGMA wal_checkpoint(TRUNCATE)") + db.close() + + for (const throwOnImmutable of [false, true]) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-wal-race-")) + const file = path.join(dir, "session.db") + let writer + try { + fs.copyFileSync(src, file) + assert.deepEqual(fs.readdirSync(dir), ["session.db"]) + let reads = 0 + const cursor = { + source: null, + idx: -1, + get generationIdx() { + if (++reads === 1) { + // Simulate agy resuming the store and writing a new WAL frame after ?immutable=1 opened. + writer = openDatabase(file) + writer.exec("PRAGMA wal_autocheckpoint = 0") + writer.run("INSERT INTO gen_metadata VALUES (1, ?)", generationBlob(second, 2000)) + if (throwOnImmutable) throw new Error("simulated mid-write page inconsistency") + } + return -1 + }, + } + const batch = modelUsageAfter(file, cursor) + assert.equal(reads, 2, `expected immutable pass followed by live WAL re-read (throw=${throwOnImmutable})`) + assert.deepEqual(batch, { + source: "gen_metadata", + steps: [ + { idx: 0, ...first, context: 1000 }, + { idx: 1, ...second, context: 2000 }, + ], + }) + writer.close() + writer = null + fs.rmSync(dir, { recursive: true }) + } finally { + try { writer?.close() } catch {} + fs.rmSync(dir, { recursive: true, force: true }) + } + } + + // Counterpart: when an immutable read throws and -wal did NOT appear, must return + // null without falling through to a live open (which would create -wal/-shm sidecars). + const noWalDir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-wal-no-sidecar-")) + try { + const noWalFile = path.join(noWalDir, "session.db") + fs.copyFileSync(src, noWalFile) + let attempts = 0 + const brokenCursor = { + source: null, + idx: -1, + get generationIdx() { + attempts++ + throw new Error("corrupt page without concurrent -wal") + }, + } + assert.equal(modelUsageAfter(noWalFile, brokenCursor), null) + assert.equal(attempts, 1) + assert.deepEqual(fs.readdirSync(noWalDir), ["session.db"]) + fs.rmSync(noWalDir, { recursive: true }) + } finally { + fs.rmSync(noWalDir, { recursive: true, force: true }) + } + } finally { + fs.rmSync(srcDir, { recursive: true, force: true }) + } +}) + +test("handles URI-sensitive path characters, relative file: prefixes, and Windows extended/UNC paths", { skip: !openDatabase }, () => { + const base = fs.mkdtempSync(path.join(os.tmpdir(), "agy-uri-edge-")) + const src = path.join(base, "src.db") + const usage = { input: 310, output: 19, write: 0, read: 1200, thinking: 4 } + const liveUsage = { input: 420, output: 28, write: 0, read: 1500, thinking: 6 } + const origCwd = process.cwd() + try { + const db = openDatabase(src) + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (0, ?)", generationBlob(usage, 2000)) + db.exec("PRAGMA wal_checkpoint(TRUNCATE)") + db.close() + + const dirNames = ["hash # %20 目录"] + if (process.platform !== "win32") { + dirNames.push("query?dir#frag", "file:rel#dir?mode=rwc") + } + + for (const name of dirNames) { + const sub = path.join(base, name) + fs.mkdirSync(sub, { recursive: true }) + const file = path.join(sub, "session.db") + fs.copyFileSync(src, file) + + // Checkpointed WAL read with `#`, `%20`, `?`, Unicode: must percent-encode cleanly and leave zero sidecars. + const initial = { source: null, idx: -1, generationIdx: -1 } + assert.deepEqual(modelUsageAfter(file, initial), { + source: "gen_metadata", + steps: [{ idx: 0, ...usage, context: 2000 }], + }) + assert.deepEqual(fs.readdirSync(sub), ["session.db"]) + + if (process.platform === "win32") { + // Extended-length `\\?\C:\...` path starts with `\\` and contains `?` plus `#`/`%20`/space/Unicode. + const extendedFile = file.startsWith("\\\\") ? file : `\\\\?\\${file}` + assert.deepEqual(modelUsageAfter(extendedFile, initial), { + source: "gen_metadata", + steps: [{ idx: 0, ...usage, context: 2000 }], + }) + assert.deepEqual(modelUsageCursor(extendedFile), { source: "gen_metadata", idx: 0 }) + assert.deepEqual(fs.readdirSync(sub), ["session.db"]) + + // If administrative loopback UNC share (`\\127.0.0.1\C$\...`) is reachable, verify UNC share too. + const driveMatch = /^([A-Za-z]):\\(.*)$/.exec(file) + if (driveMatch) { + const uncFile = `\\\\127.0.0.1\\${driveMatch[1]}$\\${driveMatch[2]}` + if (fs.existsSync(uncFile)) { + assert.deepEqual(modelUsageAfter(uncFile, initial), { + source: "gen_metadata", + steps: [{ idx: 0, ...usage, context: 2000 }], + }) + assert.deepEqual(fs.readdirSync(sub), ["session.db"]) + } + } + } + + // Live uncheckpointed WAL read via BOTH absolute and relative path (guards `file:...` under SQLITE_OPEN_URI). + const writer = openDatabase(file) + try { + writer.exec("PRAGMA wal_autocheckpoint = 0") + writer.run("INSERT INTO gen_metadata VALUES (1, ?)", generationBlob(liveUsage, 3000)) + process.chdir(base) + const relFile = path.join(name, "session.db") + assert.deepEqual(modelUsageAfter(relFile, { source: "gen_metadata", idx: 0 }), { + source: "gen_metadata", + steps: [{ idx: 1, ...liveUsage, context: 3000 }], + }) + } finally { + process.chdir(origCwd) + writer.close() + } + fs.rmSync(sub, { recursive: true }) + } + + assert.equal(lastModelStep(""), null) + assert.equal(lastModelStep("bad\0path.db"), null) + assert.equal(modelUsageCursor("bad\0path.db"), null) + } finally { + process.chdir(origCwd) + fs.rmSync(base, { recursive: true, force: true }) + } +}) + +test("uncheckpointed WAL store with incompatible schema is never checkpointed or rewritten", { skip: !openDatabase }, () => { + const srcDir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-unckpt-src-")) + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-unckpt-dst-")) + const src = path.join(srcDir, "s.db") + const dst = path.join(dir, "s.db") + let db + try { + db = openDatabase(src) + db.exec("PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0") + // Old schema: `steps` lacks `status`, and `gen_metadata` is absent. + db.run("CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, metadata BLOB)") + for (let i = 0; i < 40; i++) { + db.run("INSERT INTO steps VALUES (?, 15, ?)", i, new Uint8Array(2048).fill(7)) + } + // Snapshot while writer still holds uncheckpointed frames in -wal (simulating crashed agy). + fs.copyFileSync(src, dst) + fs.copyFileSync(`${src}-wal`, `${dst}-wal`) + db.close() + db = null + + const dbBefore = fs.readFileSync(dst) + const walBefore = fs.readFileSync(`${dst}-wal`) + assert.ok(walBefore.length > 0, "expected non-empty uncheckpointed WAL") + + assert.equal(lastModelStep(dst), null) + assert.equal(modelStepsAfter(dst, -1), null) + assert.equal(modelUsageCursor(dst), null) + + assert.equal(fs.existsSync(`${dst}-wal`), true, "WAL file must not be checkpointed away") + assert.equal(Buffer.compare(fs.readFileSync(dst), dbBefore), 0, "main DB bytes must remain untouched") + assert.equal(Buffer.compare(fs.readFileSync(`${dst}-wal`), walBefore), 0, "WAL bytes must remain untouched") + } finally { + try { db?.close() } catch {} + fs.rmSync(srcDir, { recursive: true, force: true }) + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +test("an EXCLUSIVE-locked store returns null immediately without waiting on busy timeouts", { skip: !openDatabase }, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-locked-test-")) + const file = path.join(dir, "session.db") + const locker = openDatabase(file) + try { + locker.run("CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + locker.exec("BEGIN EXCLUSIVE") + locker.run("INSERT INTO gen_metadata VALUES (0, ?)", generationBlob({ input: 100, output: 10, read: 0, thinking: 0 })) + const t0 = performance.now() + assert.equal(modelUsageCursor(file), null) + assert.equal(modelUsageAfter(file, { source: "gen_metadata", idx: -1 }), null) + const elapsed = performance.now() - t0 + assert.ok(elapsed < 150, `locked store read took ${elapsed.toFixed(1)}ms; expected immediate non-blocking return`) + locker.exec("ROLLBACK") + } finally { + try { locker.close() } catch {} + fs.rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index db9bad0..43fc62d 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -35,6 +35,7 @@ export const ARRAY_ITEMS_FILE = path.join(REPO_DIR, "array-items.mjs") export const CLOAK_FILE = path.join(REPO_DIR, "cloak.mjs") export const LOGIN_FILE = path.join(REPO_DIR, "login.mjs") export const RE2_PATTERN_FILE = path.join(REPO_DIR, "re2-pattern.mjs") +export const STEP_USAGE_FILE = path.join(REPO_DIR, "step-usage.mjs") export const MESSAGES_URL = "agy://local/v1/messages" export const COUNT_TOKENS_URL = "agy://local/v1/messages/count_tokens" export const CATALOG_TTL_MS = 5 * 60 * 1000 @@ -493,6 +494,7 @@ export async function createBridgeKit(options = {}) { const cloakUrl = pathToFileURL(CLOAK_FILE).href const loginUrl = pathToFileURL(LOGIN_FILE).href const re2Url = pathToFileURL(RE2_PATTERN_FILE).href + const stepUsageUrl = pathToFileURL(STEP_USAGE_FILE).href const linker = (specifier) => { const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER ? specifier @@ -505,6 +507,7 @@ export async function createBridgeKit(options = {}) { else if (key === "./cloak.mjs") module = sourceModule(CLOAK_FILE, "", cloakUrl) else if (key === "./login.mjs") module = sourceModule(LOGIN_FILE, "", loginUrl) else if (key === "./re2-pattern.mjs") module = sourceModule(RE2_PATTERN_FILE, "", re2Url) + else if (key === "./step-usage.mjs") module = sourceModule(STEP_USAGE_FILE, "", stepUsageUrl) else if (key.startsWith("node:")) module = builtinModule(key, overrides[key]) else throw new Error(`testkit: 未登记的依赖 ${specifier}`) cache.set(key, module) diff --git a/packages/agy-cli/test/usage-settlement.mjs b/packages/agy-cli/test/usage-settlement.mjs index 1c9d584..5954146 100644 --- a/packages/agy-cli/test/usage-settlement.mjs +++ b/packages/agy-cli/test/usage-settlement.mjs @@ -9,6 +9,9 @@ import { test } from "node:test" import assert from "node:assert/strict" +import fs from "node:fs" +import path from "node:path" +import { createRequire } from "node:module" import { baseBody, continueWithToolResults, createBridgeKit, padBodyToTokens, readJson, readSse, sleep, usageTotal, @@ -282,7 +285,7 @@ test("并行工具调用合并为一次响应,只结算一次", async () => { test("跨事件循环的 13 个并行 MCP 调用合并:旧版 14 次 HTTP,新版 2 次", async () => { const observe = async (legacy, stream) => withKit({ ...(legacy ? { indexTransform: (source) => { - const pattern = / const emittedIds = new Set\(\[event.call.id\]\)[\s\S]*?(?= stopMessage\("tool_use")/ + const pattern = / const emittedIds = new Set\(\[event.call.id\]\)[\s\S]*?(?= const usage = await settleUsage)/ assert.match(source, pattern, "旧版对照必须只恢复原来的即时队列排空逻辑") return source.replace(pattern, ' while (turn.events[0]?.type === "tool") emitToolUse(turn.events.shift().call)\n') } } : {}), @@ -946,3 +949,725 @@ test("LRU 淘汰后,改写历史 tool_use id 的 follow-up 不得 session/resu assert.equal(news.length, 3, "应新开 session,而不是 resume 会话 A") }) }) + +// ------------------------------------------------ agy 1.5.1+ 独立字段与 SQLite 步级真实计费 + +test("agy 1.5.1+ 独立 inputTokens(未含读缓存)按 totalTokens 完整保留 cachedReadTokens 并校准真实缓存占比", async () => { + await withKit({}, async (kit) => { + const cancelled = { + inputTokens: 2133, + cachedReadTokens: 6399, + cachedWriteTokens: 0, + outputTokens: 30, + thoughtTokens: 10, + totalTokens: 2133 + 6399 + 30 + 10, + } + kit.prompts.push(async (agent) => { + await agent.text("partial answer") + await agent.waitCancel() + return { stopReason: "cancelled", usage: cancelled } + }) + kit.prompts.push(async (agent) => { + await agent.tool("Read", { path: "/after-cancel" }) + await agent.text("done") + return { + stopReason: "end_turn", + usage: { + inputTokens: 2133, + cachedReadTokens: 28_610, + cachedWriteTokens: 120, + outputTokens: 45, + thoughtTokens: 15, + totalTokens: 2133 + 28_610 + 120 + 45 + 15, + }, + } + }) + const body = baseBody() + const controller = new AbortController() + const response = await kit.request(body, { signal: controller.signal }) + const reader = response.body.getReader() + const decoder = new TextDecoder() + let seen = "" + while (!seen.includes("text_delta")) { + const { value, done } = await reader.read() + if (done) break + seen += decoder.decode(value, { stream: true }) + } + controller.abort() + await reader.read().then(() => {}, () => {}) + for (let i = 0; i < 200 && !kit.turns[0]?.finalized; i++) await sleep(5) + + // 取消的 agy 1.5.1+ prompt 应教会 6399 / (2133 + 6399) = 0.75,而不是把 6399 / 2133 截断成 1.0 + const next = { + ...body, + messages: [...body.messages, { role: "assistant", content: [{ type: "text", text: "partial answer" }] }, { role: "user", content: "continue" }], + } + const second = await runTurn(kit, next) + const toolRatio = second.responses[0].usage.cache_read_input_tokens / usageTotal(second.responses[0].usage) + assert.ok(Math.abs(toolRatio - 0.75) < 0.03, `agy 1.5.1+ 取消后工具步缓存率 ${toolRatio},期望约 0.75(不应误算为 1.0)`) + }) + + await withKit({}, async (kit) => { + const raw = { + inputTokens: 2133, + cachedReadTokens: 28_610, + cachedWriteTokens: 120, + outputTokens: 45, + thoughtTokens: 15, + totalTokens: 2133 + 28_610 + 120 + 45 + 15, + } + kit.prompts.push(async (agent) => { + await agent.text("answer with high cache hit") + return { stopReason: "end_turn", usage: raw } + }) + const { responses } = await runTurn(kit, baseBody({ tools: [] })) + assert.deepEqual(plain(responses[0].usage), { + input_tokens: 2133, + cache_read_input_tokens: 28_610, + cache_creation_input_tokens: 120, + output_tokens: 60, + output_tokens_details: { thinking_tokens: 15 }, + }) + }) +}) + +const localRequire = createRequire(import.meta.url) +let openSqlite = null +try { + const { Database } = localRequire("bun:sqlite") + openSqlite = (file) => { + const db = new Database(file) + return { + exec: (sql) => db.exec(sql), + run: (sql, ...args) => { + const stmt = db.prepare(sql) + try { + return stmt.run(...args) + } finally { + stmt.finalize() + } + }, + close: () => db.close(), + } + } +} catch { + try { + const { DatabaseSync } = localRequire("node:sqlite") + openSqlite = (file) => { + const db = new DatabaseSync(file) + return { + exec: (sql) => db.exec(sql), + run: (sql, ...args) => db.prepare(sql).run(...args), + close: () => db.close(), + } + } + } catch {} +} + +test("SQLite gen_metadata 步级落盘:tool_use 中间步直接读取真实缓存命中并即时校准缓存率", { skip: !openSqlite }, async () => { + const varint = (n) => { const out = []; while (n > 127) { out.push((n & 127) | 128); n = Math.floor(n / 128) } out.push(n); return out } + const field = (n, bytes) => [n * 8 + 2, ...varint(bytes.length), ...bytes] + const genBlob = ({ input, output, write = 0, read = 0, thinking = 0 }) => new Uint8Array(field(1, field(4, [ + 0x10, ...varint(input), 0x18, ...varint(output), + ...(write ? [0x20, ...varint(write)] : []), + ...(read ? [0x28, ...varint(read)] : []), + ...(thinking ? [0x48, ...varint(thinking)] : []), + ]))) + + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (1, ?)", genBlob({ input: 1800, read: 18_200, write: 0, output: 32, thinking: 8 })) + } finally { + db.close() + } + await agent.tool("Read", { path: "/step1.ts" }) + const db2 = openSqlite(dbFile) + try { + db2.run("INSERT INTO gen_metadata VALUES (2, ?)", genBlob({ input: 2100, read: 19_900, write: 0, output: 50, thinking: 10 })) + } finally { + db2.close() + } + await agent.text("done reading") + return { + stopReason: "end_turn", + usage: { + inputTokens: 3900, + cachedReadTokens: 38_100, + cachedWriteTokens: 0, + outputTokens: 82, + thoughtTokens: 18, + totalTokens: 3900 + 38_100 + 82 + 18, + }, + } + }) + const { responses } = await runTurn(kit, baseBody()) + assert.equal(responses.length, 2) + assert.deepEqual(plain(responses[0].usage), { + input_tokens: 1800, + cache_read_input_tokens: 18_200, + cache_creation_input_tokens: 0, + output_tokens: 40, + output_tokens_details: { thinking_tokens: 8 }, + }) + assert.deepEqual(plain(responses[1].usage), { + input_tokens: 2100, + cache_read_input_tokens: 19_900, + cache_creation_input_tokens: 0, + output_tokens: 60, + output_tokens_details: { thinking_tokens: 10 }, + }) + }) +}) + +test("单次生成串行派发多工具 + WAL 关库:续接工具不虚增账单、不清空游标,后续步完整读取真实高命中率", { skip: !openSqlite }, async () => { + const varint = (n) => { const out = []; while (n > 127) { out.push((n & 127) | 128); n = Math.floor(n / 128) } out.push(n); return out } + const field = (n, bytes) => [n * 8 + 2, ...varint(bytes.length), ...bytes] + const genBlob = ({ input, output, write = 0, read = 0, thinking = 0 }) => new Uint8Array(field(1, field(4, [ + 0x10, ...varint(input), 0x18, ...varint(output), + ...(write ? [0x20, ...varint(write)] : []), + ...(read ? [0x28, ...varint(read)] : []), + ...(thinking ? [0x48, ...varint(thinking)] : []), + ]))) + + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + let secondToolElapsedMs = 0 + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const writeGen = (idx, stats) => { + const db = openSqlite(dbFile) + try { + db.run("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (?, ?)", idx, genBlob(stats)) + } finally { + db.close() + } + } + // Generation 0 一次生成 3 个工具,但 agy 串行逐个调用 MCP tools/call + writeGen(0, { input: 31_609, read: 22_528, output: 1255, thinking: 850 }) + await agent.tool("Read", { path: "/a.ts" }) + const t0 = performance.now() + await agent.tool("Read", { path: "/b.ts" }) + secondToolElapsedMs = performance.now() - t0 + await agent.tool("Read", { path: "/c.ts" }) + + // Generation 1 高缓存命中 + writeGen(1, { input: 12_852, read: 54_133, output: 509, thinking: 171 }) + await agent.tool("Read", { path: "/d.ts" }) + + // Generation 2 收尾高缓存命中 + writeGen(2, { input: 2243, read: 66_986, output: 640, thinking: 283 }) + await agent.text("all done") + return { + stopReason: "end_turn", + usage: { + inputTokens: 31_609 + 12_852 + 2243, + cachedReadTokens: 22_528 + 54_133 + 66_986, + cachedWriteTokens: 0, + outputTokens: 1255 + 509 + 640, + thoughtTokens: 850 + 171 + 283, + totalTokens: 31_609 + 12_852 + 2243 + 22_528 + 54_133 + 66_986 + 1255 + 509 + 640 + 850 + 171 + 283, + }, + } + }) + const { responses } = await runTurn(kit, baseBody()) + assert.equal(responses.length, 5) + assert.ok(secondToolElapsedMs < 500, `同次生成续接工具耗时 ${secondToolElapsedMs.toFixed(0)}ms,不应空转等待 1000ms`) + assert.deepEqual(plain(responses.map((r) => r.usage)), [ + { input_tokens: 31_609, cache_read_input_tokens: 22_528, cache_creation_input_tokens: 0, output_tokens: 2105, output_tokens_details: { thinking_tokens: 850 } }, + { input_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: 0 }, + { input_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: 0 }, + { input_tokens: 12_852, cache_read_input_tokens: 54_133, cache_creation_input_tokens: 0, output_tokens: 680, output_tokens_details: { thinking_tokens: 171 } }, + { input_tokens: 2243, cache_read_input_tokens: 66_986, cache_creation_input_tokens: 0, output_tokens: 923, output_tokens_details: { thinking_tokens: 283 } }, + ]) + }) +}) + +test("SQLite 空表回退(.pb 冷启动)+ maxInitialPromptBytes(112KiB)历史裁剪:窗口按送达裁剪值封顶,且次轮记住空库不再空等 1s", { skip: !openSqlite }, async () => { + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + kit.prompts.push(async (agent) => { + // 模拟 agy 冷启动偶发创建空 SQLite 表并将轨迹写入 .pb + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.run("CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB)") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + } finally { + db.close() + } + for (let i = 0; i < 6; i++) { + await agent.tool("Read", { path: `/repo/chunk-${i}.ts` }) + } + await agent.text("done after replay clip") + return { + stopReason: "end_turn", + usage: { + inputTokens: 75_000, + cachedReadTokens: 380_000, + cachedWriteTokens: 0, + outputTokens: 400, + totalTokens: 455_400, + }, + } + }) + kit.prompts.push(async (agent) => { + await agent.tool("Read", { path: "/repo/turn2.ts" }) + await agent.text("turn 2 done") + return { + stopReason: "end_turn", + usage: { + inputTokens: 12_000, + cachedReadTokens: 88_000, + cachedWriteTokens: 0, + outputTokens: 40, + totalTokens: 100_040, + }, + } + }) + + // 构造约 1.5MB 未裁剪历史(~360k tokens),但经 maxInitialPromptBytes()(112KiB)与单块 12KiB 裁剪后送入 agy 的窗口仅 ~100k tokens + const historyTurn = "historical context line for replay trimming verification. ".repeat(900) + const messages = [] + for (let i = 0; i < 11; i++) { + messages.push({ role: "user", content: `turn ${i}: ${historyTurn}` }) + messages.push({ role: "assistant", content: `ack ${i}: ${historyTurn}` }) + } + messages.push({ role: "user", content: "continue investigating the current module" }) + const body = await padBodyToTokens(kit, baseBody({ messages }), 360_000) + const rawEstimate = await kit.countTokens(body) + assert.equal(rawEstimate, 360_000) + + const firstTurn = await runTurn(kit, body, { + resultFor: (_block, index) => "tool output line ".repeat(200) + `#${index}`, + }) + const { responses } = firstTurn + assert.equal(responses.length, 7) + const toolSteps = responses.slice(0, 6) + + // 第 1 步按实际送入 agy 的裁剪后窗口结算,绝不报未裁剪的 ~360k + const firstWindow = usageTotal(toolSteps[0].usage) + assert.ok(firstWindow < 120_000, `裁剪后首步窗口 ${firstWindow} 仍按未裁剪全量估算`) + assert.equal(toolSteps[0].usage.cache_read_input_tokens, 0) + + // 第 2..6 步:前序已发送前缀转入 cache_read,uncached input 只计本步新增增量 + for (let i = 1; i < toolSteps.length; i++) { + const prevWindow = usageTotal(toolSteps[i - 1].usage) + const curr = toolSteps[i].usage + assertCleanUsage(curr, `裁剪回退工具步 #${i + 1}`) + assert.ok(curr.cache_read_input_tokens >= prevWindow - 1, `工具步 #${i + 1} 未命中前序前缀缓存`) + assert.ok(curr.input_tokens < 5_000, `工具步 #${i + 1} uncached input=${curr.input_tokens} 重复计入全量窗口`) + } + + const sumIn = toolSteps.reduce((s, r) => s + r.usage.input_tokens, 0) + const sumRead = toolSteps.reduce((s, r) => s + r.usage.cache_read_input_tokens, 0) + const hitRate = sumRead / (sumIn + sumRead) + assert.ok(sumIn < 130_000, `6 步累计 uncached input=${sumIn} 远超单次裁剪窗口(旧缺陷:6 × 360k = 2.16M)`) + assert.ok(hitRate > 0.75, `回退多步命中率 ${(hitRate * 100).toFixed(1)}% 过低`) + + // 第 2 回合复用同一 Proc:已记住该会话 SQLite 无可用行,首步 tool_use 不再白等 1000ms + const turn2Messages = [ + ...firstTurn.bodies.at(-1).messages, + { role: "assistant", content: plain(responses.at(-1).content) }, + { role: "user", content: "follow up on the same cold-started session" }, + ] + const t0 = performance.now() + const firstToolResp = await readSse(await kit.request({ ...body, messages: turn2Messages })) + const turn2FirstStepMs = performance.now() - t0 + assert.equal(kit.acpSpawns.length, 1, "第 2 回合应复用同一 Proc") + assert.equal(firstToolResp.stopReason, "tool_use") + assert.ok(turn2FirstStepMs < 500, `第 2 回合首步耗时 ${turn2FirstStepMs.toFixed(0)}ms,不应再次轮询等待 1000ms`) + const finishBody = continueWithToolResults({ ...body, messages: turn2Messages }, firstToolResp, () => "ok") + const finalResp = await readSse(await kit.request(finishBody)) + assert.equal(finalResp.stopReason, "end_turn") + }) +}) + +test("跨回合隔离:上一回合被取消或超时回退后延迟落盘的 SQLite 行绝不串入下一回合", { skip: !openSqlite }, async () => { + const varint = (n) => { const out = []; while (n > 127) { out.push((n & 127) | 128); n = Math.floor(n / 128) } out.push(n); return out } + const field = (n, bytes) => [n * 8 + 2, ...varint(bytes.length), ...bytes] + const genBlob = ({ input, output, write = 0, read = 0, thinking = 0 }) => new Uint8Array(field(1, field(4, [ + 0x10, ...varint(input), 0x18, ...varint(output), + ...(write ? [0x20, ...varint(write)] : []), + ...(read ? [0x28, ...varint(read)] : []), + ...(thinking ? [0x48, ...varint(thinking)] : []), + ]))) + + // 场景 1:第 1 回合取消,150ms 后延迟落盘 {input: 50000, output: 900};第 2 回合首步绝不能把这 900 output 算进来 + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + const writeGen = (sessionId, idx, stats) => { + const db = openSqlite(path.join(convDir, `${sessionId}.db`)) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (?, ?)", idx, genBlob(stats)) + } finally { + db.close() + } + } + + let lateTimer = null + kit.prompts.push(async (agent) => { + const db = openSqlite(path.join(convDir, `${agent.sessionId}.db`)) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + } finally { + db.close() + } + await agent.text("partial") + await agent.waitCancel() + lateTimer = setTimeout(() => { + try { writeGen(agent.sessionId, 1, { input: 50_000, read: 0, output: 900 }) } catch {} + }, 150) + return { stopReason: "cancelled", usage: { inputTokens: 50_000, cachedReadTokens: 0, outputTokens: 900, totalTokens: 50_900 } } + }) + kit.prompts.push(async (agent) => { + await sleep(220) + writeGen(agent.sessionId, 2, { input: 1000, read: 49_000, output: 20 }) + await agent.tool("Read", { path: "/after-cancel.ts" }) + await agent.text("done") + return { stopReason: "end_turn", usage: { inputTokens: 1000, cachedReadTokens: 49_000, outputTokens: 25, totalTokens: 50_025 } } + }) + + try { + const body = baseBody() + const controller = new AbortController() + const response = await kit.request(body, { signal: controller.signal }) + const reader = response.body.getReader() + const decoder = new TextDecoder() + let seen = "" + while (!seen.includes("text_delta")) { + const { value, done } = await reader.read() + if (done) break + seen += decoder.decode(value, { stream: true }) + } + controller.abort() + await reader.read().then(() => {}, () => {}) + for (let i = 0; i < 200 && !kit.turns[0]?.finalized; i++) await sleep(5) + + const next = { + ...body, + messages: [...body.messages, { role: "assistant", content: [{ type: "text", text: "partial" }] }, { role: "user", content: "next turn" }], + } + const { responses } = await runTurn(kit, next) + assert.equal(kit.acpSpawns.length, 1, "同一会话复用 Proc") + assert.ok(responses[0].usage.output_tokens < 200, + `第 2 回合首步 output_tokens=${responses[0].usage.output_tokens} 误吞入了上一取消回合延迟写入的 900 token`) + } finally { + clearTimeout(lateTimer) + } + }) + + // 场景 2:第 1 回合超时回退(SQLite 行在第 1 回合结束后才落盘),第 2 回合同样不得误计该晚到行 + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + let sessionId + const writeGen = (id, idx, stats) => { + const db = openSqlite(path.join(convDir, `${id}.db`)) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (?, ?)", idx, genBlob(stats)) + } finally { + db.close() + } + } + + kit.prompts.push(async (agent) => { + sessionId = agent.sessionId + const db = openSqlite(path.join(convDir, `${sessionId}.db`)) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + } finally { + db.close() + } + await agent.text("short reply") + return { stopReason: "end_turn", usage: { inputTokens: 3000, cachedReadTokens: 0, outputTokens: 10, totalTokens: 3010 } } + }) + kit.prompts.push(async (agent) => { + writeGen(agent.sessionId, 2, { input: 1000, read: 2000, output: 15 }) + await agent.tool("Read", { path: "/turn2.ts" }) + await agent.text("ok") + return { stopReason: "end_turn", usage: { inputTokens: 1000, cachedReadTokens: 2000, outputTokens: 20, totalTokens: 3020 } } + }) + + const body = baseBody() + const turn1 = await runTurn(kit, body) + // 第 1 回合已回退结算后,其延迟行(output: 900)才写入 SQLite + writeGen(sessionId, 1, { input: 3000, read: 0, output: 900 }) + const next = { + ...body, + messages: [...body.messages, { role: "assistant", content: plain(turn1.responses[0].content) }, { role: "user", content: "turn 2" }], + } + const turn2 = await runTurn(kit, next) + assert.equal(kit.acpSpawns.length, 1) + assert.ok(turn2.responses[0].usage.output_tokens < 200, + `第 2 回合首步 output_tokens=${turn2.responses[0].usage.output_tokens} 误计入了回退回合的晚到行`) + }) +}) + +test("异步延迟 >75ms 落盘:pending 预写行等待真实落盘;无预写慢行在后续步合并 output 且单步窗口只取最新一笔", { skip: !openSqlite }, async () => { + const varint = (n) => { const out = []; while (n > 127) { out.push((n & 127) | 128); n = Math.floor(n / 128) } out.push(n); return out } + const field = (n, bytes) => [n * 8 + 2, ...varint(bytes.length), ...bytes] + const genBlob = ({ input, output, write = 0, read = 0, thinking = 0 }, context = 24_000) => { + const stats = [ + 0x10, ...varint(input), 0x18, ...varint(output), + ...(write ? [0x20, ...varint(write)] : []), + ...(read ? [0x28, ...varint(read)] : []), + ...(thinking ? [0x48, ...varint(thinking)] : []), + ] + return new Uint8Array(field(1, [...field(4, stats), ...field(9, field(10, [8, ...varint(context)]))])) + } + + // 子场景 1:gen_metadata 先有 pre-send 估算行(pending: true),真实计费 150ms(>75ms)后才写入 -> 当步必须等齐并精确上报 + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + let lateTimer = null + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const upsertGen = (idx, stats) => { + const db = openSqlite(dbFile) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT OR REPLACE INTO gen_metadata VALUES (?, ?)", idx, genBlob(stats)) + } finally { + db.close() + } + } + upsertGen(1, { input: 1800, read: 18_200, output: 32, thinking: 8 }) + await agent.tool("Read", { path: "/step1.ts" }) + + // 第 2 步先写入 0 计费的 pre-send 行(触发 pending: true),150ms 后才落盘真实计费 + upsertGen(2, { input: 0, read: 0, output: 0, thinking: 0 }) + lateTimer = setTimeout(() => { + try { upsertGen(2, { input: 2100, read: 19_900, output: 50, thinking: 10 }) } catch {} + }, 150) + await agent.tool("Read", { path: "/step2.ts" }) + + upsertGen(3, { input: 2400, read: 22_000, output: 40, thinking: 5 }) + await agent.text("done") + return { + stopReason: "end_turn", + usage: { + inputTokens: 1800 + 2100 + 2400, + cachedReadTokens: 18_200 + 19_900 + 22_000, + cachedWriteTokens: 0, + outputTokens: 32 + 50 + 40, + thoughtTokens: 8 + 10 + 5, + totalTokens: 1800 + 2100 + 2400 + 18_200 + 19_900 + 22_000 + 32 + 50 + 40 + 8 + 10 + 5, + }, + } + }) + try { + const { responses } = await runTurn(kit, baseBody()) + assert.equal(responses.length, 3) + assert.deepEqual(plain(responses[1].usage), { + input_tokens: 2100, + cache_read_input_tokens: 19_900, + cache_creation_input_tokens: 0, + output_tokens: 60, + output_tokens_details: { thinking_tokens: 10 }, + }) + } finally { + clearTimeout(lateTimer) + } + }) + + // 子场景 2:无 pre-send 行且无文本块,第 2 步的整行在 150ms(>75ms)后才首次落盘: + // 钉死行为:第 2 步按 75ms 超时先结 0;第 3 步看到 [Gen 2, Gen 3] 两笔调用时, + // 必须只报最新一笔调用的上下文窗口(严禁累加翻倍),并合并两笔的 output_tokens。 + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + let lateTimer = null + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const writeGen = (idx, stats) => { + const db = openSqlite(dbFile) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (?, ?)", idx, genBlob(stats)) + } finally { + db.close() + } + } + writeGen(1, { input: 1800, read: 18_200, output: 32, thinking: 8 }) + await agent.tool("Read", { path: "/s1.ts" }) + + lateTimer = setTimeout(() => { + try { writeGen(2, { input: 2582, read: 83_270, output: 453, thinking: 0 }) } catch {} + }, 150) + await agent.tool("Read", { path: "/s2.ts" }) + + await sleep(120) + writeGen(3, { input: 2355, read: 83_803, output: 100, thinking: 15 }) + await agent.text("completed") + return { + stopReason: "end_turn", + usage: { + inputTokens: 1800 + 2582 + 2355, + cachedReadTokens: 18_200 + 83_270 + 83_803, + cachedWriteTokens: 0, + outputTokens: 32 + 453 + 100, + thoughtTokens: 8 + 15, + totalTokens: 1800 + 2582 + 2355 + 18_200 + 83_270 + 83_803 + 32 + 453 + 100 + 8 + 15, + }, + } + }) + try { + const { responses } = await runTurn(kit, baseBody()) + assert.equal(responses.length, 3) + assert.deepEqual(plain(responses.map((r) => r.usage)), [ + { input_tokens: 1800, cache_read_input_tokens: 18_200, cache_creation_input_tokens: 0, output_tokens: 40, output_tokens_details: { thinking_tokens: 8 } }, + { input_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: 0 }, + { input_tokens: 2355, cache_read_input_tokens: 83_803, cache_creation_input_tokens: 0, output_tokens: 568, output_tokens_details: { thinking_tokens: 15 } }, + ]) + } finally { + clearTimeout(lateTimer) + } + }) + + // 子场景 3:无 pre-send 行,但第 2 步在 tool_use 前已流出文本块(必为新生成,不可共享上一生成): + // 即使整行在 150ms(>75ms)后才首次落盘,也必须按 1000ms 等待并在第 2 步当步精确上报。 + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + let lateTimer = null + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const writeGen = (idx, stats) => { + const db = openSqlite(dbFile) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (?, ?)", idx, genBlob(stats)) + } finally { + db.close() + } + } + writeGen(1, { input: 1800, read: 18_200, output: 32, thinking: 8 }) + await agent.tool("Read", { path: "/t1.ts" }) + + lateTimer = setTimeout(() => { + try { writeGen(2, { input: 2100, read: 19_900, output: 50, thinking: 10 }) } catch {} + }, 150) + await agent.text("inspecting next file ") + await agent.tool("Read", { path: "/t2.ts" }) + + writeGen(3, { input: 2400, read: 22_000, output: 40, thinking: 5 }) + await agent.text("done") + return { + stopReason: "end_turn", + usage: { + inputTokens: 1800 + 2100 + 2400, + cachedReadTokens: 18_200 + 19_900 + 22_000, + cachedWriteTokens: 0, + outputTokens: 32 + 50 + 40, + thoughtTokens: 8 + 10 + 5, + totalTokens: 1800 + 2100 + 2400 + 18_200 + 19_900 + 22_000 + 32 + 50 + 40 + 8 + 10 + 5, + }, + } + }) + try { + const { responses } = await runTurn(kit, baseBody()) + assert.equal(responses.length, 3) + assert.deepEqual(plain(responses[1].usage), { + input_tokens: 2100, + cache_read_input_tokens: 19_900, + cache_creation_input_tokens: 0, + output_tokens: 60, + output_tokens_details: { thinking_tokens: 10 }, + }) + } finally { + clearTimeout(lateTimer) + } + }) +}) + +test("SQLite 异常保护:超额失真行触发回退,EXCLUSIVE 锁库立即停止轮询不阻塞", { skip: !openSqlite }, async () => { + const varint = (n) => { const out = []; while (n > 127) { out.push((n & 127) | 128); n = Math.floor(n / 128) } out.push(n); return out } + const field = (n, bytes) => [n * 8 + 2, ...varint(bytes.length), ...bytes] + const genBlob = ({ input, output, write = 0, read = 0 }) => new Uint8Array(field(1, field(4, [ + 0x10, ...varint(input), 0x18, ...varint(output), + ...(write ? [0x20, ...varint(write)] : []), + ...(read ? [0x28, ...varint(read)] : []), + ]))) + + // 子场景 1:SQLite 记录的累计 prompt 远超 ACP 终态上报(> expected + max(16, 1%)),必须拒信并回退到有界估算 + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + kit.prompts.push(async (agent) => { + const db = openSqlite(path.join(convDir, `${agent.sessionId}.db`)) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (1, ?)", genBlob({ input: 45_000, read: 45_000, output: 30 })) + } finally { + db.close() + } + await agent.text("short answer") + return { + stopReason: "end_turn", + usage: { inputTokens: 1500, cachedReadTokens: 4500, cachedWriteTokens: 0, outputTokens: 30, totalTokens: 6030 }, + } + }) + const { responses } = await runTurn(kit, baseBody()) + assert.ok(usageTotal(responses[0].usage) <= 6000, + `超额失真的 SQLite 行(90000)未被拦截,实际返回窗口=${usageTotal(responses[0].usage)}`) + }) + + // 子场景 2:数据库被 EXCLUSIVE 锁住(SQLITE_BUSY)时立即放弃轮询,不耗满 1000ms + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + let locker = null + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + locker = openSqlite(dbFile) + locker.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + locker.exec("BEGIN EXCLUSIVE") + locker.run("INSERT INTO gen_metadata VALUES (1, ?)", genBlob({ input: 2000, read: 4000, output: 20 })) + await agent.text("checking ") + await agent.tool("Read", { path: "/locked.ts" }) + locker.exec("ROLLBACK") + locker.close() + locker = null + await agent.text("unlocked done") + return { + stopReason: "end_turn", + usage: { inputTokens: 2000, cachedReadTokens: 4000, cachedWriteTokens: 0, outputTokens: 25, totalTokens: 6025 }, + } + }) + try { + const body = baseBody() + const t0 = performance.now() + const toolResp = await readSse(await kit.request(body)) + const toolElapsedMs = performance.now() - t0 + assert.equal(toolResp.stopReason, "tool_use") + assert.ok(toolElapsedMs < 500, `SQLITE_BUSY 时首步耗时 ${toolElapsedMs.toFixed(0)}ms,不应重复轮询阻塞至 1000ms`) + const finalResp = await readSse(await kit.request(continueWithToolResults(body, toolResp, () => "ok"))) + assert.equal(finalResp.stopReason, "end_turn") + } finally { + try { locker?.exec("ROLLBACK") } catch {} + try { locker?.close() } catch {} + } + }) +})