ccdeck 4.0.4 → 4.2.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.
Files changed (32) hide show
  1. package/dist/web/assets/AccountBridge-C6OFH_Ju.js +1 -0
  2. package/dist/web/assets/{AccountSection-HmlI65gN.js → AccountSection-BMuTp9CV.js} +1 -1
  3. package/dist/web/assets/{BrowserWatchModal-DwY9hX-u.js → BrowserWatchModal-CxD5MH0G.js} +1 -1
  4. package/dist/web/assets/{FeedbackConversations-6S1QZR6S.js → FeedbackConversations-E11nU0s8.js} +1 -1
  5. package/dist/web/assets/{IntegrationModal-a8CAd22m.js → IntegrationModal-BGAiSkJt.js} +1 -1
  6. package/dist/web/assets/{IntegrationSkeleton-C2RiqqMA.js → IntegrationSkeleton-DAKXKuLF.js} +1 -1
  7. package/dist/web/assets/{RadioPanel-CyJsFSkf.js → RadioPanel-1NM6GOif.js} +1 -1
  8. package/dist/web/assets/StageShell-F-zWWpCp.js +12 -0
  9. package/dist/web/assets/{TrafficRadar-CEbp0Yi7.js → TrafficRadar-DHu0CnOc.js} +1 -1
  10. package/dist/web/assets/{UsageHistoryModal-i16x6suY.js → UsageHistoryModal-3rOC8oBZ.js} +1 -1
  11. package/dist/web/assets/{app-C0usT8Zy.js → app-CXxFM7fY.js} +61 -61
  12. package/dist/web/assets/{index-BQWffZlx.js → index-B0kLYrYF.js} +1 -1
  13. package/dist/web/assets/{inspector-status-pane-DD3QOXE6.js → inspector-status-pane-BvSOWD4r.js} +1 -1
  14. package/dist/web/assets/screens-B53mAUFb.js +16 -0
  15. package/dist/web/assets/screens-C6vVzMK-.css +1 -0
  16. package/dist/web/assets/stage-board-BmcdRHaG.js +2 -0
  17. package/dist/web/assets/{use-account-x7fuCA6S.js → use-account-DaZBTcqA.js} +1 -1
  18. package/dist/web/index.html +2 -2
  19. package/package.json +1 -1
  20. package/release-notes.json +38 -0
  21. package/src/server/codex-live-engine.mjs +15 -2
  22. package/src/server/codex-live-handoff.mjs +27 -0
  23. package/src/server/codex-translate.mjs +51 -9
  24. package/src/server/memory-metrics.mjs +19 -30
  25. package/src/server/session-transcript-routes.mjs +186 -35
  26. package/src/server/transcript-turns.mjs +641 -41
  27. package/src/server/tui-codex.mjs +3 -0
  28. package/dist/web/assets/AccountBridge-Cx7no9kK.js +0 -1
  29. package/dist/web/assets/StageShell-DXcdcjPI.js +0 -4
  30. package/dist/web/assets/screens-DAn5OlXe.js +0 -12
  31. package/dist/web/assets/screens-DUniTTbC.css +0 -1
  32. package/dist/web/assets/stage-board-kUkV8N-4.js +0 -2
@@ -1,13 +1,18 @@
1
- import { codexItemText } from "./codex-translate.mjs";
1
+ import { codexItemText, codexToolOutcome } from "./codex-translate.mjs";
2
2
 
3
- // A Claude Code transcript's lines, as the turns Chat draws: what you typed,
4
- // what the assistant said, and one row per tool call. Pure: lines in, turns
5
- // out, nothing read from disk and nothing remembered between calls.
3
+ // A Claude Code transcript's lines, as the turns Chat draws: what you typed
4
+ // (and how many images came with it), each slash command you ran with what it
5
+ // printed, what the assistant said, one row per tool call (with its error, or
6
+ // the change an edit made), a card for each set of questions it asked you, its
7
+ // task list, each sub-agent it started, and a line where you interrupted it or
8
+ // the API failed. Pure: lines in, turns out, nothing read from disk and
9
+ // nothing remembered between calls.
6
10
  //
7
11
  // WHAT IS LEFT OUT, ON PURPOSE. Thinking blocks (they are not part of the
8
- // conversation a reader follows), sidechain lines (a subagent's own talk),
9
- // meta lines (text Claude Code wrote for itself), and a user line that only
10
- // carries a tool's answer: that is the tool replying, not you typing.
12
+ // conversation a reader follows), sidechain lines (a subagent's own talk: the
13
+ // call that started it is the one line it gets), meta lines (text Claude Code
14
+ // wrote for itself), and a user line that only carries a tool's answer: that
15
+ // is the tool replying, not you typing.
11
16
  //
12
17
  // BOUNDED. Chat has no virtualisation, so the answer is the last MAX_TURNS
13
18
  // turns and each text is cut at MAX_TEXT, because the transcript's own size
@@ -34,6 +39,275 @@ export function toolArg(input) {
34
39
  return "";
35
40
  }
36
41
 
