@percena/weft 0.4.0-next.3 → 0.4.0-next.5

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 (81) hide show
  1. package/dist/action-bridge.cjs +172 -6
  2. package/dist/action-bridge.d.cts +112 -13
  3. package/dist/action-bridge.d.ts +112 -13
  4. package/dist/action-bridge.js +166 -4
  5. package/dist/chat.cjs +982 -3
  6. package/dist/chat.d.cts +30 -1
  7. package/dist/chat.d.ts +30 -1
  8. package/dist/chat.js +981 -2
  9. package/dist/index.cjs +341 -1616
  10. package/dist/index.d.cts +4 -274
  11. package/dist/index.d.ts +4 -274
  12. package/dist/index.js +174 -1408
  13. package/dist/styles/fonts/KaTeX_AMS-Regular.ttf +0 -0
  14. package/dist/styles/fonts/KaTeX_AMS-Regular.woff +0 -0
  15. package/dist/styles/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  16. package/dist/styles/fonts/KaTeX_Caligraphic-Bold.ttf +0 -0
  17. package/dist/styles/fonts/KaTeX_Caligraphic-Bold.woff +0 -0
  18. package/dist/styles/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  19. package/dist/styles/fonts/KaTeX_Caligraphic-Regular.ttf +0 -0
  20. package/dist/styles/fonts/KaTeX_Caligraphic-Regular.woff +0 -0
  21. package/dist/styles/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  22. package/dist/styles/fonts/KaTeX_Fraktur-Bold.ttf +0 -0
  23. package/dist/styles/fonts/KaTeX_Fraktur-Bold.woff +0 -0
  24. package/dist/styles/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  25. package/dist/styles/fonts/KaTeX_Fraktur-Regular.ttf +0 -0
  26. package/dist/styles/fonts/KaTeX_Fraktur-Regular.woff +0 -0
  27. package/dist/styles/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  28. package/dist/styles/fonts/KaTeX_Main-Bold.ttf +0 -0
  29. package/dist/styles/fonts/KaTeX_Main-Bold.woff +0 -0
  30. package/dist/styles/fonts/KaTeX_Main-Bold.woff2 +0 -0
  31. package/dist/styles/fonts/KaTeX_Main-BoldItalic.ttf +0 -0
  32. package/dist/styles/fonts/KaTeX_Main-BoldItalic.woff +0 -0
  33. package/dist/styles/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  34. package/dist/styles/fonts/KaTeX_Main-Italic.ttf +0 -0
  35. package/dist/styles/fonts/KaTeX_Main-Italic.woff +0 -0
  36. package/dist/styles/fonts/KaTeX_Main-Italic.woff2 +0 -0
  37. package/dist/styles/fonts/KaTeX_Main-Regular.ttf +0 -0
  38. package/dist/styles/fonts/KaTeX_Main-Regular.woff +0 -0
  39. package/dist/styles/fonts/KaTeX_Main-Regular.woff2 +0 -0
  40. package/dist/styles/fonts/KaTeX_Math-BoldItalic.ttf +0 -0
  41. package/dist/styles/fonts/KaTeX_Math-BoldItalic.woff +0 -0
  42. package/dist/styles/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  43. package/dist/styles/fonts/KaTeX_Math-Italic.ttf +0 -0
  44. package/dist/styles/fonts/KaTeX_Math-Italic.woff +0 -0
  45. package/dist/styles/fonts/KaTeX_Math-Italic.woff2 +0 -0
  46. package/dist/styles/fonts/KaTeX_SansSerif-Bold.ttf +0 -0
  47. package/dist/styles/fonts/KaTeX_SansSerif-Bold.woff +0 -0
  48. package/dist/styles/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  49. package/dist/styles/fonts/KaTeX_SansSerif-Italic.ttf +0 -0
  50. package/dist/styles/fonts/KaTeX_SansSerif-Italic.woff +0 -0
  51. package/dist/styles/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  52. package/dist/styles/fonts/KaTeX_SansSerif-Regular.ttf +0 -0
  53. package/dist/styles/fonts/KaTeX_SansSerif-Regular.woff +0 -0
  54. package/dist/styles/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  55. package/dist/styles/fonts/KaTeX_Script-Regular.ttf +0 -0
  56. package/dist/styles/fonts/KaTeX_Script-Regular.woff +0 -0
  57. package/dist/styles/fonts/KaTeX_Script-Regular.woff2 +0 -0
  58. package/dist/styles/fonts/KaTeX_Size1-Regular.ttf +0 -0
  59. package/dist/styles/fonts/KaTeX_Size1-Regular.woff +0 -0
  60. package/dist/styles/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  61. package/dist/styles/fonts/KaTeX_Size2-Regular.ttf +0 -0
  62. package/dist/styles/fonts/KaTeX_Size2-Regular.woff +0 -0
  63. package/dist/styles/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  64. package/dist/styles/fonts/KaTeX_Size3-Regular.ttf +0 -0
  65. package/dist/styles/fonts/KaTeX_Size3-Regular.woff +0 -0
  66. package/dist/styles/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  67. package/dist/styles/fonts/KaTeX_Size4-Regular.ttf +0 -0
  68. package/dist/styles/fonts/KaTeX_Size4-Regular.woff +0 -0
  69. package/dist/styles/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  70. package/dist/styles/fonts/KaTeX_Typewriter-Regular.ttf +0 -0
  71. package/dist/styles/fonts/KaTeX_Typewriter-Regular.woff +0 -0
  72. package/dist/styles/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  73. package/package.json +2 -30
  74. package/dist/local-runtime.cjs +0 -1387
  75. package/dist/local-runtime.d.cts +0 -3314
  76. package/dist/local-runtime.d.ts +0 -3314
  77. package/dist/local-runtime.js +0 -1345
  78. package/dist/skills-browser.cjs +0 -118
  79. package/dist/skills-browser.d.cts +0 -105
  80. package/dist/skills-browser.d.ts +0 -105
  81. package/dist/skills-browser.js +0 -88
