@myrialabs/clopen 0.3.8 → 0.3.9

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 (125) hide show
  1. package/backend/auth/permissions.ts +41 -2
  2. package/backend/chat/stream-manager.ts +71 -0
  3. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  4. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  5. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  6. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  7. package/backend/database/migrations/index.ts +29 -1
  8. package/backend/database/queries/db-client-connection-queries.ts +160 -54
  9. package/backend/database/queries/engine-queries.ts +12 -0
  10. package/backend/database/queries/project-queries.ts +10 -5
  11. package/backend/engine/README.md +1702 -0
  12. package/backend/engine/adapters/claude/models.ts +141 -0
  13. package/backend/engine/adapters/claude/stream.ts +1 -1
  14. package/backend/engine/adapters/codex/credential.ts +179 -0
  15. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  16. package/backend/engine/adapters/codex/index.ts +1 -0
  17. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  18. package/backend/engine/adapters/codex/models.ts +105 -0
  19. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  20. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  21. package/backend/engine/adapters/codex/stream.ts +310 -0
  22. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  23. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  24. package/backend/engine/adapters/copilot/index.ts +1 -0
  25. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  26. package/backend/engine/adapters/copilot/models.ts +92 -0
  27. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  28. package/backend/engine/adapters/copilot/stream.ts +573 -0
  29. package/backend/engine/adapters/opencode/config.ts +56 -104
  30. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  31. package/backend/engine/adapters/opencode/models.ts +79 -0
  32. package/backend/engine/adapters/opencode/presets.ts +91 -0
  33. package/backend/engine/adapters/opencode/stream.ts +5 -115
  34. package/backend/engine/adapters/qwen/credential.ts +78 -0
  35. package/backend/engine/adapters/qwen/environment.ts +84 -0
  36. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  37. package/backend/engine/adapters/qwen/index.ts +1 -0
  38. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  39. package/backend/engine/adapters/qwen/models.ts +81 -0
  40. package/backend/engine/adapters/qwen/presets.ts +51 -0
  41. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  42. package/backend/engine/adapters/qwen/stream.ts +380 -0
  43. package/backend/engine/index.ts +35 -0
  44. package/backend/engine/install-recipes.ts +80 -1
  45. package/backend/engine/install-runner.ts +4 -0
  46. package/backend/mcp/README.md +84 -14
  47. package/backend/mcp/config.ts +218 -17
  48. package/backend/mcp/index.ts +2 -0
  49. package/backend/mcp/project-context.ts +55 -0
  50. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  51. package/backend/mcp/servers/helper.ts +13 -0
  52. package/backend/middleware/error-handler.ts +16 -2
  53. package/backend/preview/browser/browser-preview-service.ts +4 -4
  54. package/backend/ws/README.md +128 -3
  55. package/backend/ws/access.ts +56 -0
  56. package/backend/ws/chat/stream.ts +36 -12
  57. package/backend/ws/db-client/access.ts +19 -0
  58. package/backend/ws/db-client/connections.ts +31 -17
  59. package/backend/ws/db-client/io.ts +7 -9
  60. package/backend/ws/db-client/query.ts +83 -31
  61. package/backend/ws/db-client/schema.ts +9 -4
  62. package/backend/ws/db-client/structure.ts +22 -10
  63. package/backend/ws/engine/access.ts +39 -0
  64. package/backend/ws/engine/claude/accounts.ts +15 -10
  65. package/backend/ws/engine/codex/accounts.ts +516 -0
  66. package/backend/ws/engine/codex/index.ts +14 -0
  67. package/backend/ws/engine/codex/status.ts +87 -0
  68. package/backend/ws/engine/copilot/accounts.ts +122 -0
  69. package/backend/ws/engine/copilot/index.ts +13 -0
  70. package/backend/ws/engine/copilot/status.ts +54 -0
  71. package/backend/ws/engine/index.ts +7 -1
  72. package/backend/ws/engine/opencode/providers.ts +1 -1
  73. package/backend/ws/engine/qwen/accounts.ts +137 -0
  74. package/backend/ws/engine/qwen/index.ts +15 -0
  75. package/backend/ws/engine/qwen/presets.ts +40 -0
  76. package/backend/ws/engine/qwen/status.ts +54 -0
  77. package/backend/ws/files/read.ts +3 -1
  78. package/backend/ws/files/state.ts +3 -0
  79. package/backend/ws/files/watch.ts +7 -1
  80. package/backend/ws/git/branch.ts +13 -19
  81. package/backend/ws/git/commit-message.ts +3 -4
  82. package/backend/ws/git/commit.ts +5 -7
  83. package/backend/ws/git/conflict.ts +7 -10
  84. package/backend/ws/git/diff.ts +7 -10
  85. package/backend/ws/git/log.ts +3 -4
  86. package/backend/ws/git/remote.ts +30 -43
  87. package/backend/ws/git/staging.ts +13 -19
  88. package/backend/ws/git/status.ts +7 -11
  89. package/backend/ws/messages/crud.ts +7 -13
  90. package/backend/ws/preview/access.ts +45 -0
  91. package/backend/ws/preview/browser/cleanup.ts +3 -11
  92. package/backend/ws/preview/browser/console.ts +5 -40
  93. package/backend/ws/preview/browser/interact.ts +2 -6
  94. package/backend/ws/preview/browser/native-ui.ts +5 -18
  95. package/backend/ws/preview/browser/stats.ts +2 -12
  96. package/backend/ws/preview/browser/tab-info.ts +4 -20
  97. package/backend/ws/preview/browser/tab.ts +4 -27
  98. package/backend/ws/preview/browser/webcodecs.ts +6 -47
  99. package/backend/ws/projects/crud.ts +4 -10
  100. package/backend/ws/projects/status.ts +2 -0
  101. package/backend/ws/sessions/crud.ts +22 -33
  102. package/backend/ws/settings/crud.ts +13 -13
  103. package/backend/ws/snapshot/restore.ts +5 -2
  104. package/backend/ws/snapshot/timeline.ts +3 -1
  105. package/backend/ws/system-tools/access.ts +28 -0
  106. package/backend/ws/system-tools/install.ts +13 -4
  107. package/backend/ws/system-tools/status.ts +5 -2
  108. package/backend/ws/terminal/access.ts +56 -0
  109. package/backend/ws/terminal/persistence.ts +12 -6
  110. package/backend/ws/terminal/session.ts +35 -14
  111. package/backend/ws/terminal/stream.ts +4 -1
  112. package/dist/assets/{index-DqAGCTFT.js → index-D8V2wj9B.js} +2 -2
  113. package/dist/assets/{main-DsED0rLr.js → main-C9nYVmnw.js} +206 -198
  114. package/dist/assets/main-hspyFOoK.css +1 -0
  115. package/dist/index.html +2 -2
  116. package/package.json +4 -1
  117. package/shared/constants/engines.ts +45 -140
  118. package/shared/types/database/schema.ts +1 -0
  119. package/shared/types/unified/common.ts +1 -1
  120. package/shared/types/unified/engine.ts +29 -1
  121. package/shared/types/unified/index.ts +2 -0
  122. package/shared/types/unified/message.ts +1 -1
  123. package/shared/types/unified/tool.ts +17 -2
  124. package/shared/utils/ws-server.ts +14 -0
  125. package/dist/assets/main-eWY9R8g9.css +0 -1
@@ -0,0 +1,646 @@
1
+ /**
2
+ * Codex SDK → Unified Type Converters
3
+ *
4
+ * Translates Codex `ThreadEvent` objects into `EngineOutput` (unified types)
5
+ * so the stream-manager and frontend can stay engine-agnostic.
6
+ *
7
+ * Streaming model — live emission:
8
+ *
9
+ * thread.started → SystemInitEvent (capture thread_id)
10
+ * turn.started → StreamLifecycleEvent { event:'start' }
11
+ * item.started (reasoning) → StreamLifecycleEvent { reasoning:true, event:'start' }
12
+ * item.updated (reasoning, cumulative text) → TextDeltaEvent { reasoning:true, delta:<diff> }
13
+ * item.updated (agent_message, cumulative) → TextDeltaEvent { reasoning:false, delta:<diff> }
14
+ * item.updated (todo_list) → AssistantMessage(tool_use:TodoWrite) live
15
+ * item.completed (todo_list) → AssistantMessage(tool_use:TodoWrite) + UserMessage(tool_result)
16
+ * item.completed (reasoning) → StreamLifecycleEvent { reasoning:true, event:'stop' }
17
+ * item.completed (agent_message) → AssistantMessage live
18
+ * item.completed (command_execution) → AssistantMessage(tool_use:Bash) + UserMessage(tool_result)
19
+ * item.completed (file_change) → split N file changes → N AssistantMessage(tool_use)
20
+ * item.completed (mcp_tool_call) → AssistantMessage(tool_use) + UserMessage(tool_result)
21
+ * item.completed (web_search, non-empty query) → AssistantMessage(tool_use:WebSearch) + UserMessage(tool_result)
22
+ * (empty query → dropped — model emitted a malformed/interrupted call)
23
+ * item.completed (error) → UserMessage live (non-fatal notification)
24
+ * turn.completed (with usage) → StreamLifecycleEvent { event:'stop' } (usage captured)
25
+ * turn.failed → throw via handleStreamError
26
+ * error → throw via handleStreamError
27
+ *
28
+ * Usage attribution — Codex emits `usage` ONLY ONCE per turn, AFTER all items
29
+ * have streamed. Live emission means tool_use messages get persisted before
30
+ * usage is known. To ensure tool_use rows still carry usage in the DB (and
31
+ * therefore after refresh), the stream-manager performs a post-stream
32
+ * backfill on the `result` event for Codex streams: every saved assistant
33
+ * with `usage: null` is updated with the turn's aggregate. See
34
+ * stream-manager.ts → `backfillUsageForStream`.
35
+ *
36
+ * Usage source — `event.usage` from the SDK is the SUM of `input_tokens`
37
+ * across every internal API call within the turn (cost-accounting view).
38
+ * For the context-window % indicator we want PER-CALL input, so we read
39
+ * `last_token_usage` from the rollout JSONL after `turn.completed`. See
40
+ * ./usage-rollout.ts.
41
+ */
42
+
43
+ import type { MessageEngine } from '$shared/types/unified';
44
+ import type {
45
+ EngineOutput,
46
+ UserMessage,
47
+ AssistantMessage as UnifiedAssistantMessage,
48
+ AssistantContentBlock,
49
+ UserContentBlock,
50
+ ToolUseBlock,
51
+ TextDeltaEvent,
52
+ StreamLifecycleEvent,
53
+ SuccessResultEvent,
54
+ SystemInitEvent,
55
+ TokenUsage,
56
+ BashInput,
57
+ WriteInput,
58
+ EditInput,
59
+ WebSearchInput,
60
+ TodoWriteInput,
61
+ } from '$shared/types/unified';
62
+ import { toCanonicalToolName } from '$shared/types/unified';
63
+ import type {
64
+ ThreadEvent,
65
+ ThreadItem,
66
+ Usage,
67
+ CommandExecutionItem,
68
+ FileChangeItem,
69
+ McpToolCallItem,
70
+ AgentMessageItem,
71
+ ReasoningItem,
72
+ WebSearchItem,
73
+ TodoListItem,
74
+ ErrorItem,
75
+ ThreadStartedEvent,
76
+ TurnCompletedEvent,
77
+ } from '@openai/codex-sdk';
78
+ import { resolveOpenCodeToolName } from '../../../mcp/config';
79
+ import { readLastTokenUsageFromRollout } from './usage-rollout';
80
+ import { readApplyPatchesFromRollout, findMatchingPatch } from './patch-rollout';
81
+
82
+ // ============================================================================
83
+ // Engine Identity
84
+ // ============================================================================
85
+
86
+ export function buildEngine(modelId: string): MessageEngine {
87
+ return {
88
+ type: 'codex',
89
+ provider: 'openai',
90
+ model: { id: modelId, name: '' },
91
+ account: { id: 0, name: '' },
92
+ };
93
+ }
94
+
95
+ // ============================================================================
96
+ // Per-stream State
97
+ // ============================================================================
98
+
99
+ export interface CodexStreamState {
100
+ sessionId: string;
101
+ modelId: string;
102
+ /** Cumulative reasoning text already streamed per item id (for diffing). */
103
+ reasoningSent: Map<string, string>;
104
+ /** Cumulative agent_message text already streamed per item id (for diffing). */
105
+ agentMessageSent: Map<string, string>;
106
+ /** Whether the reasoning lifecycle is currently open. */
107
+ reasoningStreamActive: boolean;
108
+ /** Last seen usage (carried across turns into ResultEvent). */
109
+ lastUsage: Usage | null;
110
+ /** Stop reason for the current/last turn. */
111
+ stopReason: 'end_turn' | 'tool_use' | 'interrupted' | null;
112
+ /** Total turn count for ResultEvent. */
113
+ numTurns: number;
114
+ }
115
+
116
+ export function createCodexState(sessionId: string, modelId: string): CodexStreamState {
117
+ return {
118
+ sessionId,
119
+ modelId,
120
+ reasoningSent: new Map(),
121
+ agentMessageSent: new Map(),
122
+ reasoningStreamActive: false,
123
+ lastUsage: null,
124
+ stopReason: null,
125
+ numTurns: 0,
126
+ };
127
+ }
128
+
129
+ // ============================================================================
130
+ // Tool name + input mapping
131
+ // ============================================================================
132
+
133
+ function canonicalizeMcpToolName(server: string, tool: string): string {
134
+ // Codex prefixes MCP tools with the server name (`<server>__<tool>` or
135
+ // `<server>.<tool>` depending on the CLI version). We prefer the
136
+ // shared mcp config resolver so the resulting `mcp__server__tool` name
137
+ // matches what other engines emit.
138
+ const candidate = `${server}__${tool}`;
139
+ const resolved = resolveOpenCodeToolName(candidate) ?? resolveOpenCodeToolName(`clopen-mcp_${tool}`);
140
+ if (resolved) return toCanonicalToolName(resolved);
141
+ return toCanonicalToolName(`mcp__${server}__${tool}`);
142
+ }
143
+
144
+ // ============================================================================
145
+ // Event entry points
146
+ // ============================================================================
147
+
148
+ export function convertThreadStarted(event: ThreadStartedEvent, state: CodexStreamState): EngineOutput[] {
149
+ state.sessionId = event.thread_id;
150
+ const init: SystemInitEvent = {
151
+ type: 'system_init',
152
+ sessionId: event.thread_id,
153
+ model: state.modelId,
154
+ engine: 'codex',
155
+ tools: [],
156
+ mcpServers: [{ name: 'clopen-mcp', status: 'connected' }],
157
+ };
158
+ return [init];
159
+ }
160
+
161
+ export function convertTurnStarted(state: CodexStreamState): EngineOutput[] {
162
+ state.numTurns += 1;
163
+ state.stopReason = null;
164
+ const start: StreamLifecycleEvent = {
165
+ type: 'stream_event',
166
+ event: 'start',
167
+ sessionId: state.sessionId,
168
+ reasoning: false,
169
+ };
170
+ return [start];
171
+ }
172
+
173
+ export function convertItemStarted(event: { item: ThreadItem }, state: CodexStreamState): EngineOutput[] {
174
+ const item = event.item;
175
+ if (item.type === 'reasoning') {
176
+ if (!state.reasoningStreamActive) {
177
+ state.reasoningStreamActive = true;
178
+ state.reasoningSent.set(item.id, '');
179
+ const lifecycle: StreamLifecycleEvent = {
180
+ type: 'stream_event',
181
+ event: 'start',
182
+ sessionId: state.sessionId,
183
+ reasoning: true,
184
+ };
185
+ return [lifecycle];
186
+ }
187
+ }
188
+
189
+ return [];
190
+ }
191
+
192
+ export function convertItemUpdated(event: { item: ThreadItem }, state: CodexStreamState): EngineOutput[] {
193
+ const item = event.item;
194
+
195
+ if (item.type === 'reasoning') {
196
+ // Codex sends cumulative reasoning text on each update — diff against
197
+ // what we've already streamed so the UI sees only the new suffix.
198
+ return diffReasoning(item, state);
199
+ }
200
+
201
+ if (item.type === 'agent_message') {
202
+ // Stream agent text the same way: cumulative diff → TextDeltaEvent.
203
+ return diffAgentMessage(item, state);
204
+ }
205
+
206
+ if (item.type === 'todo_list') {
207
+ // Live emit so todos appear progressively. Each emit is a separate
208
+ // AssistantMessage(tool_use:TodoWrite); the frontend grouper
209
+ // dedups by tool-use id at render time.
210
+ return [buildTodoAssistantMessage(item, state)];
211
+ }
212
+
213
+ return [];
214
+ }
215
+
216
+ export function convertItemCompleted(event: { item: ThreadItem }, state: CodexStreamState): EngineOutput[] {
217
+ const item = event.item;
218
+ switch (item.type) {
219
+ case 'reasoning':
220
+ return finalizeReasoning(item, state);
221
+ case 'agent_message':
222
+ return [buildAgentAssistantMessage(item, state)];
223
+ case 'command_execution':
224
+ return buildCommandExecutionPair(item, state);
225
+ case 'file_change':
226
+ return buildFileChangePair(item, state);
227
+ case 'mcp_tool_call':
228
+ return handleMcpToolCallCompleted(item, state);
229
+ case 'web_search':
230
+ return buildWebSearchPair(item, state);
231
+ case 'todo_list':
232
+ return buildTodoListCompletedPair(item, state);
233
+ case 'error':
234
+ return [buildErrorUserMessage(item, state)];
235
+ }
236
+ return [];
237
+ }
238
+
239
+ export function convertTurnCompleted(event: TurnCompletedEvent, state: CodexStreamState): EngineOutput[] {
240
+ // `event.usage` from the SDK is the SUM of `input_tokens` across every
241
+ // internal API call within this turn (so a 5-tool-call turn reports ~5×
242
+ // the actual prompt size). Prefer `last_token_usage` from the CLI's
243
+ // rollout JSONL — that's the real per-call context-window load. Fall
244
+ // back to `event.usage` if the rollout file isn't readable.
245
+ // TODO(codex-sdk): once the SDK exposes per-call usage natively, replace
246
+ // `readLastTokenUsageFromRollout` with the SDK field and delete
247
+ // ./usage-rollout.ts (see migration steps in that file's header).
248
+ const rolloutUsage = readLastTokenUsageFromRollout(state.sessionId);
249
+ state.lastUsage = rolloutUsage ?? event.usage ?? state.lastUsage;
250
+ if (state.stopReason === null) {
251
+ state.stopReason = 'end_turn';
252
+ }
253
+
254
+ // Note: the per-turn `usage` aggregate is NOT attached to individual
255
+ // assistant messages here — they were already saved live during the turn
256
+ // (with usage:null). The stream-manager backfills usage after the result
257
+ // event by looking up each saved row's DB id. See README §9.4.
258
+
259
+ const stopLifecycle: StreamLifecycleEvent = {
260
+ type: 'stream_event',
261
+ event: 'stop',
262
+ sessionId: state.sessionId,
263
+ reasoning: false,
264
+ };
265
+
266
+ return [stopLifecycle];
267
+ }
268
+
269
+ export function buildResultEvent(state: CodexStreamState, aborted: boolean): SuccessResultEvent {
270
+ const usage = mapUsage(state.lastUsage);
271
+ return {
272
+ type: 'result',
273
+ subtype: 'success',
274
+ sessionId: state.sessionId,
275
+ numTurns: state.numTurns,
276
+ totalCostUsd: 0,
277
+ usage,
278
+ stopReason: aborted ? 'interrupted' : (state.stopReason ?? 'end_turn'),
279
+ };
280
+ }
281
+
282
+ // ============================================================================
283
+ // Reasoning helpers
284
+ // ============================================================================
285
+
286
+ function diffReasoning(item: ReasoningItem, state: CodexStreamState): EngineOutput[] {
287
+ const previous = state.reasoningSent.get(item.id) ?? '';
288
+ const next = item.text ?? '';
289
+ if (next.length <= previous.length) return [];
290
+ const delta = next.slice(previous.length);
291
+ state.reasoningSent.set(item.id, next);
292
+
293
+ const out: EngineOutput[] = [];
294
+ if (!state.reasoningStreamActive) {
295
+ state.reasoningStreamActive = true;
296
+ out.push({
297
+ type: 'stream_event',
298
+ event: 'start',
299
+ sessionId: state.sessionId,
300
+ reasoning: true,
301
+ } as StreamLifecycleEvent);
302
+ }
303
+ out.push({
304
+ type: 'stream_event',
305
+ event: 'delta',
306
+ sessionId: state.sessionId,
307
+ text: delta,
308
+ reasoning: true,
309
+ } as TextDeltaEvent);
310
+ return out;
311
+ }
312
+
313
+ function finalizeReasoning(item: ReasoningItem, state: CodexStreamState): EngineOutput[] {
314
+ const out: EngineOutput[] = [];
315
+ const previous = state.reasoningSent.get(item.id) ?? '';
316
+ const fullText = item.text ?? '';
317
+ if (fullText.length > previous.length) {
318
+ out.push({
319
+ type: 'stream_event',
320
+ event: 'delta',
321
+ sessionId: state.sessionId,
322
+ text: fullText.slice(previous.length),
323
+ reasoning: true,
324
+ } as TextDeltaEvent);
325
+ }
326
+ state.reasoningSent.delete(item.id);
327
+
328
+ if (state.reasoningStreamActive) {
329
+ state.reasoningStreamActive = false;
330
+ out.push({
331
+ type: 'stream_event',
332
+ event: 'stop',
333
+ sessionId: state.sessionId,
334
+ reasoning: true,
335
+ } as StreamLifecycleEvent);
336
+ }
337
+
338
+ if (fullText.trim()) {
339
+ out.push({
340
+ type: 'reasoning',
341
+ createdAt: new Date().toISOString(),
342
+ messageId: crypto.randomUUID(),
343
+ sessionId: state.sessionId,
344
+ parent: { messageId: null, sessionId: null, toolUseId: null },
345
+ engine: buildEngine(state.modelId),
346
+ text: fullText,
347
+ });
348
+ }
349
+
350
+ return out;
351
+ }
352
+
353
+ // ============================================================================
354
+ // Agent-message text helpers
355
+ // ============================================================================
356
+
357
+ function diffAgentMessage(item: AgentMessageItem, state: CodexStreamState): EngineOutput[] {
358
+ const previous = state.agentMessageSent.get(item.id) ?? '';
359
+ const next = item.text ?? '';
360
+ if (next.length <= previous.length) return [];
361
+ const delta = next.slice(previous.length);
362
+ state.agentMessageSent.set(item.id, next);
363
+
364
+ return [{
365
+ type: 'stream_event',
366
+ event: 'delta',
367
+ sessionId: state.sessionId,
368
+ text: delta,
369
+ reasoning: false,
370
+ } as TextDeltaEvent];
371
+ }
372
+
373
+ // ============================================================================
374
+ // Assistant message builders
375
+ // ============================================================================
376
+
377
+ function buildAgentAssistantMessage(item: AgentMessageItem, state: CodexStreamState): UnifiedAssistantMessage {
378
+ state.agentMessageSent.delete(item.id);
379
+ return {
380
+ type: 'assistant',
381
+ createdAt: new Date().toISOString(),
382
+ messageId: item.id || crypto.randomUUID(),
383
+ sessionId: state.sessionId,
384
+ parent: { messageId: null, sessionId: null, toolUseId: null },
385
+ engine: buildEngine(state.modelId),
386
+ content: [{ type: 'text', text: item.text ?? '' }],
387
+ stopReason: 'end_turn',
388
+ usage: null,
389
+ };
390
+ }
391
+
392
+ function buildToolUseBlock(name: string, input: Record<string, unknown>, id: string): ToolUseBlock {
393
+ return {
394
+ type: 'tool_use',
395
+ id,
396
+ name: toCanonicalToolName(name),
397
+ input,
398
+ result: null,
399
+ subActivities: [],
400
+ skillPrompt: null,
401
+ interrupted: false,
402
+ } as ToolUseBlock;
403
+ }
404
+
405
+ function createAssistantToolUseMessage(
406
+ state: CodexStreamState,
407
+ block: ToolUseBlock,
408
+ baseId: string,
409
+ idx?: number,
410
+ ): UnifiedAssistantMessage {
411
+ const messageId = idx === undefined ? baseId : `${baseId}:${idx}`;
412
+ return {
413
+ type: 'assistant',
414
+ createdAt: new Date().toISOString(),
415
+ messageId,
416
+ sessionId: state.sessionId,
417
+ parent: { messageId: null, sessionId: null, toolUseId: null },
418
+ engine: buildEngine(state.modelId),
419
+ content: [block as AssistantContentBlock],
420
+ stopReason: 'tool_use',
421
+ usage: null,
422
+ };
423
+ }
424
+
425
+ function buildToolResultUserMessage(
426
+ toolUseId: string,
427
+ content: string,
428
+ isError: boolean,
429
+ state: CodexStreamState,
430
+ ): UserMessage {
431
+ const block: UserContentBlock = {
432
+ type: 'tool_result',
433
+ toolUseId,
434
+ content,
435
+ isError,
436
+ };
437
+ return {
438
+ type: 'user',
439
+ createdAt: new Date().toISOString(),
440
+ messageId: crypto.randomUUID(),
441
+ sessionId: state.sessionId,
442
+ // IMPORTANT: parent.toolUseId stays null (README §9.5 sharp edge).
443
+ parent: { messageId: null, sessionId: null, toolUseId: null },
444
+ engine: buildEngine(state.modelId),
445
+ sender: { id: '', name: '' },
446
+ content: [block],
447
+ synthetic: true,
448
+ };
449
+ }
450
+
451
+ function buildCommandExecutionPair(item: CommandExecutionItem, state: CodexStreamState): EngineOutput[] {
452
+ const input: BashInput = { command: item.command };
453
+ const block = buildToolUseBlock('Bash', input as unknown as Record<string, unknown>, item.id);
454
+ const assistant = createAssistantToolUseMessage(state, block, item.id);
455
+ const result = buildToolResultUserMessage(
456
+ item.id,
457
+ item.aggregated_output ?? '',
458
+ item.status === 'failed' || (typeof item.exit_code === 'number' && item.exit_code !== 0),
459
+ state,
460
+ );
461
+ state.stopReason = 'tool_use';
462
+ return [assistant, result];
463
+ }
464
+
465
+ function buildFileChangePair(item: FileChangeItem, state: CodexStreamState): EngineOutput[] {
466
+ // Codex bundles N file changes per item. Per README §9.3 we split into N
467
+ // separate AssistantMessages so each shows up as its own tool block.
468
+ const out: EngineOutput[] = [];
469
+ const baseId = item.id;
470
+ const isFailed = item.status === 'failed';
471
+
472
+ // SDK doesn't carry diff content on FileUpdateChange — pull it from the
473
+ // rollout JSONL's apply_patch envelope so Edit blocks render real before/
474
+ // after text. Falls back to empty strings if the rollout isn't readable.
475
+ const updatePaths = item.changes.filter(c => c.kind === 'update').map(c => c.path);
476
+ const matchedPatch = updatePaths.length > 0
477
+ ? findMatchingPatch(readApplyPatchesFromRollout(state.sessionId), updatePaths)
478
+ : null;
479
+
480
+ item.changes.forEach((change, idx) => {
481
+ const toolId = `${baseId}:${idx}`;
482
+ let toolName: string;
483
+ let input: Record<string, unknown>;
484
+
485
+ if (change.kind === 'add') {
486
+ toolName = 'Write';
487
+ input = { filePath: change.path, content: '' } satisfies WriteInput as unknown as Record<string, unknown>;
488
+ } else if (change.kind === 'update') {
489
+ toolName = 'Edit';
490
+ const diff = matchedPatch?.get(change.path);
491
+ input = {
492
+ filePath: change.path,
493
+ oldString: diff?.oldString ?? '',
494
+ newString: diff?.newString ?? '',
495
+ } satisfies EditInput as unknown as Record<string, unknown>;
496
+ } else {
497
+ // delete → no canonical UI; map to Bash `rm <path>` so the user
498
+ // at least sees what was removed (plan §4.2).
499
+ toolName = 'Bash';
500
+ input = {
501
+ command: `rm ${JSON.stringify(change.path)}`,
502
+ description: `Codex deleted ${change.path}`,
503
+ } satisfies BashInput as unknown as Record<string, unknown>;
504
+ }
505
+
506
+ const block = buildToolUseBlock(toolName, input, toolId);
507
+ const assistant = createAssistantToolUseMessage(state, block, baseId, idx);
508
+ const result = buildToolResultUserMessage(
509
+ toolId,
510
+ isFailed ? `File change failed: ${change.path}` : `Applied ${change.kind} to ${change.path}`,
511
+ isFailed,
512
+ state,
513
+ );
514
+ out.push(assistant, result);
515
+ });
516
+ state.stopReason = 'tool_use';
517
+ return out;
518
+ }
519
+
520
+ function handleMcpToolCallCompleted(item: McpToolCallItem, state: CodexStreamState): EngineOutput[] {
521
+ const isError = item.status === 'failed' || !!item.error;
522
+ const resultText = extractMcpResultText(item);
523
+
524
+ const canonical = canonicalizeMcpToolName(item.server, item.tool);
525
+ const args = (item.arguments ?? {}) as Record<string, unknown>;
526
+ const block = buildToolUseBlock(canonical, args, item.id);
527
+ const assistant = createAssistantToolUseMessage(state, block, item.id);
528
+ const result = buildToolResultUserMessage(item.id, resultText, isError, state);
529
+ state.stopReason = 'tool_use';
530
+ return [assistant, result];
531
+ }
532
+
533
+ function extractMcpResultText(item: McpToolCallItem): string {
534
+ if (item.error?.message) return `Error: ${item.error.message}`;
535
+ if (!item.result) return '';
536
+ const blocks = item.result.content;
537
+ if (!Array.isArray(blocks)) return '';
538
+ const parts: string[] = [];
539
+ for (const b of blocks) {
540
+ if (b && typeof b === 'object' && 'text' in b && typeof (b as { text: unknown }).text === 'string') {
541
+ parts.push((b as { text: string }).text);
542
+ }
543
+ }
544
+ return parts.join('\n');
545
+ }
546
+
547
+ function buildWebSearchPair(item: WebSearchItem, state: CodexStreamState): EngineOutput[] {
548
+ // The Codex SDK's WebSearchItem only carries the query — search results
549
+ // are fed to the model directly and never surfaced to the adapter. If the
550
+ // query is empty (model emitted a malformed call, or the turn was
551
+ // interrupted before the call finalized), drop the entire pair so the UI
552
+ // doesn't render a tool block with `query: ""` and `result: null`.
553
+ const query = (item.query ?? '').trim();
554
+ if (!query) return [];
555
+
556
+ const input: WebSearchInput = { query };
557
+ const block = buildToolUseBlock('WebSearch', input as unknown as Record<string, unknown>, item.id);
558
+ const assistant = createAssistantToolUseMessage(state, block, item.id);
559
+ // Synthetic tool_result so the frontend grouper attaches a non-null
560
+ // result at render time (README §9.5). Without it `tool_use.result`
561
+ // stays null forever.
562
+ const result = buildToolResultUserMessage(
563
+ item.id,
564
+ `Searched the web for: ${query}`,
565
+ false,
566
+ state,
567
+ );
568
+ state.stopReason = 'tool_use';
569
+ return [assistant, result];
570
+ }
571
+
572
+ function buildTodoAssistantMessage(item: TodoListItem, state: CodexStreamState): UnifiedAssistantMessage {
573
+ const todos: TodoWriteInput['todos'] = item.items.map(t => ({
574
+ content: t.text,
575
+ status: t.completed ? 'completed' : 'pending',
576
+ activeForm: t.text,
577
+ }));
578
+ const input: TodoWriteInput = { todos };
579
+ const block = buildToolUseBlock('TodoWrite', input as unknown as Record<string, unknown>, item.id);
580
+ return createAssistantToolUseMessage(state, block, item.id);
581
+ }
582
+
583
+ function buildTodoListCompletedPair(item: TodoListItem, state: CodexStreamState): EngineOutput[] {
584
+ // item.updated emits multiple progressive snapshots (no tool_result), and
585
+ // the grouper's toolUseMap.set() overwrites prior entries so the LAST
586
+ // assistant for this tool_use.id wins. Pair the final completion with a
587
+ // synthetic tool_result so that final entry has a non-null result after
588
+ // refresh — without this the TodoWrite block stays "in progress" forever.
589
+ const assistant = buildTodoAssistantMessage(item, state);
590
+ const completedCount = item.items.filter(t => t.completed).length;
591
+ const result = buildToolResultUserMessage(
592
+ item.id,
593
+ `Todos updated (${completedCount}/${item.items.length} completed)`,
594
+ false,
595
+ state,
596
+ );
597
+ return [assistant, result];
598
+ }
599
+
600
+ function buildErrorUserMessage(item: ErrorItem, state: CodexStreamState): UserMessage {
601
+ // Item-level (non-fatal) errors surface as a synthetic user message so
602
+ // the UI shows them inline rather than terminating the stream.
603
+ return {
604
+ type: 'user',
605
+ createdAt: new Date().toISOString(),
606
+ messageId: crypto.randomUUID(),
607
+ sessionId: state.sessionId,
608
+ parent: { messageId: null, sessionId: null, toolUseId: null },
609
+ engine: buildEngine(state.modelId),
610
+ sender: { id: '', name: '' },
611
+ content: [{ type: 'text', text: `Codex error: ${item.message}` }],
612
+ synthetic: true,
613
+ };
614
+ }
615
+
616
+ // ============================================================================
617
+ // Helpers
618
+ // ============================================================================
619
+
620
+ /**
621
+ * Map Codex `Usage` → unified `TokenUsage`.
622
+ *
623
+ * Codex follows the OpenAI convention where `input_tokens` is the TOTAL
624
+ * prompt size including any cached prefix, and `cached_input_tokens` is the
625
+ * portion served from cache. The unified shape (Anthropic-aligned) treats
626
+ * `inputTokens` as the FRESH prompt only — cached tokens go on
627
+ * `cacheReadInputTokens`. Subtract here, otherwise the frontend's context
628
+ * window indicator (which sums input + cacheCreate + cacheRead) would
629
+ * double-count the cached prefix and appear to fill up far too quickly.
630
+ */
631
+ function mapUsage(raw: Usage | null): TokenUsage {
632
+ if (!raw) {
633
+ return { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0 };
634
+ }
635
+ const totalInput = raw.input_tokens ?? 0;
636
+ const cached = raw.cached_input_tokens ?? 0;
637
+ return {
638
+ inputTokens: Math.max(0, totalInput - cached),
639
+ outputTokens: (raw.output_tokens ?? 0) + (raw.reasoning_output_tokens ?? 0),
640
+ cacheCreationInputTokens: 0,
641
+ cacheReadInputTokens: cached,
642
+ };
643
+ }
644
+
645
+ // Re-export so the stream can import the union-narrowing helper
646
+ export type { ThreadEvent };