42
+ // A QUESTION CLAUDE ASKED IS NOT A TOOL ROW. AskUserQuestion's input holds the
43
+ // questions and their options, and its answer the choices: Chat draws them as
44
+ // a card, so the person reads what was asked without opening Term. Claude Code
45
+ // allows 1–4 questions of 2–4 options (a question that asks for text or a
46
+ // number has none); the caps are a little wider so a later version still
47
+ // draws, and every text is cut.
48
+ export const ASK_TOOL = "AskUserQuestion";
49
+ export const MAX_QUESTIONS = 4;
50
+ export const MAX_OPTIONS = 6;
51
+ const MAX_HEADER = 40;
52
+ const MAX_QUESTION = 1000;
53
+ const MAX_OPTION_NOTE = 400;
54
+ const MAX_ANSWER = 1000;
55
+ // What Claude Code records for a question that only got a note, no choice.
56
+ const NOTES_ONLY = "(notes only)";
57
+ // What it hands the model when the person wrote back instead of choosing.
58
+ const RESPONDED = /^The user responded: ([\s\S]*)$/;
59
+
60
+ const bounded = (value, max) => (typeof value === "string" && value.trim() ? cut(value.trim(), max) : "");
61
+
62
+ // A PLAN TO APPROVE IS NOT A TOOL ROW EITHER. Claude Code 2.1 has the model put
63
+ // the whole plan, in Markdown, in ExitPlanMode's `plan`: Chat draws it as prose,
64
+ // so the person reads what they approve without opening Term. A plan longer
65
+ // than MAX_PLAN is cut and says so (`cut`); one kept elsewhere (a version that
66
+ // leaves `plan` out) is drawn as its header only. Its answer starts "User has
67
+ // approved…" when it was approved; anything else (No, keep planning, Esc) is not.
68
+ export const PLAN_TOOL = "ExitPlanMode";
69
+ export const MAX_PLAN = 12000;
70
+ const APPROVED = /^User has approved\b/;
71
+
72
+ /** The plan turn of an ExitPlanMode call, with its answer when there is one. */
73
+ function planTurn(input, result) {
74
+ const plan = input && typeof input === "object" && typeof input.plan === "string" ? input.plan.trim() : "";
75
+ const turn = { kind: "plan", text: cut(plan, MAX_PLAN) };
76
+ if (plan.length > MAX_PLAN) turn.cut = true;
77
+ if (result) turn.approved = APPROVED.test(result.text.trim());
78
+ else turn.running = true;
79
+ return turn;
80
+ }
81
+
82
+ // THE TASK LIST IS NOT A TOOL ROW. Each TodoWrite call hands over the whole
83
+ // list as it stands, so every call is a full snapshot: Chat draws the last one
84
+ // as a checklist and the earlier ones as a line each (which one is last is the
85
+ // client's to say, since it sees the whole conversation). An input with no
86
+ // list stays a tool row.
87
+ export const TODO_TOOL = "TodoWrite";
88
+ export const MAX_TODOS = 50;
89
+ export const MAX_TODO_TEXT = 200;
90
+ const TODO_STATUS = { pending: "pending", in_progress: "active", completed: "done" };
91
+
92
+ /** The todo turn of a TodoWrite call, or null when its input carries no list. */
93
+ export function todoTurn(input) {
94
+ const list = input && typeof input === "object" && Array.isArray(input.todos) ? input.todos : null;
95
+ if (!list) return null;
96
+ const items = [];
97
+ for (const entry of list) {
98
+ if (items.length >= MAX_TODOS) break;
99
+ if (!entry || typeof entry !== "object") continue;
100
+ const text = bounded(entry.content, MAX_TODO_TEXT) || bounded(entry.activeForm, MAX_TODO_TEXT);
101
+ if (!text) continue;
102
+ const known = typeof entry.status === "string" && Object.hasOwn(TODO_STATUS, entry.status);
103
+ items.push({ text, status: known ? TODO_STATUS[entry.status] : "pending" });
104
+ }
105
+ return { kind: "todo", items };
106
+ }
107
+
108
+ // A SUB-AGENT IS ONE LINE. Agent (Claude Code 2.1) or Task (older) starts a
109
+ // sub-agent whose own lines are sidechain and stay out: what Chat keeps is the
110
+ // call, its type and description, and whether it still runs or failed. A
111
+ // running one can put a permission prompt on screen, as a running call can.
112
+ export const AGENT_TOOLS = new Set(["Agent", "Task"]);
113
+ export const MAX_AGENT_TEXT = 120;
114
+ const MAX_AGENT_TYPE = 60;
115
+
116
+ function agentTurn(input, result) {
117
+ const given = input && typeof input === "object" ? input : {};
118
+ const prompt = typeof given.prompt === "string" ? given.prompt.split(/\r?\n/).find(line => line.trim() !== "") : undefined;
119
+ const turn = {
120
+ kind: "agent",
121
+ type: bounded(given.subagent_type, MAX_AGENT_TYPE),
122
+ description: bounded(given.description, MAX_AGENT_TEXT) || bounded(prompt, MAX_AGENT_TEXT),
123
+ };
124
+ if (!result) turn.running = true;
125
+ else if (result.declined) turn.declined = true;
126
+ else if (result.error) turn.failed = true;
127
+ else if (launchedInBackground(result)) turn.background = true;
128
+ return turn;
129
+ }
130
+
131
+ // A SUB-AGENT STARTED IN THE BACKGROUND is answered at once, with a note that
132
+ // it was launched (Claude Code 2.1 records status "async_launched"): it has
133
+ // not finished, so it is not "Done".
134
+ const ASYNC_LAUNCHED = /^Async agent launched/;
135
+
136
+ function launchedInBackground(result) {
137
+ return result.own?.status === "async_launched" || ASYNC_LAUNCHED.test(result.text.trim());
138
+ }
139
+
140
+ // A DECLINED CALL DID NOT FAIL. When you answer No at the permission prompt,
141
+ // Claude Code hands the model an error that opens with this sentence: the row
142
+ // says Declined, with nothing to open, rather than Failed with the note meant
143
+ // for the model.
144
+ const DECLINED = /^The user doesn't want to proceed with this tool use/;
145
+
146
+ // A FAILED CALL SAYS WHY. A result marked is_error keeps the call's row and
147
+ // carries the text Claude Code handed the model, cut at MAX_ERROR; the wrapper
148
+ // Claude Code puts round its own refusals is left off.
149
+ export const MAX_ERROR = 2000;
150
+ const ERROR_WRAPPER = /^<tool_use_error>([\s\S]*)<\/tool_use_error>$/;
151
+
152
+ function errorText(text) {
153
+ const trimmed = text.trim();
154
+ return cut((ERROR_WRAPPER.exec(trimmed)?.[1] ?? trimmed).trim(), MAX_ERROR);
155
+ }
156
+
157
+ // AN EDIT SHOWS ITS CHANGE. Edit, MultiEdit and Write carry the change as diff
158
+ // lines (" " kept, "-" removed, "+" added), and the row's note counts them
159
+ // ("+4 −1"). The patch Claude Code recorded for the result is preferred, its
160
+ // hunks joined by a "…" line; without one (still running, or an older
161
+ // version) the change is read from the input: what was replaced as "-", what
162
+ // replaces it as "+", and a whole new file as "+". The counts are the whole
163
+ // change's; the lines stop at MAX_DIFF_LINES or MAX_DIFF_CHARS and say so
164
+ // (`cut`). A failed call changed nothing, so it has no diff.
165
+ export const EDIT_TOOLS = new Set(["Edit", "MultiEdit", "Write"]);
166
+ export const MAX_DIFF_LINES = 400;
167
+ export const MAX_DIFF_CHARS = 12000;
168
+ export const DIFF_GAP = "…";
169
+
170
+ /** A text's lines, without the empty one a final newline leaves. */
171
+ function textLines(text) {
172
+ if (typeof text !== "string" || text === "") return [];
173
+ const lines = text.split(/\r?\n/);
174
+ if (lines.at(-1) === "") lines.pop();
175
+ return lines;
176
+ }
177
+
178
+ /** The diff lines of a recorded structuredPatch, or null when there is none. */
179
+ function patchLines(own) {
180
+ const hunks = own && typeof own === "object" && Array.isArray(own.structuredPatch) ? own.structuredPatch : null;
181
+ if (!hunks) return null;
182
+ const lines = [];
183
+ for (const hunk of hunks) {
184
+ const body = hunk && typeof hunk === "object" && Array.isArray(hunk.lines) ? hunk.lines.filter(l => typeof l === "string") : [];
185
+ if (!body.length) continue;
186
+ if (lines.length) lines.push(DIFF_GAP);
187
+ lines.push(...body);
188
+ }
189
+ return lines.length ? lines : null;
190
+ }
191
+
192
+ /** The diff lines an edit's input describes. */
193
+ function inputLines(name, input) {
194
+ if (!input || typeof input !== "object") return [];
195
+ const change = (from, to) => [...textLines(from).map(l => `-${l}`), ...textLines(to).map(l => `+${l}`)];
196
+ if (name === "Write") return textLines(input.content).map(l => `+${l}`);
197
+ if (name === "Edit") return change(input.old_string, input.new_string);
198
+ const lines = [];
199
+ for (const edit of Array.isArray(input.edits) ? input.edits : []) {
200
+ const part = edit && typeof edit === "object" ? change(edit.old_string, edit.new_string) : [];
201
+ if (!part.length) continue;
202
+ if (lines.length) lines.push(DIFF_GAP);
203
+ lines.push(...part);
204
+ }
205
+ return lines;
206
+ }
207
+
208
+ /** The diff and note of an Edit, MultiEdit or Write call, or null when it changed nothing. */
209
+ export function editDiff(name, input, own) {
210
+ const all = patchLines(own) ?? inputLines(name, input);
211
+ if (!all.length) return null;
212
+ let added = 0;
213
+ let removed = 0;
214
+ for (const line of all) {
215
+ if (line.startsWith("+")) added++;
216
+ else if (line.startsWith("-")) removed++;
217
+ }
218
+ const lines = [];
219
+ let chars = 0;
220
+ let over = false;
221
+ for (const line of all) {
222
+ if (lines.length >= MAX_DIFF_LINES) { over = true; break; }
223
+ const room = MAX_DIFF_CHARS - chars;
224
+ if (line.length > room) {
225
+ // A line longer than what is left is cut to fit, so one minified line still shows.
226
+ if (room > 1) lines.push(cut(line, room));
227
+ over = true;
228
+ break;
229
+ }
230
+ lines.push(line);
231
+ chars += line.length;
232
+ }
233
+ const diff = over ? { lines, cut: true } : { lines };
234
+ return { diff, note: `+${added} −${removed}` };
235
+ }
236
+
237
+ /** The questions of an AskUserQuestion call, or null when its input is not one. */
238
+ export function askQuestions(input) {
239
+ const list = input && typeof input === "object" && Array.isArray(input.questions) ? input.questions : null;
240
+ if (!list) return null;
241
+ const questions = [];
242
+ for (const entry of list.slice(0, MAX_QUESTIONS)) {
243
+ if (!entry || typeof entry !== "object") continue;
244
+ const question = bounded(entry.question, MAX_QUESTION);
245
+ if (!question) continue;
246
+ const given = (Array.isArray(entry.options) ? entry.options : []).slice(0, MAX_OPTIONS);
247
+ const options = given
248
+ .map(option => ({ label: bounded(option?.label, MAX_ARG), description: bounded(option?.description, MAX_OPTION_NOTE) }))
249
+ .filter(option => option.label);
250
+ const turn = { header: bounded(entry.header, MAX_HEADER), question, multi: entry.multiSelect === true, options };
251
+ // Options with a preview are drawn side by side, and answered with other
252
+ // keys (ask-keys.ts): only that they have one is kept, never the preview.
253
+ if (given.some(option => bounded(option?.preview, 1))) turn.preview = true;
254
+ // A question that asks for text or a number has no options to pick.
255
+ if (typeof entry.kind === "string" && entry.kind !== "choice") turn.options = [];
256
+ questions.push(turn);
257
+ }
258
+ return questions.length ? questions : null;
259
+ }
260
+
261
+ /** The text of a tool_result part: a string, or its text parts joined. */
262
+ function resultText(part) {
263
+ const content = part?.content;
264
+ if (typeof content === "string") return content;
265
+ if (!Array.isArray(content)) return "";
266
+ return content.filter(item => item?.type === "text" && typeof item.text === "string").map(item => item.text).join("\n");
267
+ }
268
+
269
+ // Claude Code answers the model with `"<question>"="<answer>"` pairs, or
270
+ // `"<question>"=(no option selected)`, joined by ", ". Read back only by the
271
+ // questions the call asked, so a quote inside an answer cannot start a new
272
+ // pair: an answer runs up to the next asked question's pair, or to the last
273
+ // quote before the sentence that follows.
274
+ function answersFromText(said, questions) {
275
+ const found = [];
276
+ for (const { question } of questions) {
277
+ const at = said.indexOf(`"${question}"=`);
278
+ if (at >= 0) found.push({ question, at, start: at + question.length + 3 });
279
+ }
280
+ found.sort((a, b) => a.at - b.at);
281
+ const answers = {};
282
+ found.forEach((entry, i) => {
283
+ if (said[entry.start] !== '"') return;
284
+ const next = found[i + 1];
285
+ const stretch = said.slice(entry.start + 1, next ? next.at : said.length);
286
+ const close = stretch.lastIndexOf('"');
287
+ if (close >= 0) answers[entry.question] = stretch.slice(0, close);
288
+ });
289
+ return answers;
290
+ }
291
+
292
+ /** One answer as text: a choice, or several joined as Claude Code joins them. */
293
+ function answerText(value) {
294
+ const said = Array.isArray(value) ? value.filter(item => typeof item === "string").join(", ") : value;
295
+ return said === NOTES_ONLY ? "" : bounded(said, MAX_ANSWER);
296
+ }
297
+
298
+ /**
299
+ * What the person chose, per question in the order asked, and what they wrote
300
+ * back instead of choosing: from the line's own record of the result when it
301
+ * carries one, else read from the text the model was handed. An empty string
302
+ * for a question left unanswered.
303
+ */
304
+ function askAnswers(questions, result) {
305
+ const own = result.own && typeof result.own === "object" ? result.own : null;
306
+ const answers = own?.answers && typeof own.answers === "object" ? own.answers : answersFromText(result.text, questions);
307
+ const reply = own ? bounded(own.response, MAX_ANSWER) : bounded(RESPONDED.exec(result.text.trim())?.[1], MAX_ANSWER);
308
+ return { answers: questions.map(({ question }) => answerText(answers[question])), reply };
309
+ }
310
+
37
311
  function parse(line) {
38
312
  if (!line) return null;
39
313
  try {
@@ -47,7 +321,8 @@ function parse(line) {
47
321
  // notice a background task sends when it finishes, and the summary written
48
322
  // when a conversation is compacted are all user lines in the file, but none
49
323
  // was typed, and the summary alone runs to thousands of characters. They would
50
- // be drawn as "you said".
324
+ // be drawn as "you said". An interruption is still worth a line of its own (a
325
+ // notice turn), since it says why the assistant stopped.
51
326
  const WRAPPERS = /<(command-name|command-message|command-args|local-command-stdout|local-command-stderr)>[\s\S]*?<\/\1>/g;
52
327
  // The notice has to OPEN the line, as the rail reads it (injected-prompt.ts):
53
328
  // a person who mentions the tag mid-sentence typed it.
@@ -55,18 +330,89 @@ const TASK_NOTICE = /^\s*<task-notification>[\s\S]*?<\/task-notification>/;
55
330
  const INTERRUPTED = /^\[Request interrupted by user/;
56
331
  const SUMMARY_LEAD = /^This session is being continued from a previous conversation/;
57
332
 
333
+ /** A user line's text as written: a string, or its text parts joined. */
334
+ function rawUserText(content) {
335
+ if (typeof content === "string") return content;
336
+ if (!Array.isArray(content)) return "";
337
+ return content
338
+ .filter(part => part && part.type === "text" && typeof part.text === "string")
339
+ .map(part => part.text)
340
+ .join("\n");
341
+ }
342
+
58
343
  /** The text a user line carries: a string, or its text parts joined, without the bookkeeping. */
59
344
  function userText(content) {
60
- let text;
61
- if (typeof content === "string") text = content;
62
- else if (Array.isArray(content)) {
63
- text = content
64
- .filter(part => part && part.type === "text" && typeof part.text === "string")
65
- .map(part => part.text)
66
- .join("\n");
67
- } else return "";
68
- text = text.replace(WRAPPERS, "").trim().replace(TASK_NOTICE, "").trim();
69
- return INTERRUPTED.test(text) ? "" : text;
345
+ return rawUserText(content).replace(WRAPPERS, "").trim().replace(TASK_NOTICE, "").trim();
346
+ }
347
+
348
+ // A SLASH COMMAND YOU RAN IS A LINE OF ITS OWN. Claude Code 2.1 writes `/model
349
+ // opus` as one user line holding nothing but its wrappers:
350
+ // <command-message>model</command-message>, <command-name>/model</command-name>
351
+ // and, when there are any, <command-args>opus</command-args>. Chat draws it as
352
+ // you typed it. A local command's result follows as a line of its own,
353
+ // <local-command-stdout> (or -stderr when it failed), and is drawn under the
354
+ // command; output with no command just before it is left out. A skill's
355
+ // expanded prompt and the caveat before a local command are meta lines, so
356
+ // they stay out as every meta line does. What a command printed is plain
357
+ // text: its colours (ANSI escapes) go, and it is cut at MAX_COMMAND_OUTPUT.
358
+ export const MAX_COMMAND_ARGS = 200;
359
+ export const MAX_COMMAND_OUTPUT = 2000;
360
+ const COMMAND_NAME = /<command-name>([\s\S]*?)<\/command-name>/;
361
+ const COMMAND_ARGS = /<command-args>([\s\S]*?)<\/command-args>/;
362
+ const COMMAND_OUTPUT = /<local-command-(stdout|stderr)>([\s\S]*?)<\/local-command-\1>/g;
363
+ const ESCAPES = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-Z\\-_]/g;
364
+
365
+ /** The command turn of a line that only holds a command's wrappers, or null. */
366
+ function commandTurn(raw) {
367
+ const name = COMMAND_NAME.exec(raw)?.[1].trim();
368
+ if (!name) return null;
369
+ const turn = { kind: "command", name: cut(name, MAX_ARG) };
370
+ const args = COMMAND_ARGS.exec(raw)?.[1].trim();
371
+ if (args) turn.args = cut(args, MAX_COMMAND_ARGS);
372
+ return turn;
373
+ }
374
+
375
+ /** What the local-command outputs on a line printed, and whether any of it was stderr. */
376
+ function commandOutput(raw) {
377
+ const parts = [];
378
+ let failed = false;
379
+ for (const [, stream, body] of raw.matchAll(COMMAND_OUTPUT)) {
380
+ const text = body.replace(ESCAPES, "").trim();
381
+ if (!text) continue;
382
+ parts.push(text);
383
+ if (stream === "stderr") failed = true;
384
+ }
385
+ return { text: parts.join("\n"), failed };
386
+ }
387
+
388
+ /** Adds what a command printed to its turn: lines after the first join with "\n". */
389
+ function attachOutput(turn, output) {
390
+ if (!output.text) return;
391
+ turn.output = cut(turn.output ? `${turn.output}\n${output.text}` : output.text, MAX_COMMAND_OUTPUT);
392
+ if (output.failed) turn.failed = true;
393
+ }
394
+
395
+ // AN IMAGE YOU SENT IS COUNTED, NEVER CARRIED. A pasted or attached image is
396
+ // an image part beside the line's text: the turn says how many there were,
397
+ // and none of their data goes out. An image inside a tool's result is the
398
+ // tool's, not something you sent, so a line that answers a call counts none.
399
+ function imageCount(content) {
400
+ if (!Array.isArray(content) || content.some(part => part?.type === "tool_result")) return 0;
401
+ return content.filter(part => part?.type === "image").length;
402
+ }
403
+
404
+ // AN API ERROR IS NOT THE ASSISTANT TALKING. Claude Code writes a failed
405
+ // request as an assistant line flagged isApiErrorMessage ("API Error: 529
406
+ // {...}"): Chat draws its first line as a notice, cut at MAX_NOTICE.
407
+ export const MAX_NOTICE = 200;
408
+
409
+ function apiErrorTurn(content) {
410
+ const parts = typeof content === "string" ? [content]
411
+ : Array.isArray(content) ? content.filter(part => part?.type === "text" && typeof part.text === "string").map(part => part.text) : [];
412
+ const first = parts.join("\n").split(/\r?\n/).find(line => line.trim() !== "");
413
+ const turn = { kind: "notice", what: "error" };
414
+ if (first) turn.text = cut(first.trim(), MAX_NOTICE);
415
+ return turn;
70
416
  }
71
417
 
72
418
  /**
@@ -83,15 +429,24 @@ export function transcriptTurns(lines) {
83
429
  /** The same turns, and whether the cap on them dropped any from the front. */
84
430
  export function transcriptWindow(lines) {
85
431
  const records = [];
86
- const answered = new Set();
432
+ // Each answered call's result: the text the model was handed, whether it was
433
+ // marked an error and, when the line answers that call alone, the line's own
434
+ // record of it.
435
+ const answered = new Map();
87
436
  for (const line of lines) {
88
437
  const rec = parse(line);
89
438
  if (!rec) continue;
90
439
  records.push(rec);
91
440
  const content = rec.message?.content;
92
441
  if (rec.type === "user" && Array.isArray(content)) {
93
- for (const part of content) {
94
- if (part?.type === "tool_result" && typeof part.tool_use_id === "string") answered.add(part.tool_use_id);
442
+ const results = content.filter(part => part?.type === "tool_result" && typeof part.tool_use_id === "string");
443
+ for (const part of results) {
444
+ answered.set(part.tool_use_id, {
445
+ text: resultText(part),
446
+ own: results.length === 1 ? rec.toolUseResult : undefined,
447
+ error: part.is_error === true,
448
+ declined: part.is_error === true && DECLINED.test(resultText(part).trim()),
449
+ });
95
450
  }
96
451
  }
97
452
  }
@@ -106,15 +461,69 @@ export function transcriptWindow(lines) {
106
461
  afterCompaction = false;
107
462
  if (summary) continue;
108
463
  const text = userText(content);
109
- if (text) turns.push({ kind: "user", text: cut(text, MAX_TEXT) });
464
+ const images = imageCount(content);
465
+ const raw = text ? "" : rawUserText(content);
466
+ const command = text ? null : commandTurn(raw);
467
+ if (INTERRUPTED.test(text)) {
468
+ // Esc during a call writes two notes in a row; they are one interruption.
469
+ const last = turns.at(-1);
470
+ if (last?.kind !== "notice" || last.what !== "interrupted") turns.push({ kind: "notice", what: "interrupted" });
471
+ } else if (text || (images && !command)) {
472
+ const turn = { kind: "user", text: cut(text, MAX_TEXT) };
473
+ if (images) turn.images = images;
474
+ turns.push(turn);
475
+ } else if (command) {
476
+ attachOutput(command, commandOutput(raw));
477
+ turns.push(command);
478
+ } else if (raw) {
479
+ // A command's output, under the command it answers: the last turn.
480
+ const last = turns.at(-1);
481
+ if (last?.kind === "command") attachOutput(last, commandOutput(raw));
482
+ }
483
+ } else if (rec.type === "assistant" && rec.isApiErrorMessage === true) {
484
+ turns.push(apiErrorTurn(content));
110
485
  } else if (rec.type === "assistant" && Array.isArray(content)) {
111
486
  for (const part of content) {
112
487
  if (!part || typeof part !== "object") continue;
113
488
  if (part.type === "text" && typeof part.text === "string" && part.text.trim()) {
114
489
  turns.push({ kind: "assistant", text: cut(part.text.trim(), MAX_TEXT) });
115
490
  } else if (part.type === "tool_use" && typeof part.name === "string") {
491
+ const result = typeof part.id === "string" ? answered.get(part.id) : undefined;
492
+ if (part.name === PLAN_TOOL) {
493
+ turns.push(planTurn(part.input, result));
494
+ continue;
495
+ }
496
+ const questions = part.name === ASK_TOOL ? askQuestions(part.input) : null;
497
+ if (questions) {
498
+ const turn = { kind: "ask", questions };
499
+ if (result) {
500
+ const { answers, reply } = askAnswers(questions, result);
501
+ turn.answers = answers;
502
+ if (reply) turn.reply = reply;
503
+ } else turn.running = true;
504
+ turns.push(turn);
505
+ continue;
506
+ }
507
+ const todo = part.name === TODO_TOOL ? todoTurn(part.input) : null;
508
+ if (todo) {
509
+ turns.push(todo);
510
+ continue;
511
+ }
512
+ if (AGENT_TOOLS.has(part.name)) {
513
+ turns.push(agentTurn(part.input, result));
514
+ continue;
515
+ }
116
516
  const turn = { kind: "tool", name: cut(part.name, MAX_ARG), arg: toolArg(part.input) };
117
- if (typeof part.id !== "string" || !answered.has(part.id)) turn.running = true;
517
+ if (!result) turn.running = true;
518
+ else if (result.declined) turn.declined = true;
519
+ else if (result.error) turn.error = errorText(result.text);
520
+ if (EDIT_TOOLS.has(part.name) && !result?.error) {
521
+ const change = editDiff(part.name, part.input, result?.own);
522
+ if (change) {
523
+ turn.note = change.note;
524
+ turn.diff = change.diff;
525
+ }
526
+ }
118
527
  turns.push(turn);
119
528
  }
120
529
  }
@@ -128,27 +537,218 @@ function capTurns(turns) {
128
537
  }
129
538
 
130
539
  /** Prefer Codex's conversation events. The model-facing response items repeat
131
- * these messages and can also carry injected user-role context. */
540
+ * these messages and can also carry injected user-role context. Tool calls are
541
+ * read from the response items, which are the only record of them. */
132
542
  export function codexTranscriptWindow(lines) {
133
- const turns = [];
543
+ return capTurns(codexTurns(lines));
544
+ }
545
+
546
+ // ─── Codex ───────────────────────────────────────────────────────────────────
547
+ // A Codex rollout's lines, as the turns Chat draws: what you typed and what
548
+ // Codex said (its conversation events), one row per tool call with how it
549
+ // went, the change an apply_patch makes, and its plan (update_plan) as the
550
+ // task list.
551
+ //
552
+ // A CALL AND ITS RESULT ARE TWO RECORDS. Codex writes the call as a
553
+ // `response_item` when it is made and the result as another, tied by
554
+ // `call_id`: a `function_call` (arguments as JSON text), a `custom_tool_call`
555
+ // (a bare string: a patch, a script) or a `local_shell_call` (an argv). What a
556
+ // result says is read in codex-translate.mjs (codexToolOutcome). A web search
557
+ // is a `web_search_call`, with no result of its own. A call with no result is
558
+ // running until its turn ends (task_complete, turn_aborted): after that Codex
559
+ // will not answer it.
560
+
561
+ /** The tools that run a command: their row wears the terminal mark. */
562
+ const CODEX_COMMAND_TOOLS = new Set(["exec_command", "shell", "shell_command", "local_shell", "exec", "write_stdin"]);
563
+ const CODEX_PATCH_TOOL = "apply_patch";
564
+ const CODEX_PLAN_TOOL = "update_plan";
565
+ // Named as Claude Code names its own web search, so both read the same in Chat.
566
+ const CODEX_SEARCH_TOOL = "WebSearch";
567
+
568
+ /** The first line of a text that says something, cut; or "". */
569
+ function firstLine(text) {
570
+ const first = typeof text === "string" ? text.split(/\r?\n/).find(line => line.trim() !== "") : undefined;
571
+ return first === undefined ? "" : cut(first.trim(), MAX_ARG);
572
+ }
573
+
574
+ // A shell's own argv, ["bash", "-lc", "<command>"]: the command is what
575
+ // follows its script flag.
576
+ const SHELL_PROGRAM = /(?:^|[\\/])(?:(?:ba|z|da|k)?sh|powershell|pwsh|cmd)(?:\.exe)?$/i;
577
+ const SCRIPT_FLAG = /^(?:-[a-z]*c|-command|\/c)$/i;
578
+
579
+ function argvCommand(argv) {
580
+ const words = argv.filter(word => typeof word === "string");
581
+ const flag = SHELL_PROGRAM.test(words[0] ?? "") ? words.findIndex(word => SCRIPT_FLAG.test(word)) : -1;
582
+ return flag > 0 && flag + 1 < words.length ? words[flag + 1] : words.join(" ");
583
+ }
584
+
585
+ // The `exec` tool's input is a short JavaScript program that calls Codex's
586
+ // tools. What it ran is the `cmd` it hands tools.exec_command, as the board
587
+ // reads it (codexScriptCommand, tool-taxonomy.ts), else the tool it calls.
588
+ const SCRIPT_CMD = /\btools\.exec_command\s*\(\s*\{[^{}]*?\bcmd\s*:\s*(["'`])((?:\\.|(?!\1)[^\\])*)\1/;
589
+ const SCRIPT_CALL = /\btools\.([A-Za-z_$][\w$]*)\s*\(/;
590
+ const SCRIPT_ESCAPE = /\\(["'`\\nrt])/g;
591
+
592
+ function scriptArg(script) {
593
+ const cmd = SCRIPT_CMD.exec(script)?.[2].replace(SCRIPT_ESCAPE, (_, c) => (c === "n" ? "\n" : c === "r" ? "\r" : c === "t" ? "\t" : c));
594
+ if (cmd?.trim()) return firstLine(cmd);
595
+ const call = SCRIPT_CALL.exec(script)?.[1];
596
+ return call ? cut(call, MAX_ARG) : firstLine(script);
597
+ }
598
+
599
+ /** One line of a Codex call's input: the command it ran, else the usual fields. */
600
+ function codexArg(name, input) {
601
+ if (typeof input === "string") return name === "exec" ? scriptArg(input) : firstLine(input);
602
+ if (!input || typeof input !== "object") return "";
603
+ if (typeof input.cmd === "string") return firstLine(input.cmd);
604
+ if (Array.isArray(input.command)) return firstLine(argvCommand(input.command));
605
+ return toolArg(input);
606
+ }
607
+
608
+ // AN APPLY_PATCH SHOWS ITS CHANGE, as an Edit does. The patch is Codex's own
609
+ // format: "*** Add File: …", "*** Update File: …" or "*** Delete File: …"
610
+ // headers, an "@@" line before each hunk of an update, and lines that start
611
+ // " ", "-" or "+". The row's argument is the files it touches; its hunks go
612
+ // through editDiff, so the note and the caps are an Edit's.
613
+ const PATCH_FILE = /^\*\*\* (?:Add|Delete|Update) File: (.+)$/;
614
+
615
+ /** The patch text of an apply_patch call: the bare string, or its `input` or `patch` field. */
616
+ function patchText(input) {
617
+ if (typeof input === "string") return input;
618
+ if (!input || typeof input !== "object") return "";
619
+ return [input.input, input.patch].find(value => typeof value === "string") ?? "";
620
+ }
621
+
622
+ /** The files a patch touches, and its change as hunks of diff lines. */
623
+ function patchChange(patch) {
624
+ const files = [];
625
+ const hunks = [];
626
+ let hunk = null;
627
+ for (const line of patch.split(/\r?\n/)) {
628
+ const file = PATCH_FILE.exec(line);
629
+ if (file) {
630
+ files.push(file[1].trim());
631
+ hunk = null;
632
+ } else if (line.startsWith("@@")) {
633
+ hunk = null;
634
+ } else if (files.length && /^[ +-]/.test(line)) {
635
+ if (!hunk) hunks.push(hunk = []);
636
+ hunk.push(line);
637
+ }
638
+ }
639
+ return { files, hunks: hunks.map(lines => ({ lines })) };
640
+ }
641
+
642
+ /** The todo turn of an update_plan call, or null when it carries no plan. Its
643
+ * steps take the same three states as TodoWrite's. */
644
+ function planTodo(input) {
645
+ const plan = input && typeof input === "object" && Array.isArray(input.plan) ? input.plan : null;
646
+ return plan ? todoTurn({ todos: plan.map(item => ({ content: item?.step, status: item?.status })) }) : null;
647
+ }
648
+
649
+ /** The row of one call, with its result (`answered`), the patch_apply_end
650
+ * Codex wrote for it, and whether its turn has ended. */
651
+ function codexToolTurn(name, input, answered, result, applied, over) {
652
+ const patch = name === CODEX_PATCH_TOOL ? patchChange(patchText(input)) : null;
653
+ const turn = { kind: "tool", name: cut(name, MAX_ARG), arg: patch ? cut(patch.files.join(", "), MAX_ARG) : codexArg(name, input) };
654
+ if (CODEX_COMMAND_TOOLS.has(name)) turn.mark = "terminal";
655
+ const outcome = answered ? codexToolOutcome(result) : null;
656
+ const notApplied = applied?.success === false;
657
+ if (outcome?.declined) turn.declined = true;
658
+ else if (outcome?.failed) turn.error = errorText(outcome.text.replace(ESCAPES, ""));
659
+ else if (notApplied) turn.error = errorText(String(applied.stderr || applied.stdout || "").replace(ESCAPES, ""));
660
+ else if (!answered && !applied && !over) turn.running = true;
661
+ if (patch && turn.error === undefined && !turn.declined) {
662
+ const change = editDiff(name, undefined, { structuredPatch: patch.hunks });
663
+ if (change) {
664
+ turn.note = change.note;
665
+ turn.diff = change.diff;
666
+ }
667
+ }
668
+ return turn;
669
+ }
670
+
671
+ /** The row of a web search: what it looked for. */
672
+ function webSearchTurn(payload) {
673
+ const action = payload.action && typeof payload.action === "object" ? payload.action : {};
674
+ const asked = [action.query, action.url, action.pattern].find(value => typeof value === "string" && value.trim());
675
+ return { kind: "tool", name: CODEX_SEARCH_TOOL, arg: firstLine(asked), mark: "search" };
676
+ }
677
+
678
+ /** A user or assistant turn from a conversation event, or null. */
679
+ function codexMessage(event) {
680
+ let kind, text;
681
+ if (event?.type === "user_message" || event?.type === "agent_message") {
682
+ kind = event.type === "user_message" ? "user" : "assistant";
683
+ text = event.message;
684
+ } else if (event?.type === "item_completed") {
685
+ if (event.item?.type === "UserMessage") {
686
+ kind = "user";
687
+ text = codexItemText(event.item);
688
+ } else if (event.item?.type === "AgentMessage") {
689
+ kind = "assistant";
690
+ text = typeof event.item.content === "string" ? event.item.content : codexItemText(event.item);
691
+ }
692
+ }
693
+ return typeof text === "string" && text.trim() ? { kind, text: cut(text.trim(), MAX_TEXT) } : null;
694
+ }
695
+
696
+ /** The turns in a Codex rollout's `lines`, oldest first. */
697
+ function codexTurns(lines) {
698
+ const records = [];
699
+ // Each answered call's result, the patch_apply_end of each patch, and where
700
+ // the last turn ended.
701
+ const results = new Map();
702
+ const applied = new Map();
703
+ let ended = -1;
134
704
  for (const line of lines) {
135
705
  const record = parse(line);
136
- if (record?.type !== "event_msg") continue;
137
- const event = record.payload;
138
- let kind, text;
139
- if (event?.type === "user_message" || event?.type === "agent_message") {
140
- kind = event.type === "user_message" ? "user" : "assistant";
141
- text = event.message;
142
- } else if (event?.type === "item_completed") {
143
- if (event.item?.type === "UserMessage") {
144
- kind = "user";
145
- text = codexItemText(event.item);
146
- } else if (event.item?.type === "AgentMessage") {
147
- kind = "assistant";
148
- text = typeof event.item.content === "string" ? event.item.content : codexItemText(event.item);
149
- }
706
+ if (!record) continue;
707
+ const payload = record.payload;
708
+ if (record.type === "response_item" && (payload?.type === "function_call_output" || payload?.type === "custom_tool_call_output")) {
709
+ if (typeof payload.call_id === "string") results.set(payload.call_id, payload.output);
710
+ } else if (record.type === "event_msg" && payload?.type === "patch_apply_end") {
711
+ if (typeof payload.call_id === "string") applied.set(payload.call_id, payload);
712
+ } else if (record.type === "event_msg" && (payload?.type === "task_complete" || payload?.type === "turn_aborted")) {
713
+ ended = records.length;
150
714
  }
151
- if (typeof text === "string" && text.trim()) turns.push({ kind, text: cut(text.trim(), MAX_TEXT) });
715
+ records.push(record);
152
716
  }
153
- return capTurns(turns);
717
+ const turns = [];
718
+ records.forEach((record, at) => {
719
+ const payload = record.payload;
720
+ if (record.type === "event_msg") {
721
+ const message = codexMessage(payload);
722
+ if (message) turns.push(message);
723
+ return;
724
+ }
725
+ if (record.type !== "response_item" || !payload || typeof payload !== "object") return;
726
+ if (payload.type === "web_search_call") {
727
+ turns.push(webSearchTurn(payload));
728
+ return;
729
+ }
730
+ let name, input;
731
+ if (payload.type === "function_call") {
732
+ name = payload.name;
733
+ input = payload.arguments;
734
+ if (typeof input === "string") {
735
+ try { input = JSON.parse(input); } catch { /* kept as written */ }
736
+ }
737
+ } else if (payload.type === "custom_tool_call") {
738
+ name = payload.name;
739
+ input = payload.input;
740
+ } else if (payload.type === "local_shell_call") {
741
+ name = "local_shell";
742
+ input = { command: payload.action?.command };
743
+ }
744
+ if (typeof name !== "string" || !name) return;
745
+ const todo = name === CODEX_PLAN_TOOL ? planTodo(input) : null;
746
+ if (todo) {
747
+ turns.push(todo);
748
+ return;
749
+ }
750
+ const id = typeof payload.call_id === "string" ? payload.call_id : undefined;
751
+ turns.push(codexToolTurn(name, input, id !== undefined && results.has(id), results.get(id), id === undefined ? undefined : applied.get(id), at < ended));
752
+ });
753
+ return turns;
154
754
  }