mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-12-03 12:32:02 +00:00
fix(copilot): count store-row output for unclosed sessions, price grok-4.6 at xAI rates (#1652)
Session-store rows carried output only for compaction requests; every other request's output was left to the per-turn assistant.message or the shutdown rollup residual. CLI 1.0.8x and ACP hosts (JetBrains AI Chat via copilot --acp) write no per-turn output, and an ACP session usually ends without session.shutdown, so its whole output was lost. Rows now carry their own output_tokens; at serve time a row that pairs with a per-turn call carrying output (older CLIs) serves with output 0, so output counts once in every shape. grok-4.6 priced at $1.25/M input: LiteLLM has no bare grok-4.6 row and the stripped azure_ai/grok-4.6 row claims the bare id ahead of xai/grok-4.6, in the bundler and the live fetch alike. A builtin price pins xAI's list rate ($2/$6/$0.50 per M), which is what GitHub bills. On real data every Copilot model's cost now equals GitHub's total_nano_aiu to the digit.
This commit is contained in:
parent
756511e8ea
commit
1a7284c39b
9 changed files with 218 additions and 71 deletions
|
|
@ -56,11 +56,16 @@ names the project), and write no `assistant_usage_events` rows. Copilot CLI
|
|||
when the session ends. Until then the requests show as calls with no tokens
|
||||
and $0. `session.usage_checkpoint` events carry a running `totalNanoAiu` but
|
||||
no tokens; they are not read, so credits come from one place only.
|
||||
- **With session-store rows** (CLI 1.0.8x), the rows replace the rollup but
|
||||
carry output only for compaction requests, so the leg's output serves through
|
||||
its residual (rollup output minus compaction-row output). In a compacted
|
||||
session the rollup's counters reset at the compaction, so output from before
|
||||
it is recorded nowhere locally and cannot be counted. Credits stay exact.
|
||||
- **With session-store rows** (CLI 1.0.8x), the rows replace the rollup and
|
||||
carry each request's own output, input, cache and `total_nano_aiu`, so the
|
||||
session is exact request by request, compactions included, and the leg's
|
||||
residual comes out at zero.
|
||||
- **ACP sessions often never shut down.** JetBrains AI Chat (and any other ACP
|
||||
host) runs `copilot --acp`, and quitting the IDE kills the process, so
|
||||
`events.jsonl` ends without a `session.shutdown`. Its store rows still make
|
||||
the session exact: tokens, cost and credits come from the rows. Measured on
|
||||
a real PyCharm session (CLI 1.0.85, gpt-5.6-terra and kimi-k3, 9 requests,
|
||||
no shutdown): cost equals GitHub's `total_nano_aiu` to the digit.
|
||||
- **Not read.** VS Code's `agentSessionData/*/session.db`,
|
||||
`globalStorage/agent-host.db` and `globalStorage/github.copilot-chat/session-store.db`.
|
||||
`session.db` `turn_usage` does hold per-interaction totals
|
||||
|
|
@ -101,8 +106,10 @@ where the `session.shutdown` rollup in `events.jsonl` is written only on clean
|
|||
shutdown (a crash loses the leg's input/cache accounting), lumps each leg into
|
||||
one per-model total, and resets its counters at in-session compaction. Rows are
|
||||
therefore authoritative for input / cache-read / cache-write / reasoning
|
||||
tokens, with real per-request timestamps; per-turn output stays owned by the
|
||||
`events.jsonl` `assistant.message` calls. `input_tokens` is cache-INCLUSIVE
|
||||
tokens, with real per-request timestamps. Each row also carries its own
|
||||
`output_tokens`. Older CLIs write output on the `assistant.message` too, so a
|
||||
row that pairs with a per-turn call carrying output serves with output 0 (the
|
||||
per-turn call owns it); otherwise the row owns it. `input_tokens` is cache-INCLUSIVE
|
||||
(input + cache_read + cache_write), the same convention as the rollups; the
|
||||
parser emits the uncached remainder. Override the path with
|
||||
`CODEBURN_COPILOT_SESSION_STORE_DB` (deliberately NOT in the env fingerprint —
|
||||
|
|
@ -160,7 +167,9 @@ see the #927 ruling in `src/session-cache.ts`).
|
|||
and cost count, but never api-call / model-call / turn weight. A store row
|
||||
pairs with its per-turn call by timestamp adjacency (2-minute window,
|
||||
computed over the full serve set); only unpaired rows — crash-recovered,
|
||||
store-only requests — count as calls.
|
||||
store-only requests — count as calls. The same pairing decides output
|
||||
ownership (above). A mis-pair can count one request's output twice, which
|
||||
needs an older-CLI crash row inside another request's 2-minute window.
|
||||
- **Failure semantics.** True absence (ENOENT, no sqlite driver, `no such
|
||||
table/column` from pre-store CLI builds) reads as absent — no source, rollups
|
||||
rule. Every other failure (locked, EACCES, corrupt, mid-replace) emits the
|
||||
|
|
|
|||
|
|
@ -279,7 +279,12 @@ import type { DateRange, ProjectSummary } from './types.js'
|
|||
// Settled days re-derive. Calls only rise, except a store row and its message
|
||||
// straddling midnight, which moves one call to the next day; copilot's
|
||||
// PENDING_REDERIVE contract moves to 56 so that day may shrink once.
|
||||
export const DAILY_CACHE_VERSION = 56
|
||||
// v57: Copilot session-store rows carry their own output where no per-turn call
|
||||
// does, so a session that never wrote session.shutdown (ACP hosts such as
|
||||
// JetBrains AI Chat) counts its output, and grok-4.6 prices at xAI's $2/M input
|
||||
// instead of Azure's $1.25/M. Output and cost only rise; call counts are
|
||||
// unchanged, so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
|
||||
export const DAILY_CACHE_VERSION = 57
|
||||
const MIN_SUPPORTED_VERSION = 28
|
||||
|
||||
/// Providers whose per-day CALL COUNT means something different at
|
||||
|
|
|
|||
|
|
@ -52,9 +52,9 @@ export type LongContextTier = {
|
|||
/// total), and Anthropic folds thinking into output the same way, so summing
|
||||
/// the two double-counts both the cost and the displayed output tokens. Copilot
|
||||
/// is the same case: its per-request token_details_json prices input/cache/output
|
||||
/// and nothing else, and its supplementary store-row/shutdown calls carry
|
||||
/// reasoningTokens with outputTokens 0 while the per-turn assistant.message call
|
||||
/// bills the full output, so adding reasoning on top bills it twice.
|
||||
/// and nothing else, and its store-row/shutdown calls carry reasoningTokens
|
||||
/// beside an output count that already includes them, so adding reasoning on
|
||||
/// top bills it twice.
|
||||
/// DSH TokenUsage includes reasoning in output too; see the pinned contract:
|
||||
/// https://github.com/deepseek-ai/deepseek-harness/blob/c291e7961a515f6d7af9304e7fd1d257929aef26/docs/subsystems/llm-streaming.md#tokenusage
|
||||
const REASONING_INCLUDED_IN_OUTPUT = new Set(['claude', 'codex', 'copilot', 'dsh'])
|
||||
|
|
@ -120,6 +120,12 @@ const BUILTIN_PRICE_OVERRIDES: Record<string, SnapshotEntry> = {
|
|||
'composer-2': [0.5e-6, 2.5e-6, 0.5e-6, 0.2e-6],
|
||||
'composer-1.5': [3.5e-6, 17.5e-6, 3.5e-6, 0.35e-6],
|
||||
'composer-1': [1.25e-6, 10e-6, 1.25e-6, 0.125e-6],
|
||||
// LiteLLM has no bare grok-4.6 row, so the stripped `azure_ai/grok-4.6` row
|
||||
// (Azure Foundry, $1.25/M input) claims the bare id ahead of `xai/grok-4.6`
|
||||
// in both the bundler and the live fetch. xAI's list price (docs.x.ai):
|
||||
// $2/M input, $6/M output, $0.50/M cached; GitHub Copilot bills grok-4.6 at
|
||||
// exactly these rates.
|
||||
'grok-4.6': [2e-6, 6e-6, null, 0.5e-6, null, { threshold: 200000, input: 4e-6, output: 12e-6, cacheWrite: null, cacheRead: 1e-6 }],
|
||||
}
|
||||
|
||||
// Assemble a ModelCosts, applying the cache-cost heuristics (write = 1.25x
|
||||
|
|
|
|||
|
|
@ -4006,6 +4006,7 @@ export async function parseProviderSources(
|
|||
storeCalls: Map<string, CopilotStamped[]>
|
||||
rollupLegs: Map<string, Array<CopilotStamped & { rawTs: string; compactedAtMs: number }>>
|
||||
supplementaryStoreKeys: Set<string>
|
||||
turnOwnedOutputKeys: Set<string>
|
||||
sessionProject: Map<string, string>
|
||||
storeProject: Map<string, string>
|
||||
nanRollupFallbackTs: Map<string, string>
|
||||
|
|
@ -4022,8 +4023,8 @@ export async function parseProviderSources(
|
|||
const storeKeys = new Set<string>()
|
||||
const storeCalls = new Map<string, CopilotStamped[]>()
|
||||
const rollupLegs = new Map<string, Array<CopilotStamped & { rawTs: string; compactedAtMs: number }>>()
|
||||
const storeRowIds = new Map<string, Array<{ ts: number; dedupKey: string }>>()
|
||||
const perTurnTs = new Map<string, number[]>()
|
||||
const storeRowIds = new Map<string, Array<{ ts: number; dedupKey: string; stamped: CopilotStamped }>>()
|
||||
const perTurnTs = new Map<string, Array<{ ts: number; hasOutput: boolean }>>()
|
||||
const sessionProject = new Map<string, string>()
|
||||
const storeProject = new Map<string, string>()
|
||||
// Stable timestamp fallbacks for rollup calls whose own stamp cannot
|
||||
|
|
@ -4064,7 +4065,7 @@ export async function parseProviderSources(
|
|||
if (project && !sessionProject.has(turn.sessionId)) sessionProject.set(turn.sessionId, project)
|
||||
if (!Number.isNaN(ts)) {
|
||||
const list = perTurnTs.get(aggKey) ?? []
|
||||
list.push(ts)
|
||||
list.push({ ts, hasOutput: c.usage.outputTokens > 0 })
|
||||
perTurnTs.set(aggKey, list)
|
||||
}
|
||||
continue
|
||||
|
|
@ -4073,9 +4074,9 @@ export async function parseProviderSources(
|
|||
const stamped: CopilotStamped = {
|
||||
ts,
|
||||
input: c.usage.inputTokens,
|
||||
// Rollups carry output only for legs with no per-turn output, and
|
||||
// store rows only for compaction requests, so this never meets the
|
||||
// per-turn calls' output.
|
||||
// Rollups carry output only for legs with no per-turn output. A
|
||||
// store row's output is zeroed below when its per-turn partner
|
||||
// carries output, so this never meets the per-turn calls' output.
|
||||
output: c.usage.outputTokens,
|
||||
cacheRead: c.usage.cacheReadInputTokens,
|
||||
cacheWrite: c.usage.cacheCreationInputTokens,
|
||||
|
|
@ -4092,11 +4093,12 @@ export async function parseProviderSources(
|
|||
// where it does not, this row is indistinguishable from a user
|
||||
// request and keeps the pre-label behaviour.
|
||||
const isCompaction = c.initiator === 'compaction'
|
||||
list.push(isCompaction ? { ...stamped, isCompaction: true } : stamped)
|
||||
if (isCompaction) stamped.isCompaction = true
|
||||
list.push(stamped)
|
||||
storeCalls.set(aggKey, list)
|
||||
if (!isCompaction) {
|
||||
const ids = storeRowIds.get(aggKey) ?? []
|
||||
ids.push({ ts, dedupKey: c.deduplicationKey })
|
||||
ids.push({ ts, dedupKey: c.deduplicationKey, stamped })
|
||||
storeRowIds.set(aggKey, ids)
|
||||
}
|
||||
if (c.project && !storeProject.has(turn.sessionId)) storeProject.set(turn.sessionId, c.project)
|
||||
|
|
@ -4119,20 +4121,30 @@ export async function parseProviderSources(
|
|||
// against a neighbor whose own row is missing and hide the crash
|
||||
// request's call weight. The residual ambiguity (a crash row landing
|
||||
// within the window of an unrecorded-row request) is a double-failure
|
||||
// conjunction and affects only call counts, never tokens.
|
||||
// conjunction.
|
||||
// Pairing also decides who owns a request's output: older CLIs write it on
|
||||
// the per-turn call AND the row, so a row paired with a per-turn call that
|
||||
// carries output serves with output 0. CLI 1.0.8x and ACP hosts write no
|
||||
// per-turn output, so their rows keep it — the only record of it when the
|
||||
// session never shut down.
|
||||
const PAIR_WINDOW_MS = 2 * 60 * 1000
|
||||
const supplementaryStoreKeys = new Set<string>()
|
||||
const turnOwnedOutputKeys = new Set<string>()
|
||||
for (const [aggKey, ids] of storeRowIds) {
|
||||
const callTs = perTurnTs.get(aggKey)
|
||||
if (!callTs?.length) continue
|
||||
ids.sort((a, b) => a.ts - b.ts)
|
||||
callTs.sort((a, b) => a - b)
|
||||
callTs.sort((a, b) => a.ts - b.ts)
|
||||
let i = 0
|
||||
let j = 0
|
||||
while (i < ids.length && j < callTs.length) {
|
||||
const d = ids[i]!.ts - callTs[j]!
|
||||
const d = ids[i]!.ts - callTs[j]!.ts
|
||||
if (Math.abs(d) <= PAIR_WINDOW_MS) {
|
||||
supplementaryStoreKeys.add(ids[i]!.dedupKey)
|
||||
if (callTs[j]!.hasOutput && ids[i]!.stamped.output > 0) {
|
||||
ids[i]!.stamped.output = 0
|
||||
turnOwnedOutputKeys.add(ids[i]!.dedupKey)
|
||||
}
|
||||
i++
|
||||
j++
|
||||
} else if (d < 0) {
|
||||
|
|
@ -4142,7 +4154,7 @@ export async function parseProviderSources(
|
|||
}
|
||||
}
|
||||
}
|
||||
copilotRecon = { storeKeys, storeCalls, rollupLegs, supplementaryStoreKeys, sessionProject, storeProject, nanRollupFallbackTs, sessionEarliestValidTs }
|
||||
copilotRecon = { storeKeys, storeCalls, rollupLegs, supplementaryStoreKeys, turnOwnedOutputKeys, sessionProject, storeProject, nanRollupFallbackTs, sessionEarliestValidTs }
|
||||
}
|
||||
const copilotServeProject = (sessionId: string): string | undefined =>
|
||||
copilotRecon
|
||||
|
|
@ -4188,8 +4200,13 @@ export async function parseProviderSources(
|
|||
}
|
||||
if (c.deduplicationKey.startsWith('copilot-store:')) {
|
||||
const project = copilotRecon.sessionProject.get(turn.sessionId)
|
||||
if (project && c.project !== project) {
|
||||
kept.push({ ...c, project })
|
||||
let served = c
|
||||
if (project && c.project !== project) served = { ...served, project }
|
||||
if (copilotRecon.turnOwnedOutputKeys.has(c.deduplicationKey)) {
|
||||
served = { ...served, usage: { ...served.usage, outputTokens: 0 } }
|
||||
}
|
||||
if (served !== c) {
|
||||
kept.push(served)
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2749,16 +2749,14 @@ function createOtelParser(
|
|||
// parseProviderSources replaces the covered (session, model) rollup calls
|
||||
// with the rows plus a residual for anything the rollup carried beyond them.
|
||||
//
|
||||
// The emitted calls mirror the shutdown-call contract exactly: input/cache/
|
||||
// reasoning only, output 0 — per-turn output (and its tools/userMessage
|
||||
// metadata) stays owned by the events.jsonl assistant.message calls, so
|
||||
// emitting output here would double-count it. The ONE exception is the
|
||||
// `initiator='compaction'` row: that request is the CLI summarizing its own
|
||||
// context, it has no assistant.message anywhere in events.jsonl, and nothing
|
||||
// else in the journal carries its output — so leaving it at 0 simply loses
|
||||
// those tokens (measured: a matched 30-session corpus reconciled to the
|
||||
// store's own row totals within -3,085 tokens, exactly one compaction row's
|
||||
// output). It is counted here because here is the only place it exists.
|
||||
// Each emitted call carries the row's own output_tokens. Older CLIs ALSO write
|
||||
// per-turn outputTokens on assistant.message, so where a row pairs with a
|
||||
// per-turn call that carries output, the serve-time reconciliation in
|
||||
// parseProviderSources serves the row with output 0 (decided there because
|
||||
// only the full serve set knows both sides). CLI 1.0.8x and ACP hosts write no
|
||||
// per-turn output, and an ACP session often never writes session.shutdown, so
|
||||
// the row is the only record of that output. The `initiator='compaction'` row
|
||||
// never pairs: it has no assistant.message anywhere in events.jsonl.
|
||||
// The per-request billing
|
||||
// metadata (total_nano_aiu, request_multiplier) is captured onto the cached
|
||||
// calls but not priced or displayed — that design is upstream #890; the
|
||||
|
|
@ -2799,10 +2797,9 @@ const SESSION_STORE_USAGE_SELECT = `SELECT ${SESSION_STORE_USAGE_COLUMNS}${SESSI
|
|||
// way back — the columns arrived in different CLI releases and a single
|
||||
// all-or-nothing enrichment would lose the older one.
|
||||
//
|
||||
// `output_tokens` rides on the SAME rung as `initiator` deliberately: it is
|
||||
// only ever read for a row the label identifies as a compaction, so a store
|
||||
// too old to have the label has no use for it either and must not be pushed
|
||||
// down another fallback rung for it.
|
||||
// `output_tokens` rides on the SAME rung as `initiator`: both arrived after the
|
||||
// billing columns, and a store without them serves rows with output 0, leaving
|
||||
// output to the per-turn calls and the rollup residual as before.
|
||||
const SESSION_STORE_USAGE_SELECTS = [
|
||||
`SELECT ${SESSION_STORE_USAGE_COLUMNS},
|
||||
e.total_nano_aiu, e.request_multiplier, e.initiator, e.output_tokens${SESSION_STORE_USAGE_FROM}`,
|
||||
|
|
@ -2963,10 +2960,7 @@ function createSessionStoreParser(
|
|||
numberOrZero(row.input_tokens) - cacheReadTokens - cacheWriteTokens
|
||||
)
|
||||
|
||||
// A compaction row's output has no assistant.message to own it, so
|
||||
// this row is the only place it can be counted. Every other row's
|
||||
// output IS owned by a per-turn call and stays excluded here.
|
||||
const outputTokens = row.initiator === 'compaction' ? numberOrZero(row.output_tokens) : 0
|
||||
const outputTokens = numberOrZero(row.output_tokens)
|
||||
|
||||
// Nothing this call would add over the per-turn events, so skip it to
|
||||
// avoid an empty $0 row.
|
||||
|
|
@ -3006,10 +3000,8 @@ function createSessionStoreParser(
|
|||
// metadata only, never as a cost line: it is a SUBSET of the row's
|
||||
// output_tokens (the row's own token_details_json prices exactly
|
||||
// input/cache_read/cache_write/output, no reasoning entry), and
|
||||
// output — reasoning included — is billed by the per-turn
|
||||
// assistant.message call. Pricing reasoning here would double-count.
|
||||
// `outputTokens` is non-zero only for the compaction row, whose
|
||||
// output no per-turn call bills, so it is priced exactly once.
|
||||
// output — reasoning included — is billed once, on whichever call
|
||||
// owns it (see the header). Pricing reasoning here would double-count.
|
||||
const costUSD = calculateCost(model, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens, 0)
|
||||
|
||||
yield {
|
||||
|
|
|
|||
|
|
@ -470,7 +470,10 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
|
|||
// tokenless-turns-v1: assistant.message events with no outputTokens field
|
||||
// (CLI 1.0.8x, VS Code agent host) count as calls, and their leg's shutdown
|
||||
// rollup carries output and totalNanoAiu.
|
||||
copilot: 'cli-shutdown-cost-v1-skills-source-provenance-v1-session-store-v3-chatsession-otel-skills-v1-otel-trace-metadata-once-v1-transcript-unknown-usage-v1-otel-workspace-project-v1-journal-request-input-v1-tokenless-turns-v1',
|
||||
// store-row-output-v1: every session-store row carries its own
|
||||
// output_tokens; serve time zeroes it where a per-turn call owns the output.
|
||||
// Keys are unchanged, so the re-parse replaces cached output-0 rows in place.
|
||||
copilot: 'cli-shutdown-cost-v1-skills-source-provenance-v1-session-store-v3-chatsession-otel-skills-v1-otel-trace-metadata-once-v1-transcript-unknown-usage-v1-otel-workspace-project-v1-journal-request-input-v1-tokenless-turns-v1-store-row-output-v1',
|
||||
// authoritative-usage-v4: persist one Grok session call from top-level
|
||||
// authoritative totals, use modelUsage only for priced attribution, clamp
|
||||
// reasoning per record, and label mixed sessions estimated.
|
||||
|
|
|
|||
|
|
@ -170,24 +170,19 @@ describe('copilot VS Code agent-host sessions', () => {
|
|||
expect(calls.reduce((s, c) => s + c.usage.inputTokens + c.usage.outputTokens + c.costUSD, 0)).toBe(0)
|
||||
})
|
||||
|
||||
// CLI 1.0.82: tokenless messages plus session-store rows, which carry output
|
||||
// only for compaction requests. The leg's output must serve via the residual.
|
||||
it.skipIf(!isSqliteAvailable())('CLI store session: output comes from the rollup residual, once', async () => {
|
||||
const dir = fileURLToPath(new URL('./fixtures/copilot/cli-store-session/', import.meta.url))
|
||||
const sid = 'e61538c6-6e3e-4607-b468-b38972f2ba35'
|
||||
const rows = JSON.parse(await readFile(join(dir, 'store-rows.json'), 'utf-8')) as Array<Record<string, string | number>>
|
||||
function writeStore(sid: string, cwd: string, rows: Array<Record<string, string | number | null>>): string {
|
||||
const dbPath = join(tmp, 'session-store.db')
|
||||
const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite') as {
|
||||
DatabaseSync: new (path: string) => { exec(sql: string): void; prepare(sql: string): { run(...p: unknown[]): void }; close(): void }
|
||||
}
|
||||
const db = new DatabaseSync(dbPath)
|
||||
db.exec(`
|
||||
CREATE TABLE sessions (id TEXT PRIMARY KEY, cwd TEXT, repository TEXT, created_at TEXT);
|
||||
CREATE TABLE assistant_usage_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, model TEXT,
|
||||
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, cwd TEXT, repository TEXT, created_at TEXT);
|
||||
CREATE TABLE IF NOT EXISTS assistant_usage_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, model TEXT,
|
||||
input_tokens INTEGER, output_tokens INTEGER, cache_read_tokens INTEGER, cache_write_tokens INTEGER,
|
||||
reasoning_tokens INTEGER, total_nano_aiu INTEGER, request_multiplier REAL, initiator TEXT, created_at TEXT);
|
||||
`)
|
||||
db.prepare('INSERT INTO sessions (id, cwd) VALUES (?, ?)').run(sid, '/home/dev/codeburn/app')
|
||||
db.prepare('INSERT INTO sessions (id, cwd) VALUES (?, ?)').run(sid, cwd)
|
||||
const insert = db.prepare(`INSERT INTO assistant_usage_events (session_id, model, input_tokens, output_tokens, cache_read_tokens,
|
||||
cache_write_tokens, reasoning_tokens, total_nano_aiu, request_multiplier, initiator, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)`)
|
||||
for (const r of rows) {
|
||||
|
|
@ -195,19 +190,128 @@ describe('copilot VS Code agent-host sessions', () => {
|
|||
r['reasoning_tokens'], r['total_nano_aiu'], r['request_multiplier'], r['initiator'], r['created_at'])
|
||||
}
|
||||
db.close()
|
||||
|
||||
const lines = (await readFile(join(dir, 'events.jsonl'), 'utf-8')).split('\n').filter(l => l.trim())
|
||||
vi.stubEnv('CODEBURN_COPILOT_SESSION_STORE_DB', dbPath)
|
||||
const { projects, calls } = await serve(lines, sid, '/home/dev/codeburn/app')
|
||||
return dbPath
|
||||
}
|
||||
|
||||
// Rollup ground truth: inputTokens 310,703 cache-inclusive, output 3,254.
|
||||
const usage = (k: keyof (typeof calls)[number]['usage']) => calls.reduce((s, c) => s + c.usage[k], 0)
|
||||
expect(behavioralCallCount(calls)).toBe(11)
|
||||
type ServedCall = Awaited<ReturnType<typeof serve>>['calls'][number]
|
||||
|
||||
// GitHub's own per-request charge is total_nano_aiu / 1e11 USD at list
|
||||
// rates, so a model whose tokens are all counted and correctly priced costs
|
||||
// exactly its rows' nanoAiu.
|
||||
function expectCostEqualsNanoAiu(calls: ServedCall[], rows: Array<Record<string, string | number | null>>): void {
|
||||
const models = new Set(rows.map(r => r['model'] as string))
|
||||
for (const model of models) {
|
||||
const cost = calls.filter(c => c.model === model).reduce((s, c) => s + c.costUSD, 0)
|
||||
const nano = rows.filter(r => r['model'] === model).reduce((s, r) => s + (r['total_nano_aiu'] as number), 0)
|
||||
expect({ model, cost: Number(cost.toFixed(12)) }).toEqual({ model, cost: Number((nano / 1e11).toFixed(12)) })
|
||||
}
|
||||
}
|
||||
|
||||
// CLI 1.0.82: tokenless messages plus session-store rows. Rollup ground
|
||||
// truth: inputTokens 310,703 cache-inclusive, output 3,254, 9.334625 credits.
|
||||
const STORE_SID = 'e61538c6-6e3e-4607-b468-b38972f2ba35'
|
||||
const STORE_CWD = '/home/dev/codeburn/app'
|
||||
const storeDir = fileURLToPath(new URL('./fixtures/copilot/cli-store-session/', import.meta.url))
|
||||
const storeRows = async () => JSON.parse(await readFile(join(storeDir, 'store-rows.json'), 'utf-8')) as Array<Record<string, string | number>>
|
||||
const storeLines = async () => (await readFile(join(storeDir, 'events.jsonl'), 'utf-8')).split('\n').filter(l => l.trim())
|
||||
|
||||
async function serveStore(lines: string[]) {
|
||||
const rows = await storeRows()
|
||||
writeStore(STORE_SID, STORE_CWD, rows)
|
||||
const served = await serve(lines, STORE_SID, STORE_CWD)
|
||||
const usage = (k: keyof ServedCall['usage']) => served.calls.reduce((s, c) => s + c.usage[k], 0)
|
||||
expect(behavioralCallCount(served.calls)).toBe(11)
|
||||
expect(usage('outputTokens')).toBe(3_254)
|
||||
expect(usage('inputTokens')).toBe(82)
|
||||
expect(usage('cacheReadInputTokens')).toBe(270_680)
|
||||
expect(usage('cacheCreationInputTokens')).toBe(39_941)
|
||||
expect(calls.reduce((s, c) => s + c.costUSD, 0)).toBeCloseTo(calculateCost('claude-haiku-4.5', 82, 3_254, 39_941, 270_680, 0), 12)
|
||||
expect(copilotCreditSpend(projects)).toMatchObject({ spentCredits: 9.334625, creditRatedCalls: 11, creditUnratedCalls: 0 })
|
||||
expect(served.calls.reduce((s, c) => s + c.costUSD, 0)).toBeCloseTo(calculateCost('claude-haiku-4.5', 82, 3_254, 39_941, 270_680, 0), 12)
|
||||
expectCostEqualsNanoAiu(served.calls, rows)
|
||||
expect(copilotCreditSpend(served.projects)).toMatchObject({ spentCredits: 9.334625, creditRatedCalls: 11, creditUnratedCalls: 0 })
|
||||
return served
|
||||
}
|
||||
|
||||
it.skipIf(!isSqliteAvailable())('store rows + shutdown: rows carry the output, the residual carries none', async () => {
|
||||
const { calls } = await serveStore(await storeLines())
|
||||
expect(calls.filter(c => c.deduplicationKey.includes(':shutdown-residual:'))).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(!isSqliteAvailable())('store rows, no shutdown: exact from the rows alone', async () => {
|
||||
await serveStore((await storeLines()).filter(l => JSON.parse(l).type !== 'session.shutdown'))
|
||||
})
|
||||
|
||||
it.skipIf(!isSqliteAvailable())('older CLI with per-turn outputTokens and store rows: output counted once', async () => {
|
||||
const out = (await storeRows()).map(r => r['output_tokens'] as number)
|
||||
let n = 0
|
||||
const lines = (await storeLines()).map(l => {
|
||||
const e = JSON.parse(l)
|
||||
if (e.type !== 'assistant.message') return l
|
||||
e.data.outputTokens = out[n++]
|
||||
return JSON.stringify(e)
|
||||
})
|
||||
expect(n).toBe(11)
|
||||
const { calls } = await serveStore(lines)
|
||||
expect(calls.filter(c => c.deduplicationKey.startsWith('copilot-store:')).every(c => c.usage.outputTokens === 0)).toBe(true)
|
||||
})
|
||||
|
||||
// Synthetic split of the real session into two legs: a shutdown after the
|
||||
// sixth request carries the cumulative totals of rows 1-6.
|
||||
it.skipIf(!isSqliteAvailable())('resumed two-leg session: exact with or without the second leg\'s shutdown', async () => {
|
||||
const rows = await storeRows()
|
||||
const first = rows.slice(0, 6)
|
||||
const total = (k: string) => first.reduce((s, r) => s + (r[k] as number), 0)
|
||||
const legShutdown = JSON.stringify({
|
||||
type: 'session.shutdown', timestamp: '2026-08-31T10:02:40.000Z',
|
||||
data: { shutdownType: 'routine', modelMetrics: { 'claude-haiku-4.5': {
|
||||
usage: { inputTokens: total('input_tokens'), outputTokens: total('output_tokens'), cacheReadTokens: total('cache_read_tokens'),
|
||||
cacheWriteTokens: total('cache_write_tokens'), reasoningTokens: total('reasoning_tokens') },
|
||||
totalNanoAiu: total('total_nano_aiu') } } },
|
||||
})
|
||||
const lines = await storeLines()
|
||||
const resume = lines.findIndex(l => JSON.parse(l).timestamp > '2026-08-31T10:02:40.000Z')
|
||||
const twoLegs = [...lines.slice(0, resume), legShutdown, ...lines.slice(resume)]
|
||||
await serveStore(twoLegs)
|
||||
await rm(join(tmp, 'session-store.db'), { force: true })
|
||||
await rm(join(tmp, 'cache'), { recursive: true, force: true })
|
||||
await serveStore(twoLegs.filter((l, i) => i <= resume || JSON.parse(l).type !== 'session.shutdown'))
|
||||
})
|
||||
|
||||
// Real per-request rows (numbers only) from a PyCharm AI Chat session over
|
||||
// ACP (`copilot --acp`, CLI 1.0.85) that never wrote session.shutdown,
|
||||
// plus the three grok-4.6 rows of a JetBrains plugin session. Each model's
|
||||
// cost must equal GitHub's charge for its rows.
|
||||
it.skipIf(!isSqliteAvailable())('ACP session with no shutdown: every model costs exactly its nanoAiu', async () => {
|
||||
const sid = '760f62f7-0000-4000-8000-000000000000'
|
||||
const cols = ['model', 'input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens', 'reasoning_tokens', 'total_nano_aiu', 'initiator', 'created_at'] as const
|
||||
const rows = ([
|
||||
['gpt-5.6-terra', 15109, 201, 0, 15106, 39, 4018300000, 'user', '2026-10-06T16:13:10.192Z'],
|
||||
['gpt-5.6-terra', 15594, 134, 15106, 485, 11, 584770000, 'agent', '2026-10-06T16:13:15.509Z'],
|
||||
['gpt-5.6-terra', 15967, 118, 15591, 373, 77, 547270000, 'agent', '2026-10-06T16:14:54.382Z'],
|
||||
['gpt-5.6-terra', 16125, 69, 15964, 158, 0, 442180000, 'agent', '2026-10-06T16:15:18.027Z'],
|
||||
['kimi-k3', 17124, 124, 0, 0, 19, 5323200000, 'user', '2026-10-06T16:15:32.820Z'],
|
||||
['kimi-k3', 27977, 257, 4096, 0, 0, 7672680000, 'agent', '2026-10-06T16:15:40.575Z'],
|
||||
['kimi-k3', 28324, 188, 27976, 0, 0, 1225680000, 'agent', '2026-10-06T16:16:02.145Z'],
|
||||
['kimi-k3', 28562, 102, 28323, 0, 0, 1074390000, 'agent', '2026-10-06T16:16:19.210Z'],
|
||||
['kimi-k3', 28722, 66, 28561, 0, 0, 1004130000, 'agent', '2026-10-06T16:16:49.485Z'],
|
||||
['grok-4.6', 28321, 876, 0, 0, 532, 6189800000, 'user', '2026-10-06T16:17:23.490Z'],
|
||||
['grok-4.6', 29292, 29, 28288, 0, 5, 1632600000, 'agent', '2026-10-06T16:17:25.372Z'],
|
||||
['grok-4.6', 29408, 41, 29184, 0, 0, 1528600000, 'agent', '2026-10-06T16:17:35.539Z'],
|
||||
] as const).map(r => ({ ...Object.fromEntries(cols.map((c, i) => [c, r[i]])), request_multiplier: 1 }))
|
||||
const ev = (type: string, timestamp: string, data: Record<string, unknown>) => JSON.stringify({ type, timestamp, data })
|
||||
const lines = [ev('session.start', '2026-10-06T16:13:02.845Z', { producer: 'copilot-agent', copilotVersion: '1.0.85' })]
|
||||
rows.forEach((r, i) => {
|
||||
const at = new Date(Date.parse(r.created_at) + 3).toISOString()
|
||||
if (r.model !== rows[i - 1]?.model) lines.push(ev('session.model_change', r.created_at, { newModel: r.model }))
|
||||
lines.push(ev('assistant.message', at, { messageId: `m${i}`, model: r.model, toolRequests: [] }))
|
||||
})
|
||||
lines.push(ev('session.usage_checkpoint', '2026-10-06T16:17:35.600Z', { totalNanoAiu: 31_243_600_000, totalPremiumRequests: 3 }))
|
||||
|
||||
writeStore(sid, '/home/dev/pycharm-demo', rows)
|
||||
const { projects, calls } = await serve(lines, sid, '/home/dev/pycharm-demo')
|
||||
expect(behavioralCallCount(calls)).toBe(12)
|
||||
expect(calls.reduce((s, c) => s + c.usage.outputTokens, 0)).toBe(522 + 737 + 946)
|
||||
expectCostEqualsNanoAiu(calls, rows)
|
||||
expect(copilotCreditSpend(projects)).toMatchObject({ spentCredits: 31.2436, creditRatedCalls: 12, creditUnratedCalls: 0 })
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -422,9 +422,20 @@ describe('getModelCosts', () => {
|
|||
|
||||
describe('grok-4.6 prompt tier', () => {
|
||||
it('uses the low tier below 200000 prompt tokens', () => {
|
||||
// Base input is 1.25e-6 since LiteLLM's 2026-09 reprice (was 2e-6); the
|
||||
// tier rates above 200k are unchanged, so only this literal moved.
|
||||
expect(calculateCost('grok-4.6', 100_000, 10_000, 0, 99_999, 0)).toBeCloseTo(0.2349995, 12)
|
||||
expect(calculateCost('grok-4.6', 100_000, 10_000, 0, 99_999, 0)).toBeCloseTo(0.3099995, 12)
|
||||
})
|
||||
|
||||
// The snapshot's bare `grok-4.6` row is Azure Foundry's ($1.25/M input),
|
||||
// stripped from `azure_ai/grok-4.6`; xAI lists $2/M, which is what GitHub
|
||||
// Copilot bills (three real requests: 29,549 in, 946 out, 57,472 cached).
|
||||
it('prices at xAI list rates, matching GitHub Copilot\'s charge', () => {
|
||||
expect(calculateCost('grok-4.6', 29_549, 946, 0, 57_472, 0)).toBeCloseTo(9_351_000_000 / 1e11, 12)
|
||||
const xai = getModelCosts('xai/grok-4.6')!
|
||||
expect(getModelCosts('grok-4.6')).toMatchObject({
|
||||
inputCostPerToken: xai.inputCostPerToken,
|
||||
outputCostPerToken: xai.outputCostPerToken,
|
||||
cacheReadCostPerToken: xai.cacheReadCostPerToken,
|
||||
})
|
||||
})
|
||||
|
||||
it('uses the high tier for every token at exactly 200000 prompt tokens', () => {
|
||||
|
|
|
|||
|
|
@ -1971,9 +1971,9 @@ describe.skipIf(!isSqliteAvailable())('(c5) compaction-initiated store rows', ()
|
|||
.flatMap(t => t.assistantCalls).filter(c => c.deduplicationKey.startsWith('copilot-store:'))
|
||||
expect(storeCalls).toHaveLength(2)
|
||||
expect(new Set(storeCalls.map(c => c.deduplicationKey)).size).toBe(2)
|
||||
// Both rows' prompt sides survive; only the labelled one contributes output.
|
||||
// Both rows survive whole: neither has a per-turn call carrying output.
|
||||
expect(storeCalls.reduce((s, c) => s + c.usage.inputTokens, 0)).toBe((272139 - 267005) + 6272)
|
||||
expect(totalOutput(projects)).toBe(3085)
|
||||
expect(totalOutput(projects)).toBe(400 + 3085)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue