codeburn/src/providers/codex.ts
Resham Joshi bfd3437236 fix(codex): read a small cumulative drop as a correction, not a restart
Any drop in the total counted as a restart, so 8000/800 -> 7900/790 emitted
a second 7900/790 call. A restart now needs the total to fall to at most
half; a smaller drop is a correction and adds nothing.
Rule evidence: owner data has 0 cumulative-only records and 10 total drops,
all with every field falling to <=0.3% of the prior total (4 at a new
task, none at a compaction).
2026-11-06 06:16:43 -08:00

1855 lines
91 KiB
TypeScript

import { readdir, stat } from 'fs/promises'
import { createInterface } from 'readline'
import { basename, join, resolve } from 'path'
import { homedir } from 'os'
import { createTextReadStream, FS_SCAN_CONCURRENCY, mapWithConcurrency, readSessionLines } from '../fs-utils.js'
import { billableOutputTokens, calculateCost, getModelCosts, ownValue, pricingModelAt } from '../models.js'
import { readCachedCodexResults, writeCachedCodexResults, getCachedCodexProject, fingerprintFile, type CodexFileFingerprint } from '../codex-cache.js'
import { mergeToolIntervals } from '../codex-throughput.js'
import { codexReplayNativeToolIdentity, codexReplayResponseIdentity, codexReplayUsageIdentity, isCodexForkReplay, isCodexForkReplayState, loadCodexParentReplayIndex, startCodexForkReplay, type CodexForkReplayState } from '../codex-fork-replay.js'
import { findRawObjectField, getRawObjectFieldWindow } from '../codex-jsonl-fields.js'
import { normalizeContentBlocks } from '../content-utils.js'
import { estimateTokensFromChars } from '../token-estimate.js'
import { wslHomes } from '../wsl.js'
import type { ToolCall } from '../types.js'
import type { Provider, ProbeRoot, SessionSource, SessionParser, ParsedProviderCall } from './types.js'
import { defaultBilledCodexHome, defaultLauncherRoots, FIRST_LINE_READ_CAP, isNestedLauncherCodexHome, isRolloutFileName, listRolloutSessionIds, rolloutFileSessionId, rolloutStem, sameCodexHome } from '../launcher-homes.js'
const modelDisplayNames: Record<string, string> = {
'codex-auto-review': 'Codex Auto Review',
'gpt-5.5': 'GPT-5.5',
'gpt-5.4-mini': 'GPT-5.4 Mini',
'gpt-5.4': 'GPT-5.4',
'gpt-5.3-codex-spark': 'GPT-5.3 Codex Spark',
'gpt-5.3-codex': 'GPT-5.3 Codex',
'gpt-5.2-low': 'GPT-5.2 Low',
'gpt-5.2': 'GPT-5.2',
'gpt-5': 'GPT-5',
'gpt-4o-mini': 'GPT-4o Mini',
'gpt-4o': 'GPT-4o',
}
// Longest-first + version-boundary match so an unlisted future minor (gpt-5.6)
// falls through to its raw id instead of collapsing into the base "GPT-5" entry.
const modelDisplayEntries = Object.entries(modelDisplayNames).sort((a, b) => b[0].length - a[0].length)
const toolNameMap: Record<string, string> = {
exec_command: 'Bash',
// Codex Desktop's custom-tool transport uses the shorter `exec` name for
// the same shell tool that CLI rollouts record as `exec_command`.
exec: 'Bash',
read_file: 'Read',
write_file: 'Edit',
apply_diff: 'Edit',
apply_patch: 'Edit',
spawn_agent: 'Agent',
close_agent: 'Agent',
wait_agent: 'Agent',
read_dir: 'Glob',
}
// CLI-based MCP wrappers (e.g. philschmid/mcp-cli) let Codex call an MCP tool
// through a shell command instead of registering the server natively. Codex
// then logs a plain exec_command with no `mcp_tool_call_end` event, so the MCP
// usage would only appear as a shell command and be absent from the MCP
// breakdown (issue #478). Recognize the `mcp-cli [options] call <server>
// <tool>` form and return the canonical mcp__<server>__<tool> so the call is
// also attributed to MCP. Only the `call` subcommand (an actual tool execution)
// is matched; info / grep / bare listing are lookups. The exec_command still
// counts as Bash since it genuinely is a shell exec. Scoped to the mcp-cli
// binary; other wrappers would need their own pattern.
//
// `mcp-cli` must be the command being run: the first word of a command
// segment (text start, after a shell separator, `(`, a backtick, a `-c`/`-lc`
// shell flag, or the exec tool's `cmd:`), optionally behind a directory prefix.
// Options before `call` are skipped, and the server and tool must be
// identifier-shaped, so a commit message or an echo that mentions it is not a call.
const MCP_CLI_CALL = /(?:^|[;|&\n(`]|\s-l?c\s+['"]?|cmd:\s*['"]?)\s*(?:[\w.~/-]*\/)?(?<![\w.-])mcp-cli(?:\s+(?!call\b)[^\s;|&]+)*\s+call\s+(['"]?)([\w.-]+)\1\s+(['"]?)([\w.-]+)\3(?=[\s'"`;|&)]|$)/
function mcpToolFromShellCommand(text: string): string | null {
const m = MCP_CLI_CALL.exec(text)
return m ? `mcp__${m[2]}__${m[4]}` : null
}
// Codex has no dedicated skill tool: loading a skill is an ordinary shell exec
// that reads the skill's `SKILL.md`, so the usage landed entirely under Bash and
// the Skills dimension stayed empty (#478). Recognize only a *read* of a
// SKILL.md, deliberately narrowly:
// - the command segment must start with a file-reading binary (cat/sed/head/
// tail/less/more/bat) — a `grep`/`rg`/`ls` that merely mentions a SKILL.md
// is a search near the file, not a skill load, and stays plain Bash;
// - the path it reads must END in `<name>/SKILL.md`, so `<name>` is the skill.
// The name is the parent directory, the same key `src/providers/pi.ts` derives
// for a native skill read (#588) and the same vocabulary the Claude parser
// records from the `Skill` tool, so the Skills breakdown stays cross-provider
// coherent. Substring matching, so a command that merely quotes the phrase can
// false-positive, an accepted tradeoff for this matcher.
const SKILL_MD_READ = /(?<![\w.-])(?:cat|bat|sed|head|tail|less|more)\b[^;|&]*?[\s'"]([^\s;|&'"]*[\\/]([^\\/;|&'"]+)[\\/]SKILL\.md)\b/
function skillFromShellCommand(text: string): string | null {
const m = SKILL_MD_READ.exec(text)
const name = m?.[2]?.trim()
return name ? name : null
}
/// Flatten every shape Codex records a shell command in to one string:
/// `function_call` arguments carry it as a plain string, the item model's
/// `CommandExecution` item as an argv array (`["/bin/zsh","-lc","..."]`), and
/// the `exec` custom tool as the JS program that calls `tools.exec_command`.
/// One text, one classification pipeline (#478).
function shellCommandText(command: unknown): string {
if (typeof command === 'string') return command
if (Array.isArray(command)) return command.filter(x => typeof x === 'string').join(' ')
return ''
}
// Count added/removed lines from a Codex `patch_apply_end` change's
// `unified_diff`. A leading '+' is an added line and '-' a removed line; the
// '+++'/'---' file headers and '@@' hunk headers are excluded. Numbers only —
// the diff text is never stored. Rich-session-capture (capture-only).
export function countUnifiedDiffLoc(diff: unknown): { added: number; removed: number } {
let added = 0
let removed = 0
if (typeof diff !== 'string') return { added, removed }
for (const line of diff.split('\n')) {
if (line.startsWith('+') && !line.startsWith('+++')) added++
else if (line.startsWith('-') && !line.startsWith('---')) removed++
}
return { added, removed }
}
type CodexEntry = {
type: string
timestamp?: string
payload?: {
type?: string
id?: string
turn_id?: string
call_id?: string
started_at?: number
duration_ms?: number
duration?: { secs?: number; nanos?: number } | string
role?: string
cwd?: string
response_id?: string
model_provider?: string
model_name?: string
originator?: string
session_id?: string
forked_from_id?: string
/// Parent of a spawned sub-agent thread; its rollout replays the parent's
/// history like a fork does, but names the parent under `source`, not
/// `forked_from_id`.
parent_thread_id?: string
source?: { subagent?: { thread_spawn?: { parent_thread_id?: string } } }
model?: string
name?: string
/// event_msg/thread_settings_applied: the thread's service tier, flattened
/// out of `thread_settings.service_tier` (#1616) so both the full-JSON and
/// the compact-head decoders surface it at payload depth 1.
serviceTier?: string
/// Raw shape of the `thread_settings_applied` payload; only the service
/// tier is read off it.
thread_settings?: { service_tier?: string }
item?: Record<string, unknown>
invocation?: { server?: string; tool?: string }
content?: Array<{ type?: string; text?: string }>
info?: {
model?: string
model_name?: string
last_token_usage?: CodexTokenUsage
total_token_usage?: CodexTokenUsage
}
usage?: CodexTokenUsage
}
}
type CodexNativeToolEvent = {
tool: 'WebSearch' | 'ToolSearch' | 'ImageGeneration'
identity?: string
}
type CodexPendingNativeToolEvent = {
tool: CodexNativeToolEvent['tool']
toolIndex: number
sequenceIndex: number
}
function nativeToolEvent(entry: CodexEntry): CodexNativeToolEvent | null {
const payload = entry.payload
if (!payload) return null
let tool: CodexNativeToolEvent['tool'] | null = null
let identity: string | undefined
if (entry.type === 'response_item') {
if (payload.type === 'web_search_call') tool = 'WebSearch'
else if (payload.type === 'tool_search_call') tool = 'ToolSearch'
else if (payload.type === 'image_generation_call') tool = 'ImageGeneration'
if (!tool) return null
identity = typeof payload.id === 'string' && payload.id
? payload.id
: typeof payload.call_id === 'string' && payload.call_id
? payload.call_id
: undefined
} else if (entry.type === 'event_msg' && payload.type === 'item_completed') {
const item = payload.item
if (!item) return null
if (item['type'] !== 'WebSearch' && !(item['type'] === 'Extension' && item['kind'] === 'web.search')) return null
tool = 'WebSearch'
identity = typeof item['id'] === 'string' && item['id'] ? item['id'] : undefined
}
if (!tool) return null
return { tool, ...(identity ? { identity: codexReplayNativeToolIdentity(tool, identity) } : {}) }
}
type CodexTokenUsage = {
input_tokens?: number
cached_input_tokens?: number
/// Portion of `input_tokens` that was WRITTEN to the prompt cache this call
/// (codex PR #33454). Like `cached_input_tokens`, it is carved out of
/// `input_tokens`, not added on top.
cache_write_input_tokens?: number
output_tokens?: number
reasoning_output_tokens?: number
total_tokens?: number
}
const RAW_HEAD_BYTES = 64 * 1024
const LARGE_TEXT_CAP = 2000
function getCodexDir(override?: string): string {
return override ?? process.env['CODEX_HOME'] ?? join(homedir(), '.codex')
}
function sanitizeProject(cwd: string): string {
return cwd.replace(/^\//, '').replace(/\//g, '-')
}
// Cap how many bytes we'll read while looking for the first newline. Real
// Codex session_meta lines are ~22-27 KB; this leaves plenty of headroom while
// keeping memory bounded if a corrupt file has no newline at all.
// FIRST_LINE_READ_CAP is shared with rolloutFileSessionId.
async function readFirstLine(filePath: string): Promise<CodexEntry | null> {
// Codex CLI 0.128+ writes a session_meta line that can exceed 20 KB because
// it embeds the full base_instructions / system prompt. A fixed-size buffer
// would miss the trailing newline and reject the session as invalid.
// Stream the file via readline so we can read the first line up to
// FIRST_LINE_READ_CAP, which keeps memory bounded if the file has no newline.
const stream = createTextReadStream(filePath, {
start: 0,
end: FIRST_LINE_READ_CAP - 1,
})
// Silence stream errors so a late read-ahead error after we've already
// returned the first line cannot escape as an unhandled 'error' event.
// readline's async iterator re-throws underlying stream errors (ENOENT,
// EACCES, etc.) on Node 16+, which the catch below handles for the cases
// that matter for validation.
stream.on('error', () => {})
const rl = createInterface({ input: stream, crlfDelay: Infinity })
let firstLine: string | undefined
try {
for await (const line of rl) {
firstLine = line
break
}
} catch {
return null
} finally {
rl.close()
stream.destroy()
}
if (!firstLine || !firstLine.trim()) return null
try {
return JSON.parse(firstLine) as CodexEntry
} catch {
return null
}
}
// Validation is STRUCTURAL, never string-matching on `payload.originator`.
// `originator` is a free-form CLIENT IDENTITY string, not a format marker: any
// tool driving `codex app-server` writes structurally identical rollouts under
// ~/.codex/sessions with its own value ("codex-tui", "Codex Desktop",
// "t3code_desktop", "JetBrains.IntelliJ IDEA", ...). Gating on the spelling
// silently dropped every third-party frontend and needed a new allowlist entry
// per client (issues #626, #873).
//
// A `session_meta` first line with a well-formed payload object is signal
// enough: the walker only visits `rollout-*.jsonl` under the strict
// YYYY/MM/DD path or `archived_sessions/`, and codex.ts is the only provider
// that reads ~/.codex, so directory ownership — not originator content —
// decides the provider. Genuinely foreign files (wrong entry type, missing or
// non-object payload, malformed JSON) are still rejected.
async function isValidCodexSession(filePath: string): Promise<{ valid: boolean; meta?: CodexEntry }> {
const entry = await readFirstLine(filePath)
if (!entry) return { valid: false }
// `entry` comes from an unchecked JSON.parse cast, so re-check the payload
// shape at runtime instead of trusting the declared type.
const payload: unknown = entry.payload
const valid = entry.type === 'session_meta' &&
typeof payload === 'object' &&
payload !== null &&
!Array.isArray(payload)
return { valid, meta: valid ? entry : undefined }
}
function getRawJsonStringField(head: string, field: string): string | undefined {
const re = new RegExp(`"${field}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"`)
const match = re.exec(head)
if (!match) return undefined
try {
return JSON.parse(`"${match[1]}"`) as string
} catch {
return match[1]
}
}
function getRawJsonNumberField(head: string, field: string): number | undefined {
const match = new RegExp(`"${field}"\\s*:\\s*(-?\\d+(?:\\.\\d+)?)`).exec(head)
if (!match) return undefined
const value = Number(match[1])
return Number.isFinite(value) ? value : undefined
}
function getRawPayloadObjectStart(source: Buffer): number | undefined {
const payload = findRawObjectField(source, 0, 'payload')
return payload && source[payload.valueStart] === 0x7b ? payload.valueStart : undefined
}
function getRawPayloadFieldWindow(source: Buffer, field: string, windowBytes = 4096): string | undefined {
const payloadStart = getRawPayloadObjectStart(source)
return payloadStart === undefined ? undefined : getRawObjectFieldWindow(source, payloadStart, field, windowBytes)
}
function getRawPayloadItemFieldWindow(source: Buffer, field: string, windowBytes = 4096): string | undefined {
const payloadStart = getRawPayloadObjectStart(source)
if (payloadStart === undefined) return undefined
const item = findRawObjectField(source, payloadStart, 'item')
if (!item || source[item.valueStart] !== 0x7b) return undefined
return getRawObjectFieldWindow(source, item.valueStart, field, windowBytes)
}
function getRawDurationMs(head: string): number | undefined {
const objectMatch = /"duration"\s*:\s*\{\s*"secs"\s*:\s*(-?\d+(?:\.\d+)?)\s*,\s*"nanos"\s*:\s*(-?\d+(?:\.\d+)?)\s*\}/.exec(head)
if (objectMatch) {
const seconds = Number(objectMatch[1])
const nanos = Number(objectMatch[2])
if (Number.isFinite(seconds) && Number.isFinite(nanos)) return seconds * 1000 + nanos / 1e6
}
const text = getRawJsonStringField(head, 'duration')
if (text) {
const match = /^(\d+(?:\.\d+)?)(ms|s)?$/.exec(text.trim())
if (match) {
const value = Number(match[1])
if (Number.isFinite(value)) return value * (match[2] === 's' ? 1000 : 1)
}
}
return undefined
}
function durationValueMs(value: unknown): number | undefined {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'object' && value) {
const record = value as Record<string, unknown>
const seconds = record['secs']
const nanos = record['nanos']
if (typeof seconds === 'number' && typeof nanos === 'number' && Number.isFinite(seconds) && Number.isFinite(nanos)) {
return seconds * 1000 + nanos / 1e6
}
}
if (typeof value === 'string') {
const match = /^(\d+(?:\.\d+)?)(ms|s)?$/.exec(value.trim())
if (match) {
const parsed = Number(match[1])
if (Number.isFinite(parsed)) return parsed * (match[2] === 's' ? 1000 : 1)
}
}
return undefined
}
function getRawTokenUsage(head: string, field: 'last_token_usage' | 'total_token_usage'): CodexTokenUsage | undefined {
const match = new RegExp(`"${field}"\\s*:\\s*\\{([^}]*)\\}`).exec(head)
if (!match) return undefined
const body = match[1]!
return {
input_tokens: getRawJsonNumberField(body, 'input_tokens'),
cached_input_tokens: getRawJsonNumberField(body, 'cached_input_tokens'),
cache_write_input_tokens: getRawJsonNumberField(body, 'cache_write_input_tokens'),
output_tokens: getRawJsonNumberField(body, 'output_tokens'),
reasoning_output_tokens: getRawJsonNumberField(body, 'reasoning_output_tokens'),
total_tokens: getRawJsonNumberField(body, 'total_tokens'),
}
}
function payloadHead(source: Buffer): string {
const payloadStart = getRawPayloadObjectStart(source)
return payloadStart === undefined
? ''
: source.subarray(payloadStart, Math.min(source.length, payloadStart + RAW_HEAD_BYTES)).toString('utf-8')
}
function getRawInvocation(head: string): { server?: string; tool?: string } | undefined {
const idx = head.indexOf('"invocation"')
if (idx === -1) return undefined
// Server/tool are shallow fields and precede the potentially huge arguments
// object in Codex MCP records. Limit this scan to keep compact parsing cheap.
const invocationHead = head.slice(idx, idx + 8192)
const server = getRawJsonStringField(invocationHead, 'server')
const tool = getRawJsonStringField(invocationHead, 'tool')
return server || tool ? { server, tool } : undefined
}
function countJsonStringBytes(source: Buffer, valueStart: number): number {
let count = 0
for (let i = valueStart; i < source.length; i++) {
const ch = source[i]
if (ch === 0x5c) {
i++
count++
continue
}
if (ch === 0x22) return count
count++
}
return count
}
function extractFirstJsonText(source: Buffer, cap = LARGE_TEXT_CAP): string {
const key = Buffer.from('"text"')
const idx = source.indexOf(key)
if (idx === -1) return ''
const colon = source.indexOf(0x3a, idx + key.length)
if (colon === -1) return ''
const qStart = source.indexOf(0x22, colon + 1)
if (qStart === -1) return ''
const chunks: number[] = []
for (let i = qStart + 1; i < source.length && chunks.length < cap; i++) {
const ch = source[i]
if (ch === 0x5c) {
const next = source[++i]
if (next === 0x6e) chunks.push(0x0a)
else if (next === 0x72) chunks.push(0x0d)
else if (next === 0x74) chunks.push(0x09)
else if (next !== undefined) chunks.push(next)
continue
}
if (ch === 0x22) break
chunks.push(ch)
}
return Buffer.from(chunks).toString('utf-8')
}
function countFirstJsonText(source: Buffer): number {
const key = Buffer.from('"text"')
const idx = source.indexOf(key)
if (idx === -1) return 0
const colon = source.indexOf(0x3a, idx + key.length)
if (colon === -1) return 0
const qStart = source.indexOf(0x22, colon + 1)
if (qStart === -1) return 0
return countJsonStringBytes(source, qStart + 1)
}
// `thread_settings.service_tier` (#1616). The field comes off an unchecked
// JSON.parse cast, so only a genuine non-empty string reads as a tier; anything
// else is "the rollout states no tier", which prices as standard.
function serviceTierFromThreadSettings(payload: CodexEntry['payload']): string | undefined {
const tier = payload?.thread_settings?.service_tier
return typeof tier === 'string' && tier ? tier : undefined
}
// The billable speed a service tier maps to (#1616). `"priority"` is Codex's
// Fast speed setting and bills through the priority tier; `"fast"` is accepted
// too in case a build writes the speed name where the tier name belongs.
// `"flex"` bills at the model's published Flex rates, or standard without them.
// Everything else - `"default"`, an unrecognised value, no tier at all - is
// standard, never a guess.
function speedForServiceTier(tier: string): 'standard' | 'fast' | 'flex' | 'ultrafast' {
if (tier === 'flex') return 'flex'
if (tier === 'ultrafast') return 'ultrafast'
return tier === 'priority' || tier === 'fast' ? 'fast' : 'standard'
}
function parseCodexLine(line: string | Buffer): CodexEntry | null {
if (typeof line === 'string') {
const trimmed = line.trim()
if (!trimmed) return null
try {
const entry = JSON.parse(trimmed) as CodexEntry
// #1616: `thread_settings.service_tier` sits at payload depth 2, which
// the compact path below cannot express; flatten it the same way for the
// fully-parsed path so both decoders agree.
const tier = serviceTierFromThreadSettings(entry.payload)
if (tier !== undefined && entry.payload) entry.payload.serviceTier = tier
return entry
} catch {
return null
}
}
if (line.length === 0) return null
const head = line.subarray(0, RAW_HEAD_BYTES).toString('utf-8')
const type = getRawJsonStringField(head, 'type')
if (!type) return null
const pHead = payloadHead(line)
// The depth-1 scan walks past large values when the key is missing (compacted
// history has no payload type), so only native tool candidates pay for it.
const headPayloadType = getRawJsonStringField(pHead, 'type')
const payloadType = headPayloadType === 'web_search_call' || headPayloadType === 'tool_search_call'
|| headPayloadType === 'image_generation_call' || headPayloadType === 'item_completed'
? getRawJsonStringField(getRawPayloadFieldWindow(line, 'type') ?? '', 'type')
: headPayloadType
const role = getRawJsonStringField(pHead, 'role')
// task_complete appends the potentially huge final assistant message before
// its duration fields. Fall back to the full Buffer only for this event so
// timing metadata is not lost when the compact head stops early.
const needsTimingTail = type === 'event_msg' && (payloadType === 'task_complete' || payloadType === 'mcp_tool_call_end')
const timingTail = needsTimingTail && line.length > RAW_HEAD_BYTES
? line.subarray(Math.max(0, line.length - 16 * 1024)).toString('utf-8')
: pHead
const timingNumber = (field: string): number | undefined =>
getRawJsonNumberField(pHead, field) ?? getRawJsonNumberField(timingTail, field)
// MCP records can place a large invocation.arguments object before duration
// and a large result after it. Searching a small window around the field
// avoids materializing the middle of the Buffer while still preserving wait
// timing for those records.
const payloadDuration = payloadType === 'mcp_tool_call_end'
? getRawDurationMs(getRawPayloadFieldWindow(line, 'duration') ?? '')
: undefined
const timingDuration = payloadDuration ?? getRawDurationMs(pHead) ?? getRawDurationMs(timingTail)
// session_meta can embed same-name keys under base_instructions /
// dynamic_tools (including provenance.model). A depth-agnostic scan of the
// compact head steals the first nested hit and can overwrite turn_context.
// Restrict every session_meta string field to payload depth 1. Other event
// types keep the cheap first-match scan.
const payloadString = (field: string): string | undefined =>
type === 'session_meta'
? getRawJsonStringField(getRawPayloadFieldWindow(line, field) ?? '', field)
: getRawJsonStringField(pHead, field)
const compactModel = payloadString('model')
const compactModelName = getRawJsonStringField(pHead, 'model_name')
const compactLastUsage = getRawTokenUsage(pHead, 'last_token_usage')
const compactTotalUsage = getRawTokenUsage(pHead, 'total_token_usage')
const itemTypeWindow = type === 'event_msg' && payloadType === 'item_completed'
? getRawPayloadItemFieldWindow(line, 'type')
: undefined
const compactItemType = itemTypeWindow ? getRawJsonStringField(itemTypeWindow, 'type') : undefined
const isSearchItem = compactItemType === 'WebSearch' || compactItemType === 'Extension'
const itemIdWindow = isSearchItem ? getRawPayloadItemFieldWindow(line, 'id') : undefined
const itemKindWindow = isSearchItem ? getRawPayloadItemFieldWindow(line, 'kind') : undefined
const compactItemId = itemIdWindow ? getRawJsonStringField(itemIdWindow, 'id') : undefined
const compactItemKind = itemKindWindow ? getRawJsonStringField(itemKindWindow, 'kind') : undefined
const compactItem = compactItemType
? { type: compactItemType, ...(compactItemId ? { id: compactItemId } : {}), ...(compactItemKind ? { kind: compactItemKind } : {}) }
: undefined
const isNativeResponseTool = type === 'response_item' && (
payloadType === 'web_search_call' || payloadType === 'tool_search_call' || payloadType === 'image_generation_call'
)
const nativeIdWindow = isNativeResponseTool ? getRawPayloadFieldWindow(line, 'id') : undefined
const nativeCallIdWindow = isNativeResponseTool ? getRawPayloadFieldWindow(line, 'call_id') : undefined
const compactId = nativeIdWindow ? getRawJsonStringField(nativeIdWindow, 'id') : undefined
const compactCallId = isNativeResponseTool
? nativeCallIdWindow ? getRawJsonStringField(nativeCallIdWindow, 'call_id') : undefined
: getRawJsonStringField(pHead, 'call_id')
const compactInfo = compactModel || compactModelName || compactLastUsage || compactTotalUsage
? { model: compactModel, model_name: compactModelName, last_token_usage: compactLastUsage, total_token_usage: compactTotalUsage }
: undefined
const invocation = getRawInvocation(pHead) ?? getRawInvocation(timingTail)
const entry: CodexEntry = {
type,
timestamp: getRawJsonStringField(head, 'timestamp'),
payload: {
type: payloadType,
id: compactId ?? (type === 'session_meta' ? payloadString('id') : undefined),
role,
cwd: payloadString('cwd'),
model_provider: payloadString('model_provider'),
originator: payloadString('originator'),
session_id: payloadString('session_id'),
forked_from_id: payloadString('forked_from_id'),
parent_thread_id: type === 'session_meta'
? getRawJsonStringField(getRawPayloadFieldWindow(line, 'source') ?? '', 'parent_thread_id')
: undefined,
model: compactModel,
name: payloadString('name'),
item: compactItem,
invocation,
call_id: compactCallId,
turn_id: getRawJsonStringField(pHead, 'turn_id'),
// #1616: oversized thread_settings_applied records (a fat permission
// profile or plugin list can push them past the buffer threshold) still
// carry `service_tier` within the first few hundred bytes of the
// thread_settings object, so the windowed scan reaches it. Scanning
// inside the payload-depth-1 `thread_settings` window - the session_meta
// treatment above - keeps this decoder agreeing with the full-JSON path
// (which reads the nested field) even if a same-name key ever appears in
// an earlier payload field, and the payload-type guard keeps a
// coincidental same-name key inside another event's bulk from reading as
// a tier.
serviceTier: type === 'event_msg' && payloadType === 'thread_settings_applied'
? getRawJsonStringField(getRawPayloadFieldWindow(line, 'thread_settings') ?? '', 'service_tier')
: undefined,
// On mcp_tool_call_end a coincidental `duration_ms` inside the large
// invocation.arguments object can shadow the payload-level duration, so the
// depth-aware value wins. The naive scan stays as the fallback for
// task_complete, which records duration_ms at the payload level directly.
duration_ms: timingDuration ?? timingNumber('duration_ms'),
started_at: timingNumber('started_at'),
info: compactInfo,
},
}
if (type === 'response_item' && payloadType === 'message' && role === 'user') {
entry.payload!.content = [{ type: 'input_text', text: extractFirstJsonText(line) }]
} else if (type === 'response_item' && payloadType === 'message' && role === 'assistant') {
entry.payload!.content = [{ type: 'output_text', text: 'x'.repeat(Math.min(countFirstJsonText(line), LARGE_TEXT_CAP)) }]
}
return entry
}
async function discoverSessionFile(filePath: string): Promise<SessionSource | null> {
const s = await stat(filePath).catch(() => null)
if (!s?.isFile()) return null
// Fast path: cached results already know the project, so avoid opening the
// file. This keeps discovery cheap on large session directories.
const cachedProject = await getCachedCodexProject(filePath)
if (cachedProject) {
return { path: filePath, project: cachedProject, provider: 'codex' }
}
const { valid, meta } = await isValidCodexSession(filePath)
if (!valid || !meta) return null
// Same unchecked-cast caveat as the payload check above: `cwd` is declared
// `string` but comes straight off JSON.parse. A rollout carrying a number,
// object or array here would throw out of sanitizeProject, escape
// discoverSessions, and make safeDiscoverSessions return [] for the WHOLE
// codex provider — every Codex report reading zero because of one bad file.
const rawCwd: unknown = meta.payload?.cwd
const cwd = typeof rawCwd === 'string' && rawCwd ? rawCwd : 'unknown'
return { path: filePath, project: sanitizeProject(cwd), provider: 'codex' }
}
async function discoverSessionsInDir(codexDir: string): Promise<SessionSource[]> {
const sources: SessionSource[] = []
// Codex archives a session by moving it from sessions/YYYY/MM/DD/ to
// archived_sessions/, keeping the same basename. Deduplicate by basename so
// a session does not appear twice while it exists in both roots. This avoids
// reading every file to extract session_id and preserves the cheap cached
// fast path.
const seenBasenames = new Set<string>()
const sessionsDir = join(codexDir, 'sessions')
const years = (await readdir(sessionsDir).catch(() => [] as string[])).filter(y => /^\d{4}$/.test(y))
const monthDirs = (await mapWithConcurrency(years, FS_SCAN_CONCURRENCY, async year => {
const yearDir = join(sessionsDir, year)
return (await readdir(yearDir).catch(() => [] as string[]))
.filter(m => /^\d{2}$/.test(m))
.map(m => join(yearDir, m))
})).flat()
const dayDirs = (await mapWithConcurrency(monthDirs, FS_SCAN_CONCURRENCY, async monthDir =>
(await readdir(monthDir).catch(() => [] as string[]))
.filter(d => /^\d{2}$/.test(d))
.map(d => join(monthDir, d)),
)).flat()
const dated = (await mapWithConcurrency(dayDirs, FS_SCAN_CONCURRENCY, async dayDir =>
(await readdir(dayDir).catch(() => [] as string[]))
.filter(isRolloutFileName)
.map(f => ({ file: f, path: join(dayDir, f) })),
)).flat()
// Codex moves archived sessions into a flat directory. Keep them in usage
// reports so archiving a conversation does not erase its historical usage.
// Call-level deduplication (seenKeys) already collapses any remaining
// archived copies, while basename dedup below prevents double discovery.
const archivedDir = join(codexDir, 'archived_sessions')
const archived = (await readdir(archivedDir).catch(() => [] as string[]))
.filter(isRolloutFileName)
.map(f => ({ file: f, path: join(archivedDir, f) }))
// Dedup before the reads so a basename is opened once, and keep the dated
// pass ahead of the archived one — the same precedence the serial walk had.
// While Codex compresses a rollout both forms exist briefly; the plain one
// wins because it may still be growing.
const candidates: Array<{ file: string; path: string }> = []
const all = [...dated, ...archived]
const plain = new Set(all.filter(e => !e.file.endsWith('.zst')).map(e => e.file))
for (const entry of all) {
if (seenBasenames.has(entry.file)) continue
if (entry.file.endsWith('.zst') && plain.has(entry.file.slice(0, -'.zst'.length))) continue
seenBasenames.add(entry.file)
candidates.push(entry)
}
const discovered = await mapWithConcurrency(candidates, FS_SCAN_CONCURRENCY, c => discoverSessionFile(c.path))
for (const source of discovered) if (source) sources.push(source)
return sources
}
// The model fields come off an unchecked JSON.parse cast, so a third-party
// rollout can carry a non-string `model`. It flows straight into calculateCost,
// which calls `.replace()` on it, so pick the first genuine string and never let
// a number/object/array through.
function firstModelString(...values: unknown[]): string | undefined {
for (const value of values) {
if (typeof value === 'string' && value) return value
}
return undefined
}
function resolveModel(info: CodexEntry['payload'], sessionModel?: string): string {
return firstModelString(info?.model, info?.model_name, info?.info?.model, info?.info?.model_name, sessionModel) ?? 'gpt-5'
}
function isValidCodexTokenUsage(value: unknown): value is CodexTokenUsage {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false
const usage = value as Record<string, unknown>
const fields = [
usage['input_tokens'],
usage['cached_input_tokens'],
usage['cache_write_input_tokens'],
usage['output_tokens'],
usage['reasoning_output_tokens'],
]
const hasCounter = fields.some(field => typeof field === 'number' && Number.isFinite(field) && field >= 0)
return hasCounter && fields.every(field =>
field === undefined || (typeof field === 'number' && Number.isFinite(field) && field >= 0),
)
}
// Everything the single-pass decode carries across a `task_started` boundary.
// A rollout is append-only, so recording this at such a boundary (where the
// previous task has been flushed to `results` and the per-task accumulators are
// empty) lets a later run restart there and produce byte-identical output
// instead of re-reading the whole file. Every field the loop below reads from a
// PRIOR line must appear here, or a resumed decode silently diverges.
type CodexResumeState = {
sessionModel?: string
sessionId: string
threadId?: string
sessionCwd?: string
forkedFromId: string
forkReplayState?: CodexForkReplayState
prevCumulativeTotal: number | null
/// Counter restarts seen so far; keys a repeated cumulative state after one.
restartEpoch?: number
/// Byte-identity of the last token_count info payload (#257 re-emission
/// collapse). Optional so resume states written before it still decode.
prevInfoIdentity?: string | null
/// Newer Codex builds emit one token_usage_record before each token_count
/// twin. Persist the source handover across append resumes.
hasTokenUsageRecord?: boolean
/// #1616: service tier the thread currently runs under
/// (`thread_settings_applied`), so an append resume keeps pricing Fast
/// (priority) turns as Fast. Optional so a resume state written before the
/// field existed still decodes; absent reads as the default (standard) tier.
serviceTier?: string
prevInput: number
prevCached: number
prevCacheWrite: number
prevOutput: number
prevReasoning: number
pendingTools: string[]
pendingToolSequence: ToolCall[][]
/// Native tool identities make response_item / item_completed mirrors one
/// attribution after an append resume or a task-boundary checkpoint.
pendingNativeToolEvents?: CodexPendingNativeToolEvent[]
nativeToolEventIdentities?: string[]
/// Optional so a resume state written before skills attribution existed still
/// decodes (isResumeState does not require it); absent reads as "no skills".
pendingSkills?: string[]
pendingUserMessage: string
pendingOutputChars: number
pendingLocAdded: number
pendingLocRemoved: number
pendingEditFailed: number
estCounter: number
turnCounter: number
currentTurnId: string
taskStartedAt?: number
// #1088 BUG-1: timestamp of the first request-context event (turn_context,
// world_state, event_msg/user_message, or response_item/message) seen since
// the last task_started. Codex fires task_started before it assembles the
// request, so the gap up to this event is CLI/harness startup, not model
// wait -- the active window for Tok/s starts here, not at task_started.
taskActiveStartedAt?: number
}
// The state comes back off our own JSON cache; a truncated or hand-edited file
// must fall back to a full re-parse rather than decode against nonsense.
function isResumeState(value: unknown): value is CodexResumeState {
if (!value || typeof value !== 'object') return false
const v = value as Record<string, unknown>
const pendingTools = v['pendingTools']
const pendingToolSequence = v['pendingToolSequence']
const pendingNativeToolEvents = v['pendingNativeToolEvents']
const nativeToolEventIdentities = v['nativeToolEventIdentities']
const validPendingNativeToolEvents = pendingNativeToolEvents === undefined || (
Array.isArray(pendingNativeToolEvents)
&& Array.isArray(pendingTools)
&& Array.isArray(pendingToolSequence)
&& pendingNativeToolEvents.every(event => {
if (!event || typeof event !== 'object') return false
const item = event as Record<string, unknown>
const toolIndex = item['toolIndex']
const sequenceIndex = item['sequenceIndex']
return (item['tool'] === 'WebSearch' || item['tool'] === 'ToolSearch' || item['tool'] === 'ImageGeneration')
&& typeof toolIndex === 'number'
&& Number.isInteger(toolIndex)
&& toolIndex >= 0
&& toolIndex < pendingTools.length
&& pendingTools[toolIndex] === item['tool']
&& typeof sequenceIndex === 'number'
&& Number.isInteger(sequenceIndex)
&& sequenceIndex >= 0
&& sequenceIndex < pendingToolSequence.length
&& Array.isArray(pendingToolSequence[sequenceIndex])
})
)
return typeof v['sessionId'] === 'string'
&& (v['threadId'] === undefined || typeof v['threadId'] === 'string')
&& typeof v['forkedFromId'] === 'string'
&& (v['forkReplayState'] === undefined || isCodexForkReplayState(v['forkReplayState']))
&& (v['prevCumulativeTotal'] === null || typeof v['prevCumulativeTotal'] === 'number')
&& (v['restartEpoch'] === undefined || typeof v['restartEpoch'] === 'number')
&& (v['prevInfoIdentity'] === undefined || v['prevInfoIdentity'] === null || typeof v['prevInfoIdentity'] === 'string')
&& (v['hasTokenUsageRecord'] === undefined || typeof v['hasTokenUsageRecord'] === 'boolean')
&& (v['serviceTier'] === undefined || typeof v['serviceTier'] === 'string')
&& typeof v['prevInput'] === 'number'
&& typeof v['prevCached'] === 'number'
&& typeof v['prevCacheWrite'] === 'number'
&& typeof v['prevOutput'] === 'number'
&& typeof v['prevReasoning'] === 'number'
&& Array.isArray(pendingTools)
&& Array.isArray(pendingToolSequence)
&& validPendingNativeToolEvents
&& (nativeToolEventIdentities === undefined || (Array.isArray(nativeToolEventIdentities) && nativeToolEventIdentities.every(id => typeof id === 'string')))
&& typeof v['pendingUserMessage'] === 'string'
&& typeof v['pendingOutputChars'] === 'number'
&& typeof v['pendingLocAdded'] === 'number'
&& typeof v['pendingLocRemoved'] === 'number'
&& typeof v['pendingEditFailed'] === 'number'
&& typeof v['estCounter'] === 'number'
&& typeof v['turnCounter'] === 'number'
&& typeof v['currentTurnId'] === 'string'
}
/** What the serial path would have written to the codex cache for one file. */
export type CodexCacheWrite = {
project: string
fingerprint: CodexFileFingerprint
resume?: { offset: number; state: unknown; callCount: number }
}
// When `capture` is passed the parse is a whole-file decode that never touches
// the codex cache: no hit lookup (so no resume), and the entry it would have
// written comes back through `capture` for the caller to install. That is what
// lets a worker thread run this exact decode without owning the cache module's
// per-directory state.
function createParser(source: SessionSource, seenKeys: Set<string>, capture?: { write?: CodexCacheWrite }): SessionParser {
return {
async *parse(): AsyncGenerator<ParsedProviderCall> {
const hit = capture ? null : await readCachedCodexResults(source.path)
if (hit?.kind === 'exact') {
for (const call of hit.calls) {
if (seenKeys.has(call.deduplicationKey)) continue
seenKeys.add(call.deduplicationKey)
yield call
}
return
}
const resume = hit && isResumeState(hit.state)
? { offset: hit.offset, state: hit.state, calls: hit.calls.slice(0, hit.callCount) }
: null
const fp = await fingerprintFile(source.path)
if (!fp) return
let sessionModel: string | undefined = resume?.state.sessionModel
let sessionId = resume?.state.sessionId ?? ''
let threadId = resume?.state.threadId ?? sessionId
let sessionCwd: string | undefined = resume?.state.sessionCwd
let forkedFromId = resume?.state.forkedFromId ?? ''
let forkReplayState = resume?.state.forkReplayState ? { ...resume.state.forkReplayState } : undefined
// What the parent rollout recorded before the fork. Usage records use
// their conservative replay anchor; native items use exact ID membership.
// Loaded on the first relevant record; null drops the whole replay burst.
let parentReplay: Set<string> | null | undefined
let parentNativeReplay: Set<string> | null | undefined
let parentReplayAnchored = false
const loadParentReplay = async (): Promise<void> => {
if (parentReplay !== undefined) return
const index = forkedFromId && forkReplayState
? await loadCodexParentReplayIndex(source.path, forkedFromId, forkReplayState.startedAtMs)
: null
parentReplay = index?.usageIdentities.size ? index.usageIdentities : null
parentNativeReplay = index?.nativeIdentities ?? null
}
const isParentReplay = async (identity: string | undefined): Promise<boolean> => {
await loadParentReplay()
if (!parentReplay || identity === undefined) return true
if (parentReplay.has(identity)) { parentReplayAnchored = true; return true }
// A burst that opens with a record the parent lacks was not copied from
// this parent file; fall back to dropping the burst.
if (!parentReplayAnchored) { parentReplay = null; return true }
return false
}
const isParentNativeReplay = async (identity: string | undefined): Promise<boolean> => {
await loadParentReplay()
// Without a readable parent set or a stable item ID, retain the old
// burst suppression. A loaded set makes membership an exact decision,
// independent of whether a token record has anchored the fork yet.
return !parentNativeReplay || identity === undefined || parentNativeReplay.has(identity)
}
// Null sentinel rather than `0` so the FIRST event is never confused
// with a duplicate. A session that only emits last_token_usage (no
// total_token_usage) reports cumulativeTotal=0 on every event; with a
// 0-initialized prev, the first event would have matched and been
// dropped. Once we've observed any event, we record its cumulative
// total and dedup on equality regardless of whether it is zero.
let prevCumulativeTotal: number | null = resume?.state.prevCumulativeTotal ?? null
let prevInfoIdentity: string | null = resume?.state.prevInfoIdentity ?? null
let restartEpoch = resume?.state.restartEpoch ?? 0
let hasTokenUsageRecord = resume?.state.hasTokenUsageRecord ?? false
// #1616: the service tier `thread_settings_applied` last set. Everything
// the loop reads from a PRIOR line must ride CodexResumeState, and this
// one can change mid-file, so a resume that starts after the change must
// not fall back to standard.
let serviceTier: string = resume?.state.serviceTier ?? 'default'
let prevInput = resume?.state.prevInput ?? 0
let prevCached = resume?.state.prevCached ?? 0
let prevCacheWrite = resume?.state.prevCacheWrite ?? 0
let prevOutput = resume?.state.prevOutput ?? 0
let prevReasoning = resume?.state.prevReasoning ?? 0
let pendingTools: string[] = resume ? [...resume.state.pendingTools] : []
let pendingToolSequence: ToolCall[][] = resume ? [...resume.state.pendingToolSequence] : []
let pendingNativeToolEvents: CodexPendingNativeToolEvent[] = resume?.state.pendingNativeToolEvents
? resume.state.pendingNativeToolEvents.map(event => ({ ...event }))
: []
const nativeToolEventIdentities = new Set(resume?.state.nativeToolEventIdentities ?? [])
let afterSearchItem = false
let pendingSkills: string[] = resume?.state.pendingSkills ? [...resume.state.pendingSkills] : []
// Attribution names already emitted from a `response_item` tool call.
// Codex's item model repeats a finished shell command as
// `item_completed`/`CommandExecution`; a rollout that carries BOTH shapes
// must attribute the call once, and one that carries ONLY the item must
// still attribute it. Counting per derived name (not per command text,
// which the two shapes spell differently - argv array vs plain string)
// makes repeats of the same call line up one-for-one. The response item is
// always written first (the model requests the call, the item completes
// it), so the item side only ever cancels an attribution, never adds a
// duplicate.
const itemDedup = new Map<string, number>()
/// The single classification pipeline every Codex shell-command shape
/// feeds (#478): `function_call` arguments, the `exec` custom tool's JS
/// `input`, and the item model's `CommandExecution` item. It adds MCP and
/// Skill attribution only - the exec itself is counted as Bash by its
/// response item, and `viaItem` calls never add a tool of their own, so
/// call/token/cost totals cannot move.
const attributeShellCommand = (text: string, viaItem: boolean): void => {
if (!text) return
const claim = (name: string): boolean => {
const pending = itemDedup.get(name) ?? 0
if (!viaItem) { itemDedup.set(name, pending + 1); return true }
if (pending === 0) return true
itemDedup.set(name, pending - 1)
return false
}
const mcpTool = mcpToolFromShellCommand(text)
if (mcpTool && claim(mcpTool)) {
pendingTools.push(mcpTool)
pendingToolSequence.push([{ tool: mcpTool }])
}
const skill = skillFromShellCommand(text)
if (skill && claim(`skill:${skill}`)) {
pendingSkills.push(skill)
pendingTools.push('Skill')
pendingToolSequence.push([{ tool: 'Skill', file: skill }])
}
}
const attributeNativeToolEvent = (event: CodexNativeToolEvent): void => {
if (event.identity && nativeToolEventIdentities.has(event.identity)) return
if (event.identity) nativeToolEventIdentities.add(event.identity)
const toolIndex = pendingTools.length
const sequenceIndex = pendingToolSequence.length
pendingTools.push(event.tool)
pendingToolSequence.push([{ tool: event.tool }])
pendingNativeToolEvents.push({ tool: event.tool, toolIndex, sequenceIndex })
}
let pendingUserMessage = resume?.state.pendingUserMessage ?? ''
let pendingOutputChars = resume?.state.pendingOutputChars ?? 0
// Rich-session-capture: edit LOC deltas and failed-patch count accumulated
// across a turn's patch_apply_end events, flushed onto the turn's call.
let pendingLocAdded = resume?.state.pendingLocAdded ?? 0
let pendingLocRemoved = resume?.state.pendingLocRemoved ?? 0
let pendingEditFailed = resume?.state.pendingEditFailed ?? 0
let estCounter = resume?.state.estCounter ?? 0
let turnCounter = resume?.state.turnCounter ?? 0
let currentTurnId = resume?.state.currentTurnId ?? `${sessionId}:t0`
let sawAnyLine = false
const results: ParsedProviderCall[] = []
// Calls already decoded before the resume boundary. They pass through the
// same cross-provider dedup a full decode would have applied to them.
if (resume) {
for (const call of resume.calls) {
if (seenKeys.has(call.deduplicationKey)) continue
seenKeys.add(call.deduplicationKey)
results.push(call)
}
}
// Calls decoded since the last task_started, held back so task_complete can
// stamp active/toolWait timing before they are appended to results. Emitting
// a task only once its timing is known keeps single-pass and split/resume
// decodes in agreement instead of back-patching already-emitted calls.
// Bounded by one task's calls; flushed at the next task_started and at EOF.
let pendingTaskCalls: ParsedProviderCall[] = []
// Null-info ping estimates. Measured usage later in the same turn and
// task replaces all of them, so the turn is measured calls only.
let pingEstimates: ParsedProviderCall[] = []
let taskGeneratedTokens = 0
let taskToolIntervals: Array<[number, number]> = []
let taskStartedAt: number | undefined = resume?.state.taskStartedAt
let taskActiveStartedAt: number | undefined = resume?.state.taskActiveStartedAt
const openToolStarts = new Map<string, number>()
// Tool items can be serialized after their response's usage record. Keep
// normal forward attribution as the first choice, but attach any still
// pending native items to the last call in this task before it is flushed.
// The parallel indexes let this move just the native items without
// disturbing other pending tool attribution across a resume boundary.
const attachPendingNativeToolEvents = (target: ParsedProviderCall | undefined): void => {
if (!target || pendingNativeToolEvents.length === 0) return
const ordered = [...pendingNativeToolEvents].sort((a, b) => a.sequenceIndex - b.sequenceIndex)
target.tools.push(...ordered.map(event => event.tool))
target.toolSequence = [
...(target.toolSequence ?? []),
...ordered.map(event => [{ tool: event.tool }]),
]
for (const event of [...pendingNativeToolEvents].sort((a, b) => b.toolIndex - a.toolIndex)) {
pendingTools.splice(event.toolIndex, 1)
}
for (const event of [...pendingNativeToolEvents].sort((a, b) => b.sequenceIndex - a.sequenceIndex)) {
pendingToolSequence.splice(event.sequenceIndex, 1)
}
pendingNativeToolEvents = []
}
const accountUsage = (entry: CodexEntry, usage: CodexTokenUsage, dedupKey: string): void => {
const inputTokens = usage.input_tokens ?? 0
const cachedInputTokens = usage.cached_input_tokens ?? 0
const cacheWriteTokens = usage.cache_write_input_tokens ?? 0
const outputTokens = usage.output_tokens ?? 0
const reasoningTokens = usage.reasoning_output_tokens ?? 0
const totalTokens = inputTokens + cachedInputTokens + outputTokens + reasoningTokens
if (totalTokens === 0) return
const ests = pingEstimates.filter(est => est.turnId === currentTurnId && pendingTaskCalls.includes(est))
pingEstimates = []
if (ests.length > 0) {
pendingTaskCalls = pendingTaskCalls.filter(call => !ests.includes(call))
for (const est of ests) taskGeneratedTokens -= est.outputTokens
pendingTools = [...ests.flatMap(est => est.tools), ...pendingTools]
pendingToolSequence = [...ests.flatMap(est => est.toolSequence ?? []), ...pendingToolSequence]
pendingSkills = [...ests.flatMap(est => est.skills ?? []), ...pendingSkills]
pendingUserMessage = ests.find(est => est.userMessage)?.userMessage || pendingUserMessage
for (const est of ests) {
pendingLocAdded += est.locAdded ?? 0
pendingLocRemoved += est.locRemoved ?? 0
pendingEditFailed += est.editFailed ?? 0
}
}
if (seenKeys.has(dedupKey)) return
// OpenAI includes cached tokens inside input_tokens; Anthropic does not.
// Normalize to Anthropic semantics: inputTokens = non-cached only.
const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens)
// Cache writes are carved out of the uncached input, never added to
// it: clamp so a malformed or lagging count can never drive the plain
// input bucket negative.
const cacheWriteInputTokens = Math.max(0, Math.min(cacheWriteTokens, uncachedInputTokens))
const model = resolveModel(entry.payload, sessionModel)
const timestamp = entry.timestamp ?? ''
const pricingModel = pricingModelAt(model, timestamp)
// Only move tokens into the cache-write bucket when the pricing
// source publishes a real cache-write rate for this model (gpt-5.6+)
// charges 1.25x input; otherwise don't invent an unbilled surcharge.
const billedCacheWriteTokens = cacheWriteInputTokens > 0 && getModelCosts(pricingModel)?.cacheWriteCostIsExplicit
? cacheWriteInputTokens
: 0
const billedInputTokens = uncachedInputTokens - billedCacheWriteTokens
seenKeys.add(dedupKey)
// Reasoning tokens are already inside output_tokens, so they are NOT
// added here. The cache-rehydration twin of this line lives in
// src/parser.ts (cachedCallToApiCall); both call billableOutputTokens
// so a fresh parse and a cache read can never price differently.
// #1616: a turn running under the priority service tier (Codex's Fast
// speed setting) bills at the priority rates via the fast multiplier.
const speed = speedForServiceTier(serviceTier)
const costUSD = calculateCost(
pricingModel,
billedInputTokens,
billableOutputTokens('codex', outputTokens, reasoningTokens),
billedCacheWriteTokens,
cachedInputTokens,
0,
speed,
0,
'codex',
)
pendingTaskCalls.push({
provider: 'codex',
model,
inputTokens: billedInputTokens,
outputTokens,
cacheCreationInputTokens: billedCacheWriteTokens,
cacheReadInputTokens: cachedInputTokens,
cachedInputTokens,
reasoningTokens,
webSearchRequests: 0,
costUSD,
tools: pendingTools,
bashCommands: [],
timestamp,
speed,
deduplicationKey: dedupKey,
turnId: currentTurnId,
toolSequence: pendingToolSequence.length > 0 ? pendingToolSequence : undefined,
...(pendingSkills.length > 0 ? { skills: pendingSkills } : {}),
userMessage: pendingUserMessage,
sessionId,
...(sessionCwd ? { projectPath: sessionCwd, workingDirectory: sessionCwd } : {}),
...(pendingLocAdded ? { locAdded: pendingLocAdded } : {}),
...(pendingLocRemoved ? { locRemoved: pendingLocRemoved } : {}),
...(pendingEditFailed ? { editFailed: pendingEditFailed } : {}),
...(model.toLowerCase() === 'gpt-reserve' ? { costIsEstimated: true } : {}),
})
taskGeneratedTokens += billableOutputTokens('codex', outputTokens, reasoningTokens)
pendingTools = []
pendingToolSequence = []
pendingNativeToolEvents = []
pendingSkills = []
pendingUserMessage = ''
pendingOutputChars = 0
pendingLocAdded = 0
pendingLocRemoved = 0
pendingEditFailed = 0
}
// Resume point for the NEXT run, refreshed at every task boundary.
const tracker = { lastCompleteLineOffset: resume?.offset ?? 0 }
let resumeOffset = resume?.offset ?? 0
let resumeState: CodexResumeState | null = resume?.state ?? null
let resumeCallCount = results.length
// Stream the session file line by line. Heavy Codex sessions can exceed
// 250 MB on disk; reading the entire file into a string would either hit
// the readSessionFile cap or push V8 toward its 512 MB string limit
// after split('\n'). readSessionLines streams raw buffers and hands
// huge lines to the compact parser without full string conversion.
for await (const rawLine of readSessionLines(source.path, undefined, {
largeLineAsBuffer: true,
byteOffsetTracker: tracker,
...(resume ? { startByteOffset: resume.offset } : {}),
})) {
sawAnyLine = true
const entry = parseCodexLine(rawLine)
if (!entry) continue
if (entry.type === 'session_meta') {
sessionId = entry.payload?.session_id ?? rolloutStem(basename(source.path))
// Rollouts from before Codex wrote `session_id` carry only `id`, the
// thread UUID a fork names in `forked_from_id`. Dedup keys use it so a
// fork's replayed history collides with the parent's own records.
threadId = entry.payload?.session_id ?? entry.payload?.id ?? sessionId
// Guarded for the same reason as discoverSessionFile: parseCodexLine
// hands back an unchecked JSON.parse cast, and a non-string cwd would
// ride into projectPath/workingDirectory where the parser's path
// helpers (normalizeProjectPathKey, resolveCanonicalProjectPath) call
// string methods on it.
const rawSessionCwd: unknown = entry.payload?.cwd
if (typeof rawSessionCwd === 'string' && rawSessionCwd) sessionCwd = rawSessionCwd
// Small lines arrive fully parsed (nested `source`), oversized ones
// through the compact head decoder (flattened `parent_thread_id`).
forkedFromId = entry.payload?.forked_from_id
|| entry.payload?.parent_thread_id
|| entry.payload?.source?.subagent?.thread_spawn?.parent_thread_id
|| ''
parentReplay = undefined
parentNativeReplay = undefined
parentReplayAnchored = false
if (forkedFromId) {
forkReplayState = startCodexForkReplay(entry.timestamp)
// Byte identity only collapses consecutive records inside one
// stream. A fork's first real no-cumulative request may have the
// same token breakdown as its last copied parent request.
prevInfoIdentity = null
}
if (typeof entry.payload?.model === 'string') sessionModel = entry.payload.model
continue
}
// #1088 BUG-1: the first request-context event since task_started marks
// where model-request assembly actually began. Checked before any of
// these types `continue` below, and unconditionally (like turn_context's
// model capture above) so a forked replay's own request-context events
// still mark it before the replay-specific task, tool, message, and usage
// records are skipped.
if (taskActiveStartedAt === undefined && (
entry.type === 'turn_context'
|| entry.type === 'world_state'
|| (entry.type === 'event_msg' && entry.payload?.type === 'user_message')
|| (entry.type === 'response_item' && entry.payload?.type === 'message')
)) {
const ctxAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN
if (Number.isFinite(ctxAt)) taskActiveStartedAt = ctxAt
}
const isForkReplay = isCodexForkReplay(forkReplayState, entry.timestamp)
const nativeEvent = nativeToolEvent(entry)
// Codex builds of May 2026 follow each item_completed WebSearch with an
// id-less web_search_call repeating its action: the same search.
const searchMirror = afterSearchItem && entry.type === 'response_item' && nativeEvent?.tool === 'WebSearch' && !nativeEvent.identity
afterSearchItem = entry.type === 'event_msg' && nativeEvent?.tool === 'WebSearch'
if (searchMirror) continue
if (nativeEvent && isForkReplay && await isParentNativeReplay(nativeEvent.identity)) continue
if (entry.type === 'turn_context' && typeof entry.payload?.model === 'string') {
sessionModel = entry.payload.model
continue
}
// #1616: Codex's Fast speed setting bills through OpenAI's priority
// service tier, which the rollout records per THREAD SETTINGS change
// (event_msg/thread_settings_applied), never per call. The setting
// covers every turn after it in file order, so track the latest value;
// a settings event with no `service_tier` (older builds never wrote
// one) reads as the default tier. Deliberately NOT skipped during a
// fork replay: the replayed parent events carry the setting the fork
// inherited, so tracking them keeps the fork's first own turn on the
// parent's tier.
if (entry.type === 'event_msg' && entry.payload?.type === 'thread_settings_applied') {
serviceTier = entry.payload.serviceTier ?? 'default'
continue
}
if (isForkReplay && (
entry.payload?.type === 'task_started' ||
entry.payload?.type === 'task_complete' ||
entry.payload?.type === 'function_call' ||
entry.payload?.type === 'function_call_output' ||
entry.payload?.type === 'custom_tool_call' ||
entry.payload?.type === 'custom_tool_call_output' ||
entry.payload?.type === 'mcp_tool_call_end' ||
(entry.payload?.type === 'item_completed' && !nativeEvent) ||
entry.payload?.type === 'patch_apply_end'
)) continue
if (isForkReplay && entry.type === 'response_item' && entry.payload?.type === 'message') continue
if (isForkReplay && entry.type === 'event_msg' && entry.payload?.type === 'token_count'
&& await isParentReplay(entry.payload.info ? codexReplayUsageIdentity(entry.payload.info) : undefined)) {
const info = entry.payload.info
if (info) {
const total = info.total_token_usage
const reportsCumulative = typeof total?.total_tokens === 'number'
&& Number.isFinite(total.total_tokens)
&& total.total_tokens >= 0
if (reportsCumulative) prevInfoIdentity = JSON.stringify(info)
if (total) {
const cumulativeTotal = total.total_tokens ?? 0
prevCumulativeTotal = reportsCumulative ? cumulativeTotal : null
prevInput = total.input_tokens ?? prevInput
prevCached = total.cached_input_tokens ?? prevCached
prevCacheWrite = total.cache_write_input_tokens ?? prevCacheWrite
prevOutput = total.output_tokens ?? prevOutput
prevReasoning = total.reasoning_output_tokens ?? prevReasoning
} else {
prevCumulativeTotal = null
}
}
// A replay's prompt and response text is historical context. Keep it
// out of the fallback character estimate for the first real turn.
pendingUserMessage = ''
pendingOutputChars = 0
continue
}
if (entry.type === 'event_msg' && entry.payload?.type === 'task_started') {
// Emit the previous task. If it never reached task_complete its timing
// fields simply stay unset, matching the un-buffered behaviour.
attachPendingNativeToolEvents(pendingTaskCalls.at(-1))
results.push(...pendingTaskCalls)
pendingTaskCalls = []
pingEstimates = []
taskGeneratedTokens = 0
taskToolIntervals = []
const startedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN
taskStartedAt = Number.isFinite(startedAt) ? startedAt : undefined
taskActiveStartedAt = undefined
openToolStarts.clear()
// Everything decoded so far is now in `results` and the per-task
// accumulators are empty: a clean restart point for an appended tail.
resumeOffset = tracker.lastCompleteLineOffset
resumeCallCount = results.length
resumeState = {
...(sessionModel !== undefined ? { sessionModel } : {}),
sessionId,
threadId,
...(sessionCwd !== undefined ? { sessionCwd } : {}),
forkedFromId,
...(forkReplayState ? { forkReplayState: { ...forkReplayState } } : {}),
prevCumulativeTotal,
restartEpoch,
prevInfoIdentity,
hasTokenUsageRecord,
serviceTier,
prevInput,
prevCached,
prevCacheWrite,
prevOutput,
prevReasoning,
pendingTools: [...pendingTools],
pendingToolSequence: [...pendingToolSequence],
pendingNativeToolEvents: pendingNativeToolEvents.map(event => ({ ...event })),
nativeToolEventIdentities: [...nativeToolEventIdentities],
pendingSkills: [...pendingSkills],
pendingUserMessage,
pendingOutputChars,
pendingLocAdded,
pendingLocRemoved,
pendingEditFailed,
estCounter,
turnCounter,
currentTurnId,
...(taskStartedAt !== undefined ? { taskStartedAt } : {}),
...(taskActiveStartedAt !== undefined ? { taskActiveStartedAt } : {}),
}
continue
}
if (nativeEvent) {
// Status transitions share an item identity. The first observed
// record proves tool activity even when the rollout ends before its
// completed status; mirrors from the item model are ignored by id.
attributeNativeToolEvent(nativeEvent)
continue
}
if (entry.type === 'response_item' && (entry.payload?.type === 'function_call' || entry.payload?.type === 'custom_tool_call')) {
const rawName = entry.payload.name ?? ''
const mapped = ownValue(toolNameMap, rawName) ?? rawName
pendingTools.push(mapped)
const call: ToolCall = { tool: mapped }
const rawArgs = (entry.payload as Record<string, unknown>)['arguments']
const args = typeof rawArgs === 'string'
? (() => { try { return JSON.parse(rawArgs) as Record<string, unknown> } catch { return null } })()
: typeof rawArgs === 'object' && rawArgs ? rawArgs as Record<string, unknown> : null
if (args) {
const fp = args['file_path'] ?? args['path']
if (typeof fp === 'string') call.file = fp
const cmd = args['command'] ?? args['cmd']
if (typeof cmd === 'string') call.command = cmd
attributeShellCommand(shellCommandText(cmd), false)
}
// A `custom_tool_call` has no `arguments`: the shell tool's payload is
// the `input` program that calls `tools.exec_command({cmd: ...})`. The
// MCP/skill matchers never saw it, so a CLI-wrapped MCP call or a
// SKILL.md read made through Codex's custom-tool transport counted only
// as Bash (#478). Restricted to the shell tool: `apply_patch` is a
// custom tool too and its `input` is file content, where a documented
// command would read as a real invocation. `call.command` is
// deliberately NOT set from it either - that field feeds the retry
// heuristic's read-shaped-command test, and a JS program is not a
// shell command.
if (mapped === 'Bash') {
const input = (entry.payload as Record<string, unknown>)['input']
if (typeof input === 'string') attributeShellCommand(input, false)
}
const callId = entry.payload.call_id
const started = entry.timestamp ? Date.parse(entry.timestamp) : NaN
if (callId && Number.isFinite(started)) openToolStarts.set(callId, started)
pendingToolSequence.push([call])
continue
}
if (entry.type === 'response_item' && (entry.payload?.type === 'function_call_output' || entry.payload?.type === 'custom_tool_call_output')) {
const callId = entry.payload.call_id
const ended = entry.timestamp ? Date.parse(entry.timestamp) : NaN
const started = callId ? openToolStarts.get(callId) : undefined
if (started !== undefined && Number.isFinite(ended) && ended > started) taskToolIntervals.push([started, ended])
if (callId) openToolStarts.delete(callId)
continue
}
if (entry.type === 'event_msg' && entry.payload?.type === 'task_complete') {
// #1088 BUG-8: task_complete's duration can arrive as {secs,nanos} or
// a string too (mcp_tool_call_end already tolerates both, below, via
// this same durationValueMs helper); read it the same permissive way
// instead of only the plain-number `duration_ms` field.
const durationMs = durationValueMs(entry.payload.duration_ms) ?? durationValueMs(entry.payload.duration)
if (typeof durationMs === 'number' && durationMs > 0 && taskGeneratedTokens > 0 && pendingTaskCalls.length > 0) {
const completedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN
// #1088 BUG-1: Codex fires task_started before it assembles the
// request, so the gap up to the first request-context event is
// CLI/harness startup, not model wait. The active window starts
// there instead of at task_started; task completion (windowEnd,
// inside mergeToolIntervals) is unchanged.
const activeWindowStart = taskActiveStartedAt ?? taskStartedAt
const startupGapMs = activeWindowStart !== undefined && taskStartedAt !== undefined
? activeWindowStart - taskStartedAt
: 0
const effectiveDurationMs = Math.max(0, durationMs - startupGapMs)
// #1088 BUG-8: shared with codex-throughput.ts's live estimate
// instead of a second inline copy of the same clip/merge/cap.
const toolWaitMs = mergeToolIntervals(taskToolIntervals, effectiveDurationMs, activeWindowStart, Number.isFinite(completedAt) ? completedAt : undefined)
const activeMs = effectiveDurationMs - toolWaitMs
if (activeMs <= 0) continue
for (const call of pendingTaskCalls) {
// Reasoning is already inside output_tokens (#1075/#1078); the
// throughput numerator must agree with the cost numerator or
// Tok/s reads high for reasoning-heavy calls (#1079).
const generated = billableOutputTokens('codex', call.outputTokens, call.reasoningTokens)
if (generated <= 0) continue
call.activeGeneratedTokens = generated
call.activeDurationMs = activeMs * (generated / taskGeneratedTokens)
call.toolWaitMs = toolWaitMs * (generated / taskGeneratedTokens)
}
}
continue
}
if (entry.type === 'event_msg' && entry.payload?.type === 'patch_apply_end') {
pendingTools.push('Edit')
const p = entry.payload as Record<string, unknown>
const changes = p['changes']
const changesObj = typeof changes === 'object' && changes ? changes as Record<string, unknown> : {}
const filePaths = Object.keys(changesObj)
if (filePaths.length > 0) {
for (const fp of filePaths) {
pendingToolSequence.push([{ tool: 'Edit', file: fp }])
const diff = (changesObj[fp] as Record<string, unknown> | undefined)?.['unified_diff']
const loc = countUnifiedDiffLoc(diff)
pendingLocAdded += loc.added
pendingLocRemoved += loc.removed
}
} else {
pendingToolSequence.push([{ tool: 'Edit' }])
}
// Only an explicit failure counts; a missing `success` is treated as ok.
if (p['success'] === false) pendingEditFailed++
continue
}
// Recent Codex emits MCP calls as `event_msg`/`mcp_tool_call_end`
// instead of a `function_call` response_item, so the call was never
// attributed. Rebuild the canonical `mcp__<server>__<tool>` name the
// classifier recognizes.
if (entry.type === 'event_msg' && entry.payload?.type === 'mcp_tool_call_end') {
const endedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN
const durationMs = entry.payload.duration_ms ?? durationValueMs(entry.payload.duration)
if (typeof durationMs === 'number' && durationMs > 0 && Number.isFinite(endedAt)) {
taskToolIntervals.push([endedAt - durationMs, endedAt])
}
const inv = (entry.payload as Record<string, unknown>)['invocation'] as Record<string, unknown> | undefined
const server = typeof inv?.['server'] === 'string' ? inv['server'] as string : ''
const tool = typeof inv?.['tool'] === 'string' ? inv['tool'] as string : ''
if (server && tool) {
const name = `mcp__${server}__${tool}`
pendingTools.push(name)
pendingToolSequence.push([{ tool: name }])
}
continue
}
// Codex's item model records a finished shell command as
// `event_msg`/`item_completed` carrying a `CommandExecution` item whose
// `command` is the argv array (`["/bin/zsh","-lc","..."]`) - a shape the
// `function_call`-only tool path never reached, so a CLI-wrapped MCP call
// or a SKILL.md read made under it stayed invisible (#478). Attribution
// only: the exec's own Bash count comes from its response item, exactly
// as `exec_command_end` is left alone for the classic transport.
if (entry.type === 'event_msg' && entry.payload?.type === 'item_completed') {
const item = (entry.payload as Record<string, unknown>)['item'] as Record<string, unknown> | undefined
if (item && item['type'] === 'CommandExecution') {
attributeShellCommand(shellCommandText(item['command']), true)
}
continue
}
if (entry.type === 'response_item' && entry.payload?.type === 'message' && entry.payload?.role === 'user') {
const texts = normalizeContentBlocks(entry.payload.content)
.filter(c => c.type === 'input_text')
.map(c => c.text ?? '')
.filter(Boolean)
if (texts.length > 0) {
pendingUserMessage = texts.join(' ').slice(0, 500)
currentTurnId = `${sessionId}:t${++turnCounter}`
}
continue
}
if (entry.type === 'response_item' && entry.payload?.type === 'message' && entry.payload?.role === 'assistant') {
const texts = normalizeContentBlocks(entry.payload.content)
.filter(c => c.type === 'output_text' || c.type === 'text')
.map(c => c.text ?? '')
pendingOutputChars += texts.join('').length
continue
}
if (entry.type === 'token_usage_record') {
// Newer Codex builds write one response-level usage record before its
// token_count twin. The record survives compaction and interrupted
// turns, so it becomes the source for this rollout once seen.
const usage: unknown = entry.payload?.usage
if (!isValidCodexTokenUsage(usage)) continue
const responseId = entry.payload?.response_id
if (isForkReplay && await isParentReplay(typeof responseId === 'string' && responseId ? codexReplayResponseIdentity(responseId) : undefined)) continue
hasTokenUsageRecord = true
const dedupKey = typeof responseId === 'string' && responseId
? `codex:${forkedFromId || threadId}:response:${responseId}`
: `codex:usage-record:${JSON.stringify([source.path, tracker.lastCompleteLineOffset])}`
accountUsage(entry, usage, dedupKey)
continue
}
if (entry.type === 'event_msg' && entry.payload?.type === 'token_count') {
// Newer rollouts pair each response record with a token_count event.
// The response record is authoritative; all subsequent twins and
// re-emissions stay out of usage, while pre-handover legacy events
// remain counted.
if (hasTokenUsageRecord) continue
const info = entry.payload.info
if (!info) {
// Codex writes a null-info token_count (a rate-limit snapshot) at
// turn start, before any output. That is not a request: leave the
// prompt pending for the measured call that follows. A turn that
// ends on such a ping with nothing after it priced nothing: no call.
// After output, the ping estimates the turn until measured usage
// for it arrives (pingEstimates).
if (pendingOutputChars === 0) continue
const estInput = estimateTokensFromChars(pendingUserMessage.length)
const estOutput = estimateTokensFromChars(pendingOutputChars)
if (estInput === 0 && estOutput === 0) continue
const model = sessionModel ?? 'gpt-5'
const timestamp = entry.timestamp ?? ''
const dedupKey = `codex:${sessionId}:${timestamp}:est${estCounter++}`
if (seenKeys.has(dedupKey)) { pendingTools = []; pendingToolSequence = []; pendingNativeToolEvents = []; pendingSkills = []; pendingUserMessage = ''; pendingOutputChars = 0; pendingLocAdded = 0; pendingLocRemoved = 0; pendingEditFailed = 0; continue }
seenKeys.add(dedupKey)
// An estimated prompt can cross a long-context threshold and tier
// itself; measured corpora hold no estimated calls that cross. The
// service tier applies to it exactly as to a measured turn (#1616).
const speed = speedForServiceTier(serviceTier)
const costUSD = calculateCost(pricingModelAt(model, timestamp), estInput, estOutput, 0, 0, 0, speed, 0, 'codex')
pendingTaskCalls.push({
provider: 'codex',
model,
inputTokens: estInput,
outputTokens: estOutput,
cacheCreationInputTokens: 0,
cacheReadInputTokens: 0,
cachedInputTokens: 0,
reasoningTokens: 0,
webSearchRequests: 0,
costUSD,
costIsEstimated: true,
tools: pendingTools,
bashCommands: [],
timestamp,
speed,
deduplicationKey: dedupKey,
turnId: currentTurnId,
toolSequence: pendingToolSequence.length > 0 ? pendingToolSequence : undefined,
...(pendingSkills.length > 0 ? { skills: pendingSkills } : {}),
userMessage: pendingUserMessage,
sessionId,
...(sessionCwd ? { projectPath: sessionCwd, workingDirectory: sessionCwd } : {}),
...(pendingLocAdded ? { locAdded: pendingLocAdded } : {}),
...(pendingLocRemoved ? { locRemoved: pendingLocRemoved } : {}),
...(pendingEditFailed ? { editFailed: pendingEditFailed } : {}),
})
pingEstimates.push(pendingTaskCalls.at(-1)!)
taskGeneratedTokens += estOutput
pendingTools = []
pendingToolSequence = []
pendingNativeToolEvents = []
pendingSkills = []
pendingUserMessage = ''
pendingOutputChars = 0
pendingLocAdded = 0
pendingLocRemoved = 0
pendingEditFailed = 0
continue
}
const cumulativeTotal = info.total_token_usage?.total_tokens ?? 0
// Missing/null/partial cumulative data is not a repeated zero total.
const reportsCumulative = typeof info.total_token_usage?.total_tokens === 'number'
&& Number.isFinite(info.total_token_usage.total_tokens)
&& info.total_token_usage.total_tokens >= 0
// #257 regression half: a byte-identical consecutive record is a
// re-emission of the same token_count event, never a new request.
// This collapse applies with or without cumulative totals: measured
// on public Codex rollouts (codeset-ai/codeset-release-evals,
// 53 sessions / 1313 token_count events), 603 events are
// byte-identical repeats of their predecessor, all carrying the
// same cumulative snapshot. What the missing-cumulative path must
// preserve is records whose payload DIFFERS (distinct requests).
const infoIdentity = JSON.stringify(info)
if (infoIdentity === prevInfoIdentity) continue
prevInfoIdentity = infoIdentity
if (reportsCumulative && prevCumulativeTotal !== null && cumulativeTotal === prevCumulativeTotal) continue
const prevTotal = prevCumulativeTotal
prevCumulativeTotal = reportsCumulative ? cumulativeTotal : null
const last = info.last_token_usage
let inputTokens = 0
let cachedInputTokens = 0
let cacheWriteTokens = 0
let outputTokens = 0
let reasoningTokens = 0
if (last) {
inputTokens = last.input_tokens ?? 0
cachedInputTokens = last.cached_input_tokens ?? 0
cacheWriteTokens = last.cache_write_input_tokens ?? 0
outputTokens = last.output_tokens ?? 0
reasoningTokens = last.reasoning_output_tokens ?? 0
} else if (cumulativeTotal > 0) {
const total = info.total_token_usage
if (!total) continue
// A total at most half the previous one (or, without a previous
// total, every reported field at most half) is a counter restart
// (resume, compaction): every counter, reported or not, starts
// again from zero. A smaller drop is a correction: a falling field
// adds nothing. An omitted field is unchanged.
const counters: Array<[number | undefined, number]> = [
[total.input_tokens, prevInput], [total.cached_input_tokens, prevCached],
[total.cache_write_input_tokens, prevCacheWrite], [total.output_tokens, prevOutput],
[total.reasoning_output_tokens, prevReasoning],
]
const present = counters.filter(([now]) => now !== undefined) as Array<[number, number]>
const restart = prevTotal !== null
? cumulativeTotal * 2 <= prevTotal
: present.length > 0 && present.every(([now, prev]) => now * 2 <= prev)
if (restart) { restartEpoch++; prevInput = 0; prevCached = 0; prevCacheWrite = 0; prevOutput = 0; prevReasoning = 0 }
const since = (now: number | undefined, prev: number) => now === undefined ? 0 : Math.max(0, now - prev)
inputTokens = since(total.input_tokens, prevInput)
cachedInputTokens = since(total.cached_input_tokens, prevCached)
cacheWriteTokens = since(total.cache_write_input_tokens, prevCacheWrite)
outputTokens = since(total.output_tokens, prevOutput)
reasoningTokens = since(total.reasoning_output_tokens, prevReasoning)
}
// Always advance the prev counters to track the cumulative state.
// Previously prev was only updated on the fallback branch, so a
// session with mixed last_token_usage / no-last events would
// compute the next fallback delta against a stale prev=0 baseline,
// double-counting the entire cumulative window. The prev value
// must mirror what cumulative reports regardless of whether this
// event used `last` or fell back to deltas.
const total = info.total_token_usage
if (total) {
prevInput = total.input_tokens ?? prevInput
prevCached = total.cached_input_tokens ?? prevCached
prevCacheWrite = total.cache_write_input_tokens ?? prevCacheWrite
prevOutput = total.output_tokens ?? prevOutput
prevReasoning = total.reasoning_output_tokens ?? prevReasoning
}
// Forked sessions copy the parent's entire token_count history
// (re-timestamped), so replays must collide with the parent's events
// and drop to avoid double-counting -- hence the parent namespace
// (forkedFromId) and the deliberate omission of the per-session id.
// But cumulativeTotal alone is too coarse a discriminator: a genuine
// post-divergence fork event whose running total coincidentally equals
// some parent total would also collide and be lost (undercount). So we
// also key on the cumulative token breakdown, which a fork replays
// verbatim from the parent -- a true replay collides exactly, while
// genuinely different work at the same total stays distinct. We use the
// CUMULATIVE figures (not the per-event deltas) on purpose: the deltas
// are computed against a running `prev` that may start from a replay
// baseline, so a delta-based key would spuriously diverge on a replay
// and double-count it.
// Without cumulative identity, equal usage can be distinct requests.
// Use the physical record position: stable on cache resume/re-read,
// but deliberately do not guess cross-file replay identity.
// Invariant (#1088, restored): anything dropped below is a record
// that survived both guards -- with cumulative identity it is a
// strictly-advanced total, so no tokens are lost and no active-time
// rescaling is needed; without it the record differs in payload
// from its predecessor and is treated as a distinct request, which
// deliberately weakens forkedFromId replay protection past the replay
// burst (accepted trade-off: the alternative collapsed
// distinct requests wholesale).
// Two rollouts of one thread at identical cumulative totals are the
// same calls replayed (resume), so sharing this key is intended. After
// a counter restart the same totals are new calls: the epoch tells.
const dedupKey = reportsCumulative
? `codex:${forkedFromId || threadId}:${cumulativeTotal}:${total?.input_tokens ?? 0}:${total?.cached_input_tokens ?? 0}:${total?.output_tokens ?? 0}:${total?.reasoning_output_tokens ?? 0}${restartEpoch ? `:r${restartEpoch}` : ''}`
: `codex:record:${JSON.stringify([source.path, tracker.lastCompleteLineOffset])}`
accountUsage(entry, {
input_tokens: inputTokens,
cached_input_tokens: cachedInputTokens,
cache_write_input_tokens: cacheWriteTokens,
output_tokens: outputTokens,
reasoning_output_tokens: reasoningTokens,
}, dedupKey)
}
}
// If the stream yielded nothing the file was unreadable, oversized, or
// empty. Skip cache write so a transient failure can't pin an empty
// result set against a fingerprint that would otherwise be re-parsed. On a
// resume the earlier calls are still valid output, so serve them - but
// still leave the cache entry alone.
if (!sawAnyLine) {
if (resume) for (const call of results) yield call
return
}
// Flush the final task, which has no following task_started to trigger it.
attachPendingNativeToolEvents(pendingTaskCalls.at(-1))
results.push(...pendingTaskCalls)
// Offsets into decompressed text cannot pass the cache's raw-byte append
// check, and a compressed rollout is never appended to anyway.
const resumeWrite = resumeState && !source.path.endsWith('.zst') ? { offset: resumeOffset, state: resumeState, callCount: resumeCallCount } : undefined
if (capture) {
capture.write = { project: source.project, fingerprint: fp, ...(resumeWrite ? { resume: resumeWrite } : {}) }
} else {
await writeCachedCodexResults(source.path, source.project, results, fp, resumeWrite)
}
for (const call of results) {
yield call
}
},
}
}
export type CodexFullParse = { calls: ParsedProviderCall[]; write?: CodexCacheWrite }
/// Decode one rollout end to end, exactly as the serial path does for a file
/// with no cache entry, without reading or writing the codex cache. `seenKeys`
/// is the dedup set the decode runs against — pass an empty one off-thread and
/// let the caller prove no earlier file claimed any of the keys before
/// installing the result.
export async function parseCodexFileFull(source: SessionSource, seenKeys: Set<string>): Promise<CodexFullParse> {
const capture: { write?: CodexCacheWrite } = {}
const calls: ParsedProviderCall[] = []
for await (const call of createParser(source, seenKeys, capture).parse()) calls.push(call)
return { calls, ...(capture.write ? { write: capture.write } : {}) }
}
function rootsFor(home: string): ProbeRoot[] {
return [
{ path: join(home, 'sessions'), label: 'sessions' },
{ path: join(home, 'archived_sessions'), label: 'archived' },
]
}
function dropOverlappingNestSources(sources: SessionSource[], billedHome: string): SessionSource[] {
const billedIds = listRolloutSessionIds(billedHome)
return sources.filter(source => {
const id = rolloutFileSessionId(source.path)
return !(id && billedIds.has(id))
})
}
export function createCodexProvider(
codexDir?: string,
opts?: { primaryDir?: string; launcherRoots?: string[] },
): Provider {
const dir = getCodexDir(codexDir)
const primaryDir = opts?.primaryDir ?? defaultBilledCodexHome()
const launcherRoots = opts?.launcherRoots ?? defaultLauncherRoots()
// Explicit nest factory whose path is a realpath alias of the billed home:
// empty so a second factory cannot double-count the same tree. The no-arg
// singleton must not take this branch — CODEX_HOME may be that alias.
const duplicateHome =
codexDir !== undefined &&
sameCodexHome(dir, primaryDir) &&
resolve(dir) !== resolve(primaryDir)
const nestHome = isNestedLauncherCodexHome(dir, { primaryDir, launcherRoots })
// Production `codex` singleton is createCodexProvider() with no args. When
// the resolved dir is a launcher nest and ~/.codex is a distinct existing
// tree, walk BOTH and drop nest sources whose session id is already billed.
const scanBoth = nestHome && codexDir === undefined
// Extra WSL homes' ~/.codex (#1059); empty off-win32 and when a caller
// pinned an explicit dir. Separate Linux trees, so no nest double-count.
// Resolved lazily: `codex` is built at import and WSL probing spawns wsl.exe.
const wslCodexDirs = (): string[] =>
codexDir ? [] : wslHomes().map(home => join(home, '.codex'))
return {
name: 'codex',
displayName: 'Codex',
modelDisplayName(model: string): string {
for (const [key, name] of modelDisplayEntries) {
if (model === key || model.startsWith(key + '-')) return name
}
return model
},
toolDisplayName(rawTool: string): string {
return ownValue(toolNameMap, rawTool) ?? rawTool
},
// Trees discoverSessions actually walks. Honors CODEX_HOME; when the
// production singleton scans nest + billed home, both appear here, plus
// each WSL home's ~/.codex.
async probeRoots(): Promise<ProbeRoot[]> {
if (duplicateHome) return []
const local = scanBoth ? [...rootsFor(primaryDir), ...rootsFor(dir)] : rootsFor(dir)
return [...local, ...wslCodexDirs().flatMap(rootsFor)]
},
async discoverSessions(): Promise<SessionSource[]> {
// Same physical tree via two factories is complete overlap, not a
// distinct nest. isNestedLauncherCodexHome is false in that case.
if (duplicateHome) return []
const sources = await discoverSessionsInDir(dir)
const wslSources = (
await Promise.all(wslCodexDirs().map(d => discoverSessionsInDir(d)))
).flat()
let local: SessionSource[]
if (scanBoth) {
const billed = await discoverSessionsInDir(primaryDir)
local = [...billed, ...dropOverlappingNestSources(sources, primaryDir)]
} else if (!nestHome) {
local = sources
} else {
local = dropOverlappingNestSources(sources, primaryDir)
}
return [...local, ...wslSources]
},
createSessionParser(source: SessionSource, seenKeys: Set<string>): SessionParser {
return createParser(source, seenKeys)
},
}
}
export const codex = createCodexProvider()