refactor(usage): transcript readers come from their drivers (#17576)

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-09 15:26:18 -07:00
1 parent 507361bc73
commit e5dca2332f
34 files changed
+1731 -1411

No files matched your search

@@ -34,6 +34,7 @@ import {
type ClaudeAdapterV2DriverEnv,
} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import { ProviderDriverError } from "../Errors.ts";
import { claudeUsageReader } from "./claudeUsage.ts";
import { makeClaudeScopedLimitNames } from "../claudeUsageLimits.ts";
import * as ClaudeResetCredits from "../claudeResetCredits.ts";
import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
@@ -107,7 +108,7 @@ export type ClaudeDriverEnv =
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig;
export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.Path> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "Claude",
@@ -115,6 +116,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
},
configSchema: ClaudeSettings,
defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),
usage: claudeUsageReader,
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -73,6 +73,7 @@ import {
resolveCodexHomeLayout,
} from "./CodexHomeLayout.ts";
import { makeManagedCodexProvider } from "./CodexManagedProvider.ts";
import { codexUsageReader } from "./codexUsage.ts";
import * as CodexInstallation from "../CodexInstallation.ts";
import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
@@ -125,7 +126,7 @@ export type CodexDriverEnv =
| ServerEnvironment.ServerEnvironmentIdentity
| CodexInstallation.CodexInstallation;
export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv, Path.Path> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "Codex",
@@ -133,6 +134,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
},
configSchema: CodexSettings,
defaultConfig: (): CodexSettings => decodeCodexSettings({}),
usage: codexUsageReader,
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
if (config.setupMode === "managed")
@@ -0,0 +1,74 @@
import { describe, expect, it } from "@effect/vitest";
import { parseClaudeLine } from "./claudeUsage.ts";
/** Shaped after a real Claude Code assistant record. */
function claudeLine(overrides: {
messageId: string;
contentType: string;
model?: string;
outputTokens?: number;
speed?: string;
}): string {
return JSON.stringify({
type: "assistant",
timestamp: "2026-08-07T04:05:13.944Z",
sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0",
cwd: "/home/theo/project",
message: {
id: overrides.messageId,
role: "assistant",
model: overrides.model ?? "claude-fable-5",
content: [{ type: overrides.contentType }],
usage: {
input_tokens: 2,
cache_creation_input_tokens: 66818,
cache_read_input_tokens: 1000,
output_tokens: overrides.outputTokens ?? 286,
...(overrides.speed === undefined ? {} : { speed: overrides.speed }),
},
},
});
}
describe("parseClaudeLine", () => {
it("extracts token totals and a dedupe key", () => {
const record = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" }));
expect(record).not.toBeNull();
expect(record?.provider).toBe("claude");
expect(record?.model).toBe("claude-fable-5");
expect(record?.totals).toEqual({
uncachedInputTokens: 2,
cachedInputTokens: 1000,
cacheCreationTokens: 66818,
outputTokens: 286,
reasoningTokens: 0,
});
expect(record?.dedupeKey).toBe("msg_1:");
expect(record?.speed).toBe("standard");
});
it("marks fast-mode requests", () => {
const line = (speed: string) =>
parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text", speed }));
expect(line("fast")?.speed).toBe("fast");
expect(line("standard")?.speed).toBe("standard");
});
it("gives every content block of one message the same dedupe key", () => {
// T3 Code writes one record per content block, each repeating the parent
// message's full usage. Summing them would overcount ~2.4x on real data.
const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" }));
const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" }));
expect(text?.dedupeKey).toBe(toolUse?.dedupeKey);
expect(text?.totals).toEqual(toolUse?.totals);
});
it("ignores records that are not assistant messages", () => {
expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull();
expect(parseClaudeLine("not json")).toBeNull();
});
});
@@ -0,0 +1,120 @@
/**
* Usage history for Claude Code: the transcript format of its
* `<home>/projects/**.jsonl` session files and where each instance keeps them.
*
* @module provider/Drivers/claudeUsage
*/
import * as NodeOS from "node:os";
import type { ClaudeSettings } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Path from "effect/Path";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import {
parseTimestampMs,
tokenCount,
type ProviderUsageReader,
type TranscriptUsageFormat,
type UsageRecord,
} from "@t3tools/provider-core/server/usage";
/**
* Parses one line of a Claude Code transcript.
*
* T3 Code writes one record per assistant *content block*, and every one of
* those records repeats the same complete `usage` object for the parent
* message. Summing them overcounts by roughly 2.4x on a real workload, so the
* caller must drop repeats by `dedupeKey` and keep the first.
*/
export function parseClaudeLine(line: string): UsageRecord | null {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
return null;
}
return parseClaudeRecord(parsed);
}
function parseClaudeRecord(parsed: unknown): UsageRecord | null {
if (typeof parsed !== "object" || parsed === null) return null;
const record = parsed as Record<string, unknown>;
if (record["type"] !== "assistant") return null;
const message = record["message"];
if (typeof message !== "object" || message === null) return null;
const messageRecord = message as Record<string, unknown>;
const usage = messageRecord["usage"];
if (typeof usage !== "object" || usage === null) return null;
const usageRecord = usage as Record<string, unknown>;
const timestampMs = parseTimestampMs(record["timestamp"]);
if (timestampMs === null) return null;
const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : "";
if (model.length === 0) return null;
const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null;
const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null;
// Matches ccusage: prefer the message/request pair, fall back to whichever
// half exists. Records with neither cannot be de-duplicated.
const dedupeKey =
messageId === null && requestId === null ? null : `${messageId ?? ""}:${requestId ?? ""}`;
const cost = record["costUSD"];
return {
provider: "claude",
timestampMs,
model,
sessionId: typeof record["sessionId"] === "string" ? record["sessionId"] : "",
totals: {
uncachedInputTokens: tokenCount(usageRecord["input_tokens"]),
cachedInputTokens: tokenCount(usageRecord["cache_read_input_tokens"]),
cacheCreationTokens: tokenCount(usageRecord["cache_creation_input_tokens"]),
outputTokens: tokenCount(usageRecord["output_tokens"]),
// Anthropic folds thinking tokens into output and does not break them out.
reasoningTokens: 0,
},
reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null,
speed: usageRecord["speed"] === "fast" ? "fast" : "standard",
dedupeKey,
};
}
const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] =>
record === null ? [] : [record];
export const claudeUsageFormat: TranscriptUsageFormat<void> = {
// Keeps the dedupe and cost metadata. The `usage` subtree keeps future token fields.
selectFields: {
type: true,
timestamp: true,
requestId: true,
sessionId: true,
costUSD: true,
message: { id: true, model: true, usage: true },
},
mightCarryUsage: (line) => line.includes('"usage"'),
parseLine: (line) => orEmpty(parseClaudeLine(line)),
parseProjected: (projected) => orEmpty(parseClaudeRecord(projected)),
};
export const claudeUsageReader: ProviderUsageReader<ClaudeSettings, Path.Path> = {
kind: "transcripts",
provider: "claude",
format: claudeUsageFormat,
directories: Effect.fn("claudeUsageReader.directories")(function* ({ config, environment }) {
// An undecodable config has no trustworthy home to read.
if (config === undefined) return [];
const path = yield* Path.Path;
const configured = config.homePath.trim();
const home = configured
? expandHomePath(configured)
: environment.CLAUDE_CONFIG_DIR?.trim() || path.join(NodeOS.homedir(), ".claude");
return [{ dir: path.resolve(home, "projects") }];
}),
};
@@ -0,0 +1,193 @@
import { describe, expect, it } from "@effect/vitest";
import { initialCodexScanState, parseCodexLine } from "./codexUsage.ts";
describe("parseCodexLine", () => {
const sessionMeta = JSON.stringify({
type: "session_meta",
timestamp: "2026-08-01T05:17:41.289Z",
payload: { type: "session_meta", id: "019fbbc1-b12c-7360-a685-28c181f0025f" },
});
const turnContext = JSON.stringify({
type: "turn_context",
timestamp: "2026-08-01T05:17:42.694Z",
payload: { type: "turn_context", model: "gpt-5.6-sol" },
});
const tokenCount = (inputTokens: number, cached: number, output: number, reasoning: number) =>
JSON.stringify({
type: "event_msg",
timestamp: "2026-08-01T05:17:49.919Z",
payload: {
type: "token_count",
info: {
last_token_usage: {
input_tokens: inputTokens,
cached_input_tokens: cached,
cache_write_input_tokens: 0,
output_tokens: output,
reasoning_output_tokens: reasoning,
},
},
},
});
it("attributes usage to the model from the preceding turn context", () => {
const state = initialCodexScanState();
parseCodexLine(sessionMeta, state);
parseCodexLine(turnContext, state);
const record = parseCodexLine(tokenCount(19239, 11008, 299, 116), state);
expect(record?.provider).toBe("codex");
expect(record?.model).toBe("gpt-5.6-sol");
expect(record?.sessionId).toBe("019fbbc1-b12c-7360-a685-28c181f0025f");
// Codex reports input_tokens inclusive of the cached portion.
expect(record?.totals.uncachedInputTokens).toBe(19239 - 11008);
expect(record?.totals.cachedInputTokens).toBe(11008);
expect(record?.totals.reasoningTokens).toBe(116);
});
it("skips a repeated token_count so deltas are not double counted", () => {
const state = initialCodexScanState();
parseCodexLine(turnContext, state);
const first = parseCodexLine(tokenCount(100, 0, 10, 0), state);
const repeat = parseCodexLine(tokenCount(100, 0, 10, 0), state);
expect(first).not.toBeNull();
expect(repeat).toBeNull();
});
it("drops usage that arrives before any model is known", () => {
const state = initialCodexScanState();
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
});
it("does not let a pre-model event poison the duplicate signature", () => {
// A token_count before its turn_context is dropped; the identical event
// re-emitted once the model is known must still be counted.
const state = initialCodexScanState();
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
parseCodexLine(turnContext, state);
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
});
it("carries the service tier from the latest thread settings", () => {
const settings = (thread_settings: Record<string, unknown>) =>
JSON.stringify({
type: "event_msg",
timestamp: "2026-08-01T05:17:42.000Z",
payload: { type: "thread_settings_applied", thread_settings },
});
const state = initialCodexScanState();
parseCodexLine(turnContext, state);
const speedAfter = (line: string, output: number) => {
parseCodexLine(line, state);
return parseCodexLine(tokenCount(100, 0, output, 0), state)?.speed;
};
expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)?.speed).toBe("standard");
expect(speedAfter(settings({ service_tier: "ultrafast" }), 2)).toBe("ultrafast");
expect(speedAfter(settings({ service_tier: "priority" }), 3)).toBe("fast");
// Codex omits the field when no tier was requested.
expect(speedAfter(settings({ model: "gpt-6-astra" }), 4)).toBe("standard");
});
// A forked/subagent rollout opens with the parent's history copied in and
// every line re-stamped to the fork instant, then the ancestors' session
// metas. Counting those again multiplied usage ~1.85x on real data (#5758).
describe("forked rollouts", () => {
const meta = (overrides: {
id: string;
timestamp: string;
forkedFromId?: string;
spawnParentId?: string;
}) =>
JSON.stringify({
type: "session_meta",
timestamp: overrides.timestamp,
payload: {
type: "session_meta",
id: overrides.id,
...(overrides.forkedFromId === undefined
? {}
: { forked_from_id: overrides.forkedFromId }),
...(overrides.spawnParentId === undefined
? {}
: {
source: {
subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
},
}),
},
});
const stamped = (timestamp: string, line: string) => {
const parsed = JSON.parse(line) as { timestamp: string };
parsed.timestamp = timestamp;
return JSON.stringify(parsed);
};
it("keeps the child session id over copied ancestor metas", () => {
const state = initialCodexScanState();
parseCodexLine(meta({ id: "child", timestamp: "2026-08-01T05:00:00.000Z" }), state);
parseCodexLine(meta({ id: "parent", timestamp: "2026-08-01T05:00:00.000Z" }), state);
parseCodexLine(turnContext, state);
const record = parseCodexLine(tokenCount(100, 0, 10, 0), state);
expect(record?.sessionId).toBe("child");
});
it("drops the re-stamped copied burst and keeps the first real event", () => {
const state = initialCodexScanState();
const forkInstant = "2026-08-01T05:00:00.000Z";
parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
parseCodexLine(stamped(forkInstant, turnContext), state);
// Copied history: written in one burst at the fork instant.
expect(
parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
).toBeNull();
expect(
parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state),
).toBeNull();
// The child's first genuine turn lands seconds later and must count.
const real = parseCodexLine(
stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)),
state,
);
expect(real).not.toBeNull();
expect(real?.totals.outputTokens).toBe(30);
// Suppression never restarts, even for closely spaced later events.
const next = parseCodexLine(
stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)),
state,
);
expect(next).not.toBeNull();
});
it("recognizes subagent spawns without forked_from_id", () => {
const state = initialCodexScanState();
const spawnInstant = "2026-08-01T05:00:00.000Z";
parseCodexLine(
meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
state,
);
parseCodexLine(stamped(spawnInstant, turnContext), state);
expect(
parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
).toBeNull();
});
it("does not suppress anything in a rollout that is not a fork", () => {
const state = initialCodexScanState();
parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
const record = parseCodexLine(
stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
state,
);
expect(record).not.toBeNull();
});
});
});
@@ -0,0 +1,265 @@
/**
* Usage history for Codex: the rollout format of `<home>/sessions/**.jsonl`
* and where each instance's shared home keeps them.
*
* @module provider/Drivers/codexUsage
*/
import type { CodexSettings } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
parseTimestampMs,
tokenCount,
totalTokens,
type ProviderUsageReader,
type TranscriptUsageFormat,
type UsageRecord,
type UsageSpeed,
} from "@t3tools/provider-core/server/usage";
import type { UsageTokenTotals } from "@t3tools/contracts";
import { resolveCodexHomeLayout } from "./CodexHomeLayout.ts";
/**
* Rolling state for a single Codex rollout file.
*
* Codex `token_count` events carry no model or service tier, so both are
* carried forward: the model from the most recent `turn_context`, the tier from
* the most recent `thread_settings_applied`. Sessions that switch either
* mid-run attribute correctly from the switch onward.
*
* Persisted in the scan cache at each resume point. The field order is the
* stored JSON's, so keep it stable.
*/
export const CodexScanState = Schema.Struct({
model: Schema.mutableKey(Schema.String),
speed: Schema.mutableKey(Schema.Literals(["standard", "fast", "ultrafast"])),
sessionId: Schema.mutableKey(Schema.String),
lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)),
sawSessionMeta: Schema.mutableKey(Schema.Boolean),
/** While true, leading usage events are re-stamped copies of parent history. */
suppressingForkCopies: Schema.mutableKey(Schema.Boolean),
forkCopyAnchorMs: Schema.mutableKey(Schema.Finite),
});
export type CodexScanState = typeof CodexScanState.Type;
export function initialCodexScanState(): CodexScanState {
return {
model: "",
speed: "standard",
sessionId: "",
lastUsageSignature: null,
sawSessionMeta: false,
suppressingForkCopies: false,
forkCopyAnchorMs: 0,
};
}
/**
* A forked or subagent rollout opens with the parent's full history copied in,
* every line re-stamped to the fork instant. Those copies are written in one
* synchronous burst (observed gaps 0-40ms), while the child's first genuine
* usage event only lands after a real model turn (observed 5s+). One second of
* separation splits the two cleanly; `ccusage` uses the same threshold.
*/
const FORK_COPY_MAX_GAP_MS = 1000;
/** Whether a `session_meta` payload marks the rollout as a fork or subagent. */
function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
if (typeof payload["forked_from_id"] === "string") return true;
const source = payload["source"];
if (typeof source !== "object" || source === null) return false;
const subagent = (source as Record<string, unknown>)["subagent"];
if (typeof subagent !== "object" || subagent === null) return false;
const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
if (typeof spawn !== "object" || spawn === null) return false;
return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
}
/**
* Feeds one line of a Codex rollout into `state`, returning a record when the
* line was a usage event.
*
* Deltas come from `last_token_usage`. Summing those across a session
* reconciles with the session's final `total_token_usage`, provided
* consecutive duplicate events are dropped, which this does.
*/
export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
return null;
}
return parseCodexRecord(parsed, state);
}
function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | null {
if (typeof parsed !== "object" || parsed === null) return null;
const record = parsed as Record<string, unknown>;
const payload = record["payload"];
if (typeof payload !== "object" || payload === null) return null;
const payloadRecord = payload as Record<string, unknown>;
const payloadType = payloadRecord["type"];
if (record["type"] === "session_meta") {
// Only the first meta describes this file's own session. A forked rollout
// repeats the ancestors' metas right after it; letting those through would
// reassign every subsequent record to an ancestor session.
if (state.sawSessionMeta) return null;
state.sawSessionMeta = true;
const id = payloadRecord["id"] ?? payloadRecord["session_id"];
if (typeof id === "string") state.sessionId = id;
const metaTimestampMs = parseTimestampMs(record["timestamp"]);
if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
state.suppressingForkCopies = true;
state.forkCopyAnchorMs = metaTimestampMs;
}
return null;
}
if (record["type"] === "turn_context") {
if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
return null;
}
if (payloadType === "thread_settings_applied") {
const settings = payloadRecord["thread_settings"];
if (typeof settings === "object" && settings !== null) {
state.speed = codexSpeed((settings as Record<string, unknown>)["service_tier"]);
}
return null;
}
if (payloadType !== "token_count") return null;
const info = payloadRecord["info"];
if (typeof info !== "object" || info === null) return null;
const last = (info as Record<string, unknown>)["last_token_usage"];
if (typeof last !== "object" || last === null) return null;
const lastRecord = last as Record<string, unknown>;
// Only an event that is otherwise eligible may consume the duplicate
// signature. A token_count arriving before its turn_context (no model yet)
// must not poison it, or the re-emitted copy after the model is known would
// be skipped as a duplicate and those tokens never counted.
const timestampMs = parseTimestampMs(record["timestamp"]);
if (timestampMs === null) return null;
if (state.model.length === 0) return null;
// Codex re-emits an unchanged token_count on some stream boundaries. Summing
// those would double count, so identical consecutive payloads are skipped.
const signature = JSON.stringify(lastRecord);
if (signature === state.lastUsageSignature) return null;
state.lastUsageSignature = signature;
// In a forked rollout the copied parent history was already counted from the
// parent's own file. Drop the leading burst; the first usage event separated
// from its predecessor by a real turn's worth of time ends it for good.
if (state.suppressingForkCopies) {
if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
state.forkCopyAnchorMs = timestampMs;
return null;
}
state.suppressingForkCopies = false;
}
const inputTokens = tokenCount(lastRecord["input_tokens"]);
const cachedInputTokens = tokenCount(lastRecord["cached_input_tokens"]);
const cacheCreationTokens = tokenCount(lastRecord["cache_write_input_tokens"]);
const outputTokens = tokenCount(lastRecord["output_tokens"]);
const totals: UsageTokenTotals = {
// Codex reports `input_tokens` inclusive of the cached portion.
uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
cachedInputTokens,
cacheCreationTokens,
outputTokens,
// Reported inside output_tokens, surfaced separately for the token mix.
reasoningTokens: Math.min(outputTokens, tokenCount(lastRecord["reasoning_output_tokens"])),
};
if (totalTokens(totals) === 0) return null;
return {
provider: "codex",
timestampMs,
model: state.model,
sessionId: state.sessionId,
totals,
// Codex does not report cost in the rollout.
reportedCostUsd: null,
speed: state.speed,
// Events surviving the fork-copy suppression above are unique to this
// rollout, so they need no global dedup.
dedupeKey: null,
};
}
/**
* Maps a Codex `service_tier` to its billing speed. Codex omits the field when
* no tier was requested, which bills as standard, as do `default` and
* `standard`. `fast` is accepted as an alias of `priority`.
*/
function codexSpeed(serviceTier: unknown): UsageSpeed {
if (serviceTier === "priority" || serviceTier === "fast") return "fast";
if (serviceTier === "ultrafast") return "ultrafast";
return "standard";
}
const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] =>
record === null ? [] : [record];
export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
// Keeps the fields the reducer reads as well as the usage itself.
selectFields: {
type: true,
timestamp: true,
payload: {
type: true,
id: true,
session_id: true,
model: true,
thread_settings: { service_tier: true },
forked_from_id: true,
source: { subagent: { thread_spawn: { parent_thread_id: true } } },
info: { last_token_usage: true },
},
},
// `turn_context`, `thread_settings_applied` and `session_meta` lines hold no
// usage, but they carry the model, tier and session the reducer needs.
mightCarryUsage: (line) =>
line.includes('"token_count"') ||
line.includes('"turn_context"') ||
line.includes('"thread_settings_applied"') ||
line.includes('"session_meta"'),
parseLine: (line, state) => orEmpty(parseCodexLine(line, state)),
parseProjected: (projected, state) => orEmpty(parseCodexRecord(projected, state)),
state: { initial: initialCodexScanState, schema: CodexScanState },
// A rollout that moved after it was read leaves a copy in both places.
sharedSessionsAcrossFiles: true,
};
export const codexUsageReader: ProviderUsageReader<CodexSettings, Path.Path> = {
kind: "transcripts",
provider: "codex",
format: codexUsageFormat,
directories: Effect.fn("codexUsageReader.directories")(function* ({ config, environment }) {
// An undecodable config has no trustworthy home to read.
if (config === undefined) return [];
const path = yield* Path.Path;
const environmentHome = environment.CODEX_HOME?.trim();
const layout = yield* resolveCodexHomeLayout(
config.setupMode !== "managed" &&
!config.homePath.trim() &&
!config.shadowHomePath.trim() &&
environmentHome
? { ...config, homePath: environmentHome }
: config,
);
return [{ dir: path.resolve(layout.sharedHomePath, "sessions") }];
}),
};
+19 -1
View File
@@ -32,7 +32,10 @@ import { GrokDriver, type GrokDriverEnv } from "@t3tools/provider-grok/server";
import { OpenCodeDriver, type OpenCodeDriverEnv } from "@t3tools/provider-opencode/server";
import { MuseDriver, type MuseDriverEnv } from "@t3tools/provider-muse/server";
import { PiDriver, type PiDriverEnv } from "@t3tools/provider-pi/server";
import type { AnyProviderDriver } from "@t3tools/provider-core/server/driver";
import type {
AnyProviderDriver,
ProviderUsageReaderEnv,
} from "@t3tools/provider-core/server/driver";
/**
* Union of infrastructure services required to construct any built-in
@@ -66,3 +69,18 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
MuseDriver,
AcpRegistryDriver,
];
/** Services the built-in usage readers need. */
export type BuiltInUsageReadersEnv =
| ProviderUsageReaderEnv<typeof ClaudeDriver>
| ProviderUsageReaderEnv<typeof CodexDriver>
| ProviderUsageReaderEnv<typeof GrokDriver>;
/**
* The drivers that keep usage history, in the order the usage page reads
* them: transcript readers first, then scan readers. Aggregation keeps the
* first copy of a duplicate record, so the order is part of the result.
*/
export const BUILT_IN_USAGE_DRIVERS: ReadonlyArray<
AnyProviderDriver<BuiltInDriversEnv, BuiltInUsageReadersEnv>
> = [ClaudeDriver, CodexDriver, GrokDriver];
+3 -1
View File
@@ -33,7 +33,7 @@ import { HttpClient, HttpClientResponse } from "effect/http";
import * as ServerConfig from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as CursorUsageReader from "./cursorUsageReader.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
import * as UsageService from "./UsageService.ts";
const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
@@ -805,6 +805,8 @@ describe("UsageService", () => {
},
[ProviderInstanceId.make("grok-work")]: {
driver: ProviderDriverKind.make("grok"),
// An undecodable config must not hide history Grok reads by home alone.
config: { customModels: "not-a-list" },
environment: [{ name: "GROK_HOME", value: grokHome, sensitive: false }],
},
},
+97 -82
View File
@@ -21,8 +21,6 @@
import * as NodeOS from "node:os";
import {
ClaudeSettings,
CodexSettings,
type ProviderInstanceConfig,
ProviderInstanceId,
USAGE_CONTRACT_VERSION,
@@ -56,9 +54,15 @@ import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import * as ServerConfig from "../config.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import * as ServerSettings from "../serverSettings.ts";
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts";
import { BUILT_IN_USAGE_DRIVERS, type BuiltInUsageReadersEnv } from "../provider/builtInDrivers.ts";
import type { ProviderDriver } from "@t3tools/provider-core/server/driver";
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
import type {
ProviderUsageInstance,
TranscriptUsageFormat,
UsageRecord,
} from "@t3tools/provider-core/server/usage";
import { readOpenCodeUsage } from "./opencodeUsageReader.ts";
import { makeAntigravityUsageCache, readAntigravityUsage } from "./antigravityUsageReader.ts";
import {
@@ -90,7 +94,6 @@ import {
type CachedFile,
type ScanCache,
} from "./usageScanCache.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
const LITELLM_RATES_URL =
"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
@@ -119,8 +122,24 @@ const CURSOR_ACCOUNT_READ_ERROR = "Cursor account usage could not be read.";
/** Transcripts parsed at once. More gains little once the disk stays busy. */
const TRANSCRIPT_READ_CONCURRENCY = 4;
const decodeCodexSettings = Schema.decodeOption(CodexSettings);
const decodeClaudeSettings = Schema.decodeOption(ClaudeSettings);
/** The transcript readers, in driver order. */
const transcriptReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
driver.usage?.kind === "transcripts" ? [{ driver, reader: driver.usage }] : [],
);
/** Transcript formats by provider, for decoding the persisted scan cache. */
const transcriptFormats = new Map(
transcriptReaders.map(({ reader }) => [reader.provider, reader.format] as const),
);
/** One transcript directory to scan. */
interface TranscriptSource {
readonly provider: UsageProviderKind;
readonly format: TranscriptUsageFormat<unknown>;
readonly dir: string;
readonly volumeId: string;
readonly fileName?: string;
}
/** On-disk shape of the rate snapshot. */
const RatesCacheFile = Schema.Struct({
@@ -145,13 +164,21 @@ function isLaterRead(a: CachedFile, b: CachedFile): boolean {
return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size);
}
/** Providers whose format lets one session's records appear in several files. */
const sharedSessionProviders: ReadonlySet<UsageProviderKind> = new Set(
transcriptReaders.flatMap(({ reader }) =>
reader.format.sharedSessionsAcrossFiles ? [reader.provider] : [],
),
);
/**
* Codex sessions with records in more than one file, such as a rollout that
* moved after it was read. Only these need cross-file dedupe keys: within one
* file the occurrence count already keeps every key unique, so keying the rest
* would only build and hash a string for each of their records.
* Sessions of `sharedSessionProviders` with records in more than one file,
* such as a rollout that moved after it was read. Only these need cross-file
* dedupe keys: within one file the occurrence count already keeps every key
* unique, so keying the rest would only build and hash a string for each of
* their records.
*/
function sharedCodexSessions(
function sharedSessions(
files: readonly { readonly records: readonly UsageRecord[] }[],
): ReadonlySet<string> {
const firstFile = new Map<string, number>();
@@ -159,7 +186,8 @@ function sharedCodexSessions(
for (const [index, file] of files.entries()) {
let previous = "";
for (const { provider, sessionId } of file.records) {
if (provider !== "codex" || sessionId === previous || sessionId.length === 0) continue;
if (!sharedSessionProviders.has(provider) || sessionId === previous || sessionId.length === 0)
continue;
previous = sessionId;
const first = firstFile.get(sessionId);
if (first === undefined) firstFile.set(sessionId, index);
@@ -218,6 +246,8 @@ export const make = Effect.gen(function* () {
const hostEnvironment = yield* HostProcessEnvironment;
const platform = yield* HostProcessPlatform;
const cursorAccountReader = yield* CursorUsageReader.CursorAccountReader;
// The readers yield their own services; scans run them against this context.
const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
const fileCache: ScanCache = new Map();
const antigravityCache = makeAntigravityUsageCache();
@@ -338,60 +368,45 @@ export const make = Effect.gen(function* () {
),
);
/** Resolves the transcript directory for each provider. */
/**
* Every instance of `driver` with its decoded config, or none when it does
* not decode. Disabled accounts still have history. An unconfigured default
* slot runs with default config, just as it does in the provider registry.
*/
const usageInstances = <Config>(
driver: ProviderDriver<Config, unknown, unknown>,
settings: ServerSettingsValue,
): Array<ProviderUsageInstance<Config>> => {
const entries: Array<
readonly [ProviderInstanceId, Pick<ProviderInstanceConfig, "config" | "environment">, boolean]
> = Object.entries(settings.providerInstances)
.filter(([, instance]) => instance.driver === driver.driverKind)
.map(([id, instance]) => [ProviderInstanceId.make(id), instance, true] as const);
if (!Object.hasOwn(settings.providerInstances, driver.driverKind)) {
entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]);
}
const decodeConfig = Schema.decodeUnknownOption(driver.configSchema);
return entries.map(([instanceId, instance, configured]) => ({
instanceId,
config: Option.getOrUndefined(decodeConfig(instance.config ?? {})),
environment: mergeProviderInstanceEnvironment(instance.environment, hostEnvironment),
configured,
}));
};
/** Resolves every transcript directory the usage readers point at. */
const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
settings: ServerSettingsValue,
retentionCutoffMs: number,
) {
const dirs: Array<{
provider: UsageProviderKind;
dir: string;
volumeId: string;
fileName?: string;
}> = [];
const dirs: Array<TranscriptSource> = [];
const seen = new Set<string>();
for (const driver of ["claudeAgent", "codex", "grok"] as const) {
// Disabled accounts still have history. An unconfigured default slot
// runs with default config, just as it does in the provider registry.
const instances: Array<
Pick<ProviderInstanceConfig, "config" | "environment"> & { instanceId: ProviderInstanceId }
> = Object.entries(settings.providerInstances)
.filter(([, instance]) => instance.driver === driver)
.map(([id, instance]) => ({ ...instance, instanceId: ProviderInstanceId.make(id) }));
if (!Object.hasOwn(settings.providerInstances, driver)) {
instances.push({ instanceId: ProviderInstanceId.make(driver) });
}
for (const instance of instances) {
const environment = mergeProviderInstanceEnvironment(instance.environment, hostEnvironment);
const provider = driver === "claudeAgent" ? "claude" : driver;
let home: string;
if (driver === "codex") {
const decoded = decodeCodexSettings(instance.config ?? {});
if (Option.isNone(decoded)) continue;
const codexConfig = decoded.value;
const environmentHome = environment.CODEX_HOME?.trim();
const layout = yield* resolveCodexHomeLayout(
codexConfig.setupMode !== "managed" &&
!codexConfig.homePath.trim() &&
!codexConfig.shadowHomePath.trim() &&
environmentHome
? { ...codexConfig, homePath: environmentHome }
: codexConfig,
);
home = layout.sharedHomePath;
} else if (driver === "claudeAgent") {
const decoded = decodeClaudeSettings(instance.config ?? {});
if (Option.isNone(decoded)) continue;
const configured = decoded.value.homePath.trim();
home = configured
? expandHomePath(configured)
: environment.CLAUDE_CONFIG_DIR?.trim() || path.join(NodeOS.homedir(), ".claude");
} else {
home = expandHomePath(
environment.GROK_HOME?.trim() || path.join(NodeOS.homedir(), ".grok"),
);
}
const directory = path.resolve(home, provider === "claude" ? "projects" : "sessions");
for (const { driver, reader } of transcriptReaders) {
const { provider, format } = reader;
const directories = yield* Effect.forEach(usageInstances(driver, settings), (instance) =>
reader.directories(instance),
);
for (const { dir: directory, fileName } of directories.flat()) {
const sourceKey = provider + "\0" + directory;
const previous = sourceCache.get(sourceKey);
// Keep canonical paths and source fingerprints stable after root cleanup,
@@ -423,9 +438,10 @@ export const make = Effect.gen(function* () {
seen.add(key);
dirs.push({
provider,
format,
dir,
volumeId,
...(provider === "grok" ? { fileName: "updates.jsonl" } : {}),
...(fileName === undefined ? {} : { fileName }),
});
}
}
@@ -456,7 +472,9 @@ export const make = Effect.gen(function* () {
cacheDirty = document !== null;
}
if (document === null) return;
for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
for (const [path, entry] of decodeScanCache(document, transcriptFormats)) {
fileCache.set(path, entry);
}
const sources = decodeCachedSources(document);
if (Option.isSome(sources)) {
for (const [key, source] of Object.entries(sources.value.sources))
@@ -536,6 +554,7 @@ export const make = Effect.gen(function* () {
size: number,
mtimeMs: number,
provider: UsageProviderKind,
format: TranscriptUsageFormat<unknown>,
): Effect.Effect<{
readonly records: readonly UsageRecord[];
readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
@@ -566,7 +585,7 @@ export const make = Effect.gen(function* () {
: undefined;
const parsed = yield* Effect.promise(() =>
readTranscriptRecords(filePath, provider, resumeFrom),
readTranscriptRecords(filePath, format, resumeFrom),
);
// A read failure is not an empty transcript: caching it under this
// (size, mtime) would silently drop the file's usage until it changes.
@@ -611,15 +630,10 @@ export const make = Effect.gen(function* () {
}
const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
source: {
readonly provider: UsageProviderKind;
readonly dir: string;
readonly volumeId: string;
readonly fileName?: string;
},
source: TranscriptSource,
windowStartMs: number,
) {
const { provider, dir, volumeId, fileName } = source;
const { provider, format, dir, volumeId, fileName } = source;
const exists = yield* fileSystem
.exists(dir)
.pipe(Effect.catchCause(() => Effect.succeed(false)));
@@ -632,7 +646,7 @@ export const make = Effect.gen(function* () {
const read = yield* Effect.forEach(
files,
(file) =>
readFileRecords(file.path, file.size, file.mtimeMs, provider).pipe(
readFileRecords(file.path, file.size, file.mtimeMs, provider, format).pipe(
Effect.map((result) => ({ path: file.path, ...result })),
),
{ concurrency: TRANSCRIPT_READ_CONCURRENCY },
@@ -818,10 +832,8 @@ export const make = Effect.gen(function* () {
retentionCutoffMs: number,
awaitRefresh: boolean,
) {
// The home resolvers ask for `Path` themselves; satisfy them from the
// instance we already hold so the scan stays context-free.
const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe(
Effect.provideService(Path.Path, path),
Effect.provideContext(readerContext),
);
const home = NodeOS.homedir();
@@ -1100,7 +1112,7 @@ export const make = Effect.gen(function* () {
}
return retainedFiles;
});
const sharedSessions = sharedCodexSessions(filesByDir.flat());
const crossFileSessions = sharedSessions(filesByDir.flat());
for (const [
index,
@@ -1118,12 +1130,15 @@ export const make = Effect.gen(function* () {
continue;
}
scannedFiles += 1;
const codexEventOccurrences = new Map<string, number>();
const eventOccurrences = new Map<string, number>();
for (const record of file.records) {
let usageRecord = record;
if (record.provider === "codex" && sharedSessions.has(record.sessionId)) {
// Match moved rollout copies without collapsing repeated equal events
// within one rollout (timestamps can have only second precision).
if (
sharedSessionProviders.has(record.provider) &&
crossFileSessions.has(record.sessionId)
) {
// Match moved copies without collapsing repeated equal events
// within one file (timestamps can have only second precision).
// Only sessions seen in several files can have a copy to match.
const key = encodeUsageRecordKey([
record.provider,
@@ -1132,8 +1147,8 @@ export const make = Effect.gen(function* () {
record.model,
record.totals,
]);
const occurrence = (codexEventOccurrences.get(key) ?? 0) + 1;
codexEventOccurrences.set(key, occurrence);
const occurrence = (eventOccurrences.get(key) ?? 0) + 1;
eventOccurrences.set(key, occurrence);
usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
}
// Only sessions contributing in-window count; the mtime slack can
@@ -5,7 +5,7 @@ import * as NodePath from "node:path";
import * as NodeSqlite from "node:sqlite";
import * as NodeTimersPromises from "node:timers/promises";
import type { UsageRecord } from "./usageTranscripts.ts";
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
type FieldValue = number | bigint | Uint8Array;
type Fields = Map<number, FieldValue[]>;
@@ -1,7 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import { cursorFetchRange, mergeCursorFetch } from "./cursorAccountCache.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
const DAY_MS = 24 * 60 * 60 * 1000;
+1 -1
View File
@@ -13,7 +13,7 @@
* @module cursorAccountCache
*/
import { cursorRateModel } from "./cursorUsageReader.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
export type CursorCredentialSource = string | { readonly kind: "keychain" };
+1 -1
View File
@@ -8,7 +8,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type { UsageRecord } from "./usageTranscripts.ts";
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
import {
CursorKeychainTimeoutError,
readMacCursorAccessToken,
+1 -1
View File
@@ -5,7 +5,7 @@ import * as NodePath from "node:path";
import * as NodeSqlite from "node:sqlite";
import * as NodeTimersPromises from "node:timers/promises";
import { totalTokens, type UsageRecord } from "./usageTranscripts.ts";
import { totalTokens, type UsageRecord } from "@t3tools/provider-core/server/usage";
function object(value: unknown): Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
@@ -2,7 +2,7 @@ import { describe, expect, it } from "@effect/vitest";
import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
import type { RateTable } from "./usagePricing.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
const rates: RateTable = new Map([
[
+1 -1
View File
@@ -20,7 +20,7 @@ import type {
UsageTokenTotals,
} from "@t3tools/contracts";
import { EMPTY_TOTALS, type UsageRecord } from "./usageTranscripts.ts";
import { EMPTY_TOTALS, type UsageRecord } from "@t3tools/provider-core/server/usage";
import { cacheSavingsUsd, priceUsage, type RateTable } from "./usagePricing.ts";
/**
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "@effect/vitest";
import { cursorRateModel } from "./cursorUsageReader.ts";
import type { UsageSpeed } from "./usageTranscripts.ts";
import type { UsageSpeed } from "@t3tools/provider-core/server/usage";
import {
cacheSavingsUsd,
createOverrideRateTable,
+1 -1
View File
@@ -14,7 +14,7 @@ import type {
UsageTokenTotals,
} from "@t3tools/contracts";
import type { UsageRecord, UsageSpeed } from "./usageTranscripts.ts";
import type { UsageRecord, UsageSpeed } from "@t3tools/provider-core/server/usage";
/** Token rates for one billing speed. All values are USD per token. */
export interface TokenRates {
+29 -16
View File
@@ -9,7 +9,9 @@ import {
type CachedFile,
type ScanCache,
} from "./usageScanCache.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
import { TEST_FORMAT_MAP } from "./usageTestFormats.ts";
function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
return {
@@ -36,7 +38,7 @@ function position(overrides: Partial<CachedFile["position"]> = {}): CachedFile["
resumeOffset: 120,
guardLength: 64,
guardHash: 0xdeadbeef,
codexState: null,
state: null,
...overrides,
};
}
@@ -85,7 +87,7 @@ describe("scan cache round trip", () => {
],
tailRecords: [],
position: position({
codexState: {
state: {
model: "gpt-6-astra",
speed: "ultrafast",
sessionId: "session-c",
@@ -97,7 +99,10 @@ describe("scan cache round trip", () => {
}),
});
const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original))));
const restored = decodeScanCache(
JSON.parse(JSON.stringify(encodeScanCache(original))),
TEST_FORMAT_MAP,
);
expect(restored.size).toBe(4);
expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl"));
@@ -117,7 +122,9 @@ describe("scan cache round trip", () => {
},
};
expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
expect(
decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).has("/a.jsonl"),
).toBe(false);
});
it("drops an entry whose guard length is outside the supported range", () => {
@@ -129,7 +136,9 @@ describe("scan cache round trip", () => {
files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, gl: 1e20 } },
};
expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
expect(
decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).has("/a.jsonl"),
).toBe(false);
});
it("drops an entry whose speed is not a known index", () => {
@@ -140,14 +149,16 @@ describe("scan cache round trip", () => {
files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, r: [[...row.slice(0, 10), true]] } },
};
expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
expect(
decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).has("/a.jsonl"),
).toBe(false);
});
it("rejects a document from before records carried a speed", () => {
const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
const previous = { ...encoded, version: 3 };
expect(decodeScanCache(JSON.parse(JSON.stringify(previous))).size).toBe(0);
expect(decodeScanCache(JSON.parse(JSON.stringify(previous)), TEST_FORMAT_MAP).size).toBe(0);
});
it("rewrites only changed entries and still restores the whole cache", () => {
@@ -157,7 +168,7 @@ describe("scan cache round trip", () => {
["/b.jsonl", 200, [record({ sessionId: "session-b" })]],
]);
const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } };
expect(decodeScanCache(JSON.parse(write(cache, { sources })))).toEqual(cache);
expect(decodeScanCache(JSON.parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache);
// The replacement adds intern entries; /a's memoised indexes must hold.
cache.set("/b.jsonl", {
@@ -166,7 +177,7 @@ describe("scan cache round trip", () => {
records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })],
});
const document = JSON.parse(write(cache, { sources }));
expect(decodeScanCache(document)).toEqual(cache);
expect(decodeScanCache(document, TEST_FORMAT_MAP)).toEqual(cache);
expect(document.sources).toEqual(sources);
});
@@ -181,9 +192,11 @@ describe("scan cache round trip", () => {
it("treats a corrupt or foreign document as an empty cache", () => {
// A bad cache should cost one cold scan, never a broken page.
expect(decodeScanCache(null).size).toBe(0);
expect(decodeScanCache("nonsense").size).toBe(0);
expect(decodeScanCache({ version: 999, models: [], sessions: [], files: {} }).size).toBe(0);
expect(decodeScanCache(null, TEST_FORMAT_MAP).size).toBe(0);
expect(decodeScanCache("nonsense", TEST_FORMAT_MAP).size).toBe(0);
expect(
decodeScanCache({ version: 999, models: [], sessions: [], files: {} }, TEST_FORMAT_MAP).size,
).toBe(0);
});
it("skips malformed file entries but keeps good ones", () => {
@@ -193,7 +206,7 @@ describe("scan cache round trip", () => {
files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } },
};
const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)));
const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)), TEST_FORMAT_MAP);
expect([...restored.keys()]).toEqual(["/good.jsonl"]);
});
@@ -203,7 +216,7 @@ describe("scan cache round trip", () => {
const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
const poisoned = { ...encoded, models: [1] };
expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).size).toBe(0);
expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).size).toBe(0);
});
it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
@@ -223,7 +236,7 @@ describe("scan cache round trip", () => {
},
};
const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP);
expect(restored.has("/a.jsonl")).toBe(false);
});
});
+52 -51
View File
@@ -15,9 +15,14 @@
* @module usageScanCache
*/
import type { UsageProviderKind } from "@t3tools/contracts";
import type {
TranscriptUsageFormat,
UsageRecord,
UsageSpeed,
} from "@t3tools/provider-core/server/usage";
import * as Schema from "effect/Schema";
import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
import type { CodexScanState, UsageRecord, UsageSpeed } from "./usageTranscripts.ts";
// v2: Codex fork-copy suppression changed what a file parses to, so v1
// entries would keep serving double-counted records forever.
@@ -25,7 +30,7 @@ import type { CodexScanState, UsageRecord, UsageSpeed } from "./usageTranscripts
// re-parses only its appended bytes instead of starting over.
// v4: records carry Claude fast mode, which v3 rows never captured.
// v5: Codex records carry their service tier. v4 rows store speed the same
// way, so v4 entries still load; see `decodeScanCache` for v4 Codex entries.
// way, so v4 entries still load; see `decodeScanCache` for v4 stateful entries.
const USAGE_SCAN_CACHE_VERSION = 5 as const;
const SPEED_COMPATIBLE_SINCE_VERSION = 4;
@@ -41,10 +46,6 @@ export const LEGACY_SCAN_CACHE_FILE_NAME = "usage-scan-cache.json";
/** Serialised as the index into this list. */
const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
function isSpeed(value: unknown): value is UsageSpeed {
return SPEEDS.some((speed) => speed === value);
}
export interface CachedFile {
readonly size: number;
readonly mtimeMs: number;
@@ -92,8 +93,8 @@ interface SerializedFile {
readonly o: number;
readonly gl: number;
readonly gh: number;
/** Codex reducer state at `o`; `null` for stateless providers. */
readonly cs: CodexScanState | null;
/** The format's encoded reducer state at `o`; `null` for stateless formats. */
readonly cs: unknown;
}
interface SerializedCache {
@@ -147,7 +148,7 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile
o: entry.position.resumeOffset,
gl: entry.position.guardLength,
gh: entry.position.guardHash,
cs: entry.position.codexState,
cs: entry.position.state,
};
}
@@ -210,10 +211,15 @@ function isRecordArray(value: unknown): value is readonly unknown[] {
* Rebuilds the cache from a parsed document.
*
* Anything malformed yields an empty cache rather than an error: a corrupt
* cache should cost one cold scan, never a broken page.
* cache should cost one cold scan, never a broken page. Entries of a provider
* without a transcript format in `formats` are dropped.
*/
export function decodeScanCache(document: unknown): ScanCache {
export function decodeScanCache(
document: unknown,
formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
): ScanCache {
const cache: ScanCache = new Map();
const isValidState = makeStateValidators(formats);
if (typeof document !== "object" || document === null) return cache;
const root = document as Partial<SerializedCache>;
@@ -300,7 +306,9 @@ export function decodeScanCache(document: unknown): ScanCache {
if (typeof raw !== "object" || raw === null) continue;
const entry = raw as Partial<SerializedFile>;
if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "grok") continue;
if (entry.p === undefined) continue;
const format = formats.get(entry.p);
if (format === undefined) continue;
if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
// Position fields feed byte offsets and a Buffer allocation in the reader,
// so anything outside their real ranges must reject the entry: a bogus
@@ -320,27 +328,34 @@ export function decodeScanCache(document: unknown): ScanCache {
) {
continue;
}
// v4 Codex records predate service tiers, so they all priced as standard.
// Keep them, because the rollout may be gone, but make a live rollout
// re-parse whole: no file has size -1, and a zero position cannot resume.
const legacyCodex = entry.p === "codex" && version < USAGE_SCAN_CACHE_VERSION;
const codexState = legacyCodex ? null : decodeCodexState(entry.cs);
if (codexState === undefined) continue;
// v4 records of stateful formats (Codex) predate service tiers, so they
// all priced as standard. Keep them, because the rollout may be gone, but
// make a live rollout re-parse whole: no file has size -1, and a zero
// position cannot resume.
const legacy = format.state !== undefined && version < USAGE_SCAN_CACHE_VERSION;
// A corrupt state disqualifies the entry: resuming with it would attach
// appended usage to the wrong model or replay fork-copied history.
if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue;
const provider: UsageProviderKind = entry.p;
const provider = entry.p;
const records = decodeRecords(entry.r, provider);
const tailRecords = decodeRecords(entry.t, provider);
if (records === null || tailRecords === null) continue;
cache.set(path, {
size: legacyCodex ? -1 : entry.s,
size: legacy ? -1 : entry.s,
mtimeMs: entry.m,
provider,
records,
tailRecords,
position: legacyCodex
? { resumeOffset: 0, guardLength: 0, guardHash: 0, codexState: null }
: { resumeOffset: entry.o, guardLength: entry.gl, guardHash: entry.gh, codexState },
position: legacy
? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }
: {
resumeOffset: entry.o,
guardLength: entry.gl,
guardHash: entry.gh,
state: entry.cs,
},
});
}
@@ -348,35 +363,21 @@ export function decodeScanCache(document: unknown): ScanCache {
}
/**
* Validates a persisted Codex reducer state. Returns `undefined` for a corrupt
* value, which disqualifies the entry: resuming with a bad state would attach
* appended usage to the wrong model or replay fork-copied history.
* Per provider, whether a persisted state is valid: `null`, or one the
* format's schema accepts.
*/
function decodeCodexState(value: unknown): CodexScanState | null | undefined {
if (value === null) return null;
if (typeof value !== "object") return undefined;
const state = value as Partial<CodexScanState>;
if (
typeof state.model !== "string" ||
!isSpeed(state.speed) ||
typeof state.sessionId !== "string" ||
(state.lastUsageSignature !== null && typeof state.lastUsageSignature !== "string") ||
typeof state.sawSessionMeta !== "boolean" ||
typeof state.suppressingForkCopies !== "boolean" ||
typeof state.forkCopyAnchorMs !== "number" ||
!Number.isFinite(state.forkCopyAnchorMs)
) {
return undefined;
}
return {
model: state.model,
speed: state.speed,
sessionId: state.sessionId,
lastUsageSignature: state.lastUsageSignature ?? null,
sawSessionMeta: state.sawSessionMeta,
suppressingForkCopies: state.suppressingForkCopies,
forkCopyAnchorMs: state.forkCopyAnchorMs,
};
function makeStateValidators(
formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
): ReadonlyMap<UsageProviderKind, (value: unknown) => boolean> {
return new Map(
[...formats].map(([provider, format]) => {
const isState = format.state === undefined ? undefined : Schema.is(format.state.schema);
return [
provider,
(value: unknown) => value === null || (isState !== undefined && isState(value)),
] as const;
}),
);
}
/** Keeps saved usage after transcript cleanup, until the reporting retention expires. */
+21
View File
@@ -0,0 +1,21 @@
/**
* The built-in transcript formats by provider, for engine and cache tests.
*
* @module usageTestFormats
*/
import type { UsageProviderKind } from "@t3tools/contracts";
import type { TranscriptUsageFormat } from "@t3tools/provider-core/server/usage";
import { grokUsageFormat } from "@t3tools/provider-grok/server/usage";
import { claudeUsageFormat } from "../provider/Drivers/claudeUsage.ts";
import { codexUsageFormat } from "../provider/Drivers/codexUsage.ts";
export const TEST_FORMATS: Record<"claude" | "codex" | "grok", TranscriptUsageFormat<unknown>> = {
claude: claudeUsageFormat,
codex: codexUsageFormat,
grok: grokUsageFormat,
};
export const TEST_FORMAT_MAP = new Map<UsageProviderKind, TranscriptUsageFormat<unknown>>(
Object.entries(TEST_FORMATS) as Array<[UsageProviderKind, TranscriptUsageFormat<unknown>]>,
);
@@ -8,6 +8,7 @@ import * as NodeSqlite from "node:sqlite";
import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest";
import { TEST_FORMATS } from "./usageTestFormats.ts";
import { readTranscriptRecords } from "./usageTranscriptReader.ts";
import { readOpenCodeUsage } from "./opencodeUsageReader.ts";
import { readCursorAccountUsage } from "./cursorUsageReader.ts";
@@ -99,20 +100,20 @@ describe("readTranscriptRecords resume", () => {
it("parses only appended lines when resuming a grown file", async () => {
const path = NodePath.join(dir, "claude.jsonl");
await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
const first = await readTranscriptRecords(path, "claude");
const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
assert.isNotNull(first);
assert.strictEqual(first.records.length, 2);
assert.isFalse(first.resumed);
await NodeFSP.appendFile(path, claudeLine(3, 11));
const second = await readTranscriptRecords(path, "claude", first.position);
const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
assert.isNotNull(second);
assert.isTrue(second.resumed);
assert.strictEqual(second.records.length, 1);
assert.strictEqual(second.records[0]?.totals.outputTokens, 11);
// The stitched result matches a from-scratch parse of the whole file.
const full = await readTranscriptRecords(path, "claude");
const full = await readTranscriptRecords(path, TEST_FORMATS.claude);
assert.isNotNull(full);
assert.deepStrictEqual([...first.records, ...second.records], [...full.records]);
});
@@ -123,7 +124,7 @@ describe("readTranscriptRecords resume", () => {
path,
codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexTierLine("ultrafast"),
);
const first = await readTranscriptRecords(path, "codex");
const first = await readTranscriptRecords(path, TEST_FORMATS.codex);
assert.isNotNull(first);
assert.strictEqual(first.records.length, 0);
@@ -131,7 +132,7 @@ describe("readTranscriptRecords resume", () => {
// session_meta of its own; model, tier, and session must come from the
// state captured before the boundary.
await NodeFSP.appendFile(path, codexUsageLine(9, 5));
const second = await readTranscriptRecords(path, "codex", first.position);
const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position);
assert.isNotNull(second);
assert.isTrue(second.resumed);
assert.strictEqual(second.records.length, 1);
@@ -146,14 +147,14 @@ describe("readTranscriptRecords resume", () => {
path,
codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexUsageLine(9, 5),
);
const first = await readTranscriptRecords(path, "codex");
const first = await readTranscriptRecords(path, TEST_FORMATS.codex);
assert.isNotNull(first);
assert.strictEqual(first.records.length, 1);
// Codex re-emits an unchanged token_count on stream boundaries; the copy
// lands after the resume point and must still be dropped.
await NodeFSP.appendFile(path, codexUsageLine(9, 5) + codexUsageLine(21, 8));
const second = await readTranscriptRecords(path, "codex", first.position);
const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position);
assert.isNotNull(second);
assert.isTrue(second.resumed);
assert.deepStrictEqual(
@@ -166,7 +167,7 @@ describe("readTranscriptRecords resume", () => {
const path = NodePath.join(dir, "claude.jsonl");
const unterminated = claudeLine(2, 7).trimEnd();
await NodeFSP.writeFile(path, claudeLine(1, 5) + unterminated);
const first = await readTranscriptRecords(path, "claude");
const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
assert.isNotNull(first);
assert.strictEqual(first.records.length, 1);
assert.strictEqual(first.tailRecords.length, 1);
@@ -175,7 +176,7 @@ describe("readTranscriptRecords resume", () => {
// Completing the line and appending another re-reads from the resume
// point, so the once-tail record arrives exactly once as a line record.
await NodeFSP.appendFile(path, `\n${claudeLine(3, 11)}`);
const second = await readTranscriptRecords(path, "claude", first.position);
const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
assert.isNotNull(second);
assert.isTrue(second.resumed);
assert.deepStrictEqual(
@@ -188,12 +189,12 @@ describe("readTranscriptRecords resume", () => {
it("re-parses from the start when the guard bytes no longer match", async () => {
const path = NodePath.join(dir, "claude.jsonl");
await NodeFSP.writeFile(path, claudeLine(1, 5));
const first = await readTranscriptRecords(path, "claude");
const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
assert.isNotNull(first);
// Same path, larger size, different content: a replaced file, not growth.
await NodeFSP.writeFile(path, claudeLine(4, 13) + claudeLine(5, 17));
const second = await readTranscriptRecords(path, "claude", first.position);
const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
assert.isNotNull(second);
assert.isFalse(second.resumed);
assert.deepStrictEqual(
@@ -205,11 +206,11 @@ describe("readTranscriptRecords resume", () => {
it("re-parses from the start when the file shrank below the resume point", async () => {
const path = NodePath.join(dir, "claude.jsonl");
await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
const first = await readTranscriptRecords(path, "claude");
const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
assert.isNotNull(first);
await NodeFSP.writeFile(path, claudeLine(3, 11));
const second = await readTranscriptRecords(path, "claude", first.position);
const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
assert.isNotNull(second);
assert.isFalse(second.resumed);
assert.deepStrictEqual(
@@ -236,7 +237,7 @@ describe("readTranscriptRecords resume", () => {
})}\n`;
await NodeFSP.writeFile(path, bigLine + claudeLine(2, 7));
const parsed = await readTranscriptRecords(path, "claude");
const parsed = await readTranscriptRecords(path, TEST_FORMATS.claude);
assert.isNotNull(parsed);
assert.deepStrictEqual(
parsed.records.map((record) => record.totals.outputTokens),
@@ -245,7 +246,9 @@ describe("readTranscriptRecords resume", () => {
});
it("returns null for an unreadable file", async () => {
assert.isNull(await readTranscriptRecords(NodePath.join(dir, "missing.jsonl"), "claude"));
assert.isNull(
await readTranscriptRecords(NodePath.join(dir, "missing.jsonl"), TEST_FORMATS.claude),
);
});
});
+45 -101
View File
@@ -19,23 +19,16 @@ import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import * as NodeStringDecoder from "node:string_decoder";
import type { UsageProviderKind } from "@t3tools/contracts";
import type {
SelectedFields,
TranscriptUsageFormat,
UsageRecord,
} from "@t3tools/provider-core/server/usage";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { createTranscriptJsonReader } from "../project/AgentSessionJson.ts";
import {
initialCodexScanState,
mightCarryUsage,
parseClaudeLine,
parseClaudeRecord,
parseCodexLine,
parseCodexRecord,
parseGrokLine,
parseGrokRecord,
type CodexScanState,
type UsageRecord,
} from "./usageTranscripts.ts";
export interface TranscriptFile {
readonly path: string;
readonly size: number;
@@ -60,8 +53,11 @@ export interface TranscriptParsePosition {
readonly guardLength: number;
/** FNV-1a hash of that window. */
readonly guardHash: number;
/** Codex reducer state as of `resumeOffset`; `null` for stateless providers. */
readonly codexState: CodexScanState | null;
/**
* The format's reducer state as of `resumeOffset`, encoded by its schema;
* `null` for stateless formats.
*/
readonly state: unknown;
}
export interface TranscriptParseResult {
@@ -89,45 +85,7 @@ const NEWLINE = 0x0a;
const STAT_CONCURRENCY = 32;
const CARRIAGE_RETURN = 0x0d;
type SelectedFields = { readonly [key: string]: true | SelectedFields };
// Keep the fields consumed by usageTranscripts, including reducer state and
// dedupe/cost metadata. A selected subtree (usage) keeps future token fields.
const USAGE_FIELDS: Record<"claude" | "codex" | "grok", SelectedFields> = {
claude: {
type: true,
timestamp: true,
requestId: true,
sessionId: true,
costUSD: true,
message: { id: true, model: true, usage: true },
},
codex: {
type: true,
timestamp: true,
payload: {
type: true,
id: true,
session_id: true,
model: true,
thread_settings: { service_tier: true },
forked_from_id: true,
source: { subagent: { thread_spawn: { parent_thread_id: true } } },
info: { last_token_usage: true },
},
},
grok: {
timestamp: true,
params: {
sessionId: true,
_meta: { agentTimestampMs: true },
update: { sessionUpdate: true, prompt_id: true, usage: true },
},
},
};
function selectUsageFields(provider: UsageProviderKind) {
const fields = USAGE_FIELDS[provider === "codex" || provider === "grok" ? provider : "claude"];
function selectUsageFields(fields: SelectedFields) {
return (path: ReadonlyArray<string | number | null>): boolean => {
let selected: true | SelectedFields = fields;
for (const key of path) {
@@ -257,14 +215,12 @@ async function guardMatches(
* still match, so only appended lines are read; otherwise the whole file is
* re-parsed from the start and `resumed` reports `false`.
*
* Codex carries the active model on `turn_context` lines and the service tier
* on `thread_settings_applied` lines. Neither holds usage of its own, but both
* still have to pass through the reducer to keep attribution and pricing
* correct.
* A stateful format resumes with the state saved at that position; a saved
* state its schema rejects re-parses the file whole.
*/
export async function readTranscriptRecords(
export async function readTranscriptRecords<State>(
filePath: string,
provider: UsageProviderKind,
format: TranscriptUsageFormat<State>,
resumeFrom?: TranscriptParsePosition,
options?: { readonly streamingThresholdBytes?: number },
): Promise<TranscriptParseResult | null> {
@@ -277,41 +233,31 @@ export async function readTranscriptRecords(
}
try {
let codexState = initialCodexScanState();
const codec = format.state;
const decodeState = codec === undefined ? undefined : Schema.decodeUnknownOption(codec.schema);
const encodeState = codec === undefined ? undefined : Schema.encodeSync(codec.schema);
// Stateless formats never read their state argument.
let state = codec === undefined ? (undefined as State) : codec.initial();
let resumed = false;
let start = 0;
const savedState =
resumeFrom === undefined || decodeState === undefined || resumeFrom.state === null
? Option.none()
: decodeState(resumeFrom.state);
if (
resumeFrom !== undefined &&
resumeFrom.resumeOffset > 0 &&
(provider !== "codex" || resumeFrom.codexState !== null) &&
(codec === undefined || Option.isSome(savedState)) &&
(await guardMatches(handle, resumeFrom))
) {
if (resumeFrom.codexState !== null) codexState = { ...resumeFrom.codexState };
if (Option.isSome(savedState)) state = savedState.value;
start = resumeFrom.resumeOffset;
resumed = true;
}
const parseLine = (line: string, state: CodexScanState, out: UsageRecord[]): void => {
if (provider === "codex") {
if (
!mightCarryUsage(line, provider) &&
!line.includes('"turn_context"') &&
!line.includes('"thread_settings_applied"') &&
!line.includes('"session_meta"')
) {
return;
}
const record = parseCodexLine(line, state);
if (record !== null) out.push(record);
return;
}
if (!mightCarryUsage(line, provider)) return;
if (provider === "grok") {
for (const grokRecord of parseGrokLine(line)) out.push(grokRecord);
return;
}
const record = parseClaudeLine(line);
if (record !== null) out.push(record);
const parseLine = (line: string, lineState: State, out: UsageRecord[]): void => {
if (!format.mightCarryUsage(line)) return;
for (const record of format.parseLine(line, lineState)) out.push(record);
};
const toLineString = (lineBuffer: Buffer): string => {
@@ -331,7 +277,7 @@ export async function readTranscriptRecords(
let pendingBytes = 0;
let streaming: ReturnType<typeof createTranscriptJsonReader> | undefined;
let decoder: NodeStringDecoder.StringDecoder | undefined;
const selectPath = selectUsageFields(provider);
const selectPath = selectUsageFields(format.selectFields);
const append = (segment: Buffer) => {
if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) {
@@ -350,25 +296,17 @@ export async function readTranscriptRecords(
}
streaming.write(decoder!.write(segment));
};
const finish = (state: CodexScanState, out: UsageRecord[]) => {
const finish = (lineState: State, out: UsageRecord[]) => {
if (streaming) {
streaming.write(decoder!.end());
const projected = streaming.finish();
if (provider === "grok") {
out.push(...parseGrokRecord(projected));
} else {
const record =
provider === "codex"
? parseCodexRecord(projected, state)
: parseClaudeRecord(projected);
if (record !== null) out.push(record);
}
for (const record of format.parseProjected(projected, lineState)) out.push(record);
} else if (pendingBytes > 0) {
const line =
pendingChunks.length === 1
? pendingChunks[0]!
: Buffer.concat(pendingChunks, pendingBytes);
parseLine(toLineString(line), state, out);
parseLine(toLineString(line), lineState, out);
}
pendingChunks = [];
pendingBytes = 0;
@@ -391,10 +329,10 @@ export async function readTranscriptRecords(
// Most lines fit in the current chunk. Avoid buffering/streaming
// machinery on this hot path.
if (!streaming && pendingBytes === 0) {
parseLine(toLineString(chunk.subarray(lineStart, newlineIndex)), codexState, records);
parseLine(toLineString(chunk.subarray(lineStart, newlineIndex)), state, records);
} else {
append(chunk.subarray(lineStart, newlineIndex));
finish(codexState, records);
finish(state, records);
}
lineStart = newlineIndex + 1;
resumeOffset = scanOffset + lineStart;
@@ -402,8 +340,14 @@ export async function readTranscriptRecords(
scanOffset += chunk.length;
}
// The unfinished tail parses against a copy, so the saved state stays at
// `resumeOffset` and the next scan replays the tail from it.
const encodedState = encodeState === undefined ? null : encodeState(state);
const tailRecords: UsageRecord[] = [];
finish({ ...codexState }, tailRecords);
finish(
decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState)),
tailRecords,
);
const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
let guardHash = 0;
@@ -420,7 +364,7 @@ export async function readTranscriptRecords(
resumeOffset,
guardLength,
guardHash,
codexState: provider === "codex" ? codexState : null,
state: encodedState,
},
resumed,
};
@@ -5,6 +5,7 @@ import * as NodePath from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "@effect/vitest";
import { TEST_FORMATS } from "./usageTestFormats.ts";
import {
readTranscriptRecords as readWithDefaultThreshold,
type TranscriptParsePosition,
@@ -16,7 +17,10 @@ const readTranscriptRecords = (
path: string,
provider: "claude" | "codex" | "grok",
position?: TranscriptParsePosition,
) => readWithDefaultThreshold(path, provider, position, { streamingThresholdBytes: 256 * 1024 });
) =>
readWithDefaultThreshold(path, TEST_FORMATS[provider], position, {
streamingThresholdBytes: 256 * 1024,
});
let dir: string;
beforeEach(async () => {
@@ -144,7 +148,7 @@ describe("large usage records", () => {
);
const actual = await scan(large, provider);
expect(actual.records).toEqual(expected.records);
expect(actual.position.codexState).toEqual(expected.position.codexState);
expect(actual.position.state).toEqual(expected.position.state);
}
},
);
@@ -1,598 +0,0 @@
import { describe, expect, it } from "@effect/vitest";
import {
GROK_COST_USD_TICKS_PER_DOLLAR,
initialCodexScanState,
parseClaudeLine,
parseCodexLine,
parseGrokLine,
totalTokens,
} from "./usageTranscripts.ts";
/** Shaped after a real Claude Code assistant record. */
function claudeLine(overrides: {
messageId: string;
contentType: string;
model?: string;
outputTokens?: number;
speed?: string;
}): string {
return JSON.stringify({
type: "assistant",
timestamp: "2026-08-07T04:05:13.944Z",
sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0",
cwd: "/home/theo/project",
message: {
id: overrides.messageId,
role: "assistant",
model: overrides.model ?? "claude-fable-5",
content: [{ type: overrides.contentType }],
usage: {
input_tokens: 2,
cache_creation_input_tokens: 66818,
cache_read_input_tokens: 1000,
output_tokens: overrides.outputTokens ?? 286,
...(overrides.speed === undefined ? {} : { speed: overrides.speed }),
},
},
});
}
describe("parseClaudeLine", () => {
it("extracts token totals and a dedupe key", () => {
const record = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" }));
expect(record).not.toBeNull();
expect(record?.provider).toBe("claude");
expect(record?.model).toBe("claude-fable-5");
expect(record?.totals).toEqual({
uncachedInputTokens: 2,
cachedInputTokens: 1000,
cacheCreationTokens: 66818,
outputTokens: 286,
reasoningTokens: 0,
});
expect(record?.dedupeKey).toBe("msg_1:");
expect(record?.speed).toBe("standard");
});
it("marks fast-mode requests", () => {
const line = (speed: string) =>
parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text", speed }));
expect(line("fast")?.speed).toBe("fast");
expect(line("standard")?.speed).toBe("standard");
});
it("gives every content block of one message the same dedupe key", () => {
// T3 Code writes one record per content block, each repeating the parent
// message's full usage. Summing them would overcount ~2.4x on real data.
const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" }));
const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" }));
expect(text?.dedupeKey).toBe(toolUse?.dedupeKey);
expect(text?.totals).toEqual(toolUse?.totals);
});
it("ignores records that are not assistant messages", () => {
expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull();
expect(parseClaudeLine("not json")).toBeNull();
});
});
describe("parseCodexLine", () => {
const sessionMeta = JSON.stringify({
type: "session_meta",
timestamp: "2026-08-01T05:17:41.289Z",
payload: { type: "session_meta", id: "019fbbc1-b12c-7360-a685-28c181f0025f" },
});
const turnContext = JSON.stringify({
type: "turn_context",
timestamp: "2026-08-01T05:17:42.694Z",
payload: { type: "turn_context", model: "gpt-5.6-sol" },
});
const tokenCount = (inputTokens: number, cached: number, output: number, reasoning: number) =>
JSON.stringify({
type: "event_msg",
timestamp: "2026-08-01T05:17:49.919Z",
payload: {
type: "token_count",
info: {
last_token_usage: {
input_tokens: inputTokens,
cached_input_tokens: cached,
cache_write_input_tokens: 0,
output_tokens: output,
reasoning_output_tokens: reasoning,
},
},
},
});
it("attributes usage to the model from the preceding turn context", () => {
const state = initialCodexScanState();
parseCodexLine(sessionMeta, state);
parseCodexLine(turnContext, state);
const record = parseCodexLine(tokenCount(19239, 11008, 299, 116), state);
expect(record?.provider).toBe("codex");
expect(record?.model).toBe("gpt-5.6-sol");
expect(record?.sessionId).toBe("019fbbc1-b12c-7360-a685-28c181f0025f");
// Codex reports input_tokens inclusive of the cached portion.
expect(record?.totals.uncachedInputTokens).toBe(19239 - 11008);
expect(record?.totals.cachedInputTokens).toBe(11008);
expect(record?.totals.reasoningTokens).toBe(116);
});
it("skips a repeated token_count so deltas are not double counted", () => {
const state = initialCodexScanState();
parseCodexLine(turnContext, state);
const first = parseCodexLine(tokenCount(100, 0, 10, 0), state);
const repeat = parseCodexLine(tokenCount(100, 0, 10, 0), state);
expect(first).not.toBeNull();
expect(repeat).toBeNull();
});
it("drops usage that arrives before any model is known", () => {
const state = initialCodexScanState();
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
});
it("does not let a pre-model event poison the duplicate signature", () => {
// A token_count before its turn_context is dropped; the identical event
// re-emitted once the model is known must still be counted.
const state = initialCodexScanState();
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
parseCodexLine(turnContext, state);
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
});
it("carries the service tier from the latest thread settings", () => {
const settings = (thread_settings: Record<string, unknown>) =>
JSON.stringify({
type: "event_msg",
timestamp: "2026-08-01T05:17:42.000Z",
payload: { type: "thread_settings_applied", thread_settings },
});
const state = initialCodexScanState();
parseCodexLine(turnContext, state);
const speedAfter = (line: string, output: number) => {
parseCodexLine(line, state);
return parseCodexLine(tokenCount(100, 0, output, 0), state)?.speed;
};
expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)?.speed).toBe("standard");
expect(speedAfter(settings({ service_tier: "ultrafast" }), 2)).toBe("ultrafast");
expect(speedAfter(settings({ service_tier: "priority" }), 3)).toBe("fast");
// Codex omits the field when no tier was requested.
expect(speedAfter(settings({ model: "gpt-6-astra" }), 4)).toBe("standard");
});
// A forked/subagent rollout opens with the parent's history copied in and
// every line re-stamped to the fork instant, then the ancestors' session
// metas. Counting those again multiplied usage ~1.85x on real data (#5758).
describe("forked rollouts", () => {
const meta = (overrides: {
id: string;
timestamp: string;
forkedFromId?: string;
spawnParentId?: string;
}) =>
JSON.stringify({
type: "session_meta",
timestamp: overrides.timestamp,
payload: {
type: "session_meta",
id: overrides.id,
...(overrides.forkedFromId === undefined
? {}
: { forked_from_id: overrides.forkedFromId }),
...(overrides.spawnParentId === undefined
? {}
: {
source: {
subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
},
}),
},
});
const stamped = (timestamp: string, line: string) => {
const parsed = JSON.parse(line) as { timestamp: string };
parsed.timestamp = timestamp;
return JSON.stringify(parsed);
};
it("keeps the child session id over copied ancestor metas", () => {
const state = initialCodexScanState();
parseCodexLine(meta({ id: "child", timestamp: "2026-08-01T05:00:00.000Z" }), state);
parseCodexLine(meta({ id: "parent", timestamp: "2026-08-01T05:00:00.000Z" }), state);
parseCodexLine(turnContext, state);
const record = parseCodexLine(tokenCount(100, 0, 10, 0), state);
expect(record?.sessionId).toBe("child");
});
it("drops the re-stamped copied burst and keeps the first real event", () => {
const state = initialCodexScanState();
const forkInstant = "2026-08-01T05:00:00.000Z";
parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
parseCodexLine(stamped(forkInstant, turnContext), state);
// Copied history: written in one burst at the fork instant.
expect(
parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
).toBeNull();
expect(
parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state),
).toBeNull();
// The child's first genuine turn lands seconds later and must count.
const real = parseCodexLine(
stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)),
state,
);
expect(real).not.toBeNull();
expect(real?.totals.outputTokens).toBe(30);
// Suppression never restarts, even for closely spaced later events.
const next = parseCodexLine(
stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)),
state,
);
expect(next).not.toBeNull();
});
it("recognizes subagent spawns without forked_from_id", () => {
const state = initialCodexScanState();
const spawnInstant = "2026-08-01T05:00:00.000Z";
parseCodexLine(
meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
state,
);
parseCodexLine(stamped(spawnInstant, turnContext), state);
expect(
parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
).toBeNull();
});
it("does not suppress anything in a rollout that is not a fork", () => {
const state = initialCodexScanState();
parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
const record = parseCodexLine(
stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
state,
);
expect(record).not.toBeNull();
});
});
});
describe("totalTokens", () => {
it("does not add reasoning on top of output", () => {
expect(
totalTokens({
uncachedInputTokens: 10,
cachedInputTokens: 20,
cacheCreationTokens: 30,
outputTokens: 40,
reasoningTokens: 25,
}),
).toBe(100);
});
});
describe("parseGrokLine", () => {
/** Shaped after a real Grok Build `turn_completed` session update. */
function turnCompleted(overrides?: {
sessionId?: string;
promptId?: string;
timestamp?: number;
agentTimestampMs?: number;
usage?: Record<string, unknown>;
modelUsage?: Record<string, Record<string, unknown>> | null;
}): string {
const modelUsage =
overrides && "modelUsage" in overrides
? overrides.modelUsage
: {
"grok-4.5-build": {
inputTokens: 20_272,
outputTokens: 272,
totalTokens: 20_544,
cachedReadTokens: 11_264,
cacheCreationTokens: 0,
reasoningTokens: 180,
costUsdTicks: 230_272_000,
},
};
return JSON.stringify({
timestamp: overrides?.timestamp ?? 1_786_372_566,
method: "_x.ai/session/update",
params: {
sessionId: overrides?.sessionId ?? "019fec1a-12f7-72f2-9b1f-7778a00aea3c",
update: {
sessionUpdate: "turn_completed",
prompt_id: overrides?.promptId ?? "prompt-1",
stop_reason: "end_turn",
usage: {
inputTokens: 20_272,
outputTokens: 272,
totalTokens: 20_544,
cachedReadTokens: 11_264,
cacheCreationTokens: 0,
reasoningTokens: 180,
costUsdTicks: 230_272_000,
...(modelUsage === null ? {} : { modelUsage }),
...overrides?.usage,
},
},
_meta: {
eventId: "event-1",
agentTimestampMs: overrides?.agentTimestampMs ?? 1_786_372_566_485,
},
},
});
}
it("extracts per-model totals and provider-reported cost ticks", () => {
const records = parseGrokLine(turnCompleted());
expect(records).toHaveLength(1);
const [record] = records;
expect(record?.provider).toBe("grok");
expect(record?.model).toBe("grok-4.5-build");
expect(record?.sessionId).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c");
expect(record?.timestampMs).toBe(1_786_372_566_485);
expect(record?.totals).toEqual({
uncachedInputTokens: 20_272 - 11_264,
cachedInputTokens: 11_264,
cacheCreationTokens: 0,
outputTokens: 272,
reasoningTokens: 180,
});
expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok-4.5-build");
});
it("emits one record per model when modelUsage has several entries", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5": {
inputTokens: 1000,
outputTokens: 50,
cachedReadTokens: 400,
reasoningTokens: 20,
costUsdTicks: 50_000_000,
},
"grok-composer-2.5-fast": {
inputTokens: 200,
outputTokens: 30,
cachedReadTokens: 100,
reasoningTokens: 0,
costUsdTicks: 10_000_000,
},
},
}),
);
expect(records.map((record) => record.model).toSorted()).toEqual([
"grok-4.5",
"grok-composer-2.5-fast",
]);
expect(records.every((record) => record.provider === "grok")).toBe(true);
expect(records.find((record) => record.model === "grok-4.5")?.reportedCostUsd).toBeCloseTo(
0.005,
12,
);
});
it("inherits top-level cost ticks for a single model without its own ticks", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5-build": {
inputTokens: 1000,
outputTokens: 10,
cachedReadTokens: 0,
reasoningTokens: 0,
},
},
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
}),
);
expect(records).toHaveLength(1);
expect(records[0]?.reportedCostUsd).toBe(1);
});
it("falls back to a generic grok model when modelUsage is absent", () => {
const records = parseGrokLine(turnCompleted({ modelUsage: null }));
expect(records).toHaveLength(1);
const [record] = records;
expect(record?.provider).toBe("grok");
expect(record?.model).toBe("grok");
expect(record?.totals).toEqual({
uncachedInputTokens: 20_272 - 11_264,
cachedInputTokens: 11_264,
cacheCreationTokens: 0,
outputTokens: 272,
reasoningTokens: 180,
});
expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok");
});
it("pro-rates top-level cost ticks across multi-model turns without per-model ticks", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5": {
inputTokens: 300,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
"grok-composer-2.5-fast": {
inputTokens: 100,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
},
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
}),
);
expect(records).toHaveLength(2);
const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
const sum =
(byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
(byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
expect(sum).toBeCloseTo(1, 12);
});
it("pro-rates aggregate cost when a zero-token sibling carries costUsdTicks: 0", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5": {
inputTokens: 300,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
"grok-composer-2.5-fast": {
inputTokens: 100,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
"empty-sibling": {
inputTokens: 0,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
costUsdTicks: 0,
},
},
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
}),
);
expect(records).toHaveLength(2);
expect(records.every((record) => record.model !== "empty-sibling")).toBe(true);
const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
const sum =
(byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
(byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
expect(sum).toBeCloseTo(1, 12);
});
it("allocates leftover aggregate ticks to models that omit per-model ticks", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5": {
inputTokens: 300,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
costUsdTicks: 0.4 * GROK_COST_USD_TICKS_PER_DOLLAR,
},
"grok-composer-2.5-fast": {
inputTokens: 100,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
},
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
}),
);
expect(records).toHaveLength(2);
const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.4, 12);
expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.6, 12);
const sum =
(byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
(byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
expect(sum).toBeCloseTo(1, 12);
});
it("does not invent a colliding dedupe key when prompt_id is missing", () => {
const line = JSON.stringify({
timestamp: 1_786_372_566,
method: "_x.ai/session/update",
params: {
sessionId: "s1",
update: {
sessionUpdate: "turn_completed",
usage: {
inputTokens: 10,
outputTokens: 2,
modelUsage: {
"grok-4.5": { inputTokens: 10, outputTokens: 2 },
},
},
},
},
});
expect(parseGrokLine(line)[0]?.dedupeKey).toBeNull();
});
it("ignores non-turn lines and empty usage", () => {
expect(parseGrokLine(JSON.stringify({ method: "session/update", params: {} }))).toEqual([]);
expect(parseGrokLine("not json")).toEqual([]);
expect(
parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5-build": {
inputTokens: 0,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
costUsdTicks: 0,
},
},
}),
),
).toEqual([]);
});
it("falls back to the outer unix-seconds timestamp when agent meta is missing", () => {
const line = JSON.stringify({
timestamp: 1_786_372_566,
method: "_x.ai/session/update",
params: {
sessionId: "s1",
update: {
sessionUpdate: "turn_completed",
prompt_id: "p1",
usage: {
inputTokens: 10,
outputTokens: 2,
modelUsage: {
"grok-4.5": { inputTokens: 10, outputTokens: 2 },
},
},
},
},
});
const records = parseGrokLine(line);
expect(records[0]?.timestampMs).toBe(1_786_372_566_000);
});
});
-530
View File
@@ -1,530 +0,0 @@
/**
* Pure parsers for the provider CLIs' on-disk session transcripts.
*
* Each parser is a line-at-a-time reducer so callers can stream large files
* without materialising them. None of them touch the filesystem.
*
* @module usageTranscripts
*/
import type { UsageProviderKind, UsageTokenTotals } from "@t3tools/contracts";
/**
* Billing speed of a request. Faster speeds bill at a model-specific premium.
* Claude fast mode and Codex `priority` are `fast`; Codex `ultrafast` is its
* own, more expensive tier.
*/
export type UsageSpeed = "standard" | "fast" | "ultrafast";
export interface UsageRecord {
readonly provider: UsageProviderKind;
readonly timestampMs: number;
readonly model: string;
/**
* Rate-table key when the provider's display name carries tiers the table
* does not know, such as Cursor's `claude-opus-5-5-high`. Defaults to `model`.
*/
readonly rateModel?: string;
readonly sessionId: string;
readonly totals: UsageTokenTotals;
readonly reportedCostUsd: number | null;
/** Only Claude Code and Codex record a speed; other providers are `standard`. */
readonly speed: UsageSpeed;
/**
* Key for cross-file de-duplication, or `null` when the record is inherently
* unique and needs no dedup.
*/
readonly dedupeKey: string | null;
}
const EMPTY_TOTALS: UsageTokenTotals = {
uncachedInputTokens: 0,
cachedInputTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
reasoningTokens: 0,
};
function int(value: unknown): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
}
function parseTimestampMs(value: unknown): number | null {
if (typeof value !== "string") return null;
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? null : parsed;
}
export function totalTokens(totals: UsageTokenTotals): number {
// reasoningTokens is a subset of outputTokens and must not be added again.
return (
totals.uncachedInputTokens +
totals.cachedInputTokens +
totals.cacheCreationTokens +
totals.outputTokens
);
}
/**
* Cheap substring gate applied before `JSON.parse`.
*
* Transcripts are mostly tool output; only a minority of lines carry usage. On
* a 30-day window this skips roughly half the lines outright and is worth about
* an order of magnitude.
*/
export function mightCarryUsage(line: string, provider: UsageProviderKind): boolean {
if (provider === "claude") return line.includes('"usage"');
if (provider === "grok") return line.includes('"turn_completed"');
return line.includes('"token_count"');
}
/**
* Grok reports cost in integer ticks where `1 USD = 10^10` ticks. See Grok
* headless `total_cost_usd_ticks`. Convert to dollars for pricing.
*/
export const GROK_COST_USD_TICKS_PER_DOLLAR = 10_000_000_000;
function grokCostTicksToUsd(ticks: unknown): number | null {
if (typeof ticks !== "number" || !Number.isFinite(ticks) || ticks < 0) return null;
return ticks / GROK_COST_USD_TICKS_PER_DOLLAR;
}
/* -------------------------------------------------------------------------- */
/* Claude Code */
/* -------------------------------------------------------------------------- */
/**
* Parses one line of a Claude Code transcript.
*
* T3 Code writes one record per assistant *content block*, and every one of
* those records repeats the same complete `usage` object for the parent
* message. Summing them overcounts by roughly 2.4x on a real workload, so the
* caller must drop repeats by `dedupeKey` and keep the first.
*/
export function parseClaudeLine(line: string): UsageRecord | null {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
return null;
}
return parseClaudeRecord(parsed);
}
export function parseClaudeRecord(parsed: unknown): UsageRecord | null {
if (typeof parsed !== "object" || parsed === null) return null;
const record = parsed as Record<string, unknown>;
if (record["type"] !== "assistant") return null;
const message = record["message"];
if (typeof message !== "object" || message === null) return null;
const messageRecord = message as Record<string, unknown>;
const usage = messageRecord["usage"];
if (typeof usage !== "object" || usage === null) return null;
const usageRecord = usage as Record<string, unknown>;
const timestampMs = parseTimestampMs(record["timestamp"]);
if (timestampMs === null) return null;
const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : "";
if (model.length === 0) return null;
const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null;
const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null;
// Matches ccusage: prefer the message/request pair, fall back to whichever
// half exists. Records with neither cannot be de-duplicated.
const dedupeKey =
messageId === null && requestId === null ? null : `${messageId ?? ""}:${requestId ?? ""}`;
const cost = record["costUSD"];
return {
provider: "claude",
timestampMs,
model,
sessionId: typeof record["sessionId"] === "string" ? record["sessionId"] : "",
totals: {
uncachedInputTokens: int(usageRecord["input_tokens"]),
cachedInputTokens: int(usageRecord["cache_read_input_tokens"]),
cacheCreationTokens: int(usageRecord["cache_creation_input_tokens"]),
outputTokens: int(usageRecord["output_tokens"]),
// Anthropic folds thinking tokens into output and does not break them out.
reasoningTokens: 0,
},
reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null,
speed: usageRecord["speed"] === "fast" ? "fast" : "standard",
dedupeKey,
};
}
/* -------------------------------------------------------------------------- */
/* Codex */
/* -------------------------------------------------------------------------- */
/**
* Rolling state for a single Codex rollout file.
*
* Codex `token_count` events carry no model or service tier, so both are
* carried forward: the model from the most recent `turn_context`, the tier from
* the most recent `thread_settings_applied`. Sessions that switch either
* mid-run attribute correctly from the switch onward.
*/
export interface CodexScanState {
model: string;
speed: UsageSpeed;
sessionId: string;
lastUsageSignature: string | null;
sawSessionMeta: boolean;
/** While true, leading usage events are re-stamped copies of parent history. */
suppressingForkCopies: boolean;
forkCopyAnchorMs: number;
}
export function initialCodexScanState(): CodexScanState {
return {
model: "",
speed: "standard",
sessionId: "",
lastUsageSignature: null,
sawSessionMeta: false,
suppressingForkCopies: false,
forkCopyAnchorMs: 0,
};
}
/**
* A forked or subagent rollout opens with the parent's full history copied in,
* every line re-stamped to the fork instant. Those copies are written in one
* synchronous burst (observed gaps 0-40ms), while the child's first genuine
* usage event only lands after a real model turn (observed 5s+). One second of
* separation splits the two cleanly; `ccusage` uses the same threshold.
*/
const FORK_COPY_MAX_GAP_MS = 1000;
/** Whether a `session_meta` payload marks the rollout as a fork or subagent. */
function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
if (typeof payload["forked_from_id"] === "string") return true;
const source = payload["source"];
if (typeof source !== "object" || source === null) return false;
const subagent = (source as Record<string, unknown>)["subagent"];
if (typeof subagent !== "object" || subagent === null) return false;
const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
if (typeof spawn !== "object" || spawn === null) return false;
return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
}
/**
* Feeds one line of a Codex rollout into `state`, returning a record when the
* line was a usage event.
*
* Deltas come from `last_token_usage`. Summing those across a session
* reconciles with the session's final `total_token_usage`, provided
* consecutive duplicate events are dropped, which this does.
*/
export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
return null;
}
return parseCodexRecord(parsed, state);
}
export function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | null {
if (typeof parsed !== "object" || parsed === null) return null;
const record = parsed as Record<string, unknown>;
const payload = record["payload"];
if (typeof payload !== "object" || payload === null) return null;
const payloadRecord = payload as Record<string, unknown>;
const payloadType = payloadRecord["type"];
if (record["type"] === "session_meta") {
// Only the first meta describes this file's own session. A forked rollout
// repeats the ancestors' metas right after it; letting those through would
// reassign every subsequent record to an ancestor session.
if (state.sawSessionMeta) return null;
state.sawSessionMeta = true;
const id = payloadRecord["id"] ?? payloadRecord["session_id"];
if (typeof id === "string") state.sessionId = id;
const metaTimestampMs = parseTimestampMs(record["timestamp"]);
if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
state.suppressingForkCopies = true;
state.forkCopyAnchorMs = metaTimestampMs;
}
return null;
}
if (record["type"] === "turn_context") {
if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
return null;
}
if (payloadType === "thread_settings_applied") {
const settings = payloadRecord["thread_settings"];
if (typeof settings === "object" && settings !== null) {
state.speed = codexSpeed((settings as Record<string, unknown>)["service_tier"]);
}
return null;
}
if (payloadType !== "token_count") return null;
const info = payloadRecord["info"];
if (typeof info !== "object" || info === null) return null;
const last = (info as Record<string, unknown>)["last_token_usage"];
if (typeof last !== "object" || last === null) return null;
const lastRecord = last as Record<string, unknown>;
// Only an event that is otherwise eligible may consume the duplicate
// signature. A token_count arriving before its turn_context (no model yet)
// must not poison it, or the re-emitted copy after the model is known would
// be skipped as a duplicate and those tokens never counted.
const timestampMs = parseTimestampMs(record["timestamp"]);
if (timestampMs === null) return null;
if (state.model.length === 0) return null;
// Codex re-emits an unchanged token_count on some stream boundaries. Summing
// those would double count, so identical consecutive payloads are skipped.
const signature = JSON.stringify(lastRecord);
if (signature === state.lastUsageSignature) return null;
state.lastUsageSignature = signature;
// In a forked rollout the copied parent history was already counted from the
// parent's own file. Drop the leading burst; the first usage event separated
// from its predecessor by a real turn's worth of time ends it for good.
if (state.suppressingForkCopies) {
if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
state.forkCopyAnchorMs = timestampMs;
return null;
}
state.suppressingForkCopies = false;
}
const inputTokens = int(lastRecord["input_tokens"]);
const cachedInputTokens = int(lastRecord["cached_input_tokens"]);
const cacheCreationTokens = int(lastRecord["cache_write_input_tokens"]);
const outputTokens = int(lastRecord["output_tokens"]);
const totals: UsageTokenTotals = {
// Codex reports `input_tokens` inclusive of the cached portion.
uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
cachedInputTokens,
cacheCreationTokens,
outputTokens,
// Reported inside output_tokens, surfaced separately for the token mix.
reasoningTokens: Math.min(outputTokens, int(lastRecord["reasoning_output_tokens"])),
};
if (totalTokens(totals) === 0) return null;
return {
provider: "codex",
timestampMs,
model: state.model,
sessionId: state.sessionId,
totals,
// Codex does not report cost in the rollout.
reportedCostUsd: null,
speed: state.speed,
// Events surviving the fork-copy suppression above are unique to this
// rollout, so they need no global dedup.
dedupeKey: null,
};
}
/**
* Maps a Codex `service_tier` to its billing speed. Codex omits the field when
* no tier was requested, which bills as standard, as do `default` and
* `standard`. `fast` is accepted as an alias of `priority`.
*/
function codexSpeed(serviceTier: unknown): UsageSpeed {
if (serviceTier === "priority" || serviceTier === "fast") return "fast";
if (serviceTier === "ultrafast") return "ultrafast";
return "standard";
}
/* -------------------------------------------------------------------------- */
/* Grok Build */
/* -------------------------------------------------------------------------- */
interface GrokUsageTotals {
readonly inputTokens: number;
readonly outputTokens: number;
readonly cachedReadTokens: number;
readonly cacheCreationTokens: number;
readonly reasoningTokens: number;
readonly costUsdTicks: number | null;
}
function readGrokUsageTotals(value: unknown): GrokUsageTotals | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
return {
inputTokens: int(record["inputTokens"]),
outputTokens: int(record["outputTokens"]),
cachedReadTokens: int(record["cachedReadTokens"]),
cacheCreationTokens: int(record["cacheCreationTokens"]),
reasoningTokens: int(record["reasoningTokens"]),
costUsdTicks:
typeof record["costUsdTicks"] === "number" && Number.isFinite(record["costUsdTicks"])
? record["costUsdTicks"]
: null,
};
}
function grokTotalsToUsage(totals: GrokUsageTotals): UsageTokenTotals {
const cachedInputTokens = totals.cachedReadTokens;
const cacheCreationTokens = totals.cacheCreationTokens;
// Grok reports `inputTokens` inclusive of the cached portion, matching Codex.
const uncachedInputTokens = Math.max(
0,
totals.inputTokens - cachedInputTokens - cacheCreationTokens,
);
const outputTokens = totals.outputTokens;
return {
uncachedInputTokens,
cachedInputTokens,
cacheCreationTokens,
outputTokens,
reasoningTokens: Math.min(outputTokens, totals.reasoningTokens),
};
}
/**
* Parses one line of a Grok Build `updates.jsonl` session log.
*
* Usage lands on `turn_completed` session updates. Per-model breakdowns live
* under `usage.modelUsage`; when present each model becomes its own record.
*
* Returns every record for the line (0 or more). Callers stream line-by-line
* and flatten.
*/
export function parseGrokLine(line: string): readonly UsageRecord[] {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
return [];
}
return parseGrokRecord(parsed);
}
export function parseGrokRecord(parsed: unknown): readonly UsageRecord[] {
if (typeof parsed !== "object" || parsed === null) return [];
const record = parsed as Record<string, unknown>;
const params = record["params"];
if (typeof params !== "object" || params === null) return [];
const paramsRecord = params as Record<string, unknown>;
const update = paramsRecord["update"];
if (typeof update !== "object" || update === null) return [];
const updateRecord = update as Record<string, unknown>;
if (updateRecord["sessionUpdate"] !== "turn_completed") return [];
const usage = updateRecord["usage"];
if (typeof usage !== "object" || usage === null) return [];
const usageRecord = usage as Record<string, unknown>;
const sessionId = typeof paramsRecord["sessionId"] === "string" ? paramsRecord["sessionId"] : "";
const promptId = typeof updateRecord["prompt_id"] === "string" ? updateRecord["prompt_id"] : null;
// Prefer the high-resolution agent clock; fall back to the outer unix seconds.
const meta = paramsRecord["_meta"];
let timestampMs: number | null = null;
if (typeof meta === "object" && meta !== null) {
const agentTimestampMs = (meta as Record<string, unknown>)["agentTimestampMs"];
if (typeof agentTimestampMs === "number" && Number.isFinite(agentTimestampMs)) {
timestampMs = agentTimestampMs;
}
}
if (timestampMs === null) {
const timestamp = record["timestamp"];
if (typeof timestamp === "number" && Number.isFinite(timestamp)) {
timestampMs = timestamp > 1e12 ? timestamp : timestamp * 1000;
}
}
if (timestampMs === null) return [];
const topLevel = readGrokUsageTotals(usageRecord);
if (topLevel === null) return [];
const modelUsage = usageRecord["modelUsage"];
const modelEntries: Array<{ model: string; totals: GrokUsageTotals }> = [];
if (typeof modelUsage === "object" && modelUsage !== null) {
for (const [model, raw] of Object.entries(modelUsage as Record<string, unknown>)) {
if (model.length === 0) continue;
const totals = readGrokUsageTotals(raw);
if (totals === null) continue;
modelEntries.push({ model, totals });
}
}
if (modelEntries.length === 0) {
if (totalTokens(grokTotalsToUsage(topLevel)) === 0) return [];
return [
{
provider: "grok",
timestampMs,
model: "grok",
sessionId,
totals: grokTotalsToUsage(topLevel),
reportedCostUsd: grokCostTicksToUsd(topLevel.costUsdTicks),
speed: "standard",
// No prompt id means we cannot tell two same-second updates apart.
dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:grok`,
},
];
}
// Cost allocation:
// 1. Emitted models with their own costUsdTicks keep those values.
// 2. Remaining aggregate cost (top-level minus those per-model ticks,
// clamped at 0) is pro-rated across emitted models that lack ticks,
// by token share among the unticked models only.
// 3. When no model has per-model ticks, remaining equals the full
// aggregate and every emitted model gets a token-share slice.
// Zero-token rows are never emitted and never count toward used ticks.
const topLevelCostUsd = grokCostTicksToUsd(topLevel.costUsdTicks);
let usedTickedCostUsd = 0;
let untickedTokenDenominator = 0;
for (const entry of modelEntries) {
const tokens = totalTokens(grokTotalsToUsage(entry.totals));
if (tokens === 0) continue;
if (entry.totals.costUsdTicks !== null) {
usedTickedCostUsd += grokCostTicksToUsd(entry.totals.costUsdTicks) ?? 0;
} else {
untickedTokenDenominator += tokens;
}
}
const remainingCostUsd =
topLevelCostUsd === null ? null : Math.max(0, topLevelCostUsd - usedTickedCostUsd);
const results: UsageRecord[] = [];
for (const entry of modelEntries) {
const totals = grokTotalsToUsage(entry.totals);
if (totalTokens(totals) === 0) continue;
let reportedCostUsd = grokCostTicksToUsd(entry.totals.costUsdTicks);
if (reportedCostUsd === null && remainingCostUsd !== null && untickedTokenDenominator > 0) {
reportedCostUsd = remainingCostUsd * (totalTokens(totals) / untickedTokenDenominator);
}
results.push({
provider: "grok",
timestampMs,
model: entry.model,
sessionId,
totals,
reportedCostUsd,
speed: "standard",
dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${entry.model}`,
});
}
return results;
}
export { EMPTY_TOTALS };
+4
View File
@@ -175,6 +175,10 @@
"types": "./src/server/threadTitleContext.ts",
"import": "./src/server/threadTitleContext.ts"
},
"./server/usage": {
"types": "./src/server/usage.ts",
"import": "./src/server/usage.ts"
},
"./server/usageLimits": {
"types": "./src/server/usageLimits.ts",
"import": "./src/server/usageLimits.ts"
+12 -2
View File
@@ -42,6 +42,7 @@ import type { ProviderAuthController } from "./auth.ts";
import type { ProviderDriverError } from "./errors.ts";
import type { ManagedServerProvider } from "./snapshot.ts";
import type { ProviderTextGeneration } from "./textGeneration.ts";
import type { ProviderUsageReader } from "./usage.ts";
/**
* Static metadata advertised by a driver. Used for default presentation
@@ -172,7 +173,7 @@ export interface ProviderDriverCreateInput<Config> {
* scope closes. Two calls to `create` with different `instanceId` /
* `config` MUST yield instances with no shared mutable state.
*/
export interface ProviderDriver<Config, R = never> {
export interface ProviderDriver<Config, R = never, UsageR = never> {
readonly driverKind: ProviderDriverKind;
readonly metadata: ProviderDriverMetadata;
/**
@@ -207,6 +208,11 @@ export interface ProviderDriver<Config, R = never> {
readonly create: (
input: ProviderDriverCreateInput<Config>,
) => Effect.Effect<ProviderInstance, ProviderDriverError, R | Scope.Scope>;
/**
* Where the usage page reads this provider's token history, when it keeps
* one. `UsageR` is what the reader needs, usually far less than `R`.
*/
readonly usage?: ProviderUsageReader<Config, UsageR>;
}
/**
@@ -219,4 +225,8 @@ export interface ProviderDriver<Config, R = never> {
// needs the original `Config` type. Using `unknown` instead would force
// `create` callers into casts since `unknown` is not assignable to a
// concrete `Config` from inside the driver body.
export type AnyProviderDriver<R = never> = ProviderDriver<any, R>;
export type AnyProviderDriver<R = never, UsageR = unknown> = ProviderDriver<any, R, UsageR>;
/** The services a driver's usage reader needs. */
export type ProviderUsageReaderEnv<Driver> =
Driver extends ProviderDriver<any, any, infer UsageR> ? UsageR : never;
@@ -0,0 +1,17 @@
import { describe, expect, it } from "@effect/vitest";
import { totalTokens } from "./usage.ts";
describe("totalTokens", () => {
it("does not add reasoning on top of output", () => {
expect(
totalTokens({
uncachedInputTokens: 10,
cachedInputTokens: 20,
cacheCreationTokens: 30,
outputTokens: 40,
reasoningTokens: 25,
}),
).toBe(100);
});
});
+179
View File
@@ -0,0 +1,179 @@
/**
* The usage reader contract: how a driver tells the server's usage page where
* its history lives and how to read it.
*
* A driver either points at JSONL transcripts that the server's shared engine
* streams, caches and resumes (`kind: "transcripts"`), or scans its own
* sources and returns their records (`kind: "scan"`). The server owns
* pricing, aggregation, de-duplication and the scan cache.
*
* @module provider-core/server/usage
*/
import type {
ProviderInstanceId,
UsageProviderKind,
UsageSource,
UsageTokenTotals,
} from "@t3tools/contracts";
import type * as Effect from "effect/Effect";
import type * as Schema from "effect/Schema";
/**
* Billing speed of a request. Faster speeds bill at a model-specific premium.
* Claude fast mode and Codex `priority` are `fast`; Codex `ultrafast` is its
* own, more expensive tier.
*/
export type UsageSpeed = "standard" | "fast" | "ultrafast";
export interface UsageRecord {
readonly provider: UsageProviderKind;
readonly timestampMs: number;
readonly model: string;
/**
* Rate-table key when the provider's display name carries tiers the table
* does not know, such as Cursor's `claude-opus-5-5-high`. Defaults to `model`.
*/
readonly rateModel?: string;
readonly sessionId: string;
readonly totals: UsageTokenTotals;
readonly reportedCostUsd: number | null;
/** Only Claude Code and Codex record a speed; other providers are `standard`. */
readonly speed: UsageSpeed;
/**
* Key for cross-file de-duplication, or `null` when the record is inherently
* unique and needs no dedup.
*/
readonly dedupeKey: string | null;
}
export const EMPTY_TOTALS: UsageTokenTotals = {
uncachedInputTokens: 0,
cachedInputTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
reasoningTokens: 0,
};
export function totalTokens(totals: UsageTokenTotals): number {
// reasoningTokens is a subset of outputTokens and must not be added again.
return (
totals.uncachedInputTokens +
totals.cachedInputTokens +
totals.cacheCreationTokens +
totals.outputTokens
);
}
/** A token count from untrusted JSON: a positive finite number, truncated, else 0. */
export function tokenCount(value: unknown): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
}
/** Epoch milliseconds of an ISO timestamp string, or `null`. */
export function parseTimestampMs(value: unknown): number | null {
if (typeof value !== "string") return null;
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? null : parsed;
}
/** JSON fields a format reads. `true` keeps the whole subtree. */
export type SelectedFields = { readonly [key: string]: true | SelectedFields };
/**
* How the server's JSONL engine reads one provider's transcript lines.
*
* Lines arrive one at a time. A line too large to parse whole is projected to
* `selectFields` and handed to `parseProjected` instead of `parseLine`.
*/
export interface TranscriptUsageFormat<State> {
readonly selectFields: SelectedFields;
/**
* Cheap substring gate applied before `JSON.parse`. Transcripts are mostly
* tool output; skipping lines that cannot matter is worth an order of
* magnitude. Lines that only update `State` must pass too.
*/
mightCarryUsage(line: string): boolean;
parseLine(line: string, state: State): readonly UsageRecord[];
parseProjected(projected: unknown, state: State): readonly UsageRecord[];
/**
* Present for formats whose records depend on earlier lines. The state at a
* resume point is persisted in the scan cache through `schema`, so a grown
* file resumes with it. Absent means every line stands alone.
*/
readonly state?: {
readonly initial: () => State;
readonly schema: Schema.Codec<State, unknown>;
};
/**
* Whether one session's records may appear in several files, such as a
* rollout copied when it moves. The server then keys those sessions'
* records for cross-file de-duplication.
*/
readonly sharedSessionsAcrossFiles?: true;
}
/** A configured instance of the driver, its config already decoded by `driver.configSchema`. */
export interface ProviderUsageInstance<Config> {
readonly instanceId: ProviderInstanceId;
/**
* `undefined` when the stored config does not decode. The instance still has
* history on disk, so readers that need no config read it anyway.
*/
readonly config: Config | undefined;
/** The instance's environment merged over the host environment. */
readonly environment: NodeJS.ProcessEnv;
/** Whether settings list the instance, rather than it being the implicit default. */
readonly configured: boolean;
}
/** One source a `scan` reader read. */
export interface ProviderUsageScan {
readonly dir: string;
readonly volumeId: string;
/** Overrides the server's host name in the source fingerprint, for account-wide sources. */
readonly hostId?: string;
readonly status?: UsageSource["status"];
readonly message?: string;
readonly action?: UsageSource["action"];
/** Parsed records per file, or `null` when the source does not exist. */
readonly files:
| readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
| null;
/** Answered from a cache while a refresh runs. */
readonly refreshing?: true;
}
export interface ProviderUsageScanInput<Config> {
readonly instances: ReadonlyArray<ProviderUsageInstance<Config>>;
/** Files last written before this cannot hold records inside the window. */
readonly windowStartMs: number;
/** The oldest usage the server keeps; account caches cover back to here. */
readonly retentionCutoffMs: number;
/** Wait for a slow refresh instead of answering from a cache. */
readonly awaitRefresh: boolean;
}
export type ProviderUsageReader<Config, R> =
| {
readonly kind: "transcripts";
readonly provider: UsageProviderKind;
readonly format: TranscriptUsageFormat<unknown>;
/**
* Transcript directories for one instance. The server canonicalizes,
* de-duplicates and scans them; `fileName` limits a walk to one basename.
*/
readonly directories: (
instance: ProviderUsageInstance<Config>,
) => Effect.Effect<
ReadonlyArray<{ readonly dir: string; readonly fileName?: string }>,
never,
R
>;
}
| {
readonly kind: "scan";
readonly provider: UsageProviderKind;
readonly scan: (
input: ProviderUsageScanInput<Config>,
) => Effect.Effect<ReadonlyArray<ProviderUsageScan>, never, R>;
};
+4
View File
@@ -15,6 +15,10 @@
"types": "./src/server.ts",
"import": "./src/server.ts"
},
"./server/usage": {
"types": "./src/server/usage.ts",
"import": "./src/server/usage.ts"
},
"./testing": {
"types": "./src/testing.ts",
"import": "./src/testing.ts"
+3 -1
View File
@@ -19,6 +19,7 @@ import {
checkGrokProviderStatus,
enrichGrokSnapshot,
} from "./status.ts";
import { grokUsageReader } from "./usage.ts";
import { readGrokAccount } from "./usageLimits.ts";
import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
import {
@@ -82,7 +83,7 @@ export type GrokDriverEnv =
| Path.Path
| ProviderEventLoggers.ProviderEventLoggers;
export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv, Path.Path> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "Grok",
@@ -90,6 +91,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
},
configSchema: GrokSettings,
defaultConfig: (): GrokSettings => decodeGrokSettings({}),
usage: grokUsageReader,
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
@@ -0,0 +1,316 @@
import { describe, expect, it } from "@effect/vitest";
import { GROK_COST_USD_TICKS_PER_DOLLAR, parseGrokLine } from "./usage.ts";
describe("parseGrokLine", () => {
/** Shaped after a real Grok Build `turn_completed` session update. */
function turnCompleted(overrides?: {
sessionId?: string;
promptId?: string;
timestamp?: number;
agentTimestampMs?: number;
usage?: Record<string, unknown>;
modelUsage?: Record<string, Record<string, unknown>> | null;
}): string {
const modelUsage =
overrides && "modelUsage" in overrides
? overrides.modelUsage
: {
"grok-4.5-build": {
inputTokens: 20_272,
outputTokens: 272,
totalTokens: 20_544,
cachedReadTokens: 11_264,
cacheCreationTokens: 0,
reasoningTokens: 180,
costUsdTicks: 230_272_000,
},
};
return JSON.stringify({
timestamp: overrides?.timestamp ?? 1_786_372_566,
method: "_x.ai/session/update",
params: {
sessionId: overrides?.sessionId ?? "019fec1a-12f7-72f2-9b1f-7778a00aea3c",
update: {
sessionUpdate: "turn_completed",
prompt_id: overrides?.promptId ?? "prompt-1",
stop_reason: "end_turn",
usage: {
inputTokens: 20_272,
outputTokens: 272,
totalTokens: 20_544,
cachedReadTokens: 11_264,
cacheCreationTokens: 0,
reasoningTokens: 180,
costUsdTicks: 230_272_000,
...(modelUsage === null ? {} : { modelUsage }),
...overrides?.usage,
},
},
_meta: {
eventId: "event-1",
agentTimestampMs: overrides?.agentTimestampMs ?? 1_786_372_566_485,
},
},
});
}
it("extracts per-model totals and provider-reported cost ticks", () => {
const records = parseGrokLine(turnCompleted());
expect(records).toHaveLength(1);
const [record] = records;
expect(record?.provider).toBe("grok");
expect(record?.model).toBe("grok-4.5-build");
expect(record?.sessionId).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c");
expect(record?.timestampMs).toBe(1_786_372_566_485);
expect(record?.totals).toEqual({
uncachedInputTokens: 20_272 - 11_264,
cachedInputTokens: 11_264,
cacheCreationTokens: 0,
outputTokens: 272,
reasoningTokens: 180,
});
expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok-4.5-build");
});
it("emits one record per model when modelUsage has several entries", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5": {
inputTokens: 1000,
outputTokens: 50,
cachedReadTokens: 400,
reasoningTokens: 20,
costUsdTicks: 50_000_000,
},
"grok-composer-2.5-fast": {
inputTokens: 200,
outputTokens: 30,
cachedReadTokens: 100,
reasoningTokens: 0,
costUsdTicks: 10_000_000,
},
},
}),
);
expect(records.map((record) => record.model).toSorted()).toEqual([
"grok-4.5",
"grok-composer-2.5-fast",
]);
expect(records.every((record) => record.provider === "grok")).toBe(true);
expect(records.find((record) => record.model === "grok-4.5")?.reportedCostUsd).toBeCloseTo(
0.005,
12,
);
});
it("inherits top-level cost ticks for a single model without its own ticks", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5-build": {
inputTokens: 1000,
outputTokens: 10,
cachedReadTokens: 0,
reasoningTokens: 0,
},
},
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
}),
);
expect(records).toHaveLength(1);
expect(records[0]?.reportedCostUsd).toBe(1);
});
it("falls back to a generic grok model when modelUsage is absent", () => {
const records = parseGrokLine(turnCompleted({ modelUsage: null }));
expect(records).toHaveLength(1);
const [record] = records;
expect(record?.provider).toBe("grok");
expect(record?.model).toBe("grok");
expect(record?.totals).toEqual({
uncachedInputTokens: 20_272 - 11_264,
cachedInputTokens: 11_264,
cacheCreationTokens: 0,
outputTokens: 272,
reasoningTokens: 180,
});
expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok");
});
it("pro-rates top-level cost ticks across multi-model turns without per-model ticks", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5": {
inputTokens: 300,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
"grok-composer-2.5-fast": {
inputTokens: 100,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
},
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
}),
);
expect(records).toHaveLength(2);
const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
const sum =
(byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
(byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
expect(sum).toBeCloseTo(1, 12);
});
it("pro-rates aggregate cost when a zero-token sibling carries costUsdTicks: 0", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5": {
inputTokens: 300,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
"grok-composer-2.5-fast": {
inputTokens: 100,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
"empty-sibling": {
inputTokens: 0,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
costUsdTicks: 0,
},
},
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
}),
);
expect(records).toHaveLength(2);
expect(records.every((record) => record.model !== "empty-sibling")).toBe(true);
const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
const sum =
(byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
(byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
expect(sum).toBeCloseTo(1, 12);
});
it("allocates leftover aggregate ticks to models that omit per-model ticks", () => {
const records = parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5": {
inputTokens: 300,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
costUsdTicks: 0.4 * GROK_COST_USD_TICKS_PER_DOLLAR,
},
"grok-composer-2.5-fast": {
inputTokens: 100,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
},
},
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
}),
);
expect(records).toHaveLength(2);
const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.4, 12);
expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.6, 12);
const sum =
(byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
(byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
expect(sum).toBeCloseTo(1, 12);
});
it("does not invent a colliding dedupe key when prompt_id is missing", () => {
const line = JSON.stringify({
timestamp: 1_786_372_566,
method: "_x.ai/session/update",
params: {
sessionId: "s1",
update: {
sessionUpdate: "turn_completed",
usage: {
inputTokens: 10,
outputTokens: 2,
modelUsage: {
"grok-4.5": { inputTokens: 10, outputTokens: 2 },
},
},
},
},
});
expect(parseGrokLine(line)[0]?.dedupeKey).toBeNull();
});
it("ignores non-turn lines and empty usage", () => {
expect(parseGrokLine(JSON.stringify({ method: "session/update", params: {} }))).toEqual([]);
expect(parseGrokLine("not json")).toEqual([]);
expect(
parseGrokLine(
turnCompleted({
modelUsage: {
"grok-4.5-build": {
inputTokens: 0,
outputTokens: 0,
cachedReadTokens: 0,
reasoningTokens: 0,
costUsdTicks: 0,
},
},
}),
),
).toEqual([]);
});
it("falls back to the outer unix-seconds timestamp when agent meta is missing", () => {
const line = JSON.stringify({
timestamp: 1_786_372_566,
method: "_x.ai/session/update",
params: {
sessionId: "s1",
update: {
sessionUpdate: "turn_completed",
prompt_id: "p1",
usage: {
inputTokens: 10,
outputTokens: 2,
modelUsage: {
"grok-4.5": { inputTokens: 10, outputTokens: 2 },
},
},
},
},
});
const records = parseGrokLine(line);
expect(records[0]?.timestampMs).toBe(1_786_372_566_000);
});
});
+239
View File
@@ -0,0 +1,239 @@
/**
* Usage history for Grok Build: the format of its per-session
* `updates.jsonl` logs and where each instance's `GROK_HOME` keeps them.
*
* @module provider-grok/server/usage
*/
import * as NodeOS from "node:os";
import type { UsageTokenTotals } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Path from "effect/Path";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import {
tokenCount,
totalTokens,
type ProviderUsageReader,
type TranscriptUsageFormat,
type UsageRecord,
} from "@t3tools/provider-core/server/usage";
import type { GrokSettings } from "../settings.ts";
/**
* Grok reports cost in integer ticks where `1 USD = 10^10` ticks. See Grok
* headless `total_cost_usd_ticks`. Convert to dollars for pricing.
*/
export const GROK_COST_USD_TICKS_PER_DOLLAR = 10_000_000_000;
function grokCostTicksToUsd(ticks: unknown): number | null {
if (typeof ticks !== "number" || !Number.isFinite(ticks) || ticks < 0) return null;
return ticks / GROK_COST_USD_TICKS_PER_DOLLAR;
}
interface GrokUsageTotals {
readonly inputTokens: number;
readonly outputTokens: number;
readonly cachedReadTokens: number;
readonly cacheCreationTokens: number;
readonly reasoningTokens: number;
readonly costUsdTicks: number | null;
}
function readGrokUsageTotals(value: unknown): GrokUsageTotals | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
return {
inputTokens: tokenCount(record["inputTokens"]),
outputTokens: tokenCount(record["outputTokens"]),
cachedReadTokens: tokenCount(record["cachedReadTokens"]),
cacheCreationTokens: tokenCount(record["cacheCreationTokens"]),
reasoningTokens: tokenCount(record["reasoningTokens"]),
costUsdTicks:
typeof record["costUsdTicks"] === "number" && Number.isFinite(record["costUsdTicks"])
? record["costUsdTicks"]
: null,
};
}
function grokTotalsToUsage(totals: GrokUsageTotals): UsageTokenTotals {
const cachedInputTokens = totals.cachedReadTokens;
const cacheCreationTokens = totals.cacheCreationTokens;
// Grok reports `inputTokens` inclusive of the cached portion, matching Codex.
const uncachedInputTokens = Math.max(
0,
totals.inputTokens - cachedInputTokens - cacheCreationTokens,
);
const outputTokens = totals.outputTokens;
return {
uncachedInputTokens,
cachedInputTokens,
cacheCreationTokens,
outputTokens,
reasoningTokens: Math.min(outputTokens, totals.reasoningTokens),
};
}
/**
* Parses one line of a Grok Build `updates.jsonl` session log.
*
* Usage lands on `turn_completed` session updates. Per-model breakdowns live
* under `usage.modelUsage`; when present each model becomes its own record.
*
* Returns every record for the line (0 or more). Callers stream line-by-line
* and flatten.
*/
export function parseGrokLine(line: string): readonly UsageRecord[] {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
return [];
}
return parseGrokRecord(parsed);
}
function parseGrokRecord(parsed: unknown): readonly UsageRecord[] {
if (typeof parsed !== "object" || parsed === null) return [];
const record = parsed as Record<string, unknown>;
const params = record["params"];
if (typeof params !== "object" || params === null) return [];
const paramsRecord = params as Record<string, unknown>;
const update = paramsRecord["update"];
if (typeof update !== "object" || update === null) return [];
const updateRecord = update as Record<string, unknown>;
if (updateRecord["sessionUpdate"] !== "turn_completed") return [];
const usage = updateRecord["usage"];
if (typeof usage !== "object" || usage === null) return [];
const usageRecord = usage as Record<string, unknown>;
const sessionId = typeof paramsRecord["sessionId"] === "string" ? paramsRecord["sessionId"] : "";
const promptId = typeof updateRecord["prompt_id"] === "string" ? updateRecord["prompt_id"] : null;
// Prefer the high-resolution agent clock; fall back to the outer unix seconds.
const meta = paramsRecord["_meta"];
let timestampMs: number | null = null;
if (typeof meta === "object" && meta !== null) {
const agentTimestampMs = (meta as Record<string, unknown>)["agentTimestampMs"];
if (typeof agentTimestampMs === "number" && Number.isFinite(agentTimestampMs)) {
timestampMs = agentTimestampMs;
}
}
if (timestampMs === null) {
const timestamp = record["timestamp"];
if (typeof timestamp === "number" && Number.isFinite(timestamp)) {
timestampMs = timestamp > 1e12 ? timestamp : timestamp * 1000;
}
}
if (timestampMs === null) return [];
const topLevel = readGrokUsageTotals(usageRecord);
if (topLevel === null) return [];
const modelUsage = usageRecord["modelUsage"];
const modelEntries: Array<{ model: string; totals: GrokUsageTotals }> = [];
if (typeof modelUsage === "object" && modelUsage !== null) {
for (const [model, raw] of Object.entries(modelUsage as Record<string, unknown>)) {
if (model.length === 0) continue;
const totals = readGrokUsageTotals(raw);
if (totals === null) continue;
modelEntries.push({ model, totals });
}
}
if (modelEntries.length === 0) {
if (totalTokens(grokTotalsToUsage(topLevel)) === 0) return [];
return [
{
provider: "grok",
timestampMs,
model: "grok",
sessionId,
totals: grokTotalsToUsage(topLevel),
reportedCostUsd: grokCostTicksToUsd(topLevel.costUsdTicks),
speed: "standard",
// No prompt id means we cannot tell two same-second updates apart.
dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:grok`,
},
];
}
// Cost allocation:
// 1. Emitted models with their own costUsdTicks keep those values.
// 2. Remaining aggregate cost (top-level minus those per-model ticks,
// clamped at 0) is pro-rated across emitted models that lack ticks,
// by token share among the unticked models only.
// 3. When no model has per-model ticks, remaining equals the full
// aggregate and every emitted model gets a token-share slice.
// Zero-token rows are never emitted and never count toward used ticks.
const topLevelCostUsd = grokCostTicksToUsd(topLevel.costUsdTicks);
let usedTickedCostUsd = 0;
let untickedTokenDenominator = 0;
for (const entry of modelEntries) {
const tokens = totalTokens(grokTotalsToUsage(entry.totals));
if (tokens === 0) continue;
if (entry.totals.costUsdTicks !== null) {
usedTickedCostUsd += grokCostTicksToUsd(entry.totals.costUsdTicks) ?? 0;
} else {
untickedTokenDenominator += tokens;
}
}
const remainingCostUsd =
topLevelCostUsd === null ? null : Math.max(0, topLevelCostUsd - usedTickedCostUsd);
const results: UsageRecord[] = [];
for (const entry of modelEntries) {
const totals = grokTotalsToUsage(entry.totals);
if (totalTokens(totals) === 0) continue;
let reportedCostUsd = grokCostTicksToUsd(entry.totals.costUsdTicks);
if (reportedCostUsd === null && remainingCostUsd !== null && untickedTokenDenominator > 0) {
reportedCostUsd = remainingCostUsd * (totalTokens(totals) / untickedTokenDenominator);
}
results.push({
provider: "grok",
timestampMs,
model: entry.model,
sessionId,
totals,
reportedCostUsd,
speed: "standard",
dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${entry.model}`,
});
}
return results;
}
export const grokUsageFormat: TranscriptUsageFormat<void> = {
selectFields: {
timestamp: true,
params: {
sessionId: true,
_meta: { agentTimestampMs: true },
update: { sessionUpdate: true, prompt_id: true, usage: true },
},
},
mightCarryUsage: (line) => line.includes('"turn_completed"'),
parseLine: (line) => parseGrokLine(line),
parseProjected: (projected) => parseGrokRecord(projected),
};
export const grokUsageReader: ProviderUsageReader<GrokSettings, Path.Path> = {
kind: "transcripts",
provider: "grok",
format: grokUsageFormat,
directories: Effect.fn("grokUsageReader.directories")(function* ({ environment }) {
const path = yield* Path.Path;
const home = expandHomePath(
environment.GROK_HOME?.trim() || path.join(NodeOS.homedir(), ".grok"),
);
// Sessions also ship multi-megabyte `chat_history` and `events` logs that
// never carry usage; only `updates.jsonl` does.
return [{ dir: path.resolve(home, "sessions"), fileName: "updates.jsonl" }];
}),
};