@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,973 @@
1
+ /**
2
+ * Copilot SDK → Unified Type Converters
3
+ *
4
+ * Translates Copilot SessionEvent objects into EngineOutput (unified types)
5
+ * so the stream-manager and frontend can stay engine-agnostic.
6
+ *
7
+ * Streaming model:
8
+ * session.start → SystemInitEvent
9
+ * assistant.turn_start → StreamLifecycleEvent { event:'start' }
10
+ * assistant.reasoning_delta → TextDeltaEvent { reasoning:true } (and reasoning stream lifecycle)
11
+ * assistant.reasoning → ReasoningMessage (final reasoning text)
12
+ * assistant.message_delta → TextDeltaEvent { reasoning:false }
13
+ * assistant.message → AssistantMessage (text + tool_use blocks)
14
+ * tool.execution_start → AssistantMessage { tool_use only }
15
+ * tool.execution_complete → UserMessage { tool_result only }
16
+ * assistant.usage → captured for ResultEvent
17
+ * assistant.turn_end → StreamLifecycleEvent { event:'stop' }
18
+ * session.idle → SuccessResultEvent (or aborted no-op)
19
+ * session.error → throw buildSessionError(data)
20
+ */
21
+
22
+ import type { MessageEngine } from '$shared/types/unified';
23
+ import type {
24
+ EngineOutput,
25
+ UserMessage,
26
+ AssistantMessage as UnifiedAssistantMessage,
27
+ ReasoningMessage,
28
+ AssistantContentBlock,
29
+ UserContentBlock,
30
+ ToolUseBlock,
31
+ TextDeltaEvent,
32
+ StreamLifecycleEvent,
33
+ SuccessResultEvent,
34
+ SystemInitEvent,
35
+ TokenUsage,
36
+ AgentInput,
37
+ BashInput,
38
+ ReadInput,
39
+ EditInput,
40
+ WriteInput,
41
+ GlobInput,
42
+ GrepInput,
43
+ WebFetchInput,
44
+ WebSearchInput,
45
+ AskUserQuestionInput,
46
+ TodoWriteInput,
47
+ ToolSearchInput,
48
+ ListInput,
49
+ } from '$shared/types/unified';
50
+ import { toCanonicalToolName } from '$shared/types/unified';
51
+ import type { SessionEvent } from '@github/copilot-sdk';
52
+ import { resolveOpenCodeToolName } from '../../../mcp/config';
53
+
54
+ // Derive data payload types from the SessionEvent discriminated union so we
55
+ // don't depend on internal type re-exports that aren't part of the SDK's
56
+ // public surface.
57
+ type StartData = Extract<SessionEvent, { type: 'session.start' }>['data'];
58
+ type AssistantReasoningData = Extract<SessionEvent, { type: 'assistant.reasoning' }>['data'];
59
+ type AssistantReasoningDeltaData = Extract<SessionEvent, { type: 'assistant.reasoning_delta' }>['data'];
60
+ type AssistantMessageData = Extract<SessionEvent, { type: 'assistant.message' }>['data'];
61
+ type AssistantMessageDeltaData = Extract<SessionEvent, { type: 'assistant.message_delta' }>['data'];
62
+ type AssistantMessageToolRequest = NonNullable<AssistantMessageData['toolRequests']>[number];
63
+ type AssistantTurnEndData = Extract<SessionEvent, { type: 'assistant.turn_end' }>['data'];
64
+ type AssistantUsageData = Extract<SessionEvent, { type: 'assistant.usage' }>['data'];
65
+ type ToolExecutionStartData = Extract<SessionEvent, { type: 'tool.execution_start' }>['data'];
66
+ type ToolExecutionCompleteData = Extract<SessionEvent, { type: 'tool.execution_complete' }>['data'];
67
+ type SubagentStartedData = Extract<SessionEvent, { type: 'subagent.started' }>['data'];
68
+ type SubagentCompletedData = Extract<SessionEvent, { type: 'subagent.completed' }>['data'];
69
+ type SubagentFailedData = Extract<SessionEvent, { type: 'subagent.failed' }>['data'];
70
+
71
+
72
+ // ============================================================================
73
+ // Engine Identity
74
+ // ============================================================================
75
+
76
+ /** Build a MessageEngine descriptor for Copilot messages. */
77
+ export function buildEngine(modelId: string): MessageEngine {
78
+ return {
79
+ type: 'copilot',
80
+ provider: 'github',
81
+ model: { id: modelId, name: '' },
82
+ account: { id: 0, name: '' },
83
+ };
84
+ }
85
+
86
+ // ============================================================================
87
+ // Tool Name Mapping
88
+ // ============================================================================
89
+
90
+ type RawToolArgs = Record<string, unknown>;
91
+
92
+ /**
93
+ * Copilot CLI built-in tool names → canonical UI tool names.
94
+ *
95
+ * The Copilot CLI emits tool names in snake_case. The `str_replace_editor`
96
+ * umbrella tool is split server-side into discriminated subcommands
97
+ * (`view`, `create`, `str_replace`, `edit`, `insert`) which arrive as
98
+ * separate `toolName` values in `tool.execution_*` events.
99
+ */
100
+ const COPILOT_TOOL_NAME_MAP: Record<string, string> = {
101
+ // Shell / commands
102
+ 'bash': 'Bash',
103
+ 'shell': 'Bash',
104
+ 'run_in_terminal': 'Bash',
105
+
106
+ // File read (str_replace_editor view subcommand)
107
+ 'view': 'Read',
108
+ 'read': 'Read',
109
+ 'read_file': 'Read',
110
+
111
+ // File create (str_replace_editor create subcommand)
112
+ 'create': 'Write',
113
+ 'write': 'Write',
114
+ 'write_file': 'Write',
115
+ 'create_file': 'Write',
116
+
117
+ // File edit (str_replace_editor edit/str_replace/insert subcommands)
118
+ 'str_replace': 'Edit',
119
+ 'str_replace_editor': 'Edit',
120
+ 'edit': 'Edit',
121
+ 'edit_file': 'Edit',
122
+ 'insert': 'Edit',
123
+
124
+ // Search / discovery
125
+ 'grep': 'Grep',
126
+ 'grep_search': 'Grep',
127
+ 'glob': 'Glob',
128
+ 'glob_search': 'Glob',
129
+ 'list': 'List',
130
+ 'list_dir': 'List',
131
+ 'ls': 'List',
132
+
133
+ // Task / planning
134
+ 'update_todo': 'TodoWrite',
135
+ 'todo_write': 'TodoWrite',
136
+ 'todowrite': 'TodoWrite',
137
+
138
+ // Sub-agent dispatch (Copilot's `task` tool spawns a sub-agent that runs
139
+ // asynchronously; events from the sub-agent arrive with `agentId` set and
140
+ // must thread back to this tool's call id via parent.toolUseId).
141
+ 'task': 'Agent',
142
+
143
+ // User interaction
144
+ 'ask_user': 'AskUserQuestion',
145
+ 'question': 'AskUserQuestion',
146
+
147
+ // Web
148
+ 'web_search': 'WebSearch',
149
+ 'websearch': 'WebSearch',
150
+ 'fetch': 'WebFetch',
151
+ 'fetch_url': 'WebFetch',
152
+ 'web_fetch': 'WebFetch',
153
+ 'webfetch': 'WebFetch',
154
+
155
+ // Tool discovery
156
+ 'tool_search': 'ToolSearch',
157
+ 'tool_search_tool_regex': 'ToolSearch',
158
+ };
159
+
160
+ /**
161
+ * Copilot CLI internal tools used for model↔harness coordination (intent
162
+ * reporting, task completion markers, work proposals, doc fetches). They
163
+ * carry no user-actionable information, so we filter them out at the adapter
164
+ * boundary instead of rendering them as `Unknown:*` blocks in the chat UI.
165
+ */
166
+ const IGNORED_COPILOT_TOOLS = new Set<string>([
167
+ 'report_intent',
168
+ 'task_complete',
169
+ 'propose_work',
170
+ 'fetch_copilot_cli_documentation',
171
+ ]);
172
+
173
+ /** True if a tool name should be silently dropped from the stream. */
174
+ export function isIgnoredCopilotTool(rawName: string, mcpServerName?: string): boolean {
175
+ if (mcpServerName) return false;
176
+ return IGNORED_COPILOT_TOOLS.has(rawName.toLowerCase());
177
+ }
178
+
179
+ /** Map a raw Copilot tool name (with optional MCP server) to a canonical UI name. */
180
+ function mapCopilotToolName(rawName: string, mcpServerName?: string): string {
181
+ if (mcpServerName) {
182
+ // Tools served via our remote MCP HTTP endpoint (`clopen-mcp`) come
183
+ // back as `{ name: '<bare-tool>', mcpServerName: 'clopen-mcp' }`. Resolve
184
+ // the bare name to `mcp__<server>__<tool>` via the same registry helper
185
+ // Open Code uses so the UI renders the matching MCP tool component.
186
+ const resolved = resolveOpenCodeToolName(rawName);
187
+ if (resolved) return resolved;
188
+ return `mcp__${mcpServerName}__${rawName}`;
189
+ }
190
+ const lower = rawName.toLowerCase();
191
+ const mapped = COPILOT_TOOL_NAME_MAP[lower] ?? COPILOT_TOOL_NAME_MAP[rawName] ?? rawName;
192
+ return toCanonicalToolName(mapped);
193
+ }
194
+
195
+ // ============================================================================
196
+ // Tool Input Normalizer Helpers
197
+ // ============================================================================
198
+
199
+ function str(raw: RawToolArgs, ...keys: string[]): string {
200
+ for (const k of keys) {
201
+ const v = raw[k];
202
+ if (v != null) return String(v);
203
+ }
204
+ return '';
205
+ }
206
+
207
+ function optStr(raw: RawToolArgs, ...keys: string[]): string | undefined {
208
+ for (const k of keys) {
209
+ const v = raw[k];
210
+ if (v != null) return String(v);
211
+ }
212
+ return undefined;
213
+ }
214
+
215
+ function optNum(raw: RawToolArgs, ...keys: string[]): number | undefined {
216
+ for (const k of keys) {
217
+ const v = raw[k];
218
+ if (v != null) return Number(v);
219
+ }
220
+ return undefined;
221
+ }
222
+
223
+ function optBool(raw: RawToolArgs, ...keys: string[]): boolean | undefined {
224
+ for (const k of keys) {
225
+ const v = raw[k];
226
+ if (v != null) return Boolean(v);
227
+ }
228
+ return undefined;
229
+ }
230
+
231
+ // ============================================================================
232
+ // Per-Tool Input Normalizers
233
+ // ============================================================================
234
+
235
+ function normalizeBashInput(raw: RawToolArgs): BashInput {
236
+ const result: BashInput = { command: str(raw, 'command', 'cmd', 'shell') };
237
+ const description = optStr(raw, 'description', 'desc');
238
+ if (description != null) result.description = description;
239
+ const timeout = optNum(raw, 'timeout', 'timeoutMs', 'timeout_ms');
240
+ if (timeout != null) result.timeout = timeout;
241
+ const runInBackground = optBool(raw, 'run_in_background', 'runInBackground', 'background');
242
+ if (runInBackground != null) result.runInBackground = runInBackground;
243
+ return result;
244
+ }
245
+
246
+ /**
247
+ * `view` subcommand of `str_replace_editor` accepts `view_range: [start, end]`
248
+ * (1-indexed, inclusive). Translate it into Read's `offset` + `limit`.
249
+ */
250
+ function normalizeReadInput(raw: RawToolArgs): ReadInput {
251
+ const result: ReadInput = {
252
+ filePath: str(raw, 'path', 'file_path', 'filePath'),
253
+ };
254
+ const offset = optNum(raw, 'offset');
255
+ if (offset != null) result.offset = offset;
256
+ const limit = optNum(raw, 'limit');
257
+ if (limit != null) result.limit = limit;
258
+
259
+ const range = raw.view_range ?? raw.viewRange;
260
+ if (Array.isArray(range) && range.length >= 1) {
261
+ const start = Number(range[0]);
262
+ const end = range.length >= 2 ? Number(range[1]) : undefined;
263
+ if (Number.isFinite(start)) {
264
+ if (result.offset == null) result.offset = start;
265
+ if (result.limit == null && end != null && Number.isFinite(end)) {
266
+ result.limit = Math.max(end - start + 1, 1);
267
+ }
268
+ }
269
+ }
270
+ return result;
271
+ }
272
+
273
+ function normalizeWriteInput(raw: RawToolArgs): WriteInput {
274
+ return {
275
+ filePath: str(raw, 'path', 'file_path', 'filePath'),
276
+ content: str(raw, 'file_text', 'content', 'text'),
277
+ };
278
+ }
279
+
280
+ /**
281
+ * Edit covers three Copilot subcommands: `str_replace`, `edit`, and `insert`.
282
+ * - str_replace/edit: `{ path, old_str, new_str }`
283
+ * - insert: `{ path, insert_line, new_str }` (oldString left empty)
284
+ */
285
+ function normalizeEditInput(raw: RawToolArgs): EditInput {
286
+ const result: EditInput = {
287
+ filePath: str(raw, 'path', 'file_path', 'filePath'),
288
+ oldString: str(raw, 'old_str', 'old_string', 'oldString'),
289
+ newString: str(raw, 'new_str', 'new_string', 'newString'),
290
+ };
291
+ const replaceAll = optBool(raw, 'replace_all', 'replaceAll');
292
+ if (replaceAll != null) result.replaceAll = replaceAll;
293
+ return result;
294
+ }
295
+
296
+ function normalizeGrepInput(raw: RawToolArgs): GrepInput {
297
+ const result: GrepInput = { pattern: str(raw, 'pattern', 'query') };
298
+ const path = optStr(raw, 'path', 'directory', 'dir');
299
+ if (path != null) result.path = path;
300
+ const glob = optStr(raw, 'glob', 'include', 'file_pattern');
301
+ if (glob != null) result.glob = glob;
302
+ const outputMode = optStr(raw, 'output_mode', 'outputMode') as GrepInput['outputMode'];
303
+ if (outputMode != null) result.outputMode = outputMode;
304
+ const type = optStr(raw, 'type', 'file_type');
305
+ if (type != null) result.type = type;
306
+ const headLimit = optNum(raw, 'head_limit', 'headLimit', 'max_results');
307
+ if (headLimit != null) result.headLimit = headLimit;
308
+ const offset = optNum(raw, 'offset');
309
+ if (offset != null) result.offset = offset;
310
+ const multiline = optBool(raw, 'multiline');
311
+ if (multiline != null) result.multiline = multiline;
312
+ const caseInsensitive = optBool(raw, 'case_insensitive', 'caseInsensitive', 'ignore_case', '-i');
313
+ if (caseInsensitive != null) result.caseInsensitive = caseInsensitive;
314
+ const beforeContext = optNum(raw, 'before_context', 'beforeContext', '-B');
315
+ if (beforeContext != null) result.beforeContext = beforeContext;
316
+ const afterContext = optNum(raw, 'after_context', 'afterContext', '-A');
317
+ if (afterContext != null) result.afterContext = afterContext;
318
+ const context = optNum(raw, 'context', '-C');
319
+ if (context != null) result.context = context;
320
+ const lineNumbers = optBool(raw, 'line_numbers', 'lineNumbers', '-n');
321
+ if (lineNumbers != null) result.lineNumbers = lineNumbers;
322
+ return result;
323
+ }
324
+
325
+ function normalizeGlobInput(raw: RawToolArgs): GlobInput {
326
+ const result: GlobInput = { pattern: str(raw, 'pattern', 'glob', 'query') };
327
+ const path = optStr(raw, 'path', 'directory', 'dir');
328
+ if (path != null) result.path = path;
329
+ return result;
330
+ }
331
+
332
+ function normalizeListInput(raw: RawToolArgs): ListInput {
333
+ const result: ListInput = {};
334
+ const path = optStr(raw, 'path', 'directory', 'dir');
335
+ if (path != null) result.path = path;
336
+ const ignore = raw.ignore;
337
+ if (Array.isArray(ignore) && ignore.length) result.ignore = ignore.map(String);
338
+ return result;
339
+ }
340
+
341
+ function normalizeWebSearchInput(raw: RawToolArgs): WebSearchInput {
342
+ const result: WebSearchInput = { query: str(raw, 'query', 'q', 'search') };
343
+ const allowed = raw.allowed_domains ?? raw.allowedDomains;
344
+ if (Array.isArray(allowed) && allowed.length) result.allowedDomains = allowed.map(String);
345
+ const blocked = raw.blocked_domains ?? raw.blockedDomains;
346
+ if (Array.isArray(blocked) && blocked.length) result.blockedDomains = blocked.map(String);
347
+ return result;
348
+ }
349
+
350
+ function normalizeWebFetchInput(raw: RawToolArgs): WebFetchInput {
351
+ return {
352
+ url: str(raw, 'url', 'href'),
353
+ prompt: str(raw, 'prompt', 'instruction', 'query', 'format'),
354
+ };
355
+ }
356
+
357
+ function normalizeAskUserQuestionInput(raw: RawToolArgs): AskUserQuestionInput {
358
+ const questions = raw.questions;
359
+ if (Array.isArray(questions)) {
360
+ return { questions: questions as AskUserQuestionInput['questions'] };
361
+ }
362
+ // Copilot's `ask_user` typically passes a single `question` string + optional `choices` array.
363
+ const question = str(raw, 'question', 'prompt');
364
+ if (!question) return { questions: [] };
365
+ const choices = raw.choices ?? raw.options;
366
+ const options = Array.isArray(choices)
367
+ ? choices.map(c => ({
368
+ label: String(typeof c === 'object' && c && 'label' in c ? (c as Record<string, unknown>).label : c),
369
+ description: '',
370
+ }))
371
+ : [];
372
+ return {
373
+ questions: [{
374
+ question,
375
+ header: '',
376
+ options,
377
+ multiSelect: false,
378
+ }],
379
+ };
380
+ }
381
+
382
+ function normalizeTodoWriteInput(raw: RawToolArgs): TodoWriteInput {
383
+ const todos = raw.todos ?? raw.items ?? raw.list;
384
+ return { todos: Array.isArray(todos) ? (todos as TodoWriteInput['todos']) : [] };
385
+ }
386
+
387
+ function normalizeToolSearchInput(raw: RawToolArgs): ToolSearchInput {
388
+ const result: ToolSearchInput = { query: str(raw, 'query', 'pattern', 'regex') };
389
+ const maxResults = optNum(raw, 'max_results', 'maxResults', 'limit');
390
+ if (maxResults != null) result.maxResults = maxResults;
391
+ return result;
392
+ }
393
+
394
+ /**
395
+ * Copilot's `task` tool dispatches a named sub-agent. Its arguments look like:
396
+ * { name, agent_type, description, prompt, mode }
397
+ * Map those to the unified `AgentInput` so the Agent tool component renders
398
+ * the same way as Claude's `Task` and OpenCode's `task`.
399
+ */
400
+ function normalizeAgentInput(raw: RawToolArgs): AgentInput {
401
+ return {
402
+ prompt: str(raw, 'prompt', 'task', 'instruction'),
403
+ description: optStr(raw, 'description', 'desc') ?? '',
404
+ subagentType: optStr(raw, 'agent_type', 'agentType', 'subagent_type', 'subagentType', 'agent', 'name')
405
+ ?? 'general-purpose',
406
+ };
407
+ }
408
+
409
+ /**
410
+ * Normalize raw Copilot tool arguments → canonical input shape. Unknown/MCP
411
+ * tools fall through with their args unchanged.
412
+ */
413
+ function normalizeCopilotToolInput(canonical: string, raw: RawToolArgs): Record<string, unknown> {
414
+ if (canonical.startsWith('mcp__') || canonical.startsWith('Unknown:')) return raw;
415
+ switch (canonical) {
416
+ case 'Bash': return normalizeBashInput(raw) as unknown as Record<string, unknown>;
417
+ case 'Read': return normalizeReadInput(raw) as unknown as Record<string, unknown>;
418
+ case 'Write': return normalizeWriteInput(raw) as unknown as Record<string, unknown>;
419
+ case 'Edit': return normalizeEditInput(raw) as unknown as Record<string, unknown>;
420
+ case 'Grep': return normalizeGrepInput(raw) as unknown as Record<string, unknown>;
421
+ case 'Glob': return normalizeGlobInput(raw) as unknown as Record<string, unknown>;
422
+ case 'List': return normalizeListInput(raw) as unknown as Record<string, unknown>;
423
+ case 'WebSearch': return normalizeWebSearchInput(raw) as unknown as Record<string, unknown>;
424
+ case 'WebFetch': return normalizeWebFetchInput(raw) as unknown as Record<string, unknown>;
425
+ case 'AskUserQuestion': return normalizeAskUserQuestionInput(raw) as unknown as Record<string, unknown>;
426
+ case 'TodoWrite': return normalizeTodoWriteInput(raw) as unknown as Record<string, unknown>;
427
+ case 'ToolSearch': return normalizeToolSearchInput(raw) as unknown as Record<string, unknown>;
428
+ case 'Agent': return normalizeAgentInput(raw) as unknown as Record<string, unknown>;
429
+ default: return raw;
430
+ }
431
+ }
432
+
433
+ // ============================================================================
434
+ // Stream State (per-stream, isolated across concurrent sessions)
435
+ // ============================================================================
436
+
437
+ export interface StreamConverterState {
438
+ sessionId: string;
439
+ modelId: string;
440
+ /** Reasoning text accumulated from reasoning_delta events, keyed by reasoningId. */
441
+ reasoningBuffers: Map<string, string>;
442
+ /** ToolCallId → tool name (canonicalised) so tool_result can reference it. */
443
+ toolNames: Map<string, string>;
444
+ /** Whether the assistant text stream is currently open (for lifecycle pairing). */
445
+ textStreamActive: boolean;
446
+ /** Whether the assistant reasoning stream is currently open. */
447
+ reasoningStreamActive: boolean;
448
+ /** Last seen usage payload — held until session.idle to build the ResultEvent. */
449
+ lastUsage: AssistantUsageData | null;
450
+ /** Most recent assistant.message ID (used for stable parenting if needed). */
451
+ lastAssistantMessageId: string | null;
452
+ /**
453
+ * Assistant messages awaiting flush. We buffer because `assistant.usage`
454
+ * arrives AFTER `assistant.message` for the same turn iteration — we want
455
+ * to attach usage to the originating message before emitting it downstream.
456
+ */
457
+ pendingMessages: UnifiedAssistantMessage[];
458
+ /**
459
+ * Tool call IDs whose tool_use was filtered out (Copilot harness tools).
460
+ * `tool.execution_complete` for these IDs must also be dropped so the UI
461
+ * never receives an orphan tool_result without its tool_use.
462
+ */
463
+ ignoredToolCallIds: Set<string>;
464
+ /**
465
+ * Sub-agent instance id → tool call id of the parent `task` (Agent) tool.
466
+ *
467
+ * Populated on `subagent.started`. Every event a sub-agent emits carries
468
+ * `event.agentId`; we use this map to resolve the originating Agent
469
+ * tool_use id and stamp `parent.toolUseId` on the sub-agent's
470
+ * assistant/user messages. Without this, the message grouper at
471
+ * `frontend/utils/chat/message-grouper.ts` cannot route sub-agent activity
472
+ * into the parent Agent block — sub-agent tool calls render as orphan
473
+ * top-level messages.
474
+ */
475
+ agentParentMap: Map<string, string>;
476
+ /**
477
+ * AskUserQuestion tool call id → original question text. Captured when
478
+ * the `ask_user` tool_use block is built so that, on
479
+ * `tool.execution_complete`, we can reformat Copilot's plain-text
480
+ * "User selected: X" payload into the JSON shape
481
+ * (`{"answers": {<question>: <answer>}}`) the UI's parser expects (see
482
+ * `frontend/components/chat/tools/variants/.../AskUserQuestionTool.svelte`).
483
+ * Without this, the UI fails to parse the answer and renders the
484
+ * AskUserQuestion bubble as a red error instead of the green answered
485
+ * state.
486
+ */
487
+ askUserQuestions: Map<string, string>;
488
+ }
489
+
490
+ export function createStreamConverterState(sessionId: string, modelId: string): StreamConverterState {
491
+ return {
492
+ sessionId,
493
+ modelId,
494
+ reasoningBuffers: new Map(),
495
+ toolNames: new Map(),
496
+ textStreamActive: false,
497
+ reasoningStreamActive: false,
498
+ lastUsage: null,
499
+ lastAssistantMessageId: null,
500
+ pendingMessages: [],
501
+ ignoredToolCallIds: new Set(),
502
+ agentParentMap: new Map(),
503
+ askUserQuestions: new Map(),
504
+ };
505
+ }
506
+
507
+ /**
508
+ * Resolve the parent Agent tool call id for an event emitted from inside a
509
+ * sub-agent. Prefers the (deprecated but still emitted) `data.parentToolCallId`
510
+ * direct hint; falls back to `event.agentId` looked up in `agentParentMap`.
511
+ * Returns `null` for events from the root agent or session-level events.
512
+ */
513
+ export function resolveParentToolUseId(
514
+ event: SessionEvent,
515
+ state: StreamConverterState,
516
+ ): string | null {
517
+ const data = (event as { data?: { parentToolCallId?: string } }).data;
518
+ const direct = data?.parentToolCallId;
519
+ if (direct) return direct;
520
+ const agentId = (event as { agentId?: string }).agentId;
521
+ if (agentId) {
522
+ const mapped = state.agentParentMap.get(agentId);
523
+ if (mapped) return mapped;
524
+ }
525
+ return null;
526
+ }
527
+
528
+ /**
529
+ * `subagent.started` registers a sub-agent instance. Every subsequent event
530
+ * with the same `agentId` belongs to this sub-agent, and its `toolCallId` is
531
+ * the parent Agent (`task`) tool block id.
532
+ */
533
+ export function convertSubagentStarted(
534
+ event: { agentId?: string; data: SubagentStartedData },
535
+ state: StreamConverterState,
536
+ ): EngineOutput[] {
537
+ if (event.agentId) {
538
+ state.agentParentMap.set(event.agentId, event.data.toolCallId);
539
+ }
540
+ return [];
541
+ }
542
+
543
+ /**
544
+ * Cleanup mapping when a sub-agent finishes. Late-arriving events still resolve
545
+ * via `data.parentToolCallId`, so dropping the entry is safe.
546
+ */
547
+ export function convertSubagentEnded(
548
+ event: { agentId?: string; data: SubagentCompletedData | SubagentFailedData },
549
+ state: StreamConverterState,
550
+ ): EngineOutput[] {
551
+ if (event.agentId) state.agentParentMap.delete(event.agentId);
552
+ return [];
553
+ }
554
+
555
+ /**
556
+ * Drain `pendingMessages` and return them as EngineOutput. Call before any
557
+ * downstream-visible event (tool execution, turn end, session idle) so that
558
+ * messages are emitted in source order even if usage attaches late.
559
+ *
560
+ * Fallback: if a message is being emitted with no usage attached (i.e.
561
+ * `assistant.usage` for its LLM call hasn't arrived yet), backfill from the
562
+ * most recent known usage. This keeps the chat header's context-window
563
+ * indicator non-zero in turns where the SDK emits usage AFTER the assistant
564
+ * message has already been forced out (e.g. by a downstream tool event).
565
+ */
566
+ export function flushPending(state: StreamConverterState): EngineOutput[] {
567
+ if (state.pendingMessages.length === 0) return [];
568
+ const fallback = state.lastUsage ? mapUsage(state.lastUsage) : null;
569
+ if (fallback) {
570
+ for (const msg of state.pendingMessages) {
571
+ if (msg.usage == null) msg.usage = fallback;
572
+ }
573
+ }
574
+ const out: EngineOutput[] = state.pendingMessages.slice();
575
+ state.pendingMessages = [];
576
+ return out;
577
+ }
578
+
579
+ // ============================================================================
580
+ // System / Lifecycle Converters
581
+ // ============================================================================
582
+
583
+ export function convertSessionStart(data: StartData, modelId: string): SystemInitEvent {
584
+ return {
585
+ type: 'system_init',
586
+ sessionId: data.sessionId,
587
+ model: data.selectedModel || modelId || '',
588
+ engine: 'copilot',
589
+ tools: [],
590
+ mcpServers: [],
591
+ };
592
+ }
593
+
594
+ export function convertTurnStart(state: StreamConverterState): StreamLifecycleEvent {
595
+ state.textStreamActive = true;
596
+ return {
597
+ type: 'stream_event',
598
+ event: 'start',
599
+ sessionId: state.sessionId,
600
+ reasoning: false,
601
+ };
602
+ }
603
+
604
+ export function convertTurnEnd(_data: AssistantTurnEndData, state: StreamConverterState): EngineOutput[] {
605
+ const events: EngineOutput[] = flushPending(state);
606
+ if (state.reasoningStreamActive) {
607
+ events.push({ type: 'stream_event', event: 'stop', sessionId: state.sessionId, reasoning: true });
608
+ state.reasoningStreamActive = false;
609
+ }
610
+ if (state.textStreamActive) {
611
+ events.push({ type: 'stream_event', event: 'stop', sessionId: state.sessionId, reasoning: false });
612
+ state.textStreamActive = false;
613
+ }
614
+ return events;
615
+ }
616
+
617
+ // ============================================================================
618
+ // Reasoning Converters
619
+ // ============================================================================
620
+
621
+ export function convertReasoningDelta(data: AssistantReasoningDeltaData, state: StreamConverterState): EngineOutput[] {
622
+ const out: EngineOutput[] = [];
623
+
624
+ if (!state.reasoningStreamActive) {
625
+ // Pause text stream while reasoning streams.
626
+ if (state.textStreamActive) {
627
+ out.push({ type: 'stream_event', event: 'stop', sessionId: state.sessionId, reasoning: false } as StreamLifecycleEvent);
628
+ state.textStreamActive = false;
629
+ }
630
+ out.push({ type: 'stream_event', event: 'start', sessionId: state.sessionId, reasoning: true } as StreamLifecycleEvent);
631
+ state.reasoningStreamActive = true;
632
+ }
633
+
634
+ const prev = state.reasoningBuffers.get(data.reasoningId) ?? '';
635
+ state.reasoningBuffers.set(data.reasoningId, prev + (data.deltaContent ?? ''));
636
+
637
+ const delta: TextDeltaEvent = {
638
+ type: 'stream_event',
639
+ event: 'delta',
640
+ sessionId: state.sessionId,
641
+ text: data.deltaContent ?? '',
642
+ reasoning: true,
643
+ };
644
+ out.push(delta);
645
+ return out;
646
+ }
647
+
648
+ export function convertReasoning(
649
+ data: AssistantReasoningData,
650
+ state: StreamConverterState,
651
+ parentToolUseId: string | null = null,
652
+ ): EngineOutput[] {
653
+ const out: EngineOutput[] = [];
654
+ const text = (data.content ?? state.reasoningBuffers.get(data.reasoningId) ?? '').trim();
655
+ state.reasoningBuffers.delete(data.reasoningId);
656
+
657
+ if (state.reasoningStreamActive) {
658
+ out.push({ type: 'stream_event', event: 'stop', sessionId: state.sessionId, reasoning: true } as StreamLifecycleEvent);
659
+ state.reasoningStreamActive = false;
660
+ }
661
+
662
+ if (!text) return out;
663
+
664
+ const reasoning: ReasoningMessage = {
665
+ type: 'reasoning',
666
+ createdAt: new Date().toISOString(),
667
+ messageId: crypto.randomUUID(),
668
+ sessionId: state.sessionId,
669
+ parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId },
670
+ engine: buildEngine(state.modelId),
671
+ text,
672
+ };
673
+ out.push(reasoning);
674
+ return out;
675
+ }
676
+
677
+ // ============================================================================
678
+ // Assistant Message Converters
679
+ // ============================================================================
680
+
681
+ export function convertMessageDelta(data: AssistantMessageDeltaData, state: StreamConverterState): EngineOutput[] {
682
+ const out: EngineOutput[] = [];
683
+ if (state.reasoningStreamActive) {
684
+ out.push({ type: 'stream_event', event: 'stop', sessionId: state.sessionId, reasoning: true } as StreamLifecycleEvent);
685
+ state.reasoningStreamActive = false;
686
+ }
687
+ if (!state.textStreamActive) {
688
+ out.push({ type: 'stream_event', event: 'start', sessionId: state.sessionId, reasoning: false } as StreamLifecycleEvent);
689
+ state.textStreamActive = true;
690
+ }
691
+ const delta: TextDeltaEvent = {
692
+ type: 'stream_event',
693
+ event: 'delta',
694
+ sessionId: state.sessionId,
695
+ text: data.deltaContent ?? '',
696
+ reasoning: false,
697
+ };
698
+ out.push(delta);
699
+ return out;
700
+ }
701
+
702
+ /**
703
+ * Convert a final assistant.message event into one or more assistant messages,
704
+ * one per logical block (text + each tool_use), matching the convention used
705
+ * by the Claude and OpenCode adapters where every assistant message in the
706
+ * chat surface holds AT MOST one tool_use block.
707
+ *
708
+ * Internal Copilot harness tools (see IGNORED_COPILOT_TOOLS) are dropped here
709
+ * so they never reach the UI as `Unknown:*` blocks.
710
+ *
711
+ * Returns previously-buffered messages and buffers the new ones — the actual
712
+ * emission happens lazily so `assistant.usage` (which arrives next in the
713
+ * stream) can attach to the most recent message before it leaves the adapter.
714
+ */
715
+ export function convertAssistantMessage(
716
+ data: AssistantMessageData,
717
+ state: StreamConverterState,
718
+ parentToolUseId: string | null = null,
719
+ ): EngineOutput[] {
720
+ state.lastAssistantMessageId = data.messageId;
721
+
722
+ const flushed = flushPending(state);
723
+
724
+ const visibleToolRequests: AssistantMessageToolRequest[] = [];
725
+ for (const req of data.toolRequests ?? []) {
726
+ const canonical = mapCopilotToolName(req.name, req.mcpServerName);
727
+ state.toolNames.set(req.toolCallId, canonical);
728
+ if (isIgnoredCopilotTool(req.name, req.mcpServerName)) {
729
+ state.ignoredToolCallIds.add(req.toolCallId);
730
+ } else {
731
+ visibleToolRequests.push(req);
732
+ }
733
+ }
734
+
735
+ const blocks: AssistantContentBlock[] = [];
736
+ if (data.content && data.content.length > 0) {
737
+ blocks.push({ type: 'text', text: data.content });
738
+ }
739
+ for (const req of visibleToolRequests) {
740
+ blocks.push(buildToolUseBlock(req, state));
741
+ }
742
+
743
+ if (blocks.length === 0) {
744
+ return flushed;
745
+ }
746
+
747
+ const baseId = data.messageId || crypto.randomUUID();
748
+ const messages: UnifiedAssistantMessage[] = blocks.map((block, idx) => ({
749
+ type: 'assistant',
750
+ createdAt: new Date().toISOString(),
751
+ messageId: blocks.length === 1 ? baseId : `${baseId}:${idx}`,
752
+ sessionId: state.sessionId,
753
+ parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId },
754
+ engine: buildEngine(state.modelId),
755
+ content: [block],
756
+ stopReason: block.type === 'tool_use' ? 'tool_use' : 'end_turn',
757
+ usage: null,
758
+ }));
759
+
760
+ state.pendingMessages.push(...messages);
761
+ return flushed;
762
+ }
763
+
764
+ function buildToolUseBlock(req: AssistantMessageToolRequest, state: StreamConverterState): ToolUseBlock {
765
+ const canonical = mapCopilotToolName(req.name, req.mcpServerName);
766
+ const input = normalizeCopilotToolInput(canonical, (req.arguments ?? {}) as RawToolArgs);
767
+
768
+ // Remember the question text per ask_user toolCallId so we can rewrite
769
+ // `tool.execution_complete` content into the JSON shape the UI expects.
770
+ if (canonical === 'AskUserQuestion') {
771
+ const askInput = input as unknown as AskUserQuestionInput;
772
+ const firstQuestion = askInput.questions?.[0]?.question;
773
+ if (firstQuestion) state.askUserQuestions.set(req.toolCallId, firstQuestion);
774
+ }
775
+
776
+ return {
777
+ type: 'tool_use',
778
+ id: req.toolCallId,
779
+ name: canonical,
780
+ input,
781
+ result: null,
782
+ subActivities: [],
783
+ skillPrompt: null,
784
+ interrupted: false,
785
+ } as ToolUseBlock;
786
+ }
787
+
788
+ // ============================================================================
789
+ // Tool Execution Converters
790
+ // ============================================================================
791
+
792
+ /**
793
+ * tool.execution_start arrives WHEN the assistant begins executing a tool. The
794
+ * Copilot SDK already emitted the corresponding tool_use block in the prior
795
+ * assistant.message — so we don't yield anything new here. We just remember
796
+ * the tool name so a later tool_result can carry the canonical name.
797
+ */
798
+ export function convertToolStart(data: ToolExecutionStartData, state: StreamConverterState): EngineOutput[] {
799
+ const canonical = mapCopilotToolName(data.toolName, data.mcpServerName);
800
+ state.toolNames.set(data.toolCallId, canonical);
801
+ if (isIgnoredCopilotTool(data.toolName, data.mcpServerName)) {
802
+ state.ignoredToolCallIds.add(data.toolCallId);
803
+ }
804
+ return [];
805
+ }
806
+
807
+ /**
808
+ * tool.execution_complete carries the LLM-facing result content. We emit it as
809
+ * a synthetic UserMessage with a single tool_result block, mirroring how Claude's
810
+ * SDK delivers the same information back to the loop.
811
+ *
812
+ * Results for ignored Copilot harness tools (report_intent, task_complete, …)
813
+ * are dropped so the UI never sees an orphan tool_result without its tool_use.
814
+ *
815
+ * IMPORTANT: `parent.toolUseId` MUST be left null. The frontend grouper
816
+ * (frontend/utils/chat/message-grouper.ts) treats any user message whose
817
+ * parent.toolUseId is non-null as a sub-agent message — i.e. one emitted from
818
+ * inside an Agent (Task) tool execution — and either redirects it into the
819
+ * sub-agent activity bucket or silently drops it. The toolCallId belongs on
820
+ * the inner `tool_result` block, not on the message-level parent pointer.
821
+ * Setting it on `parent.toolUseId` was a bug that caused tool_results to
822
+ * never reach the UI, leaving `tool_use.result` null at render time.
823
+ */
824
+ export function convertToolComplete(
825
+ data: ToolExecutionCompleteData,
826
+ state: StreamConverterState,
827
+ parentToolUseId: string | null = null,
828
+ ): EngineOutput[] {
829
+ if (state.ignoredToolCallIds.has(data.toolCallId)) {
830
+ state.ignoredToolCallIds.delete(data.toolCallId);
831
+ state.toolNames.delete(data.toolCallId);
832
+ return [];
833
+ }
834
+
835
+ let resultText = extractToolResultContent(data);
836
+
837
+ // AskUserQuestion: rewrite Copilot's plain-text result
838
+ // (e.g. "User selected: X") into the `{"answers": {<q>: <a>}}` JSON
839
+ // shape the UI's parseResultAnswers expects. Without this rewrite, the
840
+ // parser finds no matching question key and renders the bubble in the
841
+ // red error state even though the user answered successfully.
842
+ if (state.toolNames.get(data.toolCallId) === 'AskUserQuestion') {
843
+ const question = state.askUserQuestions.get(data.toolCallId);
844
+ state.askUserQuestions.delete(data.toolCallId);
845
+ if (question) {
846
+ const answer = extractAskUserAnswer(resultText);
847
+ resultText = JSON.stringify({ answers: { [question]: answer } });
848
+ }
849
+ }
850
+
851
+ const userBlock: UserContentBlock = {
852
+ type: 'tool_result',
853
+ toolUseId: data.toolCallId,
854
+ content: resultText,
855
+ isError: !data.success || !!data.error,
856
+ };
857
+
858
+ const message: UserMessage = {
859
+ type: 'user',
860
+ createdAt: new Date().toISOString(),
861
+ messageId: crypto.randomUUID(),
862
+ sessionId: state.sessionId,
863
+ parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId },
864
+ engine: buildEngine(state.modelId),
865
+ sender: { id: '', name: '' },
866
+ content: [userBlock],
867
+ synthetic: true,
868
+ };
869
+ return [message];
870
+ }
871
+
872
+ /**
873
+ * Pull the user's answer out of Copilot's `ask_user` result text. The
874
+ * Copilot CLI formats the result as "User selected: <answer>" for the
875
+ * agent's own context, so we strip that prefix to recover the raw answer
876
+ * before re-emitting it as JSON for the UI.
877
+ */
878
+ function extractAskUserAnswer(resultText: string): string {
879
+ const trimmed = resultText.trim();
880
+ const prefix = 'User selected:';
881
+ if (trimmed.toLowerCase().startsWith(prefix.toLowerCase())) {
882
+ return trimmed.slice(prefix.length).trim();
883
+ }
884
+ return trimmed;
885
+ }
886
+
887
+ /**
888
+ * Extract the human-readable content for a tool_result from a Copilot
889
+ * `tool.execution_complete` payload. Prefers `detailedContent` (the diff /
890
+ * full output the model receives), then `content` (short summary), then any
891
+ * structured `contents` blocks, and finally falls back to the error message
892
+ * for failed tool calls.
893
+ */
894
+ function extractToolResultContent(data: ToolExecutionCompleteData): string {
895
+ const result = data.result as
896
+ | { detailedContent?: string; content?: string; contents?: unknown }
897
+ | undefined;
898
+
899
+ if (typeof result?.detailedContent === 'string' && result.detailedContent.length > 0) {
900
+ return result.detailedContent;
901
+ }
902
+ if (typeof result?.content === 'string' && result.content.length > 0) {
903
+ return result.content;
904
+ }
905
+
906
+ if (Array.isArray(result?.contents)) {
907
+ const parts: string[] = [];
908
+ for (const item of result.contents) {
909
+ if (typeof item === 'string') {
910
+ parts.push(item);
911
+ } else if (item && typeof item === 'object') {
912
+ const obj = item as Record<string, unknown>;
913
+ if (typeof obj.text === 'string') parts.push(obj.text);
914
+ else if (typeof obj.content === 'string') parts.push(obj.content);
915
+ }
916
+ }
917
+ const joined = parts.join('\n').trim();
918
+ if (joined) return joined;
919
+ }
920
+
921
+ if (data.error?.message) return `Error: ${data.error.message}`;
922
+ if (!data.success) return 'Tool execution failed';
923
+ return '';
924
+ }
925
+
926
+ // ============================================================================
927
+ // Usage / Idle Converters
928
+ // ============================================================================
929
+
930
+ /**
931
+ * `assistant.usage` arrives once per LLM call, AFTER the corresponding
932
+ * `assistant.message` (and any tool_use blocks split out of it) but BEFORE
933
+ * tool execution events. We attach the usage to the most recent pending
934
+ * message so the persisted row carries token counts, then flush.
935
+ *
936
+ * The aggregate usage is also retained on `state.lastUsage` for the final
937
+ * `result` event built at session.idle.
938
+ */
939
+ export function captureUsage(data: AssistantUsageData, state: StreamConverterState): EngineOutput[] {
940
+ state.lastUsage = data;
941
+
942
+ const pending = state.pendingMessages;
943
+ if (pending.length > 0) {
944
+ const target = pending[pending.length - 1]!;
945
+ target.usage = mapUsage(data);
946
+ }
947
+ return flushPending(state);
948
+ }
949
+
950
+ export function buildResultEvent(state: StreamConverterState, aborted: boolean): SuccessResultEvent {
951
+ const usage = mapUsage(state.lastUsage);
952
+ return {
953
+ type: 'result',
954
+ subtype: 'success',
955
+ sessionId: state.sessionId,
956
+ numTurns: 0,
957
+ totalCostUsd: state.lastUsage?.cost ?? 0,
958
+ usage,
959
+ stopReason: aborted ? 'interrupted' : 'end_turn',
960
+ };
961
+ }
962
+
963
+ function mapUsage(raw: AssistantUsageData | null): TokenUsage {
964
+ if (!raw) {
965
+ return { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0 };
966
+ }
967
+ return {
968
+ inputTokens: raw.inputTokens ?? 0,
969
+ outputTokens: raw.outputTokens ?? 0,
970
+ cacheCreationInputTokens: raw.cacheWriteTokens ?? 0,
971
+ cacheReadInputTokens: raw.cacheReadTokens ?? 0,
972
+ };
973
+ }