chompyy 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -1
- package/dist/advice.js +98 -1
- package/dist/agentlimits.js +77 -0
- package/dist/agentusage.js +96 -0
- package/dist/approvals.js +129 -0
- package/dist/appstate.js +73 -3
- package/dist/away.js +48 -5
- package/dist/blueprint.js +3 -7
- package/dist/board.js +1 -0
- package/dist/cli.js +343 -18
- package/dist/codexquota.js +106 -0
- package/dist/codexusage.js +10 -0
- package/dist/config.js +2 -0
- package/dist/context.js +30 -0
- package/dist/costs.js +41 -2
- package/dist/demon.js +20 -0
- package/dist/detect.js +38 -6
- package/dist/didwork.js +26 -0
- package/dist/label.js +33 -0
- package/dist/menu.js +17 -0
- package/dist/nightcap.js +72 -0
- package/dist/nudge.js +70 -24
- package/dist/pacing.js +16 -1
- package/dist/punchcard.js +39 -0
- package/dist/questions.js +71 -0
- package/dist/recap.js +74 -0
- package/dist/receipt.js +48 -0
- package/dist/recipe.js +79 -0
- package/dist/savings.js +111 -0
- package/dist/stamps.js +14 -0
- package/dist/suggest.js +15 -5
- package/dist/triggers.js +5 -0
- package/dist/usage.js +21 -1
- package/dist/vendor/codeburn/antigravity.js +309 -0
- package/dist/vendor/codeburn/codex.js +429 -0
- package/dist/vendor/codeburn/copilot.js +292 -0
- package/dist/vendor/codeburn/gemini.js +195 -0
- package/dist/vendor/codeburn/grokbot.js +182 -0
- package/dist/vendor/codeburn/kimi.js +178 -0
- package/dist/vendor/codeburn/shims/chalk.js +14 -0
- package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
- package/dist/vendor/codeburn/src/act/backup.js +83 -0
- package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
- package/dist/vendor/codeburn/src/act/types.js +37 -0
- package/dist/vendor/codeburn/src/bash-utils.js +204 -0
- package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
- package/dist/vendor/codeburn/src/cache-dir.js +26 -0
- package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
- package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
- package/dist/vendor/codeburn/src/classifier.js +209 -0
- package/dist/vendor/codeburn/src/claude-identity.js +223 -0
- package/dist/vendor/codeburn/src/codex-cache.js +377 -0
- package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
- package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
- package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
- package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
- package/dist/vendor/codeburn/src/compare-stats.js +405 -0
- package/dist/vendor/codeburn/src/config.js +145 -0
- package/dist/vendor/codeburn/src/content-utils.js +56 -0
- package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
- package/dist/vendor/codeburn/src/context-tree.js +664 -0
- package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
- package/dist/vendor/codeburn/src/currency.js +189 -0
- package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
- package/dist/vendor/codeburn/src/cursor-import.js +402 -0
- package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
- package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
- package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
- package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
- package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
- package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
- package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
- package/dist/vendor/codeburn/src/format.js +118 -0
- package/dist/vendor/codeburn/src/fs-utils.js +270 -0
- package/dist/vendor/codeburn/src/git-origin.js +334 -0
- package/dist/vendor/codeburn/src/granular-history.js +328 -0
- package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
- package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
- package/dist/vendor/codeburn/src/live-sessions.js +358 -0
- package/dist/vendor/codeburn/src/math-utils.js +8 -0
- package/dist/vendor/codeburn/src/menubar-json.js +294 -0
- package/dist/vendor/codeburn/src/models.js +1879 -0
- package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
- package/dist/vendor/codeburn/src/optimize.js +4110 -0
- package/dist/vendor/codeburn/src/parse-workers.js +219 -0
- package/dist/vendor/codeburn/src/parser.js +6955 -0
- package/dist/vendor/codeburn/src/path-privacy.js +26 -0
- package/dist/vendor/codeburn/src/plans.js +135 -0
- package/dist/vendor/codeburn/src/pr-signals.js +132 -0
- package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
- package/dist/vendor/codeburn/src/provider-issues.js +30 -0
- package/dist/vendor/codeburn/src/providers/amp.js +286 -0
- package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
- package/dist/vendor/codeburn/src/providers/claude.js +551 -0
- package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
- package/dist/vendor/codeburn/src/providers/cline.js +63 -0
- package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
- package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
- package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
- package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
- package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
- package/dist/vendor/codeburn/src/providers/crush.js +226 -0
- package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
- package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
- package/dist/vendor/codeburn/src/providers/devin.js +569 -0
- package/dist/vendor/codeburn/src/providers/droid.js +324 -0
- package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
- package/dist/vendor/codeburn/src/providers/forge.js +245 -0
- package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
- package/dist/vendor/codeburn/src/providers/goose.js +252 -0
- package/dist/vendor/codeburn/src/providers/grok.js +581 -0
- package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
- package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
- package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
- package/dist/vendor/codeburn/src/providers/index.js +360 -0
- package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
- package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
- package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
- package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
- package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
- package/dist/vendor/codeburn/src/providers/mux.js +242 -0
- package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
- package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
- package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
- package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
- package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
- package/dist/vendor/codeburn/src/providers/pi.js +429 -0
- package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
- package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
- package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
- package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
- package/dist/vendor/codeburn/src/providers/types.js +5 -0
- package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
- package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
- package/dist/vendor/codeburn/src/providers/warp.js +575 -0
- package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
- package/dist/vendor/codeburn/src/providers/zed.js +187 -0
- package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
- package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
- package/dist/vendor/codeburn/src/quota/claude.js +244 -0
- package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
- package/dist/vendor/codeburn/src/quota/security.js +299 -0
- package/dist/vendor/codeburn/src/quota/types.js +1 -0
- package/dist/vendor/codeburn/src/scan-facts.js +99 -0
- package/dist/vendor/codeburn/src/session-cache.js +3040 -0
- package/dist/vendor/codeburn/src/session-count-label.js +14 -0
- package/dist/vendor/codeburn/src/session-output.js +139 -0
- package/dist/vendor/codeburn/src/session-population.js +30 -0
- package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
- package/dist/vendor/codeburn/src/sqlite.js +528 -0
- package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
- package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
- package/dist/vendor/codeburn/src/token-estimate.js +5 -0
- package/dist/vendor/codeburn/src/types.js +16 -0
- package/dist/vendor/codeburn/src/work-units.js +126 -0
- package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
- package/dist/vendor/codeburn/src/wsl.js +198 -0
- package/dist/vendor/codeburn/src/yield.js +666 -0
- package/dist/wastechecks.js +233 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1720 @@
|
|
|
1
|
+
// @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
|
|
2
|
+
import { readdir, stat } from 'fs/promises';
|
|
3
|
+
import { createInterface } from 'readline';
|
|
4
|
+
import { basename, join, resolve } from 'path';
|
|
5
|
+
import { homedir } from 'os';
|
|
6
|
+
import { createTextReadStream, FS_SCAN_CONCURRENCY, mapWithConcurrency, readSessionLines } from '../fs-utils.js';
|
|
7
|
+
import { billableOutputTokens, calculateCost, getModelCosts, ownValue, pricingModelAt } from '../models.js';
|
|
8
|
+
import { readCachedCodexResults, writeCachedCodexResults, getCachedCodexProject, fingerprintFile } from '../codex-cache.js';
|
|
9
|
+
import { mergeToolIntervals } from '../codex-throughput.js';
|
|
10
|
+
import { codexReplayNativeToolIdentity, codexReplayResponseIdentity, codexReplayUsageIdentity, isCodexForkReplay, isCodexForkReplayState, loadCodexParentReplayIndex, startCodexForkReplay } from '../codex-fork-replay.js';
|
|
11
|
+
import { findRawObjectField, getRawObjectFieldWindow } from '../codex-jsonl-fields.js';
|
|
12
|
+
import { normalizeContentBlocks } from '../content-utils.js';
|
|
13
|
+
import { estimateTokensFromChars } from '../token-estimate.js';
|
|
14
|
+
import { wslHomes } from '../wsl.js';
|
|
15
|
+
import { defaultBilledCodexHome, defaultLauncherRoots, FIRST_LINE_READ_CAP, isNestedLauncherCodexHome, isRolloutFileName, listRolloutSessionIds, rolloutFileSessionId, rolloutStem, sameCodexHome } from '../launcher-homes.js';
|
|
16
|
+
const modelDisplayNames = {
|
|
17
|
+
'codex-auto-review': 'Codex Auto Review',
|
|
18
|
+
'gpt-5.5': 'GPT-5.5',
|
|
19
|
+
'gpt-5.4-mini': 'GPT-5.4 Mini',
|
|
20
|
+
'gpt-5.4': 'GPT-5.4',
|
|
21
|
+
'gpt-5.3-codex-spark': 'GPT-5.3 Codex Spark',
|
|
22
|
+
'gpt-5.3-codex': 'GPT-5.3 Codex',
|
|
23
|
+
'gpt-5.2-low': 'GPT-5.2 Low',
|
|
24
|
+
'gpt-5.2': 'GPT-5.2',
|
|
25
|
+
'gpt-5': 'GPT-5',
|
|
26
|
+
'gpt-4o-mini': 'GPT-4o Mini',
|
|
27
|
+
'gpt-4o': 'GPT-4o',
|
|
28
|
+
};
|
|
29
|
+
// Longest-first + version-boundary match so an unlisted future minor (gpt-5.6)
|
|
30
|
+
// falls through to its raw id instead of collapsing into the base "GPT-5" entry.
|
|
31
|
+
const modelDisplayEntries = Object.entries(modelDisplayNames).sort((a, b) => b[0].length - a[0].length);
|
|
32
|
+
const toolNameMap = {
|
|
33
|
+
exec_command: 'Bash',
|
|
34
|
+
// Codex Desktop's custom-tool transport uses the shorter `exec` name for
|
|
35
|
+
// the same shell tool that CLI rollouts record as `exec_command`.
|
|
36
|
+
exec: 'Bash',
|
|
37
|
+
read_file: 'Read',
|
|
38
|
+
write_file: 'Edit',
|
|
39
|
+
apply_diff: 'Edit',
|
|
40
|
+
apply_patch: 'Edit',
|
|
41
|
+
spawn_agent: 'Agent',
|
|
42
|
+
close_agent: 'Agent',
|
|
43
|
+
wait_agent: 'Agent',
|
|
44
|
+
read_dir: 'Glob',
|
|
45
|
+
};
|
|
46
|
+
// CLI-based MCP wrappers (e.g. philschmid/mcp-cli) let Codex call an MCP tool
|
|
47
|
+
// through a shell command instead of registering the server natively. Codex
|
|
48
|
+
// then logs a plain exec_command with no `mcp_tool_call_end` event, so the MCP
|
|
49
|
+
// usage would only appear as a shell command and be absent from the MCP
|
|
50
|
+
// breakdown (issue #478). Recognize the `mcp-cli [options] call <server>
|
|
51
|
+
// <tool>` form and return the canonical mcp__<server>__<tool> so the call is
|
|
52
|
+
// also attributed to MCP. Only the `call` subcommand (an actual tool execution)
|
|
53
|
+
// is matched; info / grep / bare listing are lookups. The exec_command still
|
|
54
|
+
// counts as Bash since it genuinely is a shell exec. Scoped to the mcp-cli
|
|
55
|
+
// binary; other wrappers would need their own pattern.
|
|
56
|
+
//
|
|
57
|
+
// `mcp-cli` must be the command being run: the first word of a command
|
|
58
|
+
// segment (text start, after a shell separator, `(`, a backtick, a `-c`/`-lc`
|
|
59
|
+
// shell flag, or the exec tool's `cmd:`), optionally behind a directory prefix.
|
|
60
|
+
// Options before `call` are skipped, and the server and tool must be
|
|
61
|
+
// identifier-shaped, so a commit message or an echo that mentions it is not a call.
|
|
62
|
+
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'"`;|&)]|$)/;
|
|
63
|
+
function mcpToolFromShellCommand(text) {
|
|
64
|
+
const m = MCP_CLI_CALL.exec(text);
|
|
65
|
+
return m ? `mcp__${m[2]}__${m[4]}` : null;
|
|
66
|
+
}
|
|
67
|
+
// Codex has no dedicated skill tool: loading a skill is an ordinary shell exec
|
|
68
|
+
// that reads the skill's `SKILL.md`, so the usage landed entirely under Bash and
|
|
69
|
+
// the Skills dimension stayed empty (#478). Recognize only a *read* of a
|
|
70
|
+
// SKILL.md, deliberately narrowly:
|
|
71
|
+
// - the command segment must start with a file-reading binary (cat/sed/head/
|
|
72
|
+
// tail/less/more/bat) — a `grep`/`rg`/`ls` that merely mentions a SKILL.md
|
|
73
|
+
// is a search near the file, not a skill load, and stays plain Bash;
|
|
74
|
+
// - the path it reads must END in `<name>/SKILL.md`, so `<name>` is the skill.
|
|
75
|
+
// The name is the parent directory, the same key `src/providers/pi.ts` derives
|
|
76
|
+
// for a native skill read (#588) and the same vocabulary the Claude parser
|
|
77
|
+
// records from the `Skill` tool, so the Skills breakdown stays cross-provider
|
|
78
|
+
// coherent. Substring matching, so a command that merely quotes the phrase can
|
|
79
|
+
// false-positive, an accepted tradeoff for this matcher.
|
|
80
|
+
const SKILL_MD_READ = /(?<![\w.-])(?:cat|bat|sed|head|tail|less|more)\b[^;|&]*?[\s'"]([^\s;|&'"]*[\\/]([^\\/;|&'"]+)[\\/]SKILL\.md)\b/;
|
|
81
|
+
function skillFromShellCommand(text) {
|
|
82
|
+
const m = SKILL_MD_READ.exec(text);
|
|
83
|
+
const name = m?.[2]?.trim();
|
|
84
|
+
return name ? name : null;
|
|
85
|
+
}
|
|
86
|
+
/// Flatten every shape Codex records a shell command in to one string:
|
|
87
|
+
/// `function_call` arguments carry it as a plain string, the item model's
|
|
88
|
+
/// `CommandExecution` item as an argv array (`["/bin/zsh","-lc","..."]`), and
|
|
89
|
+
/// the `exec` custom tool as the JS program that calls `tools.exec_command`.
|
|
90
|
+
/// One text, one classification pipeline (#478).
|
|
91
|
+
function shellCommandText(command) {
|
|
92
|
+
if (typeof command === 'string')
|
|
93
|
+
return command;
|
|
94
|
+
if (Array.isArray(command))
|
|
95
|
+
return command.filter(x => typeof x === 'string').join(' ');
|
|
96
|
+
return '';
|
|
97
|
+
}
|
|
98
|
+
// Count added/removed lines from a Codex `patch_apply_end` change's
|
|
99
|
+
// `unified_diff`. A leading '+' is an added line and '-' a removed line; the
|
|
100
|
+
// '+++'/'---' file headers and '@@' hunk headers are excluded. Numbers only —
|
|
101
|
+
// the diff text is never stored. Rich-session-capture (capture-only).
|
|
102
|
+
export function countUnifiedDiffLoc(diff) {
|
|
103
|
+
let added = 0;
|
|
104
|
+
let removed = 0;
|
|
105
|
+
if (typeof diff !== 'string')
|
|
106
|
+
return { added, removed };
|
|
107
|
+
for (const line of diff.split('\n')) {
|
|
108
|
+
if (line.startsWith('+') && !line.startsWith('+++'))
|
|
109
|
+
added++;
|
|
110
|
+
else if (line.startsWith('-') && !line.startsWith('---'))
|
|
111
|
+
removed++;
|
|
112
|
+
}
|
|
113
|
+
return { added, removed };
|
|
114
|
+
}
|
|
115
|
+
function nativeToolEvent(entry) {
|
|
116
|
+
const payload = entry.payload;
|
|
117
|
+
if (!payload)
|
|
118
|
+
return null;
|
|
119
|
+
let tool = null;
|
|
120
|
+
let identity;
|
|
121
|
+
if (entry.type === 'response_item') {
|
|
122
|
+
if (payload.type === 'web_search_call')
|
|
123
|
+
tool = 'WebSearch';
|
|
124
|
+
else if (payload.type === 'tool_search_call')
|
|
125
|
+
tool = 'ToolSearch';
|
|
126
|
+
else if (payload.type === 'image_generation_call')
|
|
127
|
+
tool = 'ImageGeneration';
|
|
128
|
+
if (!tool)
|
|
129
|
+
return null;
|
|
130
|
+
identity = typeof payload.id === 'string' && payload.id
|
|
131
|
+
? payload.id
|
|
132
|
+
: typeof payload.call_id === 'string' && payload.call_id
|
|
133
|
+
? payload.call_id
|
|
134
|
+
: undefined;
|
|
135
|
+
}
|
|
136
|
+
else if (entry.type === 'event_msg' && payload.type === 'item_completed') {
|
|
137
|
+
const item = payload.item;
|
|
138
|
+
if (!item)
|
|
139
|
+
return null;
|
|
140
|
+
if (item['type'] !== 'WebSearch' && !(item['type'] === 'Extension' && item['kind'] === 'web.search'))
|
|
141
|
+
return null;
|
|
142
|
+
tool = 'WebSearch';
|
|
143
|
+
identity = typeof item['id'] === 'string' && item['id'] ? item['id'] : undefined;
|
|
144
|
+
}
|
|
145
|
+
if (!tool)
|
|
146
|
+
return null;
|
|
147
|
+
return { tool, ...(identity ? { identity: codexReplayNativeToolIdentity(tool, identity) } : {}) };
|
|
148
|
+
}
|
|
149
|
+
const RAW_HEAD_BYTES = 64 * 1024;
|
|
150
|
+
const LARGE_TEXT_CAP = 2000;
|
|
151
|
+
function getCodexDir(override) {
|
|
152
|
+
return override ?? process.env['CODEX_HOME'] ?? join(homedir(), '.codex');
|
|
153
|
+
}
|
|
154
|
+
function sanitizeProject(cwd) {
|
|
155
|
+
return cwd.replace(/^\//, '').replace(/\//g, '-');
|
|
156
|
+
}
|
|
157
|
+
// Cap how many bytes we'll read while looking for the first newline. Real
|
|
158
|
+
// Codex session_meta lines are ~22-27 KB; this leaves plenty of headroom while
|
|
159
|
+
// keeping memory bounded if a corrupt file has no newline at all.
|
|
160
|
+
// FIRST_LINE_READ_CAP is shared with rolloutFileSessionId.
|
|
161
|
+
async function readFirstLine(filePath) {
|
|
162
|
+
// Codex CLI 0.128+ writes a session_meta line that can exceed 20 KB because
|
|
163
|
+
// it embeds the full base_instructions / system prompt. A fixed-size buffer
|
|
164
|
+
// would miss the trailing newline and reject the session as invalid.
|
|
165
|
+
// Stream the file via readline so we can read the first line up to
|
|
166
|
+
// FIRST_LINE_READ_CAP, which keeps memory bounded if the file has no newline.
|
|
167
|
+
const stream = createTextReadStream(filePath, {
|
|
168
|
+
start: 0,
|
|
169
|
+
end: FIRST_LINE_READ_CAP - 1,
|
|
170
|
+
});
|
|
171
|
+
// Silence stream errors so a late read-ahead error after we've already
|
|
172
|
+
// returned the first line cannot escape as an unhandled 'error' event.
|
|
173
|
+
// readline's async iterator re-throws underlying stream errors (ENOENT,
|
|
174
|
+
// EACCES, etc.) on Node 16+, which the catch below handles for the cases
|
|
175
|
+
// that matter for validation.
|
|
176
|
+
stream.on('error', () => { });
|
|
177
|
+
const rl = createInterface({ input: stream, crlfDelay: Infinity });
|
|
178
|
+
let firstLine;
|
|
179
|
+
try {
|
|
180
|
+
for await (const line of rl) {
|
|
181
|
+
firstLine = line;
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
rl.close();
|
|
190
|
+
stream.destroy();
|
|
191
|
+
}
|
|
192
|
+
if (!firstLine || !firstLine.trim())
|
|
193
|
+
return null;
|
|
194
|
+
try {
|
|
195
|
+
return JSON.parse(firstLine);
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// Validation is STRUCTURAL, never string-matching on `payload.originator`.
|
|
202
|
+
// `originator` is a free-form CLIENT IDENTITY string, not a format marker: any
|
|
203
|
+
// tool driving `codex app-server` writes structurally identical rollouts under
|
|
204
|
+
// ~/.codex/sessions with its own value ("codex-tui", "Codex Desktop",
|
|
205
|
+
// "t3code_desktop", "JetBrains.IntelliJ IDEA", ...). Gating on the spelling
|
|
206
|
+
// silently dropped every third-party frontend and needed a new allowlist entry
|
|
207
|
+
// per client (issues #626, #873).
|
|
208
|
+
//
|
|
209
|
+
// A `session_meta` first line with a well-formed payload object is signal
|
|
210
|
+
// enough: the walker only visits `rollout-*.jsonl` under the strict
|
|
211
|
+
// YYYY/MM/DD path or `archived_sessions/`, and codex.ts is the only provider
|
|
212
|
+
// that reads ~/.codex, so directory ownership — not originator content —
|
|
213
|
+
// decides the provider. Genuinely foreign files (wrong entry type, missing or
|
|
214
|
+
// non-object payload, malformed JSON) are still rejected.
|
|
215
|
+
async function isValidCodexSession(filePath) {
|
|
216
|
+
const entry = await readFirstLine(filePath);
|
|
217
|
+
if (!entry)
|
|
218
|
+
return { valid: false };
|
|
219
|
+
// `entry` comes from an unchecked JSON.parse cast, so re-check the payload
|
|
220
|
+
// shape at runtime instead of trusting the declared type.
|
|
221
|
+
const payload = entry.payload;
|
|
222
|
+
const valid = entry.type === 'session_meta' &&
|
|
223
|
+
typeof payload === 'object' &&
|
|
224
|
+
payload !== null &&
|
|
225
|
+
!Array.isArray(payload);
|
|
226
|
+
return { valid, meta: valid ? entry : undefined };
|
|
227
|
+
}
|
|
228
|
+
function getRawJsonStringField(head, field) {
|
|
229
|
+
const re = new RegExp(`"${field}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"`);
|
|
230
|
+
const match = re.exec(head);
|
|
231
|
+
if (!match)
|
|
232
|
+
return undefined;
|
|
233
|
+
try {
|
|
234
|
+
return JSON.parse(`"${match[1]}"`);
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
return match[1];
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function getRawJsonNumberField(head, field) {
|
|
241
|
+
const match = new RegExp(`"${field}"\\s*:\\s*(-?\\d+(?:\\.\\d+)?)`).exec(head);
|
|
242
|
+
if (!match)
|
|
243
|
+
return undefined;
|
|
244
|
+
const value = Number(match[1]);
|
|
245
|
+
return Number.isFinite(value) ? value : undefined;
|
|
246
|
+
}
|
|
247
|
+
function getRawPayloadObjectStart(source) {
|
|
248
|
+
const payload = findRawObjectField(source, 0, 'payload');
|
|
249
|
+
return payload && source[payload.valueStart] === 0x7b ? payload.valueStart : undefined;
|
|
250
|
+
}
|
|
251
|
+
function getRawPayloadFieldWindow(source, field, windowBytes = 4096) {
|
|
252
|
+
const payloadStart = getRawPayloadObjectStart(source);
|
|
253
|
+
return payloadStart === undefined ? undefined : getRawObjectFieldWindow(source, payloadStart, field, windowBytes);
|
|
254
|
+
}
|
|
255
|
+
function getRawPayloadItemFieldWindow(source, field, windowBytes = 4096) {
|
|
256
|
+
const payloadStart = getRawPayloadObjectStart(source);
|
|
257
|
+
if (payloadStart === undefined)
|
|
258
|
+
return undefined;
|
|
259
|
+
const item = findRawObjectField(source, payloadStart, 'item');
|
|
260
|
+
if (!item || source[item.valueStart] !== 0x7b)
|
|
261
|
+
return undefined;
|
|
262
|
+
return getRawObjectFieldWindow(source, item.valueStart, field, windowBytes);
|
|
263
|
+
}
|
|
264
|
+
function getRawDurationMs(head) {
|
|
265
|
+
const objectMatch = /"duration"\s*:\s*\{\s*"secs"\s*:\s*(-?\d+(?:\.\d+)?)\s*,\s*"nanos"\s*:\s*(-?\d+(?:\.\d+)?)\s*\}/.exec(head);
|
|
266
|
+
if (objectMatch) {
|
|
267
|
+
const seconds = Number(objectMatch[1]);
|
|
268
|
+
const nanos = Number(objectMatch[2]);
|
|
269
|
+
if (Number.isFinite(seconds) && Number.isFinite(nanos))
|
|
270
|
+
return seconds * 1000 + nanos / 1e6;
|
|
271
|
+
}
|
|
272
|
+
const text = getRawJsonStringField(head, 'duration');
|
|
273
|
+
if (text) {
|
|
274
|
+
const match = /^(\d+(?:\.\d+)?)(ms|s)?$/.exec(text.trim());
|
|
275
|
+
if (match) {
|
|
276
|
+
const value = Number(match[1]);
|
|
277
|
+
if (Number.isFinite(value))
|
|
278
|
+
return value * (match[2] === 's' ? 1000 : 1);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return undefined;
|
|
282
|
+
}
|
|
283
|
+
function durationValueMs(value) {
|
|
284
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
285
|
+
return value;
|
|
286
|
+
if (typeof value === 'object' && value) {
|
|
287
|
+
const record = value;
|
|
288
|
+
const seconds = record['secs'];
|
|
289
|
+
const nanos = record['nanos'];
|
|
290
|
+
if (typeof seconds === 'number' && typeof nanos === 'number' && Number.isFinite(seconds) && Number.isFinite(nanos)) {
|
|
291
|
+
return seconds * 1000 + nanos / 1e6;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (typeof value === 'string') {
|
|
295
|
+
const match = /^(\d+(?:\.\d+)?)(ms|s)?$/.exec(value.trim());
|
|
296
|
+
if (match) {
|
|
297
|
+
const parsed = Number(match[1]);
|
|
298
|
+
if (Number.isFinite(parsed))
|
|
299
|
+
return parsed * (match[2] === 's' ? 1000 : 1);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return undefined;
|
|
303
|
+
}
|
|
304
|
+
function getRawTokenUsage(head, field) {
|
|
305
|
+
const match = new RegExp(`"${field}"\\s*:\\s*\\{([^}]*)\\}`).exec(head);
|
|
306
|
+
if (!match)
|
|
307
|
+
return undefined;
|
|
308
|
+
const body = match[1];
|
|
309
|
+
return {
|
|
310
|
+
input_tokens: getRawJsonNumberField(body, 'input_tokens'),
|
|
311
|
+
cached_input_tokens: getRawJsonNumberField(body, 'cached_input_tokens'),
|
|
312
|
+
cache_write_input_tokens: getRawJsonNumberField(body, 'cache_write_input_tokens'),
|
|
313
|
+
output_tokens: getRawJsonNumberField(body, 'output_tokens'),
|
|
314
|
+
reasoning_output_tokens: getRawJsonNumberField(body, 'reasoning_output_tokens'),
|
|
315
|
+
total_tokens: getRawJsonNumberField(body, 'total_tokens'),
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
function payloadHead(source) {
|
|
319
|
+
const payloadStart = getRawPayloadObjectStart(source);
|
|
320
|
+
return payloadStart === undefined
|
|
321
|
+
? ''
|
|
322
|
+
: source.subarray(payloadStart, Math.min(source.length, payloadStart + RAW_HEAD_BYTES)).toString('utf-8');
|
|
323
|
+
}
|
|
324
|
+
function getRawInvocation(head) {
|
|
325
|
+
const idx = head.indexOf('"invocation"');
|
|
326
|
+
if (idx === -1)
|
|
327
|
+
return undefined;
|
|
328
|
+
// Server/tool are shallow fields and precede the potentially huge arguments
|
|
329
|
+
// object in Codex MCP records. Limit this scan to keep compact parsing cheap.
|
|
330
|
+
const invocationHead = head.slice(idx, idx + 8192);
|
|
331
|
+
const server = getRawJsonStringField(invocationHead, 'server');
|
|
332
|
+
const tool = getRawJsonStringField(invocationHead, 'tool');
|
|
333
|
+
return server || tool ? { server, tool } : undefined;
|
|
334
|
+
}
|
|
335
|
+
function countJsonStringBytes(source, valueStart) {
|
|
336
|
+
let count = 0;
|
|
337
|
+
for (let i = valueStart; i < source.length; i++) {
|
|
338
|
+
const ch = source[i];
|
|
339
|
+
if (ch === 0x5c) {
|
|
340
|
+
i++;
|
|
341
|
+
count++;
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
if (ch === 0x22)
|
|
345
|
+
return count;
|
|
346
|
+
count++;
|
|
347
|
+
}
|
|
348
|
+
return count;
|
|
349
|
+
}
|
|
350
|
+
function extractFirstJsonText(source, cap = LARGE_TEXT_CAP) {
|
|
351
|
+
const key = Buffer.from('"text"');
|
|
352
|
+
const idx = source.indexOf(key);
|
|
353
|
+
if (idx === -1)
|
|
354
|
+
return '';
|
|
355
|
+
const colon = source.indexOf(0x3a, idx + key.length);
|
|
356
|
+
if (colon === -1)
|
|
357
|
+
return '';
|
|
358
|
+
const qStart = source.indexOf(0x22, colon + 1);
|
|
359
|
+
if (qStart === -1)
|
|
360
|
+
return '';
|
|
361
|
+
const chunks = [];
|
|
362
|
+
for (let i = qStart + 1; i < source.length && chunks.length < cap; i++) {
|
|
363
|
+
const ch = source[i];
|
|
364
|
+
if (ch === 0x5c) {
|
|
365
|
+
const next = source[++i];
|
|
366
|
+
if (next === 0x6e)
|
|
367
|
+
chunks.push(0x0a);
|
|
368
|
+
else if (next === 0x72)
|
|
369
|
+
chunks.push(0x0d);
|
|
370
|
+
else if (next === 0x74)
|
|
371
|
+
chunks.push(0x09);
|
|
372
|
+
else if (next !== undefined)
|
|
373
|
+
chunks.push(next);
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
if (ch === 0x22)
|
|
377
|
+
break;
|
|
378
|
+
chunks.push(ch);
|
|
379
|
+
}
|
|
380
|
+
return Buffer.from(chunks).toString('utf-8');
|
|
381
|
+
}
|
|
382
|
+
function countFirstJsonText(source) {
|
|
383
|
+
const key = Buffer.from('"text"');
|
|
384
|
+
const idx = source.indexOf(key);
|
|
385
|
+
if (idx === -1)
|
|
386
|
+
return 0;
|
|
387
|
+
const colon = source.indexOf(0x3a, idx + key.length);
|
|
388
|
+
if (colon === -1)
|
|
389
|
+
return 0;
|
|
390
|
+
const qStart = source.indexOf(0x22, colon + 1);
|
|
391
|
+
if (qStart === -1)
|
|
392
|
+
return 0;
|
|
393
|
+
return countJsonStringBytes(source, qStart + 1);
|
|
394
|
+
}
|
|
395
|
+
// `thread_settings.service_tier` (#1616). The field comes off an unchecked
|
|
396
|
+
// JSON.parse cast, so only a genuine non-empty string reads as a tier; anything
|
|
397
|
+
// else is "the rollout states no tier", which prices as standard.
|
|
398
|
+
function serviceTierFromThreadSettings(payload) {
|
|
399
|
+
const tier = payload?.thread_settings?.service_tier;
|
|
400
|
+
return typeof tier === 'string' && tier ? tier : undefined;
|
|
401
|
+
}
|
|
402
|
+
// The billable speed a service tier maps to (#1616). `"priority"` is Codex's
|
|
403
|
+
// Fast speed setting and bills through the priority tier; `"fast"` is accepted
|
|
404
|
+
// too in case a build writes the speed name where the tier name belongs.
|
|
405
|
+
// `"flex"` bills at the model's published Flex rates, or standard without them.
|
|
406
|
+
// Everything else - `"default"`, an unrecognised value, no tier at all - is
|
|
407
|
+
// standard, never a guess.
|
|
408
|
+
function speedForServiceTier(tier) {
|
|
409
|
+
if (tier === 'flex')
|
|
410
|
+
return 'flex';
|
|
411
|
+
if (tier === 'ultrafast')
|
|
412
|
+
return 'ultrafast';
|
|
413
|
+
return tier === 'priority' || tier === 'fast' ? 'fast' : 'standard';
|
|
414
|
+
}
|
|
415
|
+
function parseCodexLine(line) {
|
|
416
|
+
if (typeof line === 'string') {
|
|
417
|
+
const trimmed = line.trim();
|
|
418
|
+
if (!trimmed)
|
|
419
|
+
return null;
|
|
420
|
+
try {
|
|
421
|
+
const entry = JSON.parse(trimmed);
|
|
422
|
+
// #1616: `thread_settings.service_tier` sits at payload depth 2, which
|
|
423
|
+
// the compact path below cannot express; flatten it the same way for the
|
|
424
|
+
// fully-parsed path so both decoders agree.
|
|
425
|
+
const tier = serviceTierFromThreadSettings(entry.payload);
|
|
426
|
+
if (tier !== undefined && entry.payload)
|
|
427
|
+
entry.payload.serviceTier = tier;
|
|
428
|
+
return entry;
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
if (line.length === 0)
|
|
435
|
+
return null;
|
|
436
|
+
const head = line.subarray(0, RAW_HEAD_BYTES).toString('utf-8');
|
|
437
|
+
const type = getRawJsonStringField(head, 'type');
|
|
438
|
+
if (!type)
|
|
439
|
+
return null;
|
|
440
|
+
const pHead = payloadHead(line);
|
|
441
|
+
// The depth-1 scan walks past large values when the key is missing (compacted
|
|
442
|
+
// history has no payload type), so only native tool candidates pay for it.
|
|
443
|
+
const headPayloadType = getRawJsonStringField(pHead, 'type');
|
|
444
|
+
const payloadType = headPayloadType === 'web_search_call' || headPayloadType === 'tool_search_call'
|
|
445
|
+
|| headPayloadType === 'image_generation_call' || headPayloadType === 'item_completed'
|
|
446
|
+
? getRawJsonStringField(getRawPayloadFieldWindow(line, 'type') ?? '', 'type')
|
|
447
|
+
: headPayloadType;
|
|
448
|
+
const role = getRawJsonStringField(pHead, 'role');
|
|
449
|
+
// task_complete appends the potentially huge final assistant message before
|
|
450
|
+
// its duration fields. Fall back to the full Buffer only for this event so
|
|
451
|
+
// timing metadata is not lost when the compact head stops early.
|
|
452
|
+
const needsTimingTail = type === 'event_msg' && (payloadType === 'task_complete' || payloadType === 'mcp_tool_call_end');
|
|
453
|
+
const timingTail = needsTimingTail && line.length > RAW_HEAD_BYTES
|
|
454
|
+
? line.subarray(Math.max(0, line.length - 16 * 1024)).toString('utf-8')
|
|
455
|
+
: pHead;
|
|
456
|
+
const timingNumber = (field) => getRawJsonNumberField(pHead, field) ?? getRawJsonNumberField(timingTail, field);
|
|
457
|
+
// MCP records can place a large invocation.arguments object before duration
|
|
458
|
+
// and a large result after it. Searching a small window around the field
|
|
459
|
+
// avoids materializing the middle of the Buffer while still preserving wait
|
|
460
|
+
// timing for those records.
|
|
461
|
+
const payloadDuration = payloadType === 'mcp_tool_call_end'
|
|
462
|
+
? getRawDurationMs(getRawPayloadFieldWindow(line, 'duration') ?? '')
|
|
463
|
+
: undefined;
|
|
464
|
+
const timingDuration = payloadDuration ?? getRawDurationMs(pHead) ?? getRawDurationMs(timingTail);
|
|
465
|
+
// session_meta can embed same-name keys under base_instructions /
|
|
466
|
+
// dynamic_tools (including provenance.model). A depth-agnostic scan of the
|
|
467
|
+
// compact head steals the first nested hit and can overwrite turn_context.
|
|
468
|
+
// Restrict every session_meta string field to payload depth 1. Other event
|
|
469
|
+
// types keep the cheap first-match scan.
|
|
470
|
+
const payloadString = (field) => type === 'session_meta'
|
|
471
|
+
? getRawJsonStringField(getRawPayloadFieldWindow(line, field) ?? '', field)
|
|
472
|
+
: getRawJsonStringField(pHead, field);
|
|
473
|
+
const compactModel = payloadString('model');
|
|
474
|
+
const compactModelName = getRawJsonStringField(pHead, 'model_name');
|
|
475
|
+
const compactLastUsage = getRawTokenUsage(pHead, 'last_token_usage');
|
|
476
|
+
const compactTotalUsage = getRawTokenUsage(pHead, 'total_token_usage');
|
|
477
|
+
const itemTypeWindow = type === 'event_msg' && payloadType === 'item_completed'
|
|
478
|
+
? getRawPayloadItemFieldWindow(line, 'type')
|
|
479
|
+
: undefined;
|
|
480
|
+
const compactItemType = itemTypeWindow ? getRawJsonStringField(itemTypeWindow, 'type') : undefined;
|
|
481
|
+
const isSearchItem = compactItemType === 'WebSearch' || compactItemType === 'Extension';
|
|
482
|
+
const itemIdWindow = isSearchItem ? getRawPayloadItemFieldWindow(line, 'id') : undefined;
|
|
483
|
+
const itemKindWindow = isSearchItem ? getRawPayloadItemFieldWindow(line, 'kind') : undefined;
|
|
484
|
+
const compactItemId = itemIdWindow ? getRawJsonStringField(itemIdWindow, 'id') : undefined;
|
|
485
|
+
const compactItemKind = itemKindWindow ? getRawJsonStringField(itemKindWindow, 'kind') : undefined;
|
|
486
|
+
const compactItem = compactItemType
|
|
487
|
+
? { type: compactItemType, ...(compactItemId ? { id: compactItemId } : {}), ...(compactItemKind ? { kind: compactItemKind } : {}) }
|
|
488
|
+
: undefined;
|
|
489
|
+
const isNativeResponseTool = type === 'response_item' && (payloadType === 'web_search_call' || payloadType === 'tool_search_call' || payloadType === 'image_generation_call');
|
|
490
|
+
const nativeIdWindow = isNativeResponseTool ? getRawPayloadFieldWindow(line, 'id') : undefined;
|
|
491
|
+
const nativeCallIdWindow = isNativeResponseTool ? getRawPayloadFieldWindow(line, 'call_id') : undefined;
|
|
492
|
+
const compactId = nativeIdWindow ? getRawJsonStringField(nativeIdWindow, 'id') : undefined;
|
|
493
|
+
const compactCallId = isNativeResponseTool
|
|
494
|
+
? nativeCallIdWindow ? getRawJsonStringField(nativeCallIdWindow, 'call_id') : undefined
|
|
495
|
+
: getRawJsonStringField(pHead, 'call_id');
|
|
496
|
+
const compactInfo = compactModel || compactModelName || compactLastUsage || compactTotalUsage
|
|
497
|
+
? { model: compactModel, model_name: compactModelName, last_token_usage: compactLastUsage, total_token_usage: compactTotalUsage }
|
|
498
|
+
: undefined;
|
|
499
|
+
const invocation = getRawInvocation(pHead) ?? getRawInvocation(timingTail);
|
|
500
|
+
const entry = {
|
|
501
|
+
type,
|
|
502
|
+
timestamp: getRawJsonStringField(head, 'timestamp'),
|
|
503
|
+
payload: {
|
|
504
|
+
type: payloadType,
|
|
505
|
+
id: compactId ?? (type === 'session_meta' ? payloadString('id') : undefined),
|
|
506
|
+
role,
|
|
507
|
+
cwd: payloadString('cwd'),
|
|
508
|
+
model_provider: payloadString('model_provider'),
|
|
509
|
+
originator: payloadString('originator'),
|
|
510
|
+
session_id: payloadString('session_id'),
|
|
511
|
+
forked_from_id: payloadString('forked_from_id'),
|
|
512
|
+
parent_thread_id: type === 'session_meta'
|
|
513
|
+
? getRawJsonStringField(getRawPayloadFieldWindow(line, 'source') ?? '', 'parent_thread_id')
|
|
514
|
+
: undefined,
|
|
515
|
+
model: compactModel,
|
|
516
|
+
name: payloadString('name'),
|
|
517
|
+
item: compactItem,
|
|
518
|
+
invocation,
|
|
519
|
+
call_id: compactCallId,
|
|
520
|
+
turn_id: getRawJsonStringField(pHead, 'turn_id'),
|
|
521
|
+
// #1616: oversized thread_settings_applied records (a fat permission
|
|
522
|
+
// profile or plugin list can push them past the buffer threshold) still
|
|
523
|
+
// carry `service_tier` within the first few hundred bytes of the
|
|
524
|
+
// thread_settings object, so the windowed scan reaches it. Scanning
|
|
525
|
+
// inside the payload-depth-1 `thread_settings` window - the session_meta
|
|
526
|
+
// treatment above - keeps this decoder agreeing with the full-JSON path
|
|
527
|
+
// (which reads the nested field) even if a same-name key ever appears in
|
|
528
|
+
// an earlier payload field, and the payload-type guard keeps a
|
|
529
|
+
// coincidental same-name key inside another event's bulk from reading as
|
|
530
|
+
// a tier.
|
|
531
|
+
serviceTier: type === 'event_msg' && payloadType === 'thread_settings_applied'
|
|
532
|
+
? getRawJsonStringField(getRawPayloadFieldWindow(line, 'thread_settings') ?? '', 'service_tier')
|
|
533
|
+
: undefined,
|
|
534
|
+
// On mcp_tool_call_end a coincidental `duration_ms` inside the large
|
|
535
|
+
// invocation.arguments object can shadow the payload-level duration, so the
|
|
536
|
+
// depth-aware value wins. The naive scan stays as the fallback for
|
|
537
|
+
// task_complete, which records duration_ms at the payload level directly.
|
|
538
|
+
duration_ms: timingDuration ?? timingNumber('duration_ms'),
|
|
539
|
+
started_at: timingNumber('started_at'),
|
|
540
|
+
info: compactInfo,
|
|
541
|
+
},
|
|
542
|
+
};
|
|
543
|
+
if (type === 'response_item' && payloadType === 'message' && role === 'user') {
|
|
544
|
+
entry.payload.content = [{ type: 'input_text', text: extractFirstJsonText(line) }];
|
|
545
|
+
}
|
|
546
|
+
else if (type === 'response_item' && payloadType === 'message' && role === 'assistant') {
|
|
547
|
+
entry.payload.content = [{ type: 'output_text', text: 'x'.repeat(Math.min(countFirstJsonText(line), LARGE_TEXT_CAP)) }];
|
|
548
|
+
}
|
|
549
|
+
return entry;
|
|
550
|
+
}
|
|
551
|
+
async function discoverSessionFile(filePath) {
|
|
552
|
+
const s = await stat(filePath).catch(() => null);
|
|
553
|
+
if (!s?.isFile())
|
|
554
|
+
return null;
|
|
555
|
+
// Fast path: cached results already know the project, so avoid opening the
|
|
556
|
+
// file. This keeps discovery cheap on large session directories.
|
|
557
|
+
const cachedProject = await getCachedCodexProject(filePath);
|
|
558
|
+
if (cachedProject) {
|
|
559
|
+
return { path: filePath, project: cachedProject, provider: 'codex' };
|
|
560
|
+
}
|
|
561
|
+
const { valid, meta } = await isValidCodexSession(filePath);
|
|
562
|
+
if (!valid || !meta)
|
|
563
|
+
return null;
|
|
564
|
+
// Same unchecked-cast caveat as the payload check above: `cwd` is declared
|
|
565
|
+
// `string` but comes straight off JSON.parse. A rollout carrying a number,
|
|
566
|
+
// object or array here would throw out of sanitizeProject, escape
|
|
567
|
+
// discoverSessions, and make safeDiscoverSessions return [] for the WHOLE
|
|
568
|
+
// codex provider — every Codex report reading zero because of one bad file.
|
|
569
|
+
const rawCwd = meta.payload?.cwd;
|
|
570
|
+
const cwd = typeof rawCwd === 'string' && rawCwd ? rawCwd : 'unknown';
|
|
571
|
+
return { path: filePath, project: sanitizeProject(cwd), provider: 'codex' };
|
|
572
|
+
}
|
|
573
|
+
async function discoverSessionsInDir(codexDir) {
|
|
574
|
+
const sources = [];
|
|
575
|
+
// Codex archives a session by moving it from sessions/YYYY/MM/DD/ to
|
|
576
|
+
// archived_sessions/, keeping the same basename. Deduplicate by basename so
|
|
577
|
+
// a session does not appear twice while it exists in both roots. This avoids
|
|
578
|
+
// reading every file to extract session_id and preserves the cheap cached
|
|
579
|
+
// fast path.
|
|
580
|
+
const seenBasenames = new Set();
|
|
581
|
+
const sessionsDir = join(codexDir, 'sessions');
|
|
582
|
+
const years = (await readdir(sessionsDir).catch(() => [])).filter(y => /^\d{4}$/.test(y));
|
|
583
|
+
const monthDirs = (await mapWithConcurrency(years, FS_SCAN_CONCURRENCY, async (year) => {
|
|
584
|
+
const yearDir = join(sessionsDir, year);
|
|
585
|
+
return (await readdir(yearDir).catch(() => []))
|
|
586
|
+
.filter(m => /^\d{2}$/.test(m))
|
|
587
|
+
.map(m => join(yearDir, m));
|
|
588
|
+
})).flat();
|
|
589
|
+
const dayDirs = (await mapWithConcurrency(monthDirs, FS_SCAN_CONCURRENCY, async (monthDir) => (await readdir(monthDir).catch(() => []))
|
|
590
|
+
.filter(d => /^\d{2}$/.test(d))
|
|
591
|
+
.map(d => join(monthDir, d)))).flat();
|
|
592
|
+
const dated = (await mapWithConcurrency(dayDirs, FS_SCAN_CONCURRENCY, async (dayDir) => (await readdir(dayDir).catch(() => []))
|
|
593
|
+
.filter(isRolloutFileName)
|
|
594
|
+
.map(f => ({ file: f, path: join(dayDir, f) })))).flat();
|
|
595
|
+
// Codex moves archived sessions into a flat directory. Keep them in usage
|
|
596
|
+
// reports so archiving a conversation does not erase its historical usage.
|
|
597
|
+
// Call-level deduplication (seenKeys) already collapses any remaining
|
|
598
|
+
// archived copies, while basename dedup below prevents double discovery.
|
|
599
|
+
const archivedDir = join(codexDir, 'archived_sessions');
|
|
600
|
+
const archived = (await readdir(archivedDir).catch(() => []))
|
|
601
|
+
.filter(isRolloutFileName)
|
|
602
|
+
.map(f => ({ file: f, path: join(archivedDir, f) }));
|
|
603
|
+
// Dedup before the reads so a basename is opened once, and keep the dated
|
|
604
|
+
// pass ahead of the archived one — the same precedence the serial walk had.
|
|
605
|
+
// While Codex compresses a rollout both forms exist briefly; the plain one
|
|
606
|
+
// wins because it may still be growing.
|
|
607
|
+
const candidates = [];
|
|
608
|
+
const all = [...dated, ...archived];
|
|
609
|
+
const plain = new Set(all.filter(e => !e.file.endsWith('.zst')).map(e => e.file));
|
|
610
|
+
for (const entry of all) {
|
|
611
|
+
if (seenBasenames.has(entry.file))
|
|
612
|
+
continue;
|
|
613
|
+
if (entry.file.endsWith('.zst') && plain.has(entry.file.slice(0, -'.zst'.length)))
|
|
614
|
+
continue;
|
|
615
|
+
seenBasenames.add(entry.file);
|
|
616
|
+
candidates.push(entry);
|
|
617
|
+
}
|
|
618
|
+
const discovered = await mapWithConcurrency(candidates, FS_SCAN_CONCURRENCY, c => discoverSessionFile(c.path));
|
|
619
|
+
for (const source of discovered)
|
|
620
|
+
if (source)
|
|
621
|
+
sources.push(source);
|
|
622
|
+
return sources;
|
|
623
|
+
}
|
|
624
|
+
// The model fields come off an unchecked JSON.parse cast, so a third-party
|
|
625
|
+
// rollout can carry a non-string `model`. It flows straight into calculateCost,
|
|
626
|
+
// which calls `.replace()` on it, so pick the first genuine string and never let
|
|
627
|
+
// a number/object/array through.
|
|
628
|
+
function firstModelString(...values) {
|
|
629
|
+
for (const value of values) {
|
|
630
|
+
if (typeof value === 'string' && value)
|
|
631
|
+
return value;
|
|
632
|
+
}
|
|
633
|
+
return undefined;
|
|
634
|
+
}
|
|
635
|
+
function resolveModel(info, sessionModel) {
|
|
636
|
+
return firstModelString(info?.model, info?.model_name, info?.info?.model, info?.info?.model_name, sessionModel) ?? 'gpt-5';
|
|
637
|
+
}
|
|
638
|
+
function isValidCodexTokenUsage(value) {
|
|
639
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
640
|
+
return false;
|
|
641
|
+
const usage = value;
|
|
642
|
+
const fields = [
|
|
643
|
+
usage['input_tokens'],
|
|
644
|
+
usage['cached_input_tokens'],
|
|
645
|
+
usage['cache_write_input_tokens'],
|
|
646
|
+
usage['output_tokens'],
|
|
647
|
+
usage['reasoning_output_tokens'],
|
|
648
|
+
];
|
|
649
|
+
const hasCounter = fields.some(field => typeof field === 'number' && Number.isFinite(field) && field >= 0);
|
|
650
|
+
return hasCounter && fields.every(field => field === undefined || (typeof field === 'number' && Number.isFinite(field) && field >= 0));
|
|
651
|
+
}
|
|
652
|
+
// The state comes back off our own JSON cache; a truncated or hand-edited file
|
|
653
|
+
// must fall back to a full re-parse rather than decode against nonsense.
|
|
654
|
+
function isResumeState(value) {
|
|
655
|
+
if (!value || typeof value !== 'object')
|
|
656
|
+
return false;
|
|
657
|
+
const v = value;
|
|
658
|
+
const pendingTools = v['pendingTools'];
|
|
659
|
+
const pendingToolSequence = v['pendingToolSequence'];
|
|
660
|
+
const pendingNativeToolEvents = v['pendingNativeToolEvents'];
|
|
661
|
+
const nativeToolEventIdentities = v['nativeToolEventIdentities'];
|
|
662
|
+
const validPendingNativeToolEvents = pendingNativeToolEvents === undefined || (Array.isArray(pendingNativeToolEvents)
|
|
663
|
+
&& Array.isArray(pendingTools)
|
|
664
|
+
&& Array.isArray(pendingToolSequence)
|
|
665
|
+
&& pendingNativeToolEvents.every(event => {
|
|
666
|
+
if (!event || typeof event !== 'object')
|
|
667
|
+
return false;
|
|
668
|
+
const item = event;
|
|
669
|
+
const toolIndex = item['toolIndex'];
|
|
670
|
+
const sequenceIndex = item['sequenceIndex'];
|
|
671
|
+
return (item['tool'] === 'WebSearch' || item['tool'] === 'ToolSearch' || item['tool'] === 'ImageGeneration')
|
|
672
|
+
&& typeof toolIndex === 'number'
|
|
673
|
+
&& Number.isInteger(toolIndex)
|
|
674
|
+
&& toolIndex >= 0
|
|
675
|
+
&& toolIndex < pendingTools.length
|
|
676
|
+
&& pendingTools[toolIndex] === item['tool']
|
|
677
|
+
&& typeof sequenceIndex === 'number'
|
|
678
|
+
&& Number.isInteger(sequenceIndex)
|
|
679
|
+
&& sequenceIndex >= 0
|
|
680
|
+
&& sequenceIndex < pendingToolSequence.length
|
|
681
|
+
&& Array.isArray(pendingToolSequence[sequenceIndex]);
|
|
682
|
+
}));
|
|
683
|
+
return typeof v['sessionId'] === 'string'
|
|
684
|
+
&& (v['threadId'] === undefined || typeof v['threadId'] === 'string')
|
|
685
|
+
&& typeof v['forkedFromId'] === 'string'
|
|
686
|
+
&& (v['forkReplayState'] === undefined || isCodexForkReplayState(v['forkReplayState']))
|
|
687
|
+
&& (v['prevCumulativeTotal'] === null || typeof v['prevCumulativeTotal'] === 'number')
|
|
688
|
+
&& (v['restartEpoch'] === undefined || typeof v['restartEpoch'] === 'number')
|
|
689
|
+
&& (v['prevInfoIdentity'] === undefined || v['prevInfoIdentity'] === null || typeof v['prevInfoIdentity'] === 'string')
|
|
690
|
+
&& (v['hasTokenUsageRecord'] === undefined || typeof v['hasTokenUsageRecord'] === 'boolean')
|
|
691
|
+
&& (v['serviceTier'] === undefined || typeof v['serviceTier'] === 'string')
|
|
692
|
+
&& typeof v['prevInput'] === 'number'
|
|
693
|
+
&& typeof v['prevCached'] === 'number'
|
|
694
|
+
&& typeof v['prevCacheWrite'] === 'number'
|
|
695
|
+
&& typeof v['prevOutput'] === 'number'
|
|
696
|
+
&& typeof v['prevReasoning'] === 'number'
|
|
697
|
+
&& Array.isArray(pendingTools)
|
|
698
|
+
&& Array.isArray(pendingToolSequence)
|
|
699
|
+
&& validPendingNativeToolEvents
|
|
700
|
+
&& (nativeToolEventIdentities === undefined || (Array.isArray(nativeToolEventIdentities) && nativeToolEventIdentities.every(id => typeof id === 'string')))
|
|
701
|
+
&& typeof v['pendingUserMessage'] === 'string'
|
|
702
|
+
&& typeof v['pendingOutputChars'] === 'number'
|
|
703
|
+
&& typeof v['pendingLocAdded'] === 'number'
|
|
704
|
+
&& typeof v['pendingLocRemoved'] === 'number'
|
|
705
|
+
&& typeof v['pendingEditFailed'] === 'number'
|
|
706
|
+
&& typeof v['estCounter'] === 'number'
|
|
707
|
+
&& typeof v['turnCounter'] === 'number'
|
|
708
|
+
&& typeof v['currentTurnId'] === 'string';
|
|
709
|
+
}
|
|
710
|
+
// When `capture` is passed the parse is a whole-file decode that never touches
|
|
711
|
+
// the codex cache: no hit lookup (so no resume), and the entry it would have
|
|
712
|
+
// written comes back through `capture` for the caller to install. That is what
|
|
713
|
+
// lets a worker thread run this exact decode without owning the cache module's
|
|
714
|
+
// per-directory state.
|
|
715
|
+
function createParser(source, seenKeys, capture) {
|
|
716
|
+
return {
|
|
717
|
+
async *parse() {
|
|
718
|
+
const hit = capture ? null : await readCachedCodexResults(source.path);
|
|
719
|
+
if (hit?.kind === 'exact') {
|
|
720
|
+
for (const call of hit.calls) {
|
|
721
|
+
if (seenKeys.has(call.deduplicationKey))
|
|
722
|
+
continue;
|
|
723
|
+
seenKeys.add(call.deduplicationKey);
|
|
724
|
+
yield call;
|
|
725
|
+
}
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
const resume = hit && isResumeState(hit.state)
|
|
729
|
+
? { offset: hit.offset, state: hit.state, calls: hit.calls.slice(0, hit.callCount) }
|
|
730
|
+
: null;
|
|
731
|
+
const fp = await fingerprintFile(source.path);
|
|
732
|
+
if (!fp)
|
|
733
|
+
return;
|
|
734
|
+
let sessionModel = resume?.state.sessionModel;
|
|
735
|
+
let sessionId = resume?.state.sessionId ?? '';
|
|
736
|
+
let threadId = resume?.state.threadId ?? sessionId;
|
|
737
|
+
let sessionCwd = resume?.state.sessionCwd;
|
|
738
|
+
let forkedFromId = resume?.state.forkedFromId ?? '';
|
|
739
|
+
let forkReplayState = resume?.state.forkReplayState ? { ...resume.state.forkReplayState } : undefined;
|
|
740
|
+
// What the parent rollout recorded before the fork. Usage records use
|
|
741
|
+
// their conservative replay anchor; native items use exact ID membership.
|
|
742
|
+
// Loaded on the first relevant record; null drops the whole replay burst.
|
|
743
|
+
let parentReplay;
|
|
744
|
+
let parentNativeReplay;
|
|
745
|
+
let parentReplayAnchored = false;
|
|
746
|
+
const loadParentReplay = async () => {
|
|
747
|
+
if (parentReplay !== undefined)
|
|
748
|
+
return;
|
|
749
|
+
const index = forkedFromId && forkReplayState
|
|
750
|
+
? await loadCodexParentReplayIndex(source.path, forkedFromId, forkReplayState.startedAtMs)
|
|
751
|
+
: null;
|
|
752
|
+
parentReplay = index?.usageIdentities.size ? index.usageIdentities : null;
|
|
753
|
+
parentNativeReplay = index?.nativeIdentities ?? null;
|
|
754
|
+
};
|
|
755
|
+
const isParentReplay = async (identity) => {
|
|
756
|
+
await loadParentReplay();
|
|
757
|
+
if (!parentReplay || identity === undefined)
|
|
758
|
+
return true;
|
|
759
|
+
if (parentReplay.has(identity)) {
|
|
760
|
+
parentReplayAnchored = true;
|
|
761
|
+
return true;
|
|
762
|
+
}
|
|
763
|
+
// A burst that opens with a record the parent lacks was not copied from
|
|
764
|
+
// this parent file; fall back to dropping the burst.
|
|
765
|
+
if (!parentReplayAnchored) {
|
|
766
|
+
parentReplay = null;
|
|
767
|
+
return true;
|
|
768
|
+
}
|
|
769
|
+
return false;
|
|
770
|
+
};
|
|
771
|
+
const isParentNativeReplay = async (identity) => {
|
|
772
|
+
await loadParentReplay();
|
|
773
|
+
// Without a readable parent set or a stable item ID, retain the old
|
|
774
|
+
// burst suppression. A loaded set makes membership an exact decision,
|
|
775
|
+
// independent of whether a token record has anchored the fork yet.
|
|
776
|
+
return !parentNativeReplay || identity === undefined || parentNativeReplay.has(identity);
|
|
777
|
+
};
|
|
778
|
+
// Null sentinel rather than `0` so the FIRST event is never confused
|
|
779
|
+
// with a duplicate. A session that only emits last_token_usage (no
|
|
780
|
+
// total_token_usage) reports cumulativeTotal=0 on every event; with a
|
|
781
|
+
// 0-initialized prev, the first event would have matched and been
|
|
782
|
+
// dropped. Once we've observed any event, we record its cumulative
|
|
783
|
+
// total and dedup on equality regardless of whether it is zero.
|
|
784
|
+
let prevCumulativeTotal = resume?.state.prevCumulativeTotal ?? null;
|
|
785
|
+
let prevInfoIdentity = resume?.state.prevInfoIdentity ?? null;
|
|
786
|
+
let restartEpoch = resume?.state.restartEpoch ?? 0;
|
|
787
|
+
let hasTokenUsageRecord = resume?.state.hasTokenUsageRecord ?? false;
|
|
788
|
+
// #1616: the service tier `thread_settings_applied` last set. Everything
|
|
789
|
+
// the loop reads from a PRIOR line must ride CodexResumeState, and this
|
|
790
|
+
// one can change mid-file, so a resume that starts after the change must
|
|
791
|
+
// not fall back to standard.
|
|
792
|
+
let serviceTier = resume?.state.serviceTier ?? 'default';
|
|
793
|
+
let prevInput = resume?.state.prevInput ?? 0;
|
|
794
|
+
let prevCached = resume?.state.prevCached ?? 0;
|
|
795
|
+
let prevCacheWrite = resume?.state.prevCacheWrite ?? 0;
|
|
796
|
+
let prevOutput = resume?.state.prevOutput ?? 0;
|
|
797
|
+
let prevReasoning = resume?.state.prevReasoning ?? 0;
|
|
798
|
+
let pendingTools = resume ? [...resume.state.pendingTools] : [];
|
|
799
|
+
let pendingToolSequence = resume ? [...resume.state.pendingToolSequence] : [];
|
|
800
|
+
let pendingNativeToolEvents = resume?.state.pendingNativeToolEvents
|
|
801
|
+
? resume.state.pendingNativeToolEvents.map(event => ({ ...event }))
|
|
802
|
+
: [];
|
|
803
|
+
const nativeToolEventIdentities = new Set(resume?.state.nativeToolEventIdentities ?? []);
|
|
804
|
+
let afterSearchItem = false;
|
|
805
|
+
let pendingSkills = resume?.state.pendingSkills ? [...resume.state.pendingSkills] : [];
|
|
806
|
+
// Attribution names already emitted from a `response_item` tool call.
|
|
807
|
+
// Codex's item model repeats a finished shell command as
|
|
808
|
+
// `item_completed`/`CommandExecution`; a rollout that carries BOTH shapes
|
|
809
|
+
// must attribute the call once, and one that carries ONLY the item must
|
|
810
|
+
// still attribute it. Counting per derived name (not per command text,
|
|
811
|
+
// which the two shapes spell differently - argv array vs plain string)
|
|
812
|
+
// makes repeats of the same call line up one-for-one. The response item is
|
|
813
|
+
// always written first (the model requests the call, the item completes
|
|
814
|
+
// it), so the item side only ever cancels an attribution, never adds a
|
|
815
|
+
// duplicate.
|
|
816
|
+
const itemDedup = new Map();
|
|
817
|
+
/// The single classification pipeline every Codex shell-command shape
|
|
818
|
+
/// feeds (#478): `function_call` arguments, the `exec` custom tool's JS
|
|
819
|
+
/// `input`, and the item model's `CommandExecution` item. It adds MCP and
|
|
820
|
+
/// Skill attribution only - the exec itself is counted as Bash by its
|
|
821
|
+
/// response item, and `viaItem` calls never add a tool of their own, so
|
|
822
|
+
/// call/token/cost totals cannot move.
|
|
823
|
+
const attributeShellCommand = (text, viaItem) => {
|
|
824
|
+
if (!text)
|
|
825
|
+
return;
|
|
826
|
+
const claim = (name) => {
|
|
827
|
+
const pending = itemDedup.get(name) ?? 0;
|
|
828
|
+
if (!viaItem) {
|
|
829
|
+
itemDedup.set(name, pending + 1);
|
|
830
|
+
return true;
|
|
831
|
+
}
|
|
832
|
+
if (pending === 0)
|
|
833
|
+
return true;
|
|
834
|
+
itemDedup.set(name, pending - 1);
|
|
835
|
+
return false;
|
|
836
|
+
};
|
|
837
|
+
const mcpTool = mcpToolFromShellCommand(text);
|
|
838
|
+
if (mcpTool && claim(mcpTool)) {
|
|
839
|
+
pendingTools.push(mcpTool);
|
|
840
|
+
pendingToolSequence.push([{ tool: mcpTool }]);
|
|
841
|
+
}
|
|
842
|
+
const skill = skillFromShellCommand(text);
|
|
843
|
+
if (skill && claim(`skill:${skill}`)) {
|
|
844
|
+
pendingSkills.push(skill);
|
|
845
|
+
pendingTools.push('Skill');
|
|
846
|
+
pendingToolSequence.push([{ tool: 'Skill', file: skill }]);
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
const attributeNativeToolEvent = (event) => {
|
|
850
|
+
if (event.identity && nativeToolEventIdentities.has(event.identity))
|
|
851
|
+
return;
|
|
852
|
+
if (event.identity)
|
|
853
|
+
nativeToolEventIdentities.add(event.identity);
|
|
854
|
+
const toolIndex = pendingTools.length;
|
|
855
|
+
const sequenceIndex = pendingToolSequence.length;
|
|
856
|
+
pendingTools.push(event.tool);
|
|
857
|
+
pendingToolSequence.push([{ tool: event.tool }]);
|
|
858
|
+
pendingNativeToolEvents.push({ tool: event.tool, toolIndex, sequenceIndex });
|
|
859
|
+
};
|
|
860
|
+
let pendingUserMessage = resume?.state.pendingUserMessage ?? '';
|
|
861
|
+
let pendingOutputChars = resume?.state.pendingOutputChars ?? 0;
|
|
862
|
+
// Rich-session-capture: edit LOC deltas and failed-patch count accumulated
|
|
863
|
+
// across a turn's patch_apply_end events, flushed onto the turn's call.
|
|
864
|
+
let pendingLocAdded = resume?.state.pendingLocAdded ?? 0;
|
|
865
|
+
let pendingLocRemoved = resume?.state.pendingLocRemoved ?? 0;
|
|
866
|
+
let pendingEditFailed = resume?.state.pendingEditFailed ?? 0;
|
|
867
|
+
let estCounter = resume?.state.estCounter ?? 0;
|
|
868
|
+
let turnCounter = resume?.state.turnCounter ?? 0;
|
|
869
|
+
let currentTurnId = resume?.state.currentTurnId ?? `${sessionId}:t0`;
|
|
870
|
+
let sawAnyLine = false;
|
|
871
|
+
const results = [];
|
|
872
|
+
// Calls already decoded before the resume boundary. They pass through the
|
|
873
|
+
// same cross-provider dedup a full decode would have applied to them.
|
|
874
|
+
if (resume) {
|
|
875
|
+
for (const call of resume.calls) {
|
|
876
|
+
if (seenKeys.has(call.deduplicationKey))
|
|
877
|
+
continue;
|
|
878
|
+
seenKeys.add(call.deduplicationKey);
|
|
879
|
+
results.push(call);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
// Calls decoded since the last task_started, held back so task_complete can
|
|
883
|
+
// stamp active/toolWait timing before they are appended to results. Emitting
|
|
884
|
+
// a task only once its timing is known keeps single-pass and split/resume
|
|
885
|
+
// decodes in agreement instead of back-patching already-emitted calls.
|
|
886
|
+
// Bounded by one task's calls; flushed at the next task_started and at EOF.
|
|
887
|
+
let pendingTaskCalls = [];
|
|
888
|
+
// Null-info ping estimates. Measured usage later in the same turn and
|
|
889
|
+
// task replaces all of them, so the turn is measured calls only.
|
|
890
|
+
let pingEstimates = [];
|
|
891
|
+
let taskGeneratedTokens = 0;
|
|
892
|
+
let taskToolIntervals = [];
|
|
893
|
+
let taskStartedAt = resume?.state.taskStartedAt;
|
|
894
|
+
let taskActiveStartedAt = resume?.state.taskActiveStartedAt;
|
|
895
|
+
const openToolStarts = new Map();
|
|
896
|
+
// Tool items can be serialized after their response's usage record. Keep
|
|
897
|
+
// normal forward attribution as the first choice, but attach any still
|
|
898
|
+
// pending native items to the last call in this task before it is flushed.
|
|
899
|
+
// The parallel indexes let this move just the native items without
|
|
900
|
+
// disturbing other pending tool attribution across a resume boundary.
|
|
901
|
+
const attachPendingNativeToolEvents = (target) => {
|
|
902
|
+
if (!target || pendingNativeToolEvents.length === 0)
|
|
903
|
+
return;
|
|
904
|
+
const ordered = [...pendingNativeToolEvents].sort((a, b) => a.sequenceIndex - b.sequenceIndex);
|
|
905
|
+
target.tools.push(...ordered.map(event => event.tool));
|
|
906
|
+
target.toolSequence = [
|
|
907
|
+
...(target.toolSequence ?? []),
|
|
908
|
+
...ordered.map(event => [{ tool: event.tool }]),
|
|
909
|
+
];
|
|
910
|
+
for (const event of [...pendingNativeToolEvents].sort((a, b) => b.toolIndex - a.toolIndex)) {
|
|
911
|
+
pendingTools.splice(event.toolIndex, 1);
|
|
912
|
+
}
|
|
913
|
+
for (const event of [...pendingNativeToolEvents].sort((a, b) => b.sequenceIndex - a.sequenceIndex)) {
|
|
914
|
+
pendingToolSequence.splice(event.sequenceIndex, 1);
|
|
915
|
+
}
|
|
916
|
+
pendingNativeToolEvents = [];
|
|
917
|
+
};
|
|
918
|
+
const accountUsage = (entry, usage, dedupKey) => {
|
|
919
|
+
const inputTokens = usage.input_tokens ?? 0;
|
|
920
|
+
const cachedInputTokens = usage.cached_input_tokens ?? 0;
|
|
921
|
+
const cacheWriteTokens = usage.cache_write_input_tokens ?? 0;
|
|
922
|
+
const outputTokens = usage.output_tokens ?? 0;
|
|
923
|
+
const reasoningTokens = usage.reasoning_output_tokens ?? 0;
|
|
924
|
+
const totalTokens = inputTokens + cachedInputTokens + outputTokens + reasoningTokens;
|
|
925
|
+
if (totalTokens === 0)
|
|
926
|
+
return;
|
|
927
|
+
const ests = pingEstimates.filter(est => est.turnId === currentTurnId && pendingTaskCalls.includes(est));
|
|
928
|
+
pingEstimates = [];
|
|
929
|
+
if (ests.length > 0) {
|
|
930
|
+
pendingTaskCalls = pendingTaskCalls.filter(call => !ests.includes(call));
|
|
931
|
+
for (const est of ests)
|
|
932
|
+
taskGeneratedTokens -= est.outputTokens;
|
|
933
|
+
pendingTools = [...ests.flatMap(est => est.tools), ...pendingTools];
|
|
934
|
+
pendingToolSequence = [...ests.flatMap(est => est.toolSequence ?? []), ...pendingToolSequence];
|
|
935
|
+
pendingSkills = [...ests.flatMap(est => est.skills ?? []), ...pendingSkills];
|
|
936
|
+
pendingUserMessage = ests.find(est => est.userMessage)?.userMessage || pendingUserMessage;
|
|
937
|
+
for (const est of ests) {
|
|
938
|
+
pendingLocAdded += est.locAdded ?? 0;
|
|
939
|
+
pendingLocRemoved += est.locRemoved ?? 0;
|
|
940
|
+
pendingEditFailed += est.editFailed ?? 0;
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
if (seenKeys.has(dedupKey))
|
|
944
|
+
return;
|
|
945
|
+
// OpenAI includes cached tokens inside input_tokens; Anthropic does not.
|
|
946
|
+
// Normalize to Anthropic semantics: inputTokens = non-cached only.
|
|
947
|
+
const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens);
|
|
948
|
+
// Cache writes are carved out of the uncached input, never added to
|
|
949
|
+
// it: clamp so a malformed or lagging count can never drive the plain
|
|
950
|
+
// input bucket negative.
|
|
951
|
+
const cacheWriteInputTokens = Math.max(0, Math.min(cacheWriteTokens, uncachedInputTokens));
|
|
952
|
+
const model = resolveModel(entry.payload, sessionModel);
|
|
953
|
+
const timestamp = entry.timestamp ?? '';
|
|
954
|
+
const pricingModel = pricingModelAt(model, timestamp);
|
|
955
|
+
// Only move tokens into the cache-write bucket when the pricing
|
|
956
|
+
// source publishes a real cache-write rate for this model (gpt-5.6+)
|
|
957
|
+
// charges 1.25x input; otherwise don't invent an unbilled surcharge.
|
|
958
|
+
const billedCacheWriteTokens = cacheWriteInputTokens > 0 && getModelCosts(pricingModel)?.cacheWriteCostIsExplicit
|
|
959
|
+
? cacheWriteInputTokens
|
|
960
|
+
: 0;
|
|
961
|
+
const billedInputTokens = uncachedInputTokens - billedCacheWriteTokens;
|
|
962
|
+
seenKeys.add(dedupKey);
|
|
963
|
+
// Reasoning tokens are already inside output_tokens, so they are NOT
|
|
964
|
+
// added here. The cache-rehydration twin of this line lives in
|
|
965
|
+
// src/parser.ts (cachedCallToApiCall); both call billableOutputTokens
|
|
966
|
+
// so a fresh parse and a cache read can never price differently.
|
|
967
|
+
// #1616: a turn running under the priority service tier (Codex's Fast
|
|
968
|
+
// speed setting) bills at the priority rates via the fast multiplier.
|
|
969
|
+
const speed = speedForServiceTier(serviceTier);
|
|
970
|
+
const costUSD = calculateCost(pricingModel, billedInputTokens, billableOutputTokens('codex', outputTokens, reasoningTokens), billedCacheWriteTokens, cachedInputTokens, 0, speed, 0, 'codex');
|
|
971
|
+
pendingTaskCalls.push({
|
|
972
|
+
provider: 'codex',
|
|
973
|
+
model,
|
|
974
|
+
inputTokens: billedInputTokens,
|
|
975
|
+
outputTokens,
|
|
976
|
+
cacheCreationInputTokens: billedCacheWriteTokens,
|
|
977
|
+
cacheReadInputTokens: cachedInputTokens,
|
|
978
|
+
cachedInputTokens,
|
|
979
|
+
reasoningTokens,
|
|
980
|
+
webSearchRequests: 0,
|
|
981
|
+
costUSD,
|
|
982
|
+
tools: pendingTools,
|
|
983
|
+
bashCommands: [],
|
|
984
|
+
timestamp,
|
|
985
|
+
speed,
|
|
986
|
+
deduplicationKey: dedupKey,
|
|
987
|
+
turnId: currentTurnId,
|
|
988
|
+
toolSequence: pendingToolSequence.length > 0 ? pendingToolSequence : undefined,
|
|
989
|
+
...(pendingSkills.length > 0 ? { skills: pendingSkills } : {}),
|
|
990
|
+
userMessage: pendingUserMessage,
|
|
991
|
+
sessionId,
|
|
992
|
+
...(sessionCwd ? { projectPath: sessionCwd, workingDirectory: sessionCwd } : {}),
|
|
993
|
+
...(pendingLocAdded ? { locAdded: pendingLocAdded } : {}),
|
|
994
|
+
...(pendingLocRemoved ? { locRemoved: pendingLocRemoved } : {}),
|
|
995
|
+
...(pendingEditFailed ? { editFailed: pendingEditFailed } : {}),
|
|
996
|
+
...(model.toLowerCase() === 'gpt-reserve' ? { costIsEstimated: true } : {}),
|
|
997
|
+
});
|
|
998
|
+
taskGeneratedTokens += billableOutputTokens('codex', outputTokens, reasoningTokens);
|
|
999
|
+
pendingTools = [];
|
|
1000
|
+
pendingToolSequence = [];
|
|
1001
|
+
pendingNativeToolEvents = [];
|
|
1002
|
+
pendingSkills = [];
|
|
1003
|
+
pendingUserMessage = '';
|
|
1004
|
+
pendingOutputChars = 0;
|
|
1005
|
+
pendingLocAdded = 0;
|
|
1006
|
+
pendingLocRemoved = 0;
|
|
1007
|
+
pendingEditFailed = 0;
|
|
1008
|
+
};
|
|
1009
|
+
// Resume point for the NEXT run, refreshed at every task boundary.
|
|
1010
|
+
const tracker = { lastCompleteLineOffset: resume?.offset ?? 0 };
|
|
1011
|
+
let resumeOffset = resume?.offset ?? 0;
|
|
1012
|
+
let resumeState = resume?.state ?? null;
|
|
1013
|
+
let resumeCallCount = results.length;
|
|
1014
|
+
// Stream the session file line by line. Heavy Codex sessions can exceed
|
|
1015
|
+
// 250 MB on disk; reading the entire file into a string would either hit
|
|
1016
|
+
// the readSessionFile cap or push V8 toward its 512 MB string limit
|
|
1017
|
+
// after split('\n'). readSessionLines streams raw buffers and hands
|
|
1018
|
+
// huge lines to the compact parser without full string conversion.
|
|
1019
|
+
for await (const rawLine of readSessionLines(source.path, undefined, {
|
|
1020
|
+
largeLineAsBuffer: true,
|
|
1021
|
+
byteOffsetTracker: tracker,
|
|
1022
|
+
...(resume ? { startByteOffset: resume.offset } : {}),
|
|
1023
|
+
})) {
|
|
1024
|
+
sawAnyLine = true;
|
|
1025
|
+
const entry = parseCodexLine(rawLine);
|
|
1026
|
+
if (!entry)
|
|
1027
|
+
continue;
|
|
1028
|
+
if (entry.type === 'session_meta') {
|
|
1029
|
+
sessionId = entry.payload?.session_id ?? rolloutStem(basename(source.path));
|
|
1030
|
+
// `id` is the thread UUID a fork names in `forked_from_id` (older
|
|
1031
|
+
// rollouts carry only `id`). Dedup keys use it so a fork's replayed
|
|
1032
|
+
// history collides with the parent's own records.
|
|
1033
|
+
threadId = entry.payload?.id ?? entry.payload?.session_id ?? sessionId;
|
|
1034
|
+
// Guarded for the same reason as discoverSessionFile: parseCodexLine
|
|
1035
|
+
// hands back an unchecked JSON.parse cast, and a non-string cwd would
|
|
1036
|
+
// ride into projectPath/workingDirectory where the parser's path
|
|
1037
|
+
// helpers (normalizeProjectPathKey, resolveCanonicalProjectPath) call
|
|
1038
|
+
// string methods on it.
|
|
1039
|
+
const rawSessionCwd = entry.payload?.cwd;
|
|
1040
|
+
if (typeof rawSessionCwd === 'string' && rawSessionCwd)
|
|
1041
|
+
sessionCwd = rawSessionCwd;
|
|
1042
|
+
// Small lines arrive fully parsed (nested `source`), oversized ones
|
|
1043
|
+
// through the compact head decoder (flattened `parent_thread_id`).
|
|
1044
|
+
forkedFromId = entry.payload?.forked_from_id
|
|
1045
|
+
|| entry.payload?.parent_thread_id
|
|
1046
|
+
|| entry.payload?.source?.subagent?.thread_spawn?.parent_thread_id
|
|
1047
|
+
|| '';
|
|
1048
|
+
parentReplay = undefined;
|
|
1049
|
+
parentNativeReplay = undefined;
|
|
1050
|
+
parentReplayAnchored = false;
|
|
1051
|
+
if (forkedFromId) {
|
|
1052
|
+
forkReplayState = startCodexForkReplay(entry.timestamp);
|
|
1053
|
+
// Byte identity only collapses consecutive records inside one
|
|
1054
|
+
// stream. A fork's first real no-cumulative request may have the
|
|
1055
|
+
// same token breakdown as its last copied parent request.
|
|
1056
|
+
prevInfoIdentity = null;
|
|
1057
|
+
}
|
|
1058
|
+
if (typeof entry.payload?.model === 'string')
|
|
1059
|
+
sessionModel = entry.payload.model;
|
|
1060
|
+
continue;
|
|
1061
|
+
}
|
|
1062
|
+
// #1088 BUG-1: the first request-context event since task_started marks
|
|
1063
|
+
// where model-request assembly actually began. Checked before any of
|
|
1064
|
+
// these types `continue` below, and unconditionally (like turn_context's
|
|
1065
|
+
// model capture above) so a forked replay's own request-context events
|
|
1066
|
+
// still mark it before the replay-specific task, tool, message, and usage
|
|
1067
|
+
// records are skipped.
|
|
1068
|
+
if (taskActiveStartedAt === undefined && (entry.type === 'turn_context'
|
|
1069
|
+
|| entry.type === 'world_state'
|
|
1070
|
+
|| (entry.type === 'event_msg' && entry.payload?.type === 'user_message')
|
|
1071
|
+
|| (entry.type === 'response_item' && entry.payload?.type === 'message'))) {
|
|
1072
|
+
const ctxAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN;
|
|
1073
|
+
if (Number.isFinite(ctxAt))
|
|
1074
|
+
taskActiveStartedAt = ctxAt;
|
|
1075
|
+
}
|
|
1076
|
+
const isForkReplay = isCodexForkReplay(forkReplayState, entry.timestamp);
|
|
1077
|
+
const nativeEvent = nativeToolEvent(entry);
|
|
1078
|
+
// Codex builds of May 2026 follow each item_completed WebSearch with an
|
|
1079
|
+
// id-less web_search_call repeating its action: the same search.
|
|
1080
|
+
const searchMirror = afterSearchItem && entry.type === 'response_item' && nativeEvent?.tool === 'WebSearch' && !nativeEvent.identity;
|
|
1081
|
+
afterSearchItem = entry.type === 'event_msg' && nativeEvent?.tool === 'WebSearch';
|
|
1082
|
+
if (searchMirror)
|
|
1083
|
+
continue;
|
|
1084
|
+
if (nativeEvent && isForkReplay && await isParentNativeReplay(nativeEvent.identity))
|
|
1085
|
+
continue;
|
|
1086
|
+
if (entry.type === 'turn_context' && typeof entry.payload?.model === 'string') {
|
|
1087
|
+
sessionModel = entry.payload.model;
|
|
1088
|
+
continue;
|
|
1089
|
+
}
|
|
1090
|
+
// #1616: Codex's Fast speed setting bills through OpenAI's priority
|
|
1091
|
+
// service tier, which the rollout records per THREAD SETTINGS change
|
|
1092
|
+
// (event_msg/thread_settings_applied), never per call. The setting
|
|
1093
|
+
// covers every turn after it in file order, so track the latest value;
|
|
1094
|
+
// a settings event with no `service_tier` (older builds never wrote
|
|
1095
|
+
// one) reads as the default tier. Deliberately NOT skipped during a
|
|
1096
|
+
// fork replay: the replayed parent events carry the setting the fork
|
|
1097
|
+
// inherited, so tracking them keeps the fork's first own turn on the
|
|
1098
|
+
// parent's tier.
|
|
1099
|
+
if (entry.type === 'event_msg' && entry.payload?.type === 'thread_settings_applied') {
|
|
1100
|
+
serviceTier = entry.payload.serviceTier ?? 'default';
|
|
1101
|
+
continue;
|
|
1102
|
+
}
|
|
1103
|
+
if (isForkReplay && (entry.payload?.type === 'task_started' ||
|
|
1104
|
+
entry.payload?.type === 'task_complete' ||
|
|
1105
|
+
entry.payload?.type === 'function_call' ||
|
|
1106
|
+
entry.payload?.type === 'function_call_output' ||
|
|
1107
|
+
entry.payload?.type === 'custom_tool_call' ||
|
|
1108
|
+
entry.payload?.type === 'custom_tool_call_output' ||
|
|
1109
|
+
entry.payload?.type === 'mcp_tool_call_end' ||
|
|
1110
|
+
(entry.payload?.type === 'item_completed' && !nativeEvent) ||
|
|
1111
|
+
entry.payload?.type === 'patch_apply_end'))
|
|
1112
|
+
continue;
|
|
1113
|
+
if (isForkReplay && entry.type === 'response_item' && entry.payload?.type === 'message')
|
|
1114
|
+
continue;
|
|
1115
|
+
if (isForkReplay && entry.type === 'event_msg' && entry.payload?.type === 'token_count'
|
|
1116
|
+
&& await isParentReplay(entry.payload.info ? codexReplayUsageIdentity(entry.payload.info) : undefined)) {
|
|
1117
|
+
const info = entry.payload.info;
|
|
1118
|
+
if (info) {
|
|
1119
|
+
const total = info.total_token_usage;
|
|
1120
|
+
const reportsCumulative = typeof total?.total_tokens === 'number'
|
|
1121
|
+
&& Number.isFinite(total.total_tokens)
|
|
1122
|
+
&& total.total_tokens >= 0;
|
|
1123
|
+
if (reportsCumulative)
|
|
1124
|
+
prevInfoIdentity = JSON.stringify(info);
|
|
1125
|
+
if (total) {
|
|
1126
|
+
const cumulativeTotal = total.total_tokens ?? 0;
|
|
1127
|
+
prevCumulativeTotal = reportsCumulative ? cumulativeTotal : null;
|
|
1128
|
+
prevInput = total.input_tokens ?? prevInput;
|
|
1129
|
+
prevCached = total.cached_input_tokens ?? prevCached;
|
|
1130
|
+
prevCacheWrite = total.cache_write_input_tokens ?? prevCacheWrite;
|
|
1131
|
+
prevOutput = total.output_tokens ?? prevOutput;
|
|
1132
|
+
prevReasoning = total.reasoning_output_tokens ?? prevReasoning;
|
|
1133
|
+
}
|
|
1134
|
+
else {
|
|
1135
|
+
prevCumulativeTotal = null;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
// A replay's prompt and response text is historical context. Keep it
|
|
1139
|
+
// out of the fallback character estimate for the first real turn.
|
|
1140
|
+
pendingUserMessage = '';
|
|
1141
|
+
pendingOutputChars = 0;
|
|
1142
|
+
continue;
|
|
1143
|
+
}
|
|
1144
|
+
if (entry.type === 'event_msg' && entry.payload?.type === 'task_started') {
|
|
1145
|
+
// Emit the previous task. If it never reached task_complete its timing
|
|
1146
|
+
// fields simply stay unset, matching the un-buffered behaviour.
|
|
1147
|
+
attachPendingNativeToolEvents(pendingTaskCalls.at(-1));
|
|
1148
|
+
results.push(...pendingTaskCalls);
|
|
1149
|
+
pendingTaskCalls = [];
|
|
1150
|
+
pingEstimates = [];
|
|
1151
|
+
taskGeneratedTokens = 0;
|
|
1152
|
+
taskToolIntervals = [];
|
|
1153
|
+
const startedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN;
|
|
1154
|
+
taskStartedAt = Number.isFinite(startedAt) ? startedAt : undefined;
|
|
1155
|
+
taskActiveStartedAt = undefined;
|
|
1156
|
+
openToolStarts.clear();
|
|
1157
|
+
// Everything decoded so far is now in `results` and the per-task
|
|
1158
|
+
// accumulators are empty: a clean restart point for an appended tail.
|
|
1159
|
+
resumeOffset = tracker.lastCompleteLineOffset;
|
|
1160
|
+
resumeCallCount = results.length;
|
|
1161
|
+
resumeState = {
|
|
1162
|
+
...(sessionModel !== undefined ? { sessionModel } : {}),
|
|
1163
|
+
sessionId,
|
|
1164
|
+
threadId,
|
|
1165
|
+
...(sessionCwd !== undefined ? { sessionCwd } : {}),
|
|
1166
|
+
forkedFromId,
|
|
1167
|
+
...(forkReplayState ? { forkReplayState: { ...forkReplayState } } : {}),
|
|
1168
|
+
prevCumulativeTotal,
|
|
1169
|
+
restartEpoch,
|
|
1170
|
+
prevInfoIdentity,
|
|
1171
|
+
hasTokenUsageRecord,
|
|
1172
|
+
serviceTier,
|
|
1173
|
+
prevInput,
|
|
1174
|
+
prevCached,
|
|
1175
|
+
prevCacheWrite,
|
|
1176
|
+
prevOutput,
|
|
1177
|
+
prevReasoning,
|
|
1178
|
+
pendingTools: [...pendingTools],
|
|
1179
|
+
pendingToolSequence: [...pendingToolSequence],
|
|
1180
|
+
pendingNativeToolEvents: pendingNativeToolEvents.map(event => ({ ...event })),
|
|
1181
|
+
nativeToolEventIdentities: [...nativeToolEventIdentities],
|
|
1182
|
+
pendingSkills: [...pendingSkills],
|
|
1183
|
+
pendingUserMessage,
|
|
1184
|
+
pendingOutputChars,
|
|
1185
|
+
pendingLocAdded,
|
|
1186
|
+
pendingLocRemoved,
|
|
1187
|
+
pendingEditFailed,
|
|
1188
|
+
estCounter,
|
|
1189
|
+
turnCounter,
|
|
1190
|
+
currentTurnId,
|
|
1191
|
+
...(taskStartedAt !== undefined ? { taskStartedAt } : {}),
|
|
1192
|
+
...(taskActiveStartedAt !== undefined ? { taskActiveStartedAt } : {}),
|
|
1193
|
+
};
|
|
1194
|
+
continue;
|
|
1195
|
+
}
|
|
1196
|
+
if (nativeEvent) {
|
|
1197
|
+
// Status transitions share an item identity. The first observed
|
|
1198
|
+
// record proves tool activity even when the rollout ends before its
|
|
1199
|
+
// completed status; mirrors from the item model are ignored by id.
|
|
1200
|
+
attributeNativeToolEvent(nativeEvent);
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
if (entry.type === 'response_item' && (entry.payload?.type === 'function_call' || entry.payload?.type === 'custom_tool_call')) {
|
|
1204
|
+
const rawName = entry.payload.name ?? '';
|
|
1205
|
+
const mapped = ownValue(toolNameMap, rawName) ?? rawName;
|
|
1206
|
+
pendingTools.push(mapped);
|
|
1207
|
+
const call = { tool: mapped };
|
|
1208
|
+
const rawArgs = entry.payload['arguments'];
|
|
1209
|
+
// The model generated this call, so a tool-only turn still has output
|
|
1210
|
+
// for the null-ping estimate.
|
|
1211
|
+
const rawInput = entry.payload['input'];
|
|
1212
|
+
pendingOutputChars += rawName.length
|
|
1213
|
+
+ (typeof rawArgs === 'string' ? rawArgs.length : rawArgs ? JSON.stringify(rawArgs).length : 0)
|
|
1214
|
+
+ (typeof rawInput === 'string' ? rawInput.length : 0);
|
|
1215
|
+
const args = typeof rawArgs === 'string'
|
|
1216
|
+
? (() => { try {
|
|
1217
|
+
return JSON.parse(rawArgs);
|
|
1218
|
+
}
|
|
1219
|
+
catch {
|
|
1220
|
+
return null;
|
|
1221
|
+
} })()
|
|
1222
|
+
: typeof rawArgs === 'object' && rawArgs ? rawArgs : null;
|
|
1223
|
+
if (args) {
|
|
1224
|
+
const fp = args['file_path'] ?? args['path'];
|
|
1225
|
+
if (typeof fp === 'string')
|
|
1226
|
+
call.file = fp;
|
|
1227
|
+
const cmd = args['command'] ?? args['cmd'];
|
|
1228
|
+
if (typeof cmd === 'string')
|
|
1229
|
+
call.command = cmd;
|
|
1230
|
+
attributeShellCommand(shellCommandText(cmd), false);
|
|
1231
|
+
}
|
|
1232
|
+
// A `custom_tool_call` has no `arguments`: the shell tool's payload is
|
|
1233
|
+
// the `input` program that calls `tools.exec_command({cmd: ...})`. The
|
|
1234
|
+
// MCP/skill matchers never saw it, so a CLI-wrapped MCP call or a
|
|
1235
|
+
// SKILL.md read made through Codex's custom-tool transport counted only
|
|
1236
|
+
// as Bash (#478). Restricted to the shell tool: `apply_patch` is a
|
|
1237
|
+
// custom tool too and its `input` is file content, where a documented
|
|
1238
|
+
// command would read as a real invocation. `call.command` is
|
|
1239
|
+
// deliberately NOT set from it either - that field feeds the retry
|
|
1240
|
+
// heuristic's read-shaped-command test, and a JS program is not a
|
|
1241
|
+
// shell command.
|
|
1242
|
+
if (mapped === 'Bash') {
|
|
1243
|
+
const input = entry.payload['input'];
|
|
1244
|
+
if (typeof input === 'string')
|
|
1245
|
+
attributeShellCommand(input, false);
|
|
1246
|
+
}
|
|
1247
|
+
const callId = entry.payload.call_id;
|
|
1248
|
+
const started = entry.timestamp ? Date.parse(entry.timestamp) : NaN;
|
|
1249
|
+
if (callId && Number.isFinite(started))
|
|
1250
|
+
openToolStarts.set(callId, started);
|
|
1251
|
+
pendingToolSequence.push([call]);
|
|
1252
|
+
continue;
|
|
1253
|
+
}
|
|
1254
|
+
if (entry.type === 'response_item' && (entry.payload?.type === 'function_call_output' || entry.payload?.type === 'custom_tool_call_output')) {
|
|
1255
|
+
const callId = entry.payload.call_id;
|
|
1256
|
+
const ended = entry.timestamp ? Date.parse(entry.timestamp) : NaN;
|
|
1257
|
+
const started = callId ? openToolStarts.get(callId) : undefined;
|
|
1258
|
+
if (started !== undefined && Number.isFinite(ended) && ended > started)
|
|
1259
|
+
taskToolIntervals.push([started, ended]);
|
|
1260
|
+
if (callId)
|
|
1261
|
+
openToolStarts.delete(callId);
|
|
1262
|
+
continue;
|
|
1263
|
+
}
|
|
1264
|
+
if (entry.type === 'event_msg' && entry.payload?.type === 'task_complete') {
|
|
1265
|
+
// #1088 BUG-8: task_complete's duration can arrive as {secs,nanos} or
|
|
1266
|
+
// a string too (mcp_tool_call_end already tolerates both, below, via
|
|
1267
|
+
// this same durationValueMs helper); read it the same permissive way
|
|
1268
|
+
// instead of only the plain-number `duration_ms` field.
|
|
1269
|
+
const durationMs = durationValueMs(entry.payload.duration_ms) ?? durationValueMs(entry.payload.duration);
|
|
1270
|
+
if (typeof durationMs === 'number' && durationMs > 0 && taskGeneratedTokens > 0 && pendingTaskCalls.length > 0) {
|
|
1271
|
+
const completedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN;
|
|
1272
|
+
// #1088 BUG-1: Codex fires task_started before it assembles the
|
|
1273
|
+
// request, so the gap up to the first request-context event is
|
|
1274
|
+
// CLI/harness startup, not model wait. The active window starts
|
|
1275
|
+
// there instead of at task_started; task completion (windowEnd,
|
|
1276
|
+
// inside mergeToolIntervals) is unchanged.
|
|
1277
|
+
const activeWindowStart = taskActiveStartedAt ?? taskStartedAt;
|
|
1278
|
+
const startupGapMs = activeWindowStart !== undefined && taskStartedAt !== undefined
|
|
1279
|
+
? activeWindowStart - taskStartedAt
|
|
1280
|
+
: 0;
|
|
1281
|
+
const effectiveDurationMs = Math.max(0, durationMs - startupGapMs);
|
|
1282
|
+
// #1088 BUG-8: shared with codex-throughput.ts's live estimate
|
|
1283
|
+
// instead of a second inline copy of the same clip/merge/cap.
|
|
1284
|
+
const toolWaitMs = mergeToolIntervals(taskToolIntervals, effectiveDurationMs, activeWindowStart, Number.isFinite(completedAt) ? completedAt : undefined);
|
|
1285
|
+
const activeMs = effectiveDurationMs - toolWaitMs;
|
|
1286
|
+
if (activeMs <= 0)
|
|
1287
|
+
continue;
|
|
1288
|
+
for (const call of pendingTaskCalls) {
|
|
1289
|
+
// Reasoning is already inside output_tokens (#1075/#1078); the
|
|
1290
|
+
// throughput numerator must agree with the cost numerator or
|
|
1291
|
+
// Tok/s reads high for reasoning-heavy calls (#1079).
|
|
1292
|
+
const generated = billableOutputTokens('codex', call.outputTokens, call.reasoningTokens);
|
|
1293
|
+
if (generated <= 0)
|
|
1294
|
+
continue;
|
|
1295
|
+
call.activeGeneratedTokens = generated;
|
|
1296
|
+
call.activeDurationMs = activeMs * (generated / taskGeneratedTokens);
|
|
1297
|
+
call.toolWaitMs = toolWaitMs * (generated / taskGeneratedTokens);
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
continue;
|
|
1301
|
+
}
|
|
1302
|
+
if (entry.type === 'event_msg' && entry.payload?.type === 'patch_apply_end') {
|
|
1303
|
+
pendingTools.push('Edit');
|
|
1304
|
+
const p = entry.payload;
|
|
1305
|
+
const changes = p['changes'];
|
|
1306
|
+
const changesObj = typeof changes === 'object' && changes ? changes : {};
|
|
1307
|
+
const filePaths = Object.keys(changesObj);
|
|
1308
|
+
if (filePaths.length > 0) {
|
|
1309
|
+
for (const fp of filePaths) {
|
|
1310
|
+
pendingToolSequence.push([{ tool: 'Edit', file: fp }]);
|
|
1311
|
+
const diff = changesObj[fp]?.['unified_diff'];
|
|
1312
|
+
const loc = countUnifiedDiffLoc(diff);
|
|
1313
|
+
pendingLocAdded += loc.added;
|
|
1314
|
+
pendingLocRemoved += loc.removed;
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
else {
|
|
1318
|
+
pendingToolSequence.push([{ tool: 'Edit' }]);
|
|
1319
|
+
}
|
|
1320
|
+
// Only an explicit failure counts; a missing `success` is treated as ok.
|
|
1321
|
+
if (p['success'] === false)
|
|
1322
|
+
pendingEditFailed++;
|
|
1323
|
+
continue;
|
|
1324
|
+
}
|
|
1325
|
+
// Recent Codex emits MCP calls as `event_msg`/`mcp_tool_call_end`
|
|
1326
|
+
// instead of a `function_call` response_item, so the call was never
|
|
1327
|
+
// attributed. Rebuild the canonical `mcp__<server>__<tool>` name the
|
|
1328
|
+
// classifier recognizes.
|
|
1329
|
+
if (entry.type === 'event_msg' && entry.payload?.type === 'mcp_tool_call_end') {
|
|
1330
|
+
const endedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN;
|
|
1331
|
+
const durationMs = entry.payload.duration_ms ?? durationValueMs(entry.payload.duration);
|
|
1332
|
+
if (typeof durationMs === 'number' && durationMs > 0 && Number.isFinite(endedAt)) {
|
|
1333
|
+
taskToolIntervals.push([endedAt - durationMs, endedAt]);
|
|
1334
|
+
}
|
|
1335
|
+
const inv = entry.payload['invocation'];
|
|
1336
|
+
const server = typeof inv?.['server'] === 'string' ? inv['server'] : '';
|
|
1337
|
+
const tool = typeof inv?.['tool'] === 'string' ? inv['tool'] : '';
|
|
1338
|
+
if (server && tool) {
|
|
1339
|
+
const name = `mcp__${server}__${tool}`;
|
|
1340
|
+
pendingTools.push(name);
|
|
1341
|
+
pendingToolSequence.push([{ tool: name }]);
|
|
1342
|
+
}
|
|
1343
|
+
continue;
|
|
1344
|
+
}
|
|
1345
|
+
// Codex's item model records a finished shell command as
|
|
1346
|
+
// `event_msg`/`item_completed` carrying a `CommandExecution` item whose
|
|
1347
|
+
// `command` is the argv array (`["/bin/zsh","-lc","..."]`) - a shape the
|
|
1348
|
+
// `function_call`-only tool path never reached, so a CLI-wrapped MCP call
|
|
1349
|
+
// or a SKILL.md read made under it stayed invisible (#478). Attribution
|
|
1350
|
+
// only: the exec's own Bash count comes from its response item, exactly
|
|
1351
|
+
// as `exec_command_end` is left alone for the classic transport.
|
|
1352
|
+
if (entry.type === 'event_msg' && entry.payload?.type === 'item_completed') {
|
|
1353
|
+
const item = entry.payload['item'];
|
|
1354
|
+
if (item && item['type'] === 'CommandExecution') {
|
|
1355
|
+
attributeShellCommand(shellCommandText(item['command']), true);
|
|
1356
|
+
}
|
|
1357
|
+
continue;
|
|
1358
|
+
}
|
|
1359
|
+
if (entry.type === 'response_item' && entry.payload?.type === 'message' && entry.payload?.role === 'user') {
|
|
1360
|
+
const texts = normalizeContentBlocks(entry.payload.content)
|
|
1361
|
+
.filter(c => c.type === 'input_text')
|
|
1362
|
+
.map(c => c.text ?? '')
|
|
1363
|
+
.filter(Boolean);
|
|
1364
|
+
if (texts.length > 0) {
|
|
1365
|
+
pendingUserMessage = texts.join(' ').slice(0, 500);
|
|
1366
|
+
currentTurnId = `${sessionId}:t${++turnCounter}`;
|
|
1367
|
+
}
|
|
1368
|
+
continue;
|
|
1369
|
+
}
|
|
1370
|
+
if (entry.type === 'response_item' && entry.payload?.type === 'message' && entry.payload?.role === 'assistant') {
|
|
1371
|
+
const texts = normalizeContentBlocks(entry.payload.content)
|
|
1372
|
+
.filter(c => c.type === 'output_text' || c.type === 'text')
|
|
1373
|
+
.map(c => c.text ?? '');
|
|
1374
|
+
pendingOutputChars += texts.join('').length;
|
|
1375
|
+
continue;
|
|
1376
|
+
}
|
|
1377
|
+
if (entry.type === 'token_usage_record') {
|
|
1378
|
+
// Newer Codex builds write one response-level usage record before its
|
|
1379
|
+
// token_count twin. The record survives compaction and interrupted
|
|
1380
|
+
// turns, so it becomes the source for this rollout once seen.
|
|
1381
|
+
const usage = entry.payload?.usage;
|
|
1382
|
+
if (!isValidCodexTokenUsage(usage))
|
|
1383
|
+
continue;
|
|
1384
|
+
const responseId = entry.payload?.response_id;
|
|
1385
|
+
if (isForkReplay && await isParentReplay(typeof responseId === 'string' && responseId ? codexReplayResponseIdentity(responseId) : undefined))
|
|
1386
|
+
continue;
|
|
1387
|
+
hasTokenUsageRecord = true;
|
|
1388
|
+
const dedupKey = typeof responseId === 'string' && responseId
|
|
1389
|
+
? `codex:${forkedFromId || threadId}:response:${responseId}`
|
|
1390
|
+
: `codex:usage-record:${JSON.stringify([source.path, tracker.lastCompleteLineOffset])}`;
|
|
1391
|
+
accountUsage(entry, usage, dedupKey);
|
|
1392
|
+
continue;
|
|
1393
|
+
}
|
|
1394
|
+
if (entry.type === 'event_msg' && entry.payload?.type === 'token_count') {
|
|
1395
|
+
// Newer rollouts pair each response record with a token_count event.
|
|
1396
|
+
// The response record is authoritative; all subsequent twins and
|
|
1397
|
+
// re-emissions stay out of usage, while pre-handover legacy events
|
|
1398
|
+
// remain counted.
|
|
1399
|
+
if (hasTokenUsageRecord)
|
|
1400
|
+
continue;
|
|
1401
|
+
const info = entry.payload.info;
|
|
1402
|
+
if (!info) {
|
|
1403
|
+
// Codex writes a null-info token_count (a rate-limit snapshot) at
|
|
1404
|
+
// turn start, before any output. That is not a request: leave the
|
|
1405
|
+
// prompt pending for the measured call that follows. A turn that
|
|
1406
|
+
// ends on such a ping with nothing after it priced nothing: no call.
|
|
1407
|
+
// After output, the ping estimates the turn until measured usage
|
|
1408
|
+
// for it arrives (pingEstimates).
|
|
1409
|
+
if (pendingOutputChars === 0)
|
|
1410
|
+
continue;
|
|
1411
|
+
const estInput = estimateTokensFromChars(pendingUserMessage.length);
|
|
1412
|
+
const estOutput = estimateTokensFromChars(pendingOutputChars);
|
|
1413
|
+
if (estInput === 0 && estOutput === 0)
|
|
1414
|
+
continue;
|
|
1415
|
+
const model = sessionModel ?? 'gpt-5';
|
|
1416
|
+
const timestamp = entry.timestamp ?? '';
|
|
1417
|
+
const dedupKey = `codex:${sessionId}:${timestamp}:est${estCounter++}`;
|
|
1418
|
+
if (seenKeys.has(dedupKey)) {
|
|
1419
|
+
pendingTools = [];
|
|
1420
|
+
pendingToolSequence = [];
|
|
1421
|
+
pendingNativeToolEvents = [];
|
|
1422
|
+
pendingSkills = [];
|
|
1423
|
+
pendingUserMessage = '';
|
|
1424
|
+
pendingOutputChars = 0;
|
|
1425
|
+
pendingLocAdded = 0;
|
|
1426
|
+
pendingLocRemoved = 0;
|
|
1427
|
+
pendingEditFailed = 0;
|
|
1428
|
+
continue;
|
|
1429
|
+
}
|
|
1430
|
+
seenKeys.add(dedupKey);
|
|
1431
|
+
// An estimated prompt can cross a long-context threshold and tier
|
|
1432
|
+
// itself; measured corpora hold no estimated calls that cross. The
|
|
1433
|
+
// service tier applies to it exactly as to a measured turn (#1616).
|
|
1434
|
+
const speed = speedForServiceTier(serviceTier);
|
|
1435
|
+
const costUSD = calculateCost(pricingModelAt(model, timestamp), estInput, estOutput, 0, 0, 0, speed, 0, 'codex');
|
|
1436
|
+
pendingTaskCalls.push({
|
|
1437
|
+
provider: 'codex',
|
|
1438
|
+
model,
|
|
1439
|
+
inputTokens: estInput,
|
|
1440
|
+
outputTokens: estOutput,
|
|
1441
|
+
cacheCreationInputTokens: 0,
|
|
1442
|
+
cacheReadInputTokens: 0,
|
|
1443
|
+
cachedInputTokens: 0,
|
|
1444
|
+
reasoningTokens: 0,
|
|
1445
|
+
webSearchRequests: 0,
|
|
1446
|
+
costUSD,
|
|
1447
|
+
costIsEstimated: true,
|
|
1448
|
+
tools: pendingTools,
|
|
1449
|
+
bashCommands: [],
|
|
1450
|
+
timestamp,
|
|
1451
|
+
speed,
|
|
1452
|
+
deduplicationKey: dedupKey,
|
|
1453
|
+
turnId: currentTurnId,
|
|
1454
|
+
toolSequence: pendingToolSequence.length > 0 ? pendingToolSequence : undefined,
|
|
1455
|
+
...(pendingSkills.length > 0 ? { skills: pendingSkills } : {}),
|
|
1456
|
+
userMessage: pendingUserMessage,
|
|
1457
|
+
sessionId,
|
|
1458
|
+
...(sessionCwd ? { projectPath: sessionCwd, workingDirectory: sessionCwd } : {}),
|
|
1459
|
+
...(pendingLocAdded ? { locAdded: pendingLocAdded } : {}),
|
|
1460
|
+
...(pendingLocRemoved ? { locRemoved: pendingLocRemoved } : {}),
|
|
1461
|
+
...(pendingEditFailed ? { editFailed: pendingEditFailed } : {}),
|
|
1462
|
+
});
|
|
1463
|
+
pingEstimates.push(pendingTaskCalls.at(-1));
|
|
1464
|
+
taskGeneratedTokens += estOutput;
|
|
1465
|
+
pendingTools = [];
|
|
1466
|
+
pendingToolSequence = [];
|
|
1467
|
+
pendingNativeToolEvents = [];
|
|
1468
|
+
pendingSkills = [];
|
|
1469
|
+
pendingUserMessage = '';
|
|
1470
|
+
pendingOutputChars = 0;
|
|
1471
|
+
pendingLocAdded = 0;
|
|
1472
|
+
pendingLocRemoved = 0;
|
|
1473
|
+
pendingEditFailed = 0;
|
|
1474
|
+
continue;
|
|
1475
|
+
}
|
|
1476
|
+
const cumulativeTotal = info.total_token_usage?.total_tokens ?? 0;
|
|
1477
|
+
// Missing/null/partial cumulative data is not a repeated zero total.
|
|
1478
|
+
const reportsCumulative = typeof info.total_token_usage?.total_tokens === 'number'
|
|
1479
|
+
&& Number.isFinite(info.total_token_usage.total_tokens)
|
|
1480
|
+
&& info.total_token_usage.total_tokens >= 0;
|
|
1481
|
+
// #257 regression half: a byte-identical consecutive record is a
|
|
1482
|
+
// re-emission of the same token_count event, never a new request.
|
|
1483
|
+
// This collapse applies with or without cumulative totals: measured
|
|
1484
|
+
// on public Codex rollouts (codeset-ai/codeset-release-evals,
|
|
1485
|
+
// 53 sessions / 1313 token_count events), 603 events are
|
|
1486
|
+
// byte-identical repeats of their predecessor, all carrying the
|
|
1487
|
+
// same cumulative snapshot. What the missing-cumulative path must
|
|
1488
|
+
// preserve is records whose payload DIFFERS (distinct requests).
|
|
1489
|
+
const infoIdentity = JSON.stringify(info);
|
|
1490
|
+
if (infoIdentity === prevInfoIdentity)
|
|
1491
|
+
continue;
|
|
1492
|
+
prevInfoIdentity = infoIdentity;
|
|
1493
|
+
if (reportsCumulative && prevCumulativeTotal !== null && cumulativeTotal === prevCumulativeTotal)
|
|
1494
|
+
continue;
|
|
1495
|
+
const prevTotal = prevCumulativeTotal;
|
|
1496
|
+
prevCumulativeTotal = reportsCumulative ? cumulativeTotal : null;
|
|
1497
|
+
const last = info.last_token_usage;
|
|
1498
|
+
let inputTokens = 0;
|
|
1499
|
+
let cachedInputTokens = 0;
|
|
1500
|
+
let cacheWriteTokens = 0;
|
|
1501
|
+
let outputTokens = 0;
|
|
1502
|
+
let reasoningTokens = 0;
|
|
1503
|
+
if (last) {
|
|
1504
|
+
inputTokens = last.input_tokens ?? 0;
|
|
1505
|
+
cachedInputTokens = last.cached_input_tokens ?? 0;
|
|
1506
|
+
cacheWriteTokens = last.cache_write_input_tokens ?? 0;
|
|
1507
|
+
outputTokens = last.output_tokens ?? 0;
|
|
1508
|
+
reasoningTokens = last.reasoning_output_tokens ?? 0;
|
|
1509
|
+
}
|
|
1510
|
+
else if (cumulativeTotal > 0) {
|
|
1511
|
+
const total = info.total_token_usage;
|
|
1512
|
+
if (!total)
|
|
1513
|
+
continue;
|
|
1514
|
+
// A total at most a tenth of the previous one (or, without a
|
|
1515
|
+
// previous total, every reported field at most a tenth) is a restart
|
|
1516
|
+
// (resume, compaction): every counter, reported or not, starts
|
|
1517
|
+
// again from zero. A smaller drop is a correction: a falling field
|
|
1518
|
+
// adds nothing. An omitted field is unchanged.
|
|
1519
|
+
const counters = [
|
|
1520
|
+
[total.input_tokens, prevInput], [total.cached_input_tokens, prevCached],
|
|
1521
|
+
[total.cache_write_input_tokens, prevCacheWrite], [total.output_tokens, prevOutput],
|
|
1522
|
+
[total.reasoning_output_tokens, prevReasoning],
|
|
1523
|
+
];
|
|
1524
|
+
const present = counters.filter(([now]) => now !== undefined);
|
|
1525
|
+
const restart = prevTotal !== null
|
|
1526
|
+
? cumulativeTotal * 10 <= prevTotal
|
|
1527
|
+
: present.length > 0 && present.every(([now, prev]) => now * 10 <= prev);
|
|
1528
|
+
if (restart) {
|
|
1529
|
+
restartEpoch++;
|
|
1530
|
+
prevInput = 0;
|
|
1531
|
+
prevCached = 0;
|
|
1532
|
+
prevCacheWrite = 0;
|
|
1533
|
+
prevOutput = 0;
|
|
1534
|
+
prevReasoning = 0;
|
|
1535
|
+
}
|
|
1536
|
+
const since = (now, prev) => now === undefined ? 0 : Math.max(0, now - prev);
|
|
1537
|
+
inputTokens = since(total.input_tokens, prevInput);
|
|
1538
|
+
cachedInputTokens = since(total.cached_input_tokens, prevCached);
|
|
1539
|
+
cacheWriteTokens = since(total.cache_write_input_tokens, prevCacheWrite);
|
|
1540
|
+
outputTokens = since(total.output_tokens, prevOutput);
|
|
1541
|
+
reasoningTokens = since(total.reasoning_output_tokens, prevReasoning);
|
|
1542
|
+
}
|
|
1543
|
+
// Always advance the prev counters to track the cumulative state.
|
|
1544
|
+
// Previously prev was only updated on the fallback branch, so a
|
|
1545
|
+
// session with mixed last_token_usage / no-last events would
|
|
1546
|
+
// compute the next fallback delta against a stale prev=0 baseline,
|
|
1547
|
+
// double-counting the entire cumulative window. The prev value
|
|
1548
|
+
// must mirror what cumulative reports regardless of whether this
|
|
1549
|
+
// event used `last` or fell back to deltas.
|
|
1550
|
+
const total = info.total_token_usage;
|
|
1551
|
+
if (total) {
|
|
1552
|
+
prevInput = total.input_tokens ?? prevInput;
|
|
1553
|
+
prevCached = total.cached_input_tokens ?? prevCached;
|
|
1554
|
+
prevCacheWrite = total.cache_write_input_tokens ?? prevCacheWrite;
|
|
1555
|
+
prevOutput = total.output_tokens ?? prevOutput;
|
|
1556
|
+
prevReasoning = total.reasoning_output_tokens ?? prevReasoning;
|
|
1557
|
+
}
|
|
1558
|
+
// Forked sessions copy the parent's entire token_count history
|
|
1559
|
+
// (re-timestamped), so replays must collide with the parent's events
|
|
1560
|
+
// and drop to avoid double-counting -- hence the parent namespace
|
|
1561
|
+
// (forkedFromId) and the deliberate omission of the per-session id.
|
|
1562
|
+
// But cumulativeTotal alone is too coarse a discriminator: a genuine
|
|
1563
|
+
// post-divergence fork event whose running total coincidentally equals
|
|
1564
|
+
// some parent total would also collide and be lost (undercount). So we
|
|
1565
|
+
// also key on the cumulative token breakdown, which a fork replays
|
|
1566
|
+
// verbatim from the parent -- a true replay collides exactly, while
|
|
1567
|
+
// genuinely different work at the same total stays distinct. We use the
|
|
1568
|
+
// CUMULATIVE figures (not the per-event deltas) on purpose: the deltas
|
|
1569
|
+
// are computed against a running `prev` that may start from a replay
|
|
1570
|
+
// baseline, so a delta-based key would spuriously diverge on a replay
|
|
1571
|
+
// and double-count it.
|
|
1572
|
+
// Without cumulative identity, equal usage can be distinct requests.
|
|
1573
|
+
// Use the physical record position: stable on cache resume/re-read,
|
|
1574
|
+
// but deliberately do not guess cross-file replay identity.
|
|
1575
|
+
// Invariant (#1088, restored): anything dropped below is a record
|
|
1576
|
+
// that survived both guards -- with cumulative identity it is a
|
|
1577
|
+
// strictly-advanced total, so no tokens are lost and no active-time
|
|
1578
|
+
// rescaling is needed; without it the record differs in payload
|
|
1579
|
+
// from its predecessor and is treated as a distinct request, which
|
|
1580
|
+
// deliberately weakens forkedFromId replay protection past the replay
|
|
1581
|
+
// burst (accepted trade-off: the alternative collapsed
|
|
1582
|
+
// distinct requests wholesale).
|
|
1583
|
+
// Two rollouts of one thread at identical cumulative totals are the
|
|
1584
|
+
// same calls replayed (resume), so sharing this key is intended. After
|
|
1585
|
+
// a counter restart the same totals are new calls: the epoch tells.
|
|
1586
|
+
// The prev counters hold the resolved totals (an omitted field reads
|
|
1587
|
+
// as unchanged), so omitted and explicit forms share one key.
|
|
1588
|
+
const dedupKey = reportsCumulative
|
|
1589
|
+
? `codex:${forkedFromId || threadId}:${cumulativeTotal}:${prevInput}:${prevCached}:${prevOutput}:${prevReasoning}${restartEpoch ? `:r${restartEpoch}` : ''}`
|
|
1590
|
+
: `codex:record:${JSON.stringify([source.path, tracker.lastCompleteLineOffset])}`;
|
|
1591
|
+
accountUsage(entry, {
|
|
1592
|
+
input_tokens: inputTokens,
|
|
1593
|
+
cached_input_tokens: cachedInputTokens,
|
|
1594
|
+
cache_write_input_tokens: cacheWriteTokens,
|
|
1595
|
+
output_tokens: outputTokens,
|
|
1596
|
+
reasoning_output_tokens: reasoningTokens,
|
|
1597
|
+
}, dedupKey);
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
// If the stream yielded nothing the file was unreadable, oversized, or
|
|
1601
|
+
// empty. Skip cache write so a transient failure can't pin an empty
|
|
1602
|
+
// result set against a fingerprint that would otherwise be re-parsed. On a
|
|
1603
|
+
// resume the earlier calls are still valid output, so serve them - but
|
|
1604
|
+
// still leave the cache entry alone.
|
|
1605
|
+
if (!sawAnyLine) {
|
|
1606
|
+
if (resume)
|
|
1607
|
+
for (const call of results)
|
|
1608
|
+
yield call;
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
// Flush the final task, which has no following task_started to trigger it.
|
|
1612
|
+
attachPendingNativeToolEvents(pendingTaskCalls.at(-1));
|
|
1613
|
+
results.push(...pendingTaskCalls);
|
|
1614
|
+
// Offsets into decompressed text cannot pass the cache's raw-byte append
|
|
1615
|
+
// check, and a compressed rollout is never appended to anyway.
|
|
1616
|
+
const resumeWrite = resumeState && !source.path.endsWith('.zst') ? { offset: resumeOffset, state: resumeState, callCount: resumeCallCount } : undefined;
|
|
1617
|
+
if (capture) {
|
|
1618
|
+
capture.write = { project: source.project, fingerprint: fp, ...(resumeWrite ? { resume: resumeWrite } : {}) };
|
|
1619
|
+
}
|
|
1620
|
+
else {
|
|
1621
|
+
await writeCachedCodexResults(source.path, source.project, results, fp, resumeWrite);
|
|
1622
|
+
}
|
|
1623
|
+
for (const call of results) {
|
|
1624
|
+
yield call;
|
|
1625
|
+
}
|
|
1626
|
+
},
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
/// Decode one rollout end to end, exactly as the serial path does for a file
|
|
1630
|
+
/// with no cache entry, without reading or writing the codex cache. `seenKeys`
|
|
1631
|
+
/// is the dedup set the decode runs against — pass an empty one off-thread and
|
|
1632
|
+
/// let the caller prove no earlier file claimed any of the keys before
|
|
1633
|
+
/// installing the result.
|
|
1634
|
+
export async function parseCodexFileFull(source, seenKeys) {
|
|
1635
|
+
const capture = {};
|
|
1636
|
+
const calls = [];
|
|
1637
|
+
for await (const call of createParser(source, seenKeys, capture).parse())
|
|
1638
|
+
calls.push(call);
|
|
1639
|
+
return { calls, ...(capture.write ? { write: capture.write } : {}) };
|
|
1640
|
+
}
|
|
1641
|
+
function rootsFor(home) {
|
|
1642
|
+
return [
|
|
1643
|
+
{ path: join(home, 'sessions'), label: 'sessions' },
|
|
1644
|
+
{ path: join(home, 'archived_sessions'), label: 'archived' },
|
|
1645
|
+
];
|
|
1646
|
+
}
|
|
1647
|
+
function dropOverlappingNestSources(sources, billedHome) {
|
|
1648
|
+
const billedIds = listRolloutSessionIds(billedHome);
|
|
1649
|
+
return sources.filter(source => {
|
|
1650
|
+
const id = rolloutFileSessionId(source.path);
|
|
1651
|
+
return !(id && billedIds.has(id));
|
|
1652
|
+
});
|
|
1653
|
+
}
|
|
1654
|
+
export function createCodexProvider(codexDir, opts) {
|
|
1655
|
+
const dir = getCodexDir(codexDir);
|
|
1656
|
+
const primaryDir = opts?.primaryDir ?? defaultBilledCodexHome();
|
|
1657
|
+
const launcherRoots = opts?.launcherRoots ?? defaultLauncherRoots();
|
|
1658
|
+
// Explicit nest factory whose path is a realpath alias of the billed home:
|
|
1659
|
+
// empty so a second factory cannot double-count the same tree. The no-arg
|
|
1660
|
+
// singleton must not take this branch — CODEX_HOME may be that alias.
|
|
1661
|
+
const duplicateHome = codexDir !== undefined &&
|
|
1662
|
+
sameCodexHome(dir, primaryDir) &&
|
|
1663
|
+
resolve(dir) !== resolve(primaryDir);
|
|
1664
|
+
const nestHome = isNestedLauncherCodexHome(dir, { primaryDir, launcherRoots });
|
|
1665
|
+
// Production `codex` singleton is createCodexProvider() with no args. When
|
|
1666
|
+
// the resolved dir is a launcher nest and ~/.codex is a distinct existing
|
|
1667
|
+
// tree, walk BOTH and drop nest sources whose session id is already billed.
|
|
1668
|
+
const scanBoth = nestHome && codexDir === undefined;
|
|
1669
|
+
// Extra WSL homes' ~/.codex (#1059); empty off-win32 and when a caller
|
|
1670
|
+
// pinned an explicit dir. Separate Linux trees, so no nest double-count.
|
|
1671
|
+
// Resolved lazily: `codex` is built at import and WSL probing spawns wsl.exe.
|
|
1672
|
+
const wslCodexDirs = () => codexDir ? [] : wslHomes().map(home => join(home, '.codex'));
|
|
1673
|
+
return {
|
|
1674
|
+
name: 'codex',
|
|
1675
|
+
displayName: 'Codex',
|
|
1676
|
+
modelDisplayName(model) {
|
|
1677
|
+
for (const [key, name] of modelDisplayEntries) {
|
|
1678
|
+
if (model === key || model.startsWith(key + '-'))
|
|
1679
|
+
return name;
|
|
1680
|
+
}
|
|
1681
|
+
return model;
|
|
1682
|
+
},
|
|
1683
|
+
toolDisplayName(rawTool) {
|
|
1684
|
+
return ownValue(toolNameMap, rawTool) ?? rawTool;
|
|
1685
|
+
},
|
|
1686
|
+
// Trees discoverSessions actually walks. Honors CODEX_HOME; when the
|
|
1687
|
+
// production singleton scans nest + billed home, both appear here, plus
|
|
1688
|
+
// each WSL home's ~/.codex.
|
|
1689
|
+
async probeRoots() {
|
|
1690
|
+
if (duplicateHome)
|
|
1691
|
+
return [];
|
|
1692
|
+
const local = scanBoth ? [...rootsFor(primaryDir), ...rootsFor(dir)] : rootsFor(dir);
|
|
1693
|
+
return [...local, ...wslCodexDirs().flatMap(rootsFor)];
|
|
1694
|
+
},
|
|
1695
|
+
async discoverSessions() {
|
|
1696
|
+
// Same physical tree via two factories is complete overlap, not a
|
|
1697
|
+
// distinct nest. isNestedLauncherCodexHome is false in that case.
|
|
1698
|
+
if (duplicateHome)
|
|
1699
|
+
return [];
|
|
1700
|
+
const sources = await discoverSessionsInDir(dir);
|
|
1701
|
+
const wslSources = (await Promise.all(wslCodexDirs().map(d => discoverSessionsInDir(d)))).flat();
|
|
1702
|
+
let local;
|
|
1703
|
+
if (scanBoth) {
|
|
1704
|
+
const billed = await discoverSessionsInDir(primaryDir);
|
|
1705
|
+
local = [...billed, ...dropOverlappingNestSources(sources, primaryDir)];
|
|
1706
|
+
}
|
|
1707
|
+
else if (!nestHome) {
|
|
1708
|
+
local = sources;
|
|
1709
|
+
}
|
|
1710
|
+
else {
|
|
1711
|
+
local = dropOverlappingNestSources(sources, primaryDir);
|
|
1712
|
+
}
|
|
1713
|
+
return [...local, ...wslSources];
|
|
1714
|
+
},
|
|
1715
|
+
createSessionParser(source, seenKeys) {
|
|
1716
|
+
return createParser(source, seenKeys);
|
|
1717
|
+
},
|
|
1718
|
+
};
|
|
1719
|
+
}
|
|
1720
|
+
export const codex = createCodexProvider();
|