{{ message }}
Repository navigation
Expand file tree
/
Copy pathparse_codex_log.cjs
More file actions
806 lines (709 loc) · 28.5 KB
/
Copy pathparse_codex_log.cjs
File metadata and controls
806 lines (709 loc) · 28.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// @ts-check
/// <reference types="@actions/github-script" />
const {
createEngineLogParser,
truncateString,
estimateTokens,
formatToolCallAsDetails,
buildStepSummaryDetailsSection,
parseLogEntries,
generateConversationMarkdown,
generateInformationSection,
formatInitializationSummary,
formatToolUse,
} = require("./log_parser_shared.cjs");
const { normalizeCodexSession, isCodexRecord } = require("./codex_session.cjs");
const { projectSessionResult, createSessionEvent, sessionToolSuccess, normalizeAgentSession } = require("./agent_session.cjs");
const {
CODEX_LEGACY_OUTCOME,
CODEX_LEGACY_METADATA,
CODEX_LEGACY_TOOL,
CODEX_LEGACY_OLD_TOOL,
CODEX_LEGACY_EXEC,
codexLegacyPayload,
codexLegacyBoundary,
codexLegacyStartupLines,
codexLegacyMessageEnd,
codexLegacyResultEnd,
extractCodexLegacyTokens,
collectCodexJSONRecords,
} = require("./codex_log_framing.cjs");
const main = createEngineLogParser({
parserName: "Codex",
parseFunction: parseCodexLog,
supportsDirectories: false,
});
/**
* Extract MCP server initialization information from Codex logs
* @param {string[]} lines - Array of log lines
* @returns {{hasInfo: boolean, markdown: string, servers: Array<{name: string, status: string, error?: string}>, tools?: string[]}} MCP initialization info
*/
function extractMCPInitialization(lines) {
const mcpServers = new Map(); // Map server name to status/error info
let serverCount = 0;
let connectedCount = 0;
let availableTools = [];
for (const line of lines) {
// Match: Initializing MCP servers from config
if (line.includes("Initializing MCP servers") || (line.includes("mcp") && line.includes("init"))) {
// Continue to next patterns
}
// Match: Found N MCP servers in configuration
const countMatch = line.match(/Found (\d+) MCP servers? in configuration/i);
if (countMatch) {
serverCount = parseInt(countMatch[1], 10);
}
// Match: Connecting to MCP server: <name>
const connectingMatch = line.match(/Connecting to MCP server[:\s]+['"]?(\w+)['"]?/i);
if (connectingMatch) {
const serverName = connectingMatch[1];
if (!mcpServers.has(serverName)) {
mcpServers.set(serverName, { name: serverName, status: "connecting" });
}
}
// Match: MCP server '<name>' connected successfully
const connectedMatch = line.match(/MCP server ['"](\w+)['"] connected successfully/i);
if (connectedMatch) {
const serverName = connectedMatch[1];
mcpServers.set(serverName, { name: serverName, status: "connected" });
connectedCount++;
}
// Match: Failed to connect to MCP server '<name>': <error>
const failedMatch = line.match(/Failed to connect to MCP server ['"](\w+)['"][:]\s*(.+)/i);
if (failedMatch) {
const serverName = failedMatch[1];
const error = failedMatch[2].trim();
mcpServers.set(serverName, { name: serverName, status: "failed", error });
}
// Match: MCP server '<name>' initialization failed
const initFailedMatch = line.match(/MCP server ['"](\w+)['"] initialization failed/i);
if (initFailedMatch) {
const serverName = initFailedMatch[1];
const existing = mcpServers.get(serverName);
if (existing && existing.status !== "failed") {
mcpServers.set(serverName, { name: serverName, status: "failed", error: "Initialization failed" });
}
}
// Match: Available tools: tool1, tool2, tool3
const toolsMatch = line.match(/Available tools:\s*(.+)/i);
if (toolsMatch) {
const toolsStr = toolsMatch[1];
availableTools = toolsStr
.split(",")
.map(t => t.trim())
.filter(t => t.length > 0);
}
}
// Build markdown output
let markdown = "";
const hasInfo = mcpServers.size > 0 || availableTools.length > 0;
if (mcpServers.size > 0) {
markdown += "**MCP Servers:**\n";
// Count by status
const servers = Array.from(mcpServers.values());
const connected = servers.filter(s => s.status === "connected");
const failed = servers.filter(s => s.status === "failed");
markdown += `- Total: ${servers.length}${serverCount > 0 && servers.length !== serverCount ? ` (configured: ${serverCount})` : ""}\n`;
markdown += `- Connected: ${connected.length}\n`;
if (failed.length > 0) {
markdown += `- Failed: ${failed.length}\n`;
}
markdown += "\n";
// List each server with status
for (const server of servers) {
const statusIcon = server.status === "connected" ? "✅" : server.status === "failed" ? "❌" : "⏳";
markdown += `- ${statusIcon} **${server.name}** (${server.status})`;
if (server.error) {
markdown += `\n - Error: ${server.error}`;
}
markdown += "\n";
}
markdown += "\n";
}
if (availableTools.length > 0) {
markdown += "**Available MCP Tools:**\n";
markdown += `- Total: ${availableTools.length} tools\n`;
markdown += `- Tools: ${availableTools.slice(0, 10).join(", ")}${availableTools.length > 10 ? ", ..." : ""}\n\n`;
}
return {
hasInfo,
markdown,
servers: Array.from(mcpServers.values()),
tools: availableTools.length > 0 ? availableTools : undefined,
};
}
/**
* Extract error messages from Codex logs (e.g., model access blocked, cyber_policy_violation)
* @param {string[]} lines - Array of log lines
* @returns {{hasErrors: boolean, messages: string[], reconnectCount: number, maxReconnects: number}} Error info
*/
function extractCodexErrorMessages(lines) {
const messages = new Set();
let reconnectCount = 0;
let maxReconnects = 0;
for (const line of lines) {
// Match: ERROR: <message> (final error after all retries exhausted)
const errorMatch = line.match(/^ERROR:\s*(.+)$/);
if (errorMatch) {
messages.add(errorMatch[1].trim());
}
// Match: Reconnecting... N/M (error message) - reconnect attempts with error details
const reconnectMatch = line.match(/^Reconnecting\.\.\.\s+(\d+)\/(\d+)\s*\((.+)\)$/);
if (reconnectMatch) {
const attempt = parseInt(reconnectMatch[1], 10);
const total = parseInt(reconnectMatch[2], 10);
if (attempt > reconnectCount) reconnectCount = attempt;
if (total > maxReconnects) maxReconnects = total;
messages.add(reconnectMatch[3].trim());
}
}
return {
hasErrors: messages.size > 0,
messages: Array.from(messages),
reconnectCount,
maxReconnects,
};
}
/**
* Extract the model name from Codex log header lines.
* Codex logs include a line like "model: o4-mini" near the top.
* @param {string} logContent - The raw log content
* @returns {string|null} The model name, or null if not found
*/
function extractCodexModel(logContent) {
const match = codexLegacyStartupLines(logContent.split("\n"))
.join("\n")
.match(/^model:\s*(.+)$/m);
if (match) {
return match[1].trim();
}
// Fallback for the experimental JSONL format, which has no "model:" header line.
// The codex harness logs the resolved spawn command, e.g.
// [codex-harness] ... spawning: codex exec --model gpt-5.4 -c ...
const spawnMatch = logContent.match(/^\[codex-harness\][^\n]*spawning:\s*codex\s+exec\s+--model\s+(\S+)/m);
if (spawnMatch) {
return spawnMatch[1].trim();
}
return null;
}
/**
* Detects whether the log is in the Codex experimental JSONL event format.
* Newer Codex CLI versions (e.g. 0.141+) emit a stream of JSON objects such as
* `{"type":"thread.started",...}`, `{"type":"turn.completed",...}` and
* `{"type":"item.completed","item":{"type":"agent_message",...}}` instead of the
* legacy pretty-printed "thinking"/"tool server.method(...)" lines.
* @param {string[]} lines - The log split into lines
* @param {Array<any>} [entries] - Already parsed records, when available
* @returns {boolean} True if at least one Codex JSONL event line is present
*/
function isCodexJsonlFormat(lines, entries = collectCodexJSONRecords(lines.join("\n"))) {
return entries.some(entry => isCodexRecord(entry) || normalizeAgentSession([entry], { sourceEngine: "codex" }).length > 0);
}
/**
* Parse the Codex experimental JSONL event stream into the shared logEntries model.
* Retains native item lifecycles, message snapshots and per-turn accounting.
* @param {string} logContent - The raw log content
* @param {Array<any>} [entries] - Already parsed records, when available
* @returns {{markdown: string, logEntries: Array, mcpFailures: Array<string>, maxTurnsHit: boolean}} Parsed log data
*/
function parseCodexJsonl(logContent, entries = collectCodexJSONRecords(logContent)) {
const canonicalLogEntries = normalizeCodexSession(collectCodexMixedRecords(logContent, entries), extractCodexModel(logContent));
const conversation = generateConversationMarkdown(canonicalLogEntries, {
includeInformation: false,
formatToolCallback: (toolUse, toolResult) => formatToolUse(toolUse, toolResult),
formatInitCallback: init => formatInitializationSummary(init),
});
const markdown = conversation.markdown + generateInformationSection(projectSessionResult(canonicalLogEntries));
return {
markdown,
logEntries: canonicalLogEntries,
mcpFailures: [],
maxTurnsHit: false,
};
}
/**
* Keep typed JSON records and recognized text observations without splitting the
* native normalizer's lifecycle/accounting state into independent sessions.
* @param {string} logContent
* @param {Array<any>} [entries]
* @returns {Array<any>}
*/
function collectCodexMixedRecords(logContent, entries = collectCodexJSONRecords(logContent)) {
try {
if (Array.isArray(JSON.parse(logContent))) return entries;
} catch {
// Mixed streams are not a single JSON document.
}
const records = [];
let text = [];
let hasFramedResult = false;
const accounting = { inlineTokens: 0, hasTokenSnapshot: false };
const flushText = () => {
const content = text.join("\n");
records.push(...parseCodexLegacySession(text, /^model:/m.test(content) ? extractCodexModel(content) : null, accounting));
text = [];
};
const lines = logContent.split("\n");
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
const messageEnd = codexLegacyMessageEnd(lines, index);
if (messageEnd !== null) {
for (const messageLine of lines.slice(index, messageEnd + 1)) text.push(messageLine);
index = messageEnd;
continue;
}
const resultEnd = codexLegacyResultEnd(lines, index);
if (resultEnd !== null) {
hasFramedResult = true;
for (const resultLine of lines.slice(index, resultEnd + 1)) text.push(resultLine);
index = resultEnd;
continue;
}
const parsed = parseLogEntries(line);
if (parsed?.some(record => typeof record?.type === "string" && record.type.length > 0)) {
flushText();
records.push(...parsed);
} else text.push(line);
}
flushText();
return records.length > 0 || hasFramedResult ? records : entries;
}
/**
* Legacy presentation uses lookahead; canonical observations must instead remain
* at their source positions, including orphan outcomes and dangling invocations.
* @param {string[]} lines
* @param {string|null} model
* @param {{inlineTokens: number, hasTokenSnapshot: boolean}} [accounting]
* @returns {import("./types/agent_session").AgentSession}
*/
function parseCodexLegacySession(lines, model, accounting = { inlineTokens: 0, hasTokenSnapshot: false }) {
/** @type {import("./types/agent_session").AgentSession} */
const events = [];
const metadata = CODEX_LEGACY_METADATA;
const tool = CODEX_LEGACY_TOOL;
const oldTool = CODEX_LEGACY_OLD_TOOL;
const exec = CODEX_LEGACY_EXEC;
const outcome = CODEX_LEGACY_OUTCOME;
const boundary = codexLegacyBoundary;
const emit = (source, type, data) => events.push(createSessionEvent(source, type, data));
const startup = codexLegacyStartupLines(lines);
const cwd = startup.find(line => line.startsWith("workdir: "))?.slice("workdir: ".length);
if (model !== null || cwd !== undefined || startup.some(line => line.startsWith("OpenAI Codex"))) {
const mcp = extractMCPInitialization(startup);
const reasoningEffort = startup.find(line => line.startsWith("reasoning effort: "))?.slice("reasoning effort: ".length);
emit({}, "session.init", { sourceEngine: "codex", model: model ?? undefined, cwd, reasoningEffort, mcpServers: mcp.servers.length ? mcp.servers : undefined, tools: mcp.tools });
}
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const payload = codexLegacyPayload(line);
const timestamp = line.match(/^\[([^\]]+)\]/)?.[1] ?? line.match(/^(\d{4}-\d{2}-\d{2}T\S+)/)?.[1];
const source = timestamp === undefined ? {} : { timestamp };
const tokens = extractCodexLegacyTokens(line);
if (tokens !== undefined) {
if (/^tokens\s+used:/i.test(payload)) {
accounting.inlineTokens += tokens;
if (!accounting.hasTokenSnapshot) emit(source, "session.result", { usage: Number.isSafeInteger(accounting.inlineTokens) ? { total_tokens: accounting.inlineTokens } : { overflowed_tokens: ["total_tokens"] } });
} else {
accounting.hasTokenSnapshot = true;
emit(source, "session.result", { usage: { total_tokens: tokens } });
}
continue;
}
if (
metadata.test(line) &&
!outcome.test(payload) &&
!tool.test(payload) &&
!oldTool.test(payload) &&
!exec.test(payload) &&
!["thinking", "codex", "user"].includes(payload) &&
!payload.startsWith("ERROR:") &&
!payload.startsWith("Reconnecting...")
)
continue;
if (["thinking", "codex", "user"].includes(payload)) {
const end = codexLegacyMessageEnd(lines, i) ?? i;
emit(source, payload === "thinking" ? "assistant.reasoning" : payload === "user" ? "user.message" : "assistant.message", { content: lines.slice(i + 1, end + 1).join("\n") });
i = end;
continue;
}
const invocation = payload.match(tool) ?? payload.match(oldTool);
const command = payload.match(exec);
if (invocation) {
let input = invocation[3];
try {
input = JSON.parse(input);
} catch {
// Intentional recovery: preserve the original argument text when JSON is malformed or partial.
}
emit(source, "tool.execution_start", { toolName: invocation[2], mcpServerName: invocation[1], input });
} else if (command) {
const text = command[1] ?? command[2];
emit(source, "tool.execution_start", { toolName: "bash", input: { command: text }, command: text });
} else {
const completion = payload.match(outcome);
if (completion) {
const output = [];
const resultEnd = codexLegacyResultEnd(lines, i);
if (resultEnd !== null) {
output.push(...lines.slice(i + 1, resultEnd + 1));
i = resultEnd;
} else while (i + 1 < lines.length && !boundary(lines[i + 1])) output.push(lines[++i]);
const outputText = output.join("\n");
let resultFailed = false;
try {
resultFailed = sessionToolSuccess(JSON.parse(outputText)) === false;
} catch {
// Plain command output is not a structured MCP result.
}
emit(source, "tool.execution_complete", {
toolName: completion[3] !== undefined ? "bash" : completion[2],
mcpServerName: completion[1],
success: !["failed", "failure"].includes(completion[4]) && !resultFailed,
durationMs: Number(completion[5]) * (completion[6] === "s" ? 1000 : 1),
output: outputText,
});
} else if (payload.startsWith("ERROR:")) {
emit(source, "session.result", { errors: [payload.replace(/^ERROR: ?/, "")] });
} else {
const retry = payload.match(/^Reconnecting\.\.\.\s+(\d+)\/(\d+)\s*\((.*)\)$/);
if (retry) emit({ ...source, reconnectAttempt: Number(retry[1]), maxReconnects: Number(retry[2]) }, "session.result", { errors: [retry[3]] });
else if (payload === "tokens used") {
const count = extractCodexLegacyTokens(`tokens used: ${lines[i + 1] ?? ""}`);
if (count !== undefined) {
i++;
accounting.hasTokenSnapshot = true;
emit(source, "session.result", { usage: { total_tokens: count } });
}
}
}
}
}
return events;
}
/**
* Parse codex log content and format as markdown
* @param {string} logContent - The raw log content to parse
* @param {Array<any>} [parsed] - Already parsed records, when available
* @returns {{markdown: string, logEntries: Array, mcpFailures: Array<string>, maxTurnsHit: boolean}} Parsed log data
*/
function parseCodexLog(logContent, parsed = collectCodexJSONRecords(logContent)) {
// Newer Codex CLI versions emit a structured JSONL event stream rather than the
// legacy pretty-printed format. Route those to the dedicated JSONL parser.
if (logContent && isCodexJsonlFormat([], parsed)) {
return parseCodexJsonl(logContent, parsed);
}
if (!logContent) {
return {
markdown: buildStepSummaryDetailsSection("Commands and Tools", "No log content provided.") + buildStepSummaryDetailsSection("Reasoning", "Unable to parse reasoning from log."),
logEntries: [],
mcpFailures: [],
maxTurnsHit: false,
};
}
const lines = logContent.split("\n");
// Look-ahead window size for finding tool results
// New format has verbose debug logs, so requires larger window
const LOOKAHEAD_WINDOW = 50;
let markdown = "";
// Extract MCP initialization information
const mcpInfo = extractMCPInitialization(lines);
if (mcpInfo.hasInfo) {
markdown += buildStepSummaryDetailsSection("Initialization", mcpInfo.markdown);
}
// Extract error messages (e.g., model access blocked, cyber_policy_violation)
const errorInfo = extractCodexErrorMessages(lines);
if (errorInfo.hasErrors) {
markdown += "<details>\n<summary>Errors</summary>\n\n";
for (const message of errorInfo.messages) {
markdown += `> ${message}\n\n`;
}
if (errorInfo.reconnectCount > 0) {
markdown += `> Reconnect attempts: ${errorInfo.reconnectCount}/${errorInfo.maxReconnects}\n\n`;
}
markdown += "</details>\n\n";
}
markdown += "<details>\n<summary>Reasoning</summary>\n\n";
// Second pass: process full conversation flow with interleaved reasoning and tools
let inThinkingSection = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Skip metadata lines (including Rust debug lines)
if (
line.includes("OpenAI Codex") ||
line.startsWith("--------") ||
line.includes("workdir:") ||
line.includes("model:") ||
line.includes("provider:") ||
line.includes("approval:") ||
line.includes("sandbox:") ||
line.includes("reasoning effort:") ||
line.includes("reasoning summaries:") ||
line.includes("tokens used:") ||
line.includes("DEBUG codex") ||
line.includes("INFO codex") ||
line.match(/^\d{4}-\d{2}-\d{2}T[\d:.]+Z\s+(DEBUG|INFO|WARN|ERROR)/)
) {
continue;
}
// Thinking section starts with standalone "thinking" line
if (line.trim() === "thinking") {
inThinkingSection = true;
continue;
}
// Tool call line "tool github.list_pull_requests(...)" (new Codex format without timestamp prefix)
const toolMatch = line.match(/^tool\s+(\w+)\.(\w+)\((.*)\)$/);
if (toolMatch) {
inThinkingSection = false;
const server = toolMatch[1];
const toolName = toolMatch[2];
const params = toolMatch[3];
// Look ahead to find the result status and response
let statusIcon = "❓"; // Unknown by default
let response = "";
for (let j = i + 1; j < Math.min(i + LOOKAHEAD_WINDOW, lines.length); j++) {
const nextLine = lines[j];
if (nextLine.includes(`${server}.${toolName}(`) && (nextLine.includes("success in") || nextLine.includes("failed in"))) {
const isError = nextLine.includes("failed in");
statusIcon = isError ? "❌" : "✅";
// Extract response - it's the JSON object following this line
let jsonLines = [];
let braceCount = 0;
let inJson = false;
for (let k = j + 1; k < Math.min(j + LOOKAHEAD_WINDOW, lines.length); k++) {
const respLine = lines[k];
// Stop if we hit the next tool call or tokens used
if (respLine.match(/^tool\s+\w+\.\w+\(/) || respLine.includes("ToolCall:") || respLine.includes("tokens used")) {
break;
}
// Count braces to track JSON boundaries
for (const char of respLine) {
if (char === "{") {
braceCount++;
inJson = true;
} else if (char === "}") {
braceCount--;
}
}
if (inJson) {
jsonLines.push(respLine);
}
if (inJson && braceCount === 0) {
break;
}
}
response = jsonLines.join("\n");
break;
}
}
markdown += `${statusIcon} ${server}::${toolName}(...)\n\n`;
continue;
}
// Process thinking content (filter out timestamp lines and very short lines)
if (inThinkingSection && line.trim().length > 20 && !line.match(/^\d{4}-\d{2}-\d{2}T/)) {
const trimmed = line.trim();
// Add thinking content directly to markdown with open circle icon and italic styling
markdown += `<sub><em>${trimmed}</em></sub>\n\n`;
}
}
markdown += "</details>\n\n<details>\n<summary>Commands and Tools</summary>\n\n";
// First pass: collect tool calls with details
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Match: tool server.method(params) or ToolCall: server__method params
const toolMatch = line.match(/^\[.*?\]\s+tool\s+(\w+)\.(\w+)\((.+)\)/) || line.match(/ToolCall:\s+(\w+)__(\w+)\s+(\{.+\})/);
// Also match: exec bash -lc 'command' in /path
const bashMatch = line.match(/^\[.*?\]\s+exec\s+bash\s+-lc\s+'([^']+)'/);
if (toolMatch) {
const server = toolMatch[1];
const toolName = toolMatch[2];
const params = toolMatch[3];
// Look ahead to find the result
let statusIcon = "❓";
let response = "";
let isError = false;
for (let j = i + 1; j < Math.min(i + LOOKAHEAD_WINDOW, lines.length); j++) {
const nextLine = lines[j];
// Check for result line: server.method(...) success/failed in Xms:
if (nextLine.includes(`${server}.${toolName}(`) && (nextLine.includes("success in") || nextLine.includes("failed in"))) {
isError = nextLine.includes("failed in");
statusIcon = isError ? "❌" : "✅";
// Extract response - it's the JSON object following this line
let jsonLines = [];
let braceCount = 0;
let inJson = false;
for (let k = j + 1; k < Math.min(j + 30, lines.length); k++) {
const respLine = lines[k];
// Stop if we hit the next tool call or tokens used
if (respLine.includes("tool ") || respLine.includes("ToolCall:") || respLine.includes("tokens used")) {
break;
}
// Count braces to track JSON boundaries
for (const char of respLine) {
if (char === "{") {
braceCount++;
inJson = true;
} else if (char === "}") {
braceCount--;
}
}
if (inJson) {
jsonLines.push(respLine);
}
if (inJson && braceCount === 0) {
break;
}
}
response = jsonLines.join("\n");
break;
}
}
// Format the tool call with HTML details
markdown += formatCodexToolCall(server, toolName, params, response, statusIcon);
} else if (bashMatch) {
const command = bashMatch[1];
// Look ahead to find the result
let statusIcon = "❓";
let response = "";
let isError = false;
for (let j = i + 1; j < Math.min(i + LOOKAHEAD_WINDOW, lines.length); j++) {
const nextLine = lines[j];
// Check for bash result line: bash -lc 'command' succeeded/failed in Xms:
if (nextLine.includes("bash -lc") && (nextLine.includes("succeeded in") || nextLine.includes("failed in"))) {
isError = nextLine.includes("failed in");
statusIcon = isError ? "❌" : "✅";
// Extract response - it's the plain text following this line
let responseLines = [];
for (let k = j + 1; k < Math.min(j + 20, lines.length); k++) {
const respLine = lines[k];
// Stop if we hit the next tool call, exec, or tokens used
if (respLine.includes("tool ") || respLine.includes("exec ") || respLine.includes("ToolCall:") || respLine.includes("tokens used") || respLine.includes("thinking")) {
break;
}
responseLines.push(respLine);
}
response = responseLines.join("\n");
break;
}
}
// Format the bash command with HTML details
markdown += formatCodexBashCall(command, response, statusIcon);
}
}
// Add Information section
markdown += "</details>\n\n<details>\n<summary>Information</summary>\n\n";
// Extract metadata from Codex logs
const model = extractCodexModel(logContent);
const canonicalLogEntries = parseCodexLegacySession(lines, model);
const totalTokens = projectSessionResult(canonicalLogEntries)?.usage?.total_tokens;
if (totalTokens !== undefined) {
markdown += `**Total Tokens Used:** ${totalTokens.toLocaleString()}\n\n`;
}
// Count tool calls
const toolCalls = (logContent.match(/ToolCall:\s+\w+__\w+/g) || []).length;
if (toolCalls > 0) {
markdown += `**Tool Calls:** ${toolCalls}\n\n`;
}
markdown += "</details>\n\n";
// Check for MCP failures
const mcpFailures = mcpInfo.servers.filter(server => server.status === "failed").map(server => server.name);
return {
markdown,
logEntries: canonicalLogEntries,
mcpFailures,
maxTurnsHit: false, // Codex doesn't have max-turns concept in logs
};
}
/**
* Format a Codex tool call with HTML details
* Uses the shared formatToolCallAsDetails helper for consistent rendering across all engines.
* @param {string} server - The server name (e.g., "github", "time")
* @param {string} toolName - The tool name (e.g., "list_pull_requests")
* @param {string} params - The parameters as JSON string
* @param {string} response - The response as JSON string
* @param {string} statusIcon - The status icon (✅, ❌, or ❓)
* @returns {string} Formatted HTML details string
*/
function formatCodexToolCall(server, toolName, params, response, statusIcon) {
// Calculate token estimate from params + response
const totalTokens = estimateTokens(params) + estimateTokens(response);
// Format metadata
let metadata = "";
if (totalTokens > 0) {
metadata = `<code>~${totalTokens}t</code>`;
}
const summary = `<code>${server}::${toolName}</code>`;
// Build sections array
const sections = [];
if (params && params.trim()) {
sections.push({
label: "Parameters",
content: params,
language: "json",
});
}
if (response && response.trim()) {
sections.push({
label: "Response",
content: response,
language: "json",
});
}
return formatToolCallAsDetails({
summary,
statusIcon,
metadata,
sections,
});
}
/**
* Format a Codex bash call with HTML details
* Uses the shared formatToolCallAsDetails helper for consistent rendering across all engines.
* @param {string} command - The bash command
* @param {string} response - The response as plain text
* @param {string} statusIcon - The status icon (✅, ❌, or ❓)
* @returns {string} Formatted HTML details string
*/
function formatCodexBashCall(command, response, statusIcon) {
// Calculate token estimate from command + response
const totalTokens = estimateTokens(command) + estimateTokens(response);
// Format metadata
let metadata = "";
if (totalTokens > 0) {
metadata = `<code>~${totalTokens}t</code>`;
}
const summary = `<code>bash: ${truncateString(command, 60)}</code>`;
// Build sections array
const sections = [];
sections.push({
label: "Command",
content: command,
language: "bash",
});
if (response && response.trim()) {
sections.push({
label: "Output",
content: response,
});
}
return formatToolCallAsDetails({
summary,
statusIcon,
metadata,
sections,
});
}
// Export for testing
if (typeof module !== "undefined" && module.exports) {
module.exports = {
main,
parseCodexLog,
parseCodexJsonl,
isCodexJsonlFormat,
formatCodexToolCall,
formatCodexBashCall,
extractMCPInitialization,
extractCodexErrorMessages,
extractCodexModel,
collectCodexMixedRecords,
};
}
You can’t perform that action at this time.