@@ -1,1387 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/local-runtime.ts
21
- var local_runtime_exports = {};
22
- __export(local_runtime_exports, {
23
- ClaudeStdoutAdapter: () => ClaudeStdoutAdapter,
24
- CodexRolloutAdapter: () => CodexRolloutAdapter,
25
- PushAgentEventStream: () => PushAgentEventStream,
26
- TraceEventAdapter: () => TraceEventAdapter,
27
- TraceToolIndex: () => TraceToolIndex,
28
- createFakeLocalAgentSession: () => createFakeLocalAgentSession,
29
- createLocalTimelineProjector: () => createLocalTimelineProjector,
30
- generateTraceToolUseId: () => generateTraceToolUseId,
31
- generateTraceTurnId: () => generateTraceTurnId,
32
- initialRuntimeState: () => initialRuntimeState,
33
- mapClaudeStreamJsonLine: () => mapClaudeStreamJsonLine,
34
- mapCodexExecJsonLine: () => mapCodexExecJsonLine,
35
- parseClaudeStdoutTrace: () => parseClaudeStdoutTrace,
36
- parseCodexRolloutTrace: () => parseCodexRolloutTrace,
37
- parseTraceReadCommand: () => parseTraceReadCommand,
38
- reduceRuntimeEvents: () => reduceRuntimeState
39
- });
40
- module.exports = __toCommonJS(local_runtime_exports);
41
-
42
- // ../packages/timeline/dist/index.js
43
- function createTimelineSequencer(options) {
44
- let seq = options.startSeq ?? 0;
45
- const now = options.now ?? Date.now;
46
- return {
47
- append(item, rawRef) {
48
- seq += 1;
49
- return appendTimelineItem({
50
- sessionId: options.sessionId,
51
- provider: options.provider,
52
- epoch: options.epoch,
53
- seq,
54
- timestamp: now(),
55
- item,
56
- rawRef
57
- });
58
- }
59
- };
60
- }
61
- function appendTimelineItem(envelope) {
62
- return {
63
- ...envelope,
64
- rawRef: envelope.rawRef ? { ...envelope.rawRef } : void 0
65
- };
66
- }
67
-
68
- // ../packages/runtime-core/dist/index.js
69
- var initialRuntimeState = {
70
- status: "idle",
71
- acceptedMessages: [],
72
- queuedMessages: []
73
- };
74
- function reduceRuntimeState(state = initialRuntimeState, action) {
75
- switch (action.type) {
76
- case "preflight_start":
77
- return { ...state, status: "preflighting", lastError: void 0 };
78
- case "preflight_ok":
79
- return { ...state, status: "ready", lastError: void 0 };
80
- case "preflight_error":
81
- return { ...state, status: "failed", lastError: action.error };
82
- case "starting":
83
- if (state.status === "ready" || state.status === "idle") {
84
- return { ...state, status: "starting" };
85
- }
86
- return state;
87
- case "send_message":
88
- if (state.status === "running" || state.status === "waiting_for_permission") {
89
- return {
90
- ...state,
91
- queuedMessages: [...state.queuedMessages, action.message]
92
- };
93
- }
94
- return {
95
- ...state,
96
- status: "running",
97
- acceptedMessages: [...state.acceptedMessages, action.message]
98
- };
99
- case "permission_request":
100
- return {
101
- ...state,
102
- status: "waiting_for_permission",
103
- waitingPermissionRequestId: action.requestId
104
- };
105
- case "permission_response":
106
- return {
107
- ...state,
108
- status: "running",
109
- waitingPermissionRequestId: void 0
110
- };
111
- case "turn_completed":
112
- if (state.status === "running") {
113
- return { ...state, status: "turn_completed" };
114
- }
115
- return state;
116
- case "complete": {
117
- if (state.status === "turn_completed") {
118
- const [nextMessage2, ...remaining2] = state.queuedMessages;
119
- if (nextMessage2) {
120
- return {
121
- ...state,
122
- status: "running",
123
- acceptedMessages: [...state.acceptedMessages, nextMessage2],
124
- queuedMessages: remaining2
125
- };
126
- }
127
- return { ...state, status: "ready" };
128
- }
129
- const [nextMessage, ...remaining] = state.queuedMessages;
130
- if (nextMessage) {
131
- return {
132
- ...state,
133
- status: "running",
134
- acceptedMessages: [...state.acceptedMessages, nextMessage],
135
- queuedMessages: remaining
136
- };
137
- }
138
- return { ...state, status: "ready" };
139
- }
140
- case "abort":
141
- return {
142
- ...state,
143
- status: "ready",
144
- lastError: action.reason,
145
- queuedMessages: [],
146
- waitingPermissionRequestId: void 0
147
- };
148
- case "error":
149
- return { ...state, status: "failed", lastError: action.error };
150
- case "dispose":
151
- return {
152
- ...state,
153
- status: "disposed",
154
- queuedMessages: [],
155
- waitingPermissionRequestId: void 0
156
- };
157
- }
158
- }
159
-
160
- // ../packages/local-runtime/dist/chunk-BGP42L4K.js
161
- var PushAgentEventStream = class {
162
- connected = false;
163
- listeners = null;
164
- connect(onEvent, onError, onClose) {
165
- this.listeners = { onEvent, onError, onClose };
166
- this.connected = true;
167
- }
168
- disconnect() {
169
- this.listeners = null;
170
- this.connected = false;
171
- }
172
- isConnected() {
173
- return this.connected;
174
- }
175
- emit(event) {
176
- this.listeners?.onEvent(event);
177
- }
178
- fail(error) {
179
- this.listeners?.onError?.(error);
180
- }
181
- close() {
182
- this.connected = false;
183
- this.listeners?.onClose?.();
184
- }
185
- };
186
- function parseJsonLine(line) {
187
- const trimmed = line.trim();
188
- if (!trimmed) return null;
189
- try {
190
- return JSON.parse(trimmed);
191
- } catch {
192
- return null;
193
- }
194
- }
195
- function asRecord(value) {
196
- return value && typeof value === "object" ? value : {};
197
- }
198
- function getText(value) {
199
- return typeof value === "string" && value.length > 0 ? value : void 0;
200
- }
201
- function normalizeUsage(raw) {
202
- const inputTokens = typeof raw.input_tokens === "number" ? raw.input_tokens : typeof raw.inputTokens === "number" ? raw.inputTokens : 0;
203
- const outputTokens = typeof raw.output_tokens === "number" ? raw.output_tokens : typeof raw.outputTokens === "number" ? raw.outputTokens : 0;
204
- return { inputTokens, outputTokens };
205
- }
206
- function mapClaudeStreamJsonLine(line) {
207
- const payload = asRecord(parseJsonLine(line));
208
- const type = getText(payload.type);
209
- if (!type) return [];
210
- if (type === "system" && payload.subtype === "init") {
211
- return [{ type: "status", message: "Claude session initialized" }];
212
- }
213
- if (type === "stream_event") {
214
- const event = asRecord(payload.event);
215
- if (event.type === "content_block_delta") {
216
- const delta = asRecord(event.delta);
217
- const text = getText(delta.text);
218
- if (text) {
219
- return [{
220
- type: "text_delta",
221
- text,
222
- turnId: getText(asRecord(payload.message).id) ?? getText(payload.message_id) ?? "msg_1"
223
- }];
224
- }
225
- }
226
- return [];
227
- }
228
- if (type === "assistant") {
229
- const message = asRecord(payload.message);
230
- const turnId = getText(message.id);
231
- const content = Array.isArray(message.content) ? message.content.map(asRecord) : [];
232
- const events = [];
233
- for (const item of content) {
234
- if (item.type === "tool_use") {
235
- const toolUseId = getText(item.id);
236
- const toolName = getText(item.name);
237
- if (toolUseId && toolName) {
238
- events.push({
239
- type: "tool_start",
240
- toolName,
241
- toolUseId,
242
- input: asRecord(item.input),
243
- turnId
244
- });
245
- }
246
- } else if (item.type === "text") {
247
- const text = getText(item.text);
248
- if (text) {
249
- events.push({
250
- type: "text_complete",
251
- text,
252
- isIntermediate: message.stop_reason === "tool_use",
253
- turnId
254
- });
255
- }
256
- }
257
- }
258
- return events;
259
- }
260
- if (type === "result") {
261
- if (payload.subtype && payload.subtype !== "success") {
262
- return [{ type: "error", message: `Claude finished with ${String(payload.subtype)}` }, { type: "complete" }];
263
- }
264
- return [{ type: "complete", usage: normalizeUsage(asRecord(payload.usage)) }];
265
- }
266
- if (type === "error") {
267
- return [{ type: "error", message: getText(payload.message) ?? "Claude stream error" }];
268
- }
269
- return [];
270
- }
271
- function mapCodexExecJsonLine(line) {
272
- const payload = asRecord(parseJsonLine(line));
273
- const type = getText(payload.type);
274
- if (!type) return [];
275
- if (type === "session.started" || type === "session_started" || type === "thread.started" || type === "thread_started") {
276
- return [{ type: "status", message: "Codex session initialized" }];
277
- }
278
- if (type === "turn.started" || type === "turn_started") {
279
- return [{ type: "status", message: "Codex turn started" }];
280
- }
281
- if (type === "item.started" || type === "item_started") {
282
- const item = asRecord(payload.item);
283
- const itemType = getText(item.type);
284
- if (itemType === "command_execution" || itemType === "commandExecution") {
285
- const toolUseId = getText(item.id) ?? getText(payload.item_id) ?? `tool-${Date.now()}`;
286
- const command = getText(item.command);
287
- return [{
288
- type: "tool_start",
289
- toolName: "Bash",
290
- toolUseId,
291
- input: command ? { command } : asRecord(item.arguments),
292
- turnId: getText(payload.turn_id) ?? getText(payload.turnId)
293
- }];
294
- }
295
- return [];
296
- }
297
- if (type === "item.completed" || type === "item_completed") {
298
- const item = asRecord(payload.item);
299
- const itemType = getText(item.type);
300
- if (itemType === "agent_message" || itemType === "agentMessage") {
301
- const text = getText(item.text) ?? getText(item.message);
302
- return text ? [{
303
- type: "text_complete",
304
- text,
305
- isIntermediate: false,
306
- turnId: getText(payload.turn_id) ?? getText(payload.turnId) ?? getText(item.id)
307
- }] : [];
308
- }
309
- if (itemType === "command_execution" || itemType === "commandExecution") {
310
- const toolUseId = getText(item.id) ?? getText(payload.item_id) ?? `tool-${Date.now()}`;
311
- const exitCode = typeof item.exit_code === "number" ? item.exit_code : typeof item.exitCode === "number" ? item.exitCode : 0;
312
- return [{
313
- type: "tool_result",
314
- toolName: "Bash",
315
- toolUseId,
316
- result: getText(item.aggregated_output) ?? getText(item.aggregatedOutput) ?? getText(item.output) ?? "",
317
- isError: exitCode !== 0 || item.is_error === true,
318
- turnId: getText(payload.turn_id) ?? getText(payload.turnId)
319
- }];
320
- }
321
- return [];
322
- }
323
- if (type === "agent_message_delta" || type === "message_delta" || type === "response.output_text.delta") {
324
- const text = getText(payload.delta) ?? getText(payload.text);
325
- return text ? [{ type: "text_delta", text }] : [];
326
- }
327
- if (type === "agent_message" || type === "message" || type === "response.output_text.done") {
328
- const text = getText(payload.message) ?? getText(payload.text);
329
- return text ? [{ type: "text_complete", text, isIntermediate: false }] : [];
330
- }
331
- if (type === "exec_command_begin" || type === "tool_call_begin") {
332
- const toolUseId = getText(payload.call_id) ?? getText(payload.id) ?? `tool-${Date.now()}`;
333
- const command = getText(payload.command);
334
- return [{
335
- type: "tool_start",
336
- toolName: getText(payload.tool_name) ?? "Bash",
337
- toolUseId,
338
- input: command ? { command } : asRecord(payload.arguments)
339
- }];
340
- }
341
- if (type === "exec_command_end" || type === "tool_call_end") {
342
- const toolUseId = getText(payload.call_id) ?? getText(payload.id) ?? `tool-${Date.now()}`;
343
- const exitCode = typeof payload.exit_code === "number" ? payload.exit_code : 0;
344
- return [{
345
- type: "tool_result",
346
- toolName: getText(payload.tool_name) ?? "Bash",
347
- toolUseId,
348
- result: getText(payload.output) ?? getText(payload.result) ?? "",
349
- isError: exitCode !== 0 || payload.is_error === true
350
- }];
351
- }
352
- if (type === "turn_completed" || type === "turn.completed" || type === "task_complete" || type === "response.completed") {
353
- return [{ type: "complete", usage: normalizeUsage(asRecord(payload.usage)) }];
354
- }
355
- if (type === "error") {
356
- return [{ type: "error", message: getText(payload.message) ?? "Codex stream error" }];
357
- }
358
- return [];
359
- }
360
- function createLocalTimelineProjector(options) {
361
- const sequencer = createTimelineSequencer(options);
362
- let lastTurnId;
363
- return {
364
- project(event) {
365
- const items = mapAgentEventToTimelineItems(event, lastTurnId);
366
- const eventTurnId = turnIdFromAgentEvent(event);
367
- const itemTurnId = items.map((item) => "turnId" in item ? item.turnId : void 0).find((turnId) => typeof turnId === "string");
368
- if (eventTurnId ?? itemTurnId) lastTurnId = eventTurnId ?? itemTurnId;
369
- return items.map((item) => append(sequencer, item, event.type));
370
- }
371
- };
372
- }
373
- function append(sequencer, item, providerEventType) {
374
- return sequencer.append(item, { providerEventType });
375
- }
376
- function mapAgentEventToTimelineItems(event, lastTurnId) {
377
- switch (event.type) {
378
- case "status":
379
- case "info":
380
- return [{ type: "session_status", status: event.message }];
381
- case "text_delta": {
382
- const turnId = event.turnId ?? lastTurnId ?? "turn-local";
383
- return [{
384
- type: "assistant_message_delta",
385
- text: event.text,
386
- messageId: messageIdForTurn(turnId),
387
- turnId
388
- }];
389
- }
390
- case "text_complete": {
391
- const turnId = event.turnId ?? lastTurnId ?? "turn-local";
392
- return [{
393
- type: "assistant_message",
394
- text: event.text,
395
- messageId: messageIdForTurn(turnId),
396
- turnId
397
- }];
398
- }
399
- case "reasoning_delta": {
400
- const turnId = event.turnId ?? lastTurnId ?? "turn-local";
401
- return [{
402
- type: "assistant_message_delta",
403
- text: event.text,
404
- messageId: messageIdForTurn(turnId),
405
- turnId
406
- }];
407
- }
408
- case "reasoning": {
409
- const turnId = event.turnId ?? lastTurnId ?? "turn-local";
410
- return [{
411
- type: "assistant_message",
412
- text: event.text,
413
- messageId: messageIdForTurn(turnId),
414
- turnId
415
- }];
416
- }
417
- case "tool_start":
418
- return [{
419
- type: "tool_call",
420
- callId: event.toolUseId,
421
- name: event.toolName,
422
- status: "running",
423
- detail: { input: event.input },
424
- turnId: event.turnId
425
- }];
426
- case "tool_result":
427
- return [{
428
- type: "tool_result",
429
- callId: event.toolUseId,
430
- result: event.result,
431
- isError: event.isError,
432
- turnId: event.turnId
433
- }];
434
- case "permission_request":
435
- return [{
436
- type: "permission_requested",
437
- request: {
438
- requestId: event.requestId,
439
- toolName: event.toolName,
440
- input: { command: event.command },
441
- reason: event.reason
442
- }
443
- }];
444
- case "permission_response":
445
- return [{
446
- type: "permission_resolved",
447
- requestId: event.requestId,
448
- resolution: {
449
- allowed: event.allowed,
450
- remember: event.remember ?? false
451
- }
452
- }];
453
- case "complete": {
454
- const items = [];
455
- if (lastTurnId) {
456
- items.push({
457
- type: "turn_completed",
458
- turnId: lastTurnId,
459
- usage: event.usage
460
- });
461
- }
462
- items.push({ type: "session_status", status: "ready" });
463
- return items;
464
- }
465
- case "error":
466
- if (lastTurnId) {
467
- return [{
468
- type: "turn_failed",
469
- turnId: lastTurnId,
470
- error: { message: event.message }
471
- }];
472
- }
473
- return [{ type: "session_status", status: "failed" }];
474
- case "typed_error":
475
- if (lastTurnId) {
476
- return [{
477
- type: "turn_failed",
478
- turnId: lastTurnId,
479
- error: event.error
480
- }];
481
- }
482
- return [{ type: "session_status", status: "failed" }];
483
- case "source_activated":
484
- return [{
485
- type: "source_state_changed",
486
- source: {
487
- sourceSlug: event.sourceSlug,
488
- state: "active",
489
- originalMessage: event.originalMessage
490
- }
491
- }];
492
- case "usage_update":
493
- return [{ type: "session_status", status: "usage_update" }];
494
- case "working_directory_changed":
495
- return [{
496
- type: "session_status",
497
- status: `working_directory:${event.workingDirectory}`
498
- }];
499
- case "compaction_started":
500
- return [{ type: "compaction_started" }];
501
- case "compaction_boundary":
502
- return [{ type: "compaction_boundary", summary: event.summary }];
503
- case "task_backgrounded":
504
- case "shell_backgrounded":
505
- case "task_progress":
506
- case "task_completed":
507
- case "shell_killed":
508
- case "steer_undelivered":
509
- return [{ type: "session_status", status: event.type }];
510
- default:
511
- return [];
512
- }
513
- }
514
- function turnIdFromAgentEvent(event) {
515
- if ("turnId" in event) return event.turnId;
516
- return void 0;
517
- }
518
- function messageIdForTurn(turnId) {
519
- return `${turnId}:assistant`;
520
- }
521
- function createFakeLocalAgentSession(options) {
522
- const events = new PushAgentEventStream();
523
- let state = initialRuntimeState;
524
- function dispatch(action) {
525
- state = reduceRuntimeState(state, action);
526
- }
527
- async function runScript() {
528
- events.emit({ type: "status", message: `${options.provider} runtime accepted message` });
529
- for (const event of options.script) {
530
- if (event.type === "permission_request") {
531
- dispatch({ type: "permission_request", requestId: event.requestId });
532
- }
533
- events.emit(event);
534
- if (event.type === "complete") {
535
- dispatch({ type: "complete" });
536
- }
537
- }
538
- }
539
- return {
540
- sessionId: options.sessionId ?? `local-${options.provider}-${Date.now()}`,
541
- provider: options.provider,
542
- events,
543
- async preflight() {
544
- dispatch({ type: "preflight_ok" });
545
- return {
546
- mode: "provider-owned",
547
- configured: true,
548
- source: "fake-local-runtime"
549
- };
550
- },
551
- getState() {
552
- return state;
553
- },
554
- commands: {
555
- async sendMessage(message, _sendOptions) {
556
- dispatch({ type: "send_message", message });
557
- await runScript();
558
- },
559
- async abort(reason) {
560
- dispatch({ type: "abort", reason });
561
- events.emit({ type: "error", message: reason ?? "Aborted" });
562
- events.emit({ type: "complete" });
563
- },
564
- async respondToPermission(_requestId, _allowed, _remember) {
565
- dispatch({ type: "permission_response" });
566
- },
567
- async dispose() {
568
- dispatch({ type: "dispose" });
569
- events.close();
570
- }
571
- }
572
- };
573
- }
574
- function generateTraceTurnId() {
575
- return `turn-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
576
- }
577
- function generateTraceToolUseId() {
578
- return `tool-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
579
- }
580
- var TraceToolIndex = class {
581
- index = /* @__PURE__ */ new Map();
582
- append(id, name, input) {
583
- this.index.set(id, { id, name, input, matched: false });
584
- }
585
- find(id) {
586
- return this.index.get(id);
587
- }
588
- markMatched(id) {
589
- const entry = this.index.get(id);
590
- if (entry) {
591
- entry.matched = true;
592
- }
593
- }
594
- isMatched(id) {
595
- return this.index.get(id)?.matched ?? false;
596
- }
597
- has(id) {
598
- return this.index.has(id);
599
- }
600
- clear() {
601
- this.index.clear();
602
- }
603
- /** Get all unmatched tool starts (for detecting orphaned tool calls) */
604
- unmatched() {
605
- return Array.from(this.index.values()).filter((entry) => !entry.matched);
606
- }
607
- };
608
- var READ_PATTERNS = [
609
- // cat file
610
- {
611
- regex: /^cat\s+['"]?([^'"\s]+)['"]?\s*$/,
612
- extract: (m) => ({ filePath: m[1], originalCommand: m[0] })
613
- },
614
- // head -n N file / head -N file
615
- {
616
- regex: /^head\s+-n\s+(\d+)\s+['"]?([^'"\s]+)['"]?\s*$/,
617
- extract: (m) => ({
618
- filePath: m[2],
619
- endLine: parseInt(m[1], 10),
620
- originalCommand: m[0]
621
- })
622
- },
623
- {
624
- regex: /^head\s+-(\d+)\s+['"]?([^'"\s]+)['"]?\s*$/,
625
- extract: (m) => ({
626
- filePath: m[2],
627
- endLine: parseInt(m[1], 10),
628
- originalCommand: m[0]
629
- })
630
- },
631
- // tail -n N file
632
- {
633
- regex: /^tail\s+-n\s+(\d+)\s+['"]?([^'"\s]+)['"]?\s*$/,
634
- extract: (m) => ({
635
- filePath: m[2],
636
- startLine: -parseInt(m[1], 10),
637
- // negative = last N lines
638
- originalCommand: m[0]
639
- })
640
- },
641
- // sed -n 'start,end' file
642
- {
643
- regex: /^sed\s+-n\s+'(\d+),(\d+)p'\s+['"]?([^'"\s]+)['"]?\s*$/,
644
- extract: (m) => ({
645
- filePath: m[3],
646
- startLine: parseInt(m[1], 10),
647
- endLine: parseInt(m[2], 10),
648
- originalCommand: m[0]
649
- })
650
- },
651
- // sed -n 'startp' file
652
- {
653
- regex: /^sed\s+-n\s+'(\d+)p'\s+['"]?([^'"\s]+)['"]?\s*$/,
654
- extract: (m) => ({
655
- filePath: m[2],
656
- startLine: parseInt(m[1], 10),
657
- endLine: parseInt(m[1], 10),
658
- originalCommand: m[0]
659
- })
660
- }
661
- ];
662
- function parseTraceReadCommand(command) {
663
- const stripped = command.replace(/^bash\s+-[lc]+\s+/, "").trim();
664
- for (const pattern of READ_PATTERNS) {
665
- const match = stripped.match(pattern.regex);
666
- if (match) {
667
- return pattern.extract(match);
668
- }
669
- }
670
- return null;
671
- }
672
- var TraceEventAdapter = class {
673
- turnIndex = 0;
674
- currentTurnId = null;
675
- // Shared state maps — reset on each turn
676
- commandOutput = /* @__PURE__ */ new Map();
677
- readCommands = /* @__PURE__ */ new Map();
678
- blockReasons = /* @__PURE__ */ new Map();
679
- toolIndex = new TraceToolIndex();
680
- /**
681
- * Start a new turn — resets shared state and calls subclass hook.
682
- */
683
- startTurn(turnId) {
684
- this.turnIndex++;
685
- this.commandOutput.clear();
686
- this.readCommands.clear();
687
- this.blockReasons.clear();
688
- this.toolIndex.clear();
689
- this.currentTurnId = turnId || generateTraceTurnId();
690
- this.onTurnStart();
691
- }
692
- setBlockReason(id, reason) {
693
- this.blockReasons.set(id, reason);
694
- }
695
- consumeBlockReason(...keys) {
696
- for (const key of keys) {
697
- const reason = this.blockReasons.get(key);
698
- if (reason !== void 0) {
699
- this.blockReasons.delete(key);
700
- return reason;
701
- }
702
- }
703
- return void 0;
704
- }
705
- classifyReadCommand(id, command) {
706
- const readInfo = parseTraceReadCommand(command);
707
- if (readInfo) {
708
- this.readCommands.set(id, readInfo);
709
- }
710
- return readInfo;
711
- }
712
- consumeReadCommand(id) {
713
- const info = this.readCommands.get(id);
714
- if (info) {
715
- this.readCommands.delete(id);
716
- }
717
- return info;
718
- }
719
- accumulateOutput(id, delta) {
720
- const current = this.commandOutput.get(id) || "";
721
- this.commandOutput.set(id, current + delta);
722
- }
723
- consumeOutput(id) {
724
- const output = this.commandOutput.get(id);
725
- if (output !== void 0) {
726
- this.commandOutput.delete(id);
727
- }
728
- return output;
729
- }
730
- createToolStart(id, toolName, input, intent, displayName, parentToolUseId) {
731
- return {
732
- type: "tool_start",
733
- toolName,
734
- toolUseId: id,
735
- input,
736
- intent,
737
- displayName,
738
- turnId: this.currentTurnId || void 0,
739
- parentToolUseId
740
- };
741
- }
742
- createToolResult(id, toolName, result, isError, parentToolUseId) {
743
- return {
744
- type: "tool_result",
745
- toolUseId: id,
746
- toolName,
747
- result,
748
- isError,
749
- turnId: this.currentTurnId || void 0,
750
- parentToolUseId
751
- };
752
- }
753
- createReadToolStart(id, readInfo, intent) {
754
- return this.createToolStart(
755
- id,
756
- "Read",
757
- {
758
- file_path: readInfo.filePath,
759
- offset: readInfo.startLine,
760
- limit: readInfo.endLine ? readInfo.endLine - (readInfo.startLine || 1) + 1 : void 0,
761
- _command: readInfo.originalCommand
762
- },
763
- intent,
764
- "Read File"
765
- );
766
- }
767
- /**
768
- * Build an MCP tool name from server and tool names.
769
- */
770
- buildMcpToolName(serverName, toolName) {
771
- if (toolName.startsWith("mcp__")) return toolName;
772
- return `mcp__${serverName}__${toolName}`;
773
- }
774
- };
775
- var ClaudeStdoutAdapter = class extends TraceEventAdapter {
776
- hasFinalResponse = false;
777
- onTurnStart() {
778
- this.hasFinalResponse = false;
779
- }
780
- /**
781
- * Parse claude -p stdout + stderr into AgentEvent[].
782
- *
783
- * Since claude -p output is mostly unstructured plain text,
784
- * we do a best-effort extraction of tool-related patterns
785
- * and map everything else to text_complete / status / error events.
786
- */
787
- parseOutput(stdout, stderr) {
788
- const events = [];
789
- this.startTurn();
790
- if (stderr.trim()) {
791
- const errorLines = stderr.split("\n").filter((l) => l.trim());
792
- for (const line of errorLines) {
793
- if (line.includes("rate_limited") || line.includes("Rate limit") || line.includes("429")) {
794
- events.push({ type: "error", message: "Rate limited \u2014 please wait and retry" });
795
- } else if (line.includes("invalid_api_key") || line.includes("Authentication") || line.includes("401") || line.includes("403")) {
796
- events.push({ type: "error", message: "Authentication error \u2014 check your API key" });
797
- } else if (line.includes("context_length_exceeded") || line.includes("too long")) {
798
- events.push({ type: "error", message: "Context limit exceeded" });
799
- } else {
800
- events.push({ type: "status", message: line.trim() });
801
- }
802
- }
803
- }
804
- const stdoutLines = stdout.split("\n");
805
- let responseText = "";
806
- let currentTool = null;
807
- let inXmlToolUse = false;
808
- let xmlToolName = "";
809
- let xmlToolInput = "";
810
- let xmlToolResult = "";
811
- let inXmlToolResult = false;
812
- for (const line of stdoutLines) {
813
- const xmlToolStartMatch = line.match(/<tool_use>\s*([\w.]+)/i);
814
- if (xmlToolStartMatch) {
815
- if (responseText.trim()) {
816
- events.push({
817
- type: "text_complete",
818
- text: responseText.trim(),
819
- isIntermediate: true,
820
- turnId: this.currentTurnId || void 0
821
- });
822
- responseText = "";
823
- }
824
- inXmlToolUse = true;
825
- xmlToolName = xmlToolStartMatch[1];
826
- xmlToolInput = "";
827
- continue;
828
- }
829
- if (inXmlToolUse && line.match(/<\/tool_use>/i)) {
830
- inXmlToolUse = false;
831
- const toolId = generateTraceToolUseId();
832
- let parsedInput = {};
833
- try {
834
- parsedInput = JSON.parse(xmlToolInput.trim());
835
- } catch {
836
- parsedInput = { raw_input: xmlToolInput.trim() };
837
- }
838
- events.push(this.createToolStart(toolId, xmlToolName, parsedInput));
839
- this.toolIndex.append(toolId, xmlToolName, parsedInput);
840
- currentTool = { id: toolId, name: xmlToolName, input: parsedInput, outputLines: [] };
841
- continue;
842
- }
843
- if (inXmlToolUse) {
844
- xmlToolInput += line + "\n";
845
- continue;
846
- }
847
- const xmlResultStartMatch = line.match(/<tool_result>/i);
848
- if (xmlResultStartMatch) {
849
- inXmlToolResult = true;
850
- xmlToolResult = "";
851
- continue;
852
- }
853
- if (inXmlToolResult && line.match(/<\/tool_result>/i)) {
854
- inXmlToolResult = false;
855
- if (currentTool) {
856
- events.push(
857
- this.createToolResult(currentTool.id, currentTool.name, xmlToolResult.trim(), false)
858
- );
859
- currentTool = null;
860
- }
861
- xmlToolResult = "";
862
- continue;
863
- }
864
- if (inXmlToolResult) {
865
- xmlToolResult += line + "\n";
866
- continue;
867
- }
868
- const toolStartMatch = matchToolStartPattern(line);
869
- if (toolStartMatch) {
870
- if (responseText.trim()) {
871
- events.push({
872
- type: "text_complete",
873
- text: responseText.trim(),
874
- isIntermediate: true,
875
- turnId: this.currentTurnId || void 0
876
- });
877
- responseText = "";
878
- }
879
- currentTool = {
880
- id: generateTraceToolUseId(),
881
- name: toolStartMatch.name,
882
- input: toolStartMatch.input,
883
- outputLines: []
884
- };
885
- events.push(
886
- this.createToolStart(currentTool.id, currentTool.name, currentTool.input)
887
- );
888
- this.toolIndex.append(currentTool.id, currentTool.name, currentTool.input);
889
- continue;
890
- }
891
- const toolEndMatch = matchToolEndPattern(line);
892
- if (toolEndMatch && currentTool) {
893
- events.push(
894
- this.createToolResult(
895
- currentTool.id,
896
- currentTool.name,
897
- currentTool.outputLines.join("\n").trim() || toolEndMatch.result,
898
- toolEndMatch.isError
899
- )
900
- );
901
- currentTool = null;
902
- continue;
903
- }
904
- if (currentTool) {
905
- currentTool.outputLines.push(line);
906
- } else {
907
- responseText += line + "\n";
908
- }
909
- }
910
- if (currentTool) {
911
- events.push(
912
- this.createToolResult(
913
- currentTool.id,
914
- currentTool.name,
915
- currentTool.outputLines.join("\n").trim(),
916
- false
917
- )
918
- );
919
- }
920
- if (responseText.trim()) {
921
- events.push({
922
- type: "text_complete",
923
- text: responseText.trim(),
924
- isIntermediate: false,
925
- turnId: this.currentTurnId || void 0
926
- });
927
- this.hasFinalResponse = true;
928
- }
929
- events.push({ type: "complete" });
930
- return events;
931
- }
932
- };
933
- function matchToolStartPattern(line) {
934
- const trimmed = line.trim();
935
- const cmdMatch = trimmed.match(/^Running command:\s+(.+)$/i) || trimmed.match(/^Executing:\s+(.+)$/i) || trimmed.match(/^Running bash command:\s+(.+)$/i);
936
- if (cmdMatch) {
937
- return { name: "Bash", input: { command: cmdMatch[1] } };
938
- }
939
- const readMatch = trimmed.match(/^Reading file:\s+(.+)$/i) || trimmed.match(/^Read:\s+(.+)$/i);
940
- if (readMatch) {
941
- return { name: "Read", input: { file_path: readMatch[1] } };
942
- }
943
- const writeMatch = trimmed.match(/^Writing file:\s+(.+)$/i) || trimmed.match(/^Edit:\s+(.+)$/i) || trimmed.match(/^Writing:\s+(.+)$/i);
944
- if (writeMatch) {
945
- return { name: "Edit", input: { file_path: writeMatch[1] } };
946
- }
947
- const searchMatch = trimmed.match(/^Searching for:\s+(.+)$/i) || trimmed.match(/^Search:\s+(.+)$/i);
948
- if (searchMatch) {
949
- return { name: "Search", input: { query: searchMatch[1] } };
950
- }
951
- return null;
952
- }
953
- function matchToolEndPattern(line) {
954
- const trimmed = line.trim();
955
- if (/^Command (completed|finished|done)/i.test(trimmed) || /^Done$/i.test(trimmed)) {
956
- return { result: trimmed, isError: false };
957
- }
958
- if (/^Command failed/i.test(trimmed) || /^Error:/i.test(trimmed)) {
959
- return { result: trimmed, isError: true };
960
- }
961
- if (/^File (written|read|updated) (successfully|complete)/i.test(trimmed)) {
962
- return { result: trimmed, isError: false };
963
- }
964
- return null;
965
- }
966
- function parseClaudeStdoutTrace(stdout, stderr) {
967
- return new ClaudeStdoutAdapter().parseOutput(stdout, stderr);
968
- }
969
- var CodexRolloutAdapter = class extends TraceEventAdapter {
970
- // Per-turn state for deduplication
971
- emittedEventMsgIds = /* @__PURE__ */ new Set();
972
- pendingAssistantText = null;
973
- pendingAssistantTurnId = null;
974
- onTurnStart() {
975
- this.emittedEventMsgIds.clear();
976
- this.pendingAssistantText = null;
977
- this.pendingAssistantTurnId = null;
978
- }
979
- /**
980
- * Parse a complete rollout JSONL string into AgentEvent[].
981
- * Each line is a JSON object representing a Codex event.
982
- */
983
- parseRollout(rolloutJsonl) {
984
- const events = [];
985
- const lines = rolloutJsonl.split("\n").filter((l) => l.trim());
986
- this.startTurn();
987
- for (const line of lines) {
988
- try {
989
- const obj = JSON.parse(line);
990
- const parsed = this.adaptRolloutEvent(obj);
991
- events.push(...parsed);
992
- } catch {
993
- }
994
- }
995
- if (this.pendingAssistantText) {
996
- events.push({
997
- type: "text_complete",
998
- text: this.pendingAssistantText,
999
- isIntermediate: false,
1000
- turnId: this.pendingAssistantTurnId || this.currentTurnId || void 0
1001
- });
1002
- this.pendingAssistantText = null;
1003
- }
1004
- const hasComplete = events.some((e) => e.type === "complete");
1005
- if (!hasComplete && events.length > 0) {
1006
- events.push({ type: "complete" });
1007
- }
1008
- return events;
1009
- }
1010
- /**
1011
- * Adapt a single Codex rollout event to AgentEvent[].
1012
- */
1013
- adaptRolloutEvent(event) {
1014
- const events = [];
1015
- switch (event.type) {
1016
- // ====================================================================
1017
- // Text & reasoning events
1018
- // ====================================================================
1019
- case "response_item": {
1020
- const item = event;
1021
- if (item.id && this.emittedEventMsgIds.has(item.id)) {
1022
- break;
1023
- }
1024
- if (item.role === "assistant") {
1025
- const text = extractTextFromContent(item.content);
1026
- if (text) {
1027
- const isReasoning = item.metadata?.reasoning === true;
1028
- const isIntermediate = isReasoning || hasToolUseInContent(item.content);
1029
- if (isIntermediate) {
1030
- events.push({
1031
- type: "text_complete",
1032
- text,
1033
- isIntermediate: true,
1034
- turnId: this.currentTurnId || void 0
1035
- });
1036
- } else {
1037
- this.pendingAssistantText = text;
1038
- this.pendingAssistantTurnId = this.currentTurnId;
1039
- }
1040
- }
1041
- const toolUses = extractToolUsesFromContent(item.content);
1042
- for (const tu of toolUses) {
1043
- this.toolIndex.append(tu.id, tu.name, tu.input);
1044
- events.push(this.createToolStart(tu.id, tu.name, tu.input, void 0, void 0));
1045
- }
1046
- }
1047
- if (item.role === "user" && isSyntheticMessage(item)) {
1048
- break;
1049
- }
1050
- break;
1051
- }
1052
- case "event_msg": {
1053
- const msg = event;
1054
- if (msg.id) {
1055
- this.emittedEventMsgIds.add(msg.id);
1056
- }
1057
- if (msg.role === "assistant" && msg.message) {
1058
- events.push({
1059
- type: "text_complete",
1060
- text: msg.message,
1061
- isIntermediate: false,
1062
- turnId: this.currentTurnId || void 0
1063
- });
1064
- }
1065
- break;
1066
- }
1067
- case "agent_message_delta": {
1068
- const delta = event;
1069
- if (delta.delta) {
1070
- events.push({
1071
- type: "text_delta",
1072
- text: delta.delta,
1073
- turnId: this.currentTurnId || void 0
1074
- });
1075
- }
1076
- break;
1077
- }
1078
- case "agent_reasoning": {
1079
- const reasoning = event;
1080
- if (reasoning.text) {
1081
- events.push({
1082
- type: "text_complete",
1083
- text: reasoning.text,
1084
- isIntermediate: true,
1085
- turnId: this.currentTurnId || void 0
1086
- });
1087
- }
1088
- break;
1089
- }
1090
- case "agent_reasoning_delta": {
1091
- const delta = event;
1092
- if (delta.delta) {
1093
- events.push({
1094
- type: "text_delta",
1095
- text: delta.delta,
1096
- turnId: this.currentTurnId || void 0
1097
- });
1098
- }
1099
- break;
1100
- }
1101
- // ====================================================================
1102
- // Command execution events
1103
- // ====================================================================
1104
- case "exec_command_begin": {
1105
- const cmd = event;
1106
- const command = Array.isArray(cmd.command) ? cmd.command.join(" ") : String(cmd.command ?? "");
1107
- const cwd = cmd.cwd ?? "";
1108
- const readInfo = this.classifyReadCommand(cmd.call_id, command);
1109
- if (readInfo) {
1110
- events.push(this.createReadToolStart(cmd.call_id, readInfo));
1111
- } else {
1112
- events.push(
1113
- this.createToolStart(cmd.call_id, "Bash", {
1114
- command,
1115
- cwd
1116
- }, void 0, "Execute Command")
1117
- );
1118
- }
1119
- this.toolIndex.append(cmd.call_id, "Bash", { command, cwd });
1120
- break;
1121
- }
1122
- case "exec_command_output_delta": {
1123
- const delta = event;
1124
- const decoded = decodeBase64Chunk(delta.chunk);
1125
- if (decoded) {
1126
- this.accumulateOutput(delta.call_id, decoded);
1127
- }
1128
- break;
1129
- }
1130
- case "exec_command_end": {
1131
- const cmdEnd = event;
1132
- const accumulated = this.consumeOutput(cmdEnd.call_id);
1133
- const output = accumulated ?? cmdEnd.stdout ?? cmdEnd.formatted_output ?? "";
1134
- const cleanOutput = stripShellEnvelope(output);
1135
- const isError = cmdEnd.exit_code !== 0;
1136
- const readInfo = this.consumeReadCommand(cmdEnd.call_id);
1137
- events.push(
1138
- this.createToolResult(
1139
- cmdEnd.call_id,
1140
- readInfo ? "Read" : "Bash",
1141
- cleanOutput,
1142
- isError
1143
- )
1144
- );
1145
- this.pendingAssistantText = null;
1146
- break;
1147
- }
1148
- // ====================================================================
1149
- // Patch / file modification events
1150
- // ====================================================================
1151
- case "apply_patch_approval_request":
1152
- case "patch_apply_begin": {
1153
- const patch = event;
1154
- const callId = patch.call_id ?? `patch-${this.turnIndex}`;
1155
- const changes = patch.changes ?? {};
1156
- const filePaths = Object.keys(changes);
1157
- const input = {
1158
- changes,
1159
- file_paths: filePaths
1160
- };
1161
- if (filePaths.length === 1) {
1162
- input.file_path = filePaths[0];
1163
- const change = changes[filePaths[0]];
1164
- if (change && typeof change === "object") {
1165
- if ("unified_diff" in change) input.unified_diff = change.unified_diff;
1166
- if ("content" in change) input.content = change.content;
1167
- }
1168
- }
1169
- events.push(
1170
- this.createToolStart(callId, "Edit", input, void 0, "Apply Patch")
1171
- );
1172
- this.toolIndex.append(callId, "Edit", input);
1173
- break;
1174
- }
1175
- case "patch_apply_end": {
1176
- const end = event;
1177
- const callId = end.call_id ?? `patch-${this.turnIndex}`;
1178
- const result = end.stdout ?? (end.success ? "Patch applied successfully" : end.error ?? "Patch failed");
1179
- events.push(
1180
- this.createToolResult(callId, "Edit", result, !end.success)
1181
- );
1182
- break;
1183
- }
1184
- // ====================================================================
1185
- // MCP tool events
1186
- // ====================================================================
1187
- case "mcp_tool_call_begin": {
1188
- const mcp = event;
1189
- const callId = mcp.call_id ?? `mcp-${this.turnIndex}`;
1190
- const invocation = mcp.invocation ?? {};
1191
- const toolName = this.buildMcpToolName(invocation.server ?? "unknown", invocation.tool ?? "unknown");
1192
- const input = invocation.arguments ?? {};
1193
- events.push(
1194
- this.createToolStart(callId, toolName, input, void 0, invocation.tool ?? toolName)
1195
- );
1196
- this.toolIndex.append(callId, toolName, input);
1197
- break;
1198
- }
1199
- case "mcp_tool_call_end": {
1200
- const mcpEnd = event;
1201
- const callId = mcpEnd.call_id ?? `mcp-${this.turnIndex}`;
1202
- const result = mcpEnd.result ?? (mcpEnd.error ?? "MCP call completed");
1203
- const isError = Boolean(mcpEnd.error);
1204
- events.push(
1205
- this.createToolResult(callId, "MCP", typeof result === "string" ? result : JSON.stringify(result), isError)
1206
- );
1207
- break;
1208
- }
1209
- // ====================================================================
1210
- // Web search events
1211
- // ====================================================================
1212
- case "web_search_begin": {
1213
- const ws = event;
1214
- const callId = ws.call_id ?? `search-${this.turnIndex}`;
1215
- events.push(
1216
- this.createToolStart(callId, "WebSearch", {}, void 0, "Web Search")
1217
- );
1218
- this.toolIndex.append(callId, "WebSearch", {});
1219
- break;
1220
- }
1221
- case "web_search_end": {
1222
- const wsEnd = event;
1223
- const callId = wsEnd.call_id ?? `search-${this.turnIndex}`;
1224
- const result = wsEnd.query ?? "Search completed";
1225
- events.push(
1226
- this.createToolResult(callId, "WebSearch", result, false)
1227
- );
1228
- break;
1229
- }
1230
- // ====================================================================
1231
- // Turn diff (file change summary)
1232
- // ====================================================================
1233
- case "turn_diff": {
1234
- const diff = event;
1235
- if (diff.unified_diff) {
1236
- const filePaths = extractFilePathsFromDiff(diff.unified_diff);
1237
- for (const fp of filePaths) {
1238
- events.push(
1239
- this.createToolStart(
1240
- `diff-${fp}-${this.turnIndex}`,
1241
- "Edit",
1242
- { file_path: fp, unified_diff: diff.unified_diff },
1243
- void 0,
1244
- `Changed: ${fp}`
1245
- )
1246
- );
1247
- }
1248
- }
1249
- break;
1250
- }
1251
- case "write_stdin": {
1252
- const stdin = event;
1253
- events.push({
1254
- type: "status",
1255
- message: stdin.content ? `Terminal input: ${stdin.content.slice(0, 80)}${stdin.content.length > 80 ? "..." : ""}` : "Terminal interaction"
1256
- });
1257
- break;
1258
- }
1259
- case "function_call_output": {
1260
- const fco = event;
1261
- const toolName = this.toolIndex.find(fco.call_id)?.name ?? "tool";
1262
- events.push(
1263
- this.createToolResult(fco.call_id, toolName, fco.output ?? "", fco.is_error ?? false)
1264
- );
1265
- this.toolIndex.markMatched(fco.call_id);
1266
- break;
1267
- }
1268
- // ====================================================================
1269
- // Lifecycle events
1270
- // ====================================================================
1271
- case "task_complete": {
1272
- const tc = event;
1273
- if (this.pendingAssistantText) {
1274
- events.push({
1275
- type: "text_complete",
1276
- text: this.pendingAssistantText,
1277
- isIntermediate: false,
1278
- turnId: this.pendingAssistantTurnId || this.currentTurnId || void 0
1279
- });
1280
- this.pendingAssistantText = null;
1281
- }
1282
- events.push({ type: "complete" });
1283
- break;
1284
- }
1285
- // ====================================================================
1286
- // Ignored events (no UI value or handled elsewhere)
1287
- // ====================================================================
1288
- case "session_configured":
1289
- case "task_started":
1290
- case "token_count":
1291
- case "user_message":
1292
- // Filter synthetic, handle real user messages separately
1293
- case "agent_message":
1294
- // Full message, redundant with delta/complete
1295
- case "conversation_path":
1296
- case "background_event":
1297
- case "turn_aborted":
1298
- break;
1299
- default:
1300
- break;
1301
- }
1302
- return events;
1303
- }
1304
- };
1305
- function extractTextFromContent(content) {
1306
- if (!content) return null;
1307
- let text = "";
1308
- for (const block of content) {
1309
- if (block.type === "text" && block.text) {
1310
- text += block.text;
1311
- }
1312
- }
1313
- return text || null;
1314
- }
1315
- function hasToolUseInContent(content) {
1316
- if (!content) return false;
1317
- return content.some((block) => block.type === "tool_use");
1318
- }
1319
- function extractToolUsesFromContent(content) {
1320
- if (!content) return [];
1321
- const result = [];
1322
- for (const block of content) {
1323
- if (block.type === "tool_use" && block.id && block.name) {
1324
- result.push({ id: block.id, name: block.name, input: block.input ?? {} });
1325
- }
1326
- }
1327
- return result;
1328
- }
1329
- function isSyntheticMessage(item) {
1330
- const content = item.content;
1331
- if (!content) return false;
1332
- for (const block of content) {
1333
- if (block.type === "text" && block.text) {
1334
- if (block.text.startsWith("<environment>") || block.text.startsWith("<system-reminder>") || block.text.includes("is not available") && block.text.includes("Working directory")) {
1335
- return true;
1336
- }
1337
- }
1338
- }
1339
- return false;
1340
- }
1341
- function decodeBase64Chunk(chunk) {
1342
- if (!chunk) return null;
1343
- try {
1344
- return atob(chunk);
1345
- } catch {
1346
- return chunk;
1347
- }
1348
- }
1349
- function stripShellEnvelope(output) {
1350
- return output.replace(/^\[(stdout|stderr)\]\s*/i, "").replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").trim();
1351
- }
1352
- function extractFilePathsFromDiff(diff) {
1353
- const paths = [];
1354
- for (const line of diff.split("\n")) {
1355
- const match = line.match(/^diff --git\s+a\/(.+)\s+b\/(.+)/);
1356
- if (match) {
1357
- paths.push(match[2]);
1358
- }
1359
- const plusMatch = line.match(/^\+\+\+\s+b\/(.+)/);
1360
- if (plusMatch && !paths.includes(plusMatch[1])) {
1361
- paths.push(plusMatch[1]);
1362
- }
1363
- }
1364
- return paths;
1365
- }
1366
- function parseCodexRolloutTrace(rolloutJsonl) {
1367
- return new CodexRolloutAdapter().parseRollout(rolloutJsonl);
1368
- }
1369
- // Annotate the CommonJS export names for ESM import in node:
1370
- 0 && (module.exports = {
1371
- ClaudeStdoutAdapter,
1372
- CodexRolloutAdapter,
1373
- PushAgentEventStream,
1374
- TraceEventAdapter,
1375
- TraceToolIndex,
1376
- createFakeLocalAgentSession,
1377
- createLocalTimelineProjector,
1378
- generateTraceToolUseId,
1379
- generateTraceTurnId,
1380
- initialRuntimeState,
1381
- mapClaudeStreamJsonLine,
1382
- mapCodexExecJsonLine,
1383
- parseClaudeStdoutTrace,
1384
- parseCodexRolloutTrace,
1385
- parseTraceReadCommand,
1386
- reduceRuntimeEvents
1387
- });