@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,573 @@
1
+ /**
2
+ * Copilot Engine Adapter
3
+ *
4
+ * Wraps the @github/copilot-sdk into the AIEngine interface.
5
+ * One CopilotClient per project — abort controllers and active sessions are
6
+ * isolated by the per-project engine registry in backend/engine/index.ts.
7
+ */
8
+
9
+ import { CopilotClient, approveAll } from '@github/copilot-sdk';
10
+ import type {
11
+ CopilotSession,
12
+ SessionConfig,
13
+ ResumeSessionConfig,
14
+ SessionEvent,
15
+ ModelInfo,
16
+ } from '@github/copilot-sdk';
17
+ import type { EngineOutput, EngineModel } from '$shared/types/unified';
18
+ import type { AIEngine, EngineQueryOptions } from '../../types';
19
+ import { engineQueries } from '$backend/database/queries/engine-queries';
20
+ import { resolveOsPath } from '$backend/utils/paths';
21
+ import { debug } from '$shared/utils/logger';
22
+ import { getCopilotMcpConfig } from '../../../mcp/config';
23
+ import { handleStreamError, buildSessionError } from './error-handler';
24
+ import { fetchCopilotModels } from './models';
25
+
26
+ // `UserInputResponse` isn't part of the SDK's public type exports
27
+ // (see `node_modules/@github/copilot-sdk/dist/index.d.ts`), but
28
+ // `onUserInputRequest`'s return type is exactly that shape — derive
29
+ // it from the SessionConfig field so we don't drift from the SDK.
30
+ type UserInputResponse = Awaited<ReturnType<NonNullable<SessionConfig['onUserInputRequest']>>>;
31
+ import {
32
+ createStreamConverterState,
33
+ convertSessionStart,
34
+ convertTurnStart,
35
+ convertTurnEnd,
36
+ convertReasoning,
37
+ convertReasoningDelta,
38
+ convertMessageDelta,
39
+ convertAssistantMessage,
40
+ convertToolStart,
41
+ convertToolComplete,
42
+ captureUsage,
43
+ buildResultEvent,
44
+ flushPending,
45
+ resolveParentToolUseId,
46
+ convertSubagentStarted,
47
+ convertSubagentEnded,
48
+ } from './message-converter';
49
+ import { forkCopilotSessionState, sessionStateExists } from './session-fork';
50
+
51
+ const ABORT_TIMEOUT_MS = 5000;
52
+
53
+ /**
54
+ * Pending AskUserQuestion entry — the Copilot SDK's `onUserInputRequest`
55
+ * callback is parked on a Promise stored here, keyed by the `toolCallId`
56
+ * of the originating `ask_user` tool block. `resolveUserAnswer` looks it
57
+ * up and resolves the Promise, unblocking the SDK so the agent's turn
58
+ * can continue.
59
+ *
60
+ * `choices` is captured so we can decide `wasFreeform` (Copilot's SDK
61
+ * field) by checking whether the user's answer is one of the predefined
62
+ * choices — a freeform answer would mean the user typed something not
63
+ * in the choices array.
64
+ */
65
+ interface PendingCopilotUserAnswer {
66
+ resolve: (response: UserInputResponse) => void;
67
+ choices?: string[];
68
+ }
69
+
70
+ export class CopilotEngine implements AIEngine {
71
+ readonly name = 'copilot' as const;
72
+
73
+ private _isInitialized = false;
74
+ private client: CopilotClient | null = null;
75
+ private activeSession: CopilotSession | null = null;
76
+ private activeController: AbortController | null = null;
77
+ private modelsCache: ModelInfo[] | null = null;
78
+ /**
79
+ * Account ID currently baked into `this.client`. The Copilot SDK takes the
80
+ * GitHub token as a constructor argument, so per-stream account overrides
81
+ * require disposing and re-creating the client (see streamQuery below).
82
+ */
83
+ private currentAccountId: number | null = null;
84
+
85
+ /**
86
+ * AskUserQuestion bookkeeping. The Copilot SDK splits the `ask_user`
87
+ * flow across two channels:
88
+ * - the `assistant.message` / `tool.execution_start` /
89
+ * `user_input.requested` events all carry the `toolCallId` of the
90
+ * `ask_user` invocation (matching the tool_use block in the UI)
91
+ * - `onUserInputRequest` callback carries the question/choices but
92
+ * NOT the toolCallId (see `node_modules/@github/copilot-sdk/dist/client.js::handleUserInputRequest`)
93
+ *
94
+ * To correlate the two we capture the most recent `toolCallId` from
95
+ * those events into `pendingAskUserToolCallId`, then read it inside
96
+ * the callback. Only one `ask_user` can be outstanding per session at
97
+ * a time (the SDK blocks the agent's turn until the callback returns),
98
+ * so a single-slot variable is sufficient.
99
+ */
100
+ private pendingUserAnswers = new Map<string, PendingCopilotUserAnswer>();
101
+ private pendingAskUserToolCallId: string | null = null;
102
+
103
+ get isInitialized(): boolean {
104
+ return this._isInitialized;
105
+ }
106
+
107
+ get isActive(): boolean {
108
+ return this.activeController !== null;
109
+ }
110
+
111
+ async initialize(accountId?: number): Promise<void> {
112
+ if (this._isInitialized && (accountId == null || accountId === this.currentAccountId)) {
113
+ return;
114
+ }
115
+
116
+ const account = accountId != null
117
+ ? engineQueries.getAccount(accountId)
118
+ : engineQueries.getActiveAccountForEngine('copilot');
119
+ if (!account) {
120
+ throw new Error('No active GitHub Copilot account. Add a Personal Access Token in Settings → Engines.');
121
+ }
122
+
123
+ this.client = new CopilotClient({
124
+ gitHubToken: account.credential,
125
+ useLoggedInUser: false,
126
+ autoStart: true,
127
+ });
128
+
129
+ await this.client.start();
130
+ this.currentAccountId = account.id;
131
+ this._isInitialized = true;
132
+ debug.log('engine', `Copilot engine initialized (account ${account.id})`);
133
+ }
134
+
135
+ async dispose(): Promise<void> {
136
+ await this.cancel();
137
+
138
+ if (this.client) {
139
+ try {
140
+ const errors = await this.client.stop();
141
+ if (errors.length > 0) {
142
+ debug.warn('engine', 'Copilot client.stop() reported errors:', errors);
143
+ }
144
+ } catch (error) {
145
+ debug.warn('engine', 'Copilot client.stop() failed (non-fatal):', error);
146
+ try {
147
+ await this.client.forceStop();
148
+ } catch (forceErr) {
149
+ debug.warn('engine', 'Copilot client.forceStop() failed:', forceErr);
150
+ }
151
+ }
152
+ }
153
+
154
+ this.client = null;
155
+ this.modelsCache = null;
156
+ this.currentAccountId = null;
157
+ this._isInitialized = false;
158
+ debug.log('engine', 'Copilot engine disposed');
159
+ }
160
+
161
+ async getAvailableModels(): Promise<EngineModel[]> {
162
+ if (!this.client) {
163
+ try {
164
+ await this.initialize();
165
+ } catch (error) {
166
+ debug.warn('engine', 'Copilot getAvailableModels: initialize failed:', error);
167
+ return [];
168
+ }
169
+ }
170
+ if (!this.client) return [];
171
+
172
+ const result = await fetchCopilotModels(this.client, this.modelsCache);
173
+ this.modelsCache = result.cache;
174
+ return result.models;
175
+ }
176
+
177
+ async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
178
+ const { projectPath, prompt, resume, modelId, abortController, accountId } = options;
179
+
180
+ // Per-stream account override: the Copilot SDK takes the GitHub token at
181
+ // construction time, so an account switch requires recreating the client.
182
+ if (this._isInitialized && accountId != null && accountId !== this.currentAccountId) {
183
+ debug.log('engine', `Copilot account switch ${this.currentAccountId} → ${accountId}; re-initializing client`);
184
+ await this.dispose();
185
+ }
186
+
187
+ if (!this._isInitialized || !this.client) {
188
+ await this.initialize(accountId);
189
+ }
190
+ if (!this.client) {
191
+ throw new Error('Copilot client unavailable.');
192
+ }
193
+
194
+ this.activeController = abortController || new AbortController();
195
+
196
+ const resolvedProjectPath = resolveOsPath(projectPath);
197
+ const state = createStreamConverterState('', modelId);
198
+
199
+ // Buffered queue between async event handler and the for-await consumer.
200
+ const queue: SessionEvent[] = [];
201
+ let waiter: ((value: SessionEvent | null) => void) | null = null;
202
+ let finished = false;
203
+
204
+ const pushEvent = (event: SessionEvent | null) => {
205
+ if (waiter) {
206
+ const w = waiter;
207
+ waiter = null;
208
+ w(event);
209
+ } else if (event) {
210
+ queue.push(event);
211
+ }
212
+ };
213
+
214
+ const handler = (event: SessionEvent) => {
215
+ // The Copilot SDK does NOT pass `toolCallId` to the
216
+ // `onUserInputRequest` callback, so we have to capture it from
217
+ // the surrounding event stream and read it inside the callback.
218
+ //
219
+ // Capture order matters — `assistant.message` is dispatched
220
+ // FIRST (when the model decides to call `ask_user`), then
221
+ // `tool.execution_start`, then the RPC that triggers our
222
+ // callback. `user_input.requested` is ephemeral and not
223
+ // guaranteed to be observed before the callback fires (in
224
+ // practice it can race or be dropped), so we cannot depend on
225
+ // it alone — that was the bug behind the empty-answer
226
+ // auto-resolve.
227
+ if (event.type === 'assistant.message' && event.data.toolRequests) {
228
+ for (const req of event.data.toolRequests) {
229
+ if (req.name === 'ask_user') {
230
+ this.pendingAskUserToolCallId = req.toolCallId;
231
+ }
232
+ }
233
+ } else if (event.type === 'tool.execution_start' && event.data.toolName === 'ask_user') {
234
+ this.pendingAskUserToolCallId = event.data.toolCallId;
235
+ } else if (event.type === 'user_input.requested' && event.data.toolCallId) {
236
+ this.pendingAskUserToolCallId = event.data.toolCallId;
237
+ }
238
+ pushEvent(event);
239
+ };
240
+
241
+ const onAbort = () => {
242
+ finished = true;
243
+ pushEvent(null);
244
+ };
245
+ this.activeController.signal.addEventListener('abort', onAbort, { once: true });
246
+
247
+ try {
248
+ const mcpConfig = getCopilotMcpConfig();
249
+
250
+ const baseConfig: ResumeSessionConfig = {
251
+ onPermissionRequest: approveAll,
252
+ // Enables the agent's `ask_user` tool. Without this callback the
253
+ // SDK reports `requestUserInput: false` to the server and the
254
+ // tool is not exposed to the model, so the AskUserQuestion
255
+ // converter at message-converter.ts::normalizeAskUserQuestionInput
256
+ // never fires. Mirrors the in-process callback pattern documented
257
+ // in README.md §6.4 (Claude's `canUseTool`).
258
+ onUserInputRequest: async (request) => {
259
+ // Match Claude's `canUseTool` and OpenCode's `question.asked`
260
+ // patterns: park the callback on a Promise and only resolve
261
+ // it when the user submits an answer via the chat UI (routed
262
+ // through `resolveUserAnswer` below). Returning early would
263
+ // inject a fake answer into the model's context.
264
+ //
265
+ // `pendingAskUserToolCallId` was captured from the preceding
266
+ // `assistant.message` / `tool.execution_start` event (see
267
+ // handler above). If for any reason it's missing, fall back
268
+ // to a synthetic id so `cancel()` can still release the
269
+ // Promise — but log loudly because the chat UI's answer
270
+ // submission won't reach this entry.
271
+ const captured = this.pendingAskUserToolCallId;
272
+ this.pendingAskUserToolCallId = null;
273
+ const toolCallId = captured ?? `copilot-ask-user-${crypto.randomUUID()}`;
274
+
275
+ if (captured) {
276
+ debug.log('engine', `Copilot ask_user: parking on resolveUserAnswer (toolCallId: ${toolCallId})`);
277
+ } else {
278
+ debug.warn('engine', `Copilot ask_user: no toolCallId captured from event stream — parked on synthetic id ${toolCallId} (UI answer will not unblock; only cancel() will)`);
279
+ }
280
+
281
+ return await new Promise<UserInputResponse>((resolve) => {
282
+ this.pendingUserAnswers.set(toolCallId, {
283
+ resolve,
284
+ choices: request.choices,
285
+ });
286
+ });
287
+ },
288
+ model: modelId,
289
+ workingDirectory: resolvedProjectPath,
290
+ onEvent: handler,
291
+ // Emit assistant.message_delta / assistant.reasoning_delta events
292
+ // so the chat UI can render text token-by-token.
293
+ streaming: true,
294
+ // Sub-agent (`task`) activity is rendered nested inside the parent
295
+ // Agent tool block (see frontend/utils/chat/tool-handler.ts), not as
296
+ // live deltas in the main stream. Suppressing sub-agent streaming
297
+ // keeps reasoning/text from sub-agents from leaking into the main
298
+ // turn; the final non-streaming `assistant.message`,
299
+ // `assistant.reasoning`, and `tool.execution_*` events still arrive
300
+ // and are routed via parent.toolUseId.
301
+ includeSubAgentStreamingEvents: false,
302
+ // Custom MCP tools served from Clopen's in-process remote MCP HTTP
303
+ // endpoint (`/mcp`). Same `clopen-mcp` namespace and URL Open Code
304
+ // and Codex consume — see backend/engine/README.md §9.12.
305
+ ...(Object.keys(mcpConfig).length > 0 && { mcpServers: mcpConfig }),
306
+ };
307
+
308
+ let session: CopilotSession;
309
+ if (resume) {
310
+ // Fork-by-copy on EVERY resume — same semantics as Claude
311
+ // (`forkSession: true`) and OpenCode (`client.session.fork()`):
312
+ // each turn must produce a brand-new session id so the original
313
+ // branch's history is never mutated and the multi-branch
314
+ // checkpoint tree stays consistent. Without this, every turn
315
+ // reuses the same Copilot session id and downstream
316
+ // checkpoint/branch logic loses the ability to replay an
317
+ // earlier point as an independent sibling.
318
+ //
319
+ // Falls through to a plain resume only when the source state
320
+ // can't be found on disk (best-effort recovery).
321
+ //
322
+ // TODO: replace this fork-by-copy block with a native SDK API
323
+ // once @github/copilot-sdk adds `forkSession` (issues
324
+ // github/copilot-cli#1313, #1697, #2058). The migration is the
325
+ // same one-liner Claude and OpenCode already use.
326
+ let resumeId = resume;
327
+ if (sessionStateExists(resume)) {
328
+ const forkId = crypto.randomUUID();
329
+ if (forkCopilotSessionState(resume, forkId)) {
330
+ resumeId = forkId;
331
+ }
332
+ }
333
+
334
+ try {
335
+ session = await this.client.resumeSession(resumeId, baseConfig);
336
+ debug.log('engine', `Copilot resumed session: ${resumeId}${resumeId === resume ? '' : ` (forked from ${resume})`}`);
337
+ } catch (error) {
338
+ debug.warn('engine', `Failed to resume Copilot session ${resumeId}, creating fresh:`, error);
339
+ session = await this.client.createSession({ ...baseConfig } as SessionConfig);
340
+ }
341
+ } else {
342
+ session = await this.client.createSession({ ...baseConfig } as SessionConfig);
343
+ }
344
+
345
+ this.activeSession = session;
346
+ state.sessionId = session.sessionId;
347
+
348
+ // Send the prompt — fire-and-forget; events arrive via the queue.
349
+ const sendPromise = session.send({ prompt: extractPromptText(prompt) }).catch(error => {
350
+ debug.error('engine', 'Copilot session.send error:', error);
351
+ pushEvent({
352
+ type: 'session.error',
353
+ id: crypto.randomUUID(),
354
+ parentId: null,
355
+ timestamp: new Date().toISOString(),
356
+ data: {
357
+ errorType: 'query',
358
+ message: error instanceof Error ? error.message : String(error),
359
+ },
360
+ } as SessionEvent);
361
+ });
362
+
363
+ // Drain the event queue.
364
+ while (!finished) {
365
+ if (this.activeController.signal.aborted) break;
366
+
367
+ const event: SessionEvent | null = queue.length > 0
368
+ ? queue.shift()!
369
+ : await new Promise<SessionEvent | null>(resolve => {
370
+ waiter = resolve;
371
+ });
372
+
373
+ if (!event || this.activeController.signal.aborted) break;
374
+
375
+ // Resolve the parent Agent (`task`) tool call id for events
376
+ // originating inside a sub-agent. Null for the root agent and
377
+ // session-level events. Stamped on persisted messages so the
378
+ // frontend grouper nests sub-agent activity under the parent
379
+ // Agent tool — same shape Claude/OpenCode produce.
380
+ const parentToolUseId = resolveParentToolUseId(event, state);
381
+
382
+ switch (event.type) {
383
+ case 'session.start':
384
+ yield convertSessionStart(event.data, state.modelId);
385
+ break;
386
+
387
+ case 'assistant.turn_start':
388
+ // Sub-agent turn lifecycle is internal to the Agent tool block —
389
+ // don't toggle the main chat's stream lifecycle for it.
390
+ if (parentToolUseId) break;
391
+ yield convertTurnStart(state);
392
+ break;
393
+
394
+ case 'assistant.reasoning_delta':
395
+ if (parentToolUseId) break;
396
+ yield* convertReasoningDelta(event.data, state);
397
+ break;
398
+
399
+ case 'assistant.reasoning':
400
+ yield* convertReasoning(event.data, state, parentToolUseId);
401
+ break;
402
+
403
+ case 'assistant.message_delta':
404
+ if (parentToolUseId) break;
405
+ yield* convertMessageDelta(event.data, state);
406
+ break;
407
+
408
+ case 'assistant.message':
409
+ // May yield previously-buffered messages; the new message
410
+ // is buffered until assistant.usage attaches token counts.
411
+ yield* convertAssistantMessage(event.data, state, parentToolUseId);
412
+ break;
413
+
414
+ case 'tool.execution_start':
415
+ // Normally we DON'T flush pending assistant messages
416
+ // here — the SDK typically emits `assistant.usage`
417
+ // AFTER `assistant.message` but BEFORE this event, and
418
+ // we want to preserve that usage attachment by leaving
419
+ // messages buffered. Tool start has no user-visible
420
+ // output so deferring is usually safe.
421
+ //
422
+ // EXCEPTION: `ask_user` parks the SDK on the
423
+ // `onUserInputRequest` callback (see baseConfig above),
424
+ // so no further events arrive until the user responds.
425
+ // If we don't flush here, the assistant.message holding
426
+ // the `ask_user` tool_use block stays buffered forever
427
+ // and the AskUserQuestion bubble never reaches the UI
428
+ // — leaving the user with no way to answer.
429
+ if (event.data.toolName === 'ask_user') {
430
+ yield* flushPending(state);
431
+ }
432
+ yield* convertToolStart(event.data, state);
433
+ break;
434
+
435
+ case 'tool.execution_complete':
436
+ yield* flushPending(state);
437
+ yield* convertToolComplete(event.data, state, parentToolUseId);
438
+ break;
439
+
440
+ case 'assistant.usage':
441
+ // Sub-agent usage belongs to its own LLM call, not the main
442
+ // turn — skip so we don't attach it to a parent message.
443
+ if (parentToolUseId) break;
444
+ // Attaches usage to the last pending message and flushes.
445
+ yield* captureUsage(event.data, state);
446
+ break;
447
+
448
+ case 'assistant.turn_end':
449
+ if (parentToolUseId) break;
450
+ for (const ev of convertTurnEnd(event.data, state)) {
451
+ yield ev;
452
+ }
453
+ break;
454
+
455
+ case 'subagent.started':
456
+ yield* convertSubagentStarted(event, state);
457
+ break;
458
+
459
+ case 'subagent.completed':
460
+ case 'subagent.failed':
461
+ yield* convertSubagentEnded(event, state);
462
+ break;
463
+
464
+ case 'abort':
465
+ finished = true;
466
+ break;
467
+
468
+ case 'session.error':
469
+ throw buildSessionError(event.data);
470
+
471
+ case 'session.idle':
472
+ yield* flushPending(state);
473
+ yield buildResultEvent(state, !!event.data?.aborted);
474
+ finished = true;
475
+ break;
476
+ }
477
+ }
478
+
479
+ await sendPromise;
480
+ } catch (error) {
481
+ handleStreamError(error);
482
+ } finally {
483
+ this.activeController.signal.removeEventListener('abort', onAbort);
484
+
485
+ if (this.activeSession) {
486
+ try {
487
+ await this.activeSession.disconnect();
488
+ } catch (error) {
489
+ debug.warn('engine', 'Copilot session.disconnect failed (non-fatal):', error);
490
+ }
491
+ }
492
+ this.activeSession = null;
493
+ this.activeController = null;
494
+ }
495
+ }
496
+
497
+ async cancel(): Promise<void> {
498
+ // 1. Release any parked `onUserInputRequest` callbacks with an empty
499
+ // answer so the SDK isn't left blocked on a Promise that will never
500
+ // resolve. Empty `answer` + `wasFreeform: false` is the SDK-safe way
501
+ // to unblock without injecting fake user input.
502
+ for (const [, pending] of this.pendingUserAnswers) {
503
+ pending.resolve({ answer: '', wasFreeform: false });
504
+ }
505
+ this.pendingUserAnswers.clear();
506
+ this.pendingAskUserToolCallId = null;
507
+
508
+ // 2. Abort the local stream first so the loop exits even if RPC hangs.
509
+ const session = this.activeSession;
510
+ if (this.activeController && !this.activeController.signal.aborted) {
511
+ this.activeController.abort();
512
+ }
513
+ this.activeController = null;
514
+
515
+ // 3. Tell the Copilot server to stop processing (with timeout).
516
+ if (session) {
517
+ try {
518
+ await Promise.race([
519
+ session.abort(),
520
+ new Promise<void>(resolve => setTimeout(resolve, ABORT_TIMEOUT_MS)),
521
+ ]);
522
+ debug.log('engine', 'Copilot session aborted:', session.sessionId);
523
+ } catch (error) {
524
+ debug.warn('engine', 'Copilot session.abort failed (non-fatal):', error);
525
+ }
526
+ }
527
+ }
528
+
529
+ async interrupt(): Promise<void> {
530
+ await this.cancel();
531
+ }
532
+
533
+ /**
534
+ * Resolve a pending Copilot AskUserQuestion. Routed here from
535
+ * `backend/chat/stream-manager.ts::resolveUserAnswer` when the user
536
+ * submits an answer via the `chat:ask-user-answer` WS event.
537
+ *
538
+ * The unified UI passes `answers` keyed by question text. Copilot's
539
+ * `ask_user` only ever has a single question per call, so we take the
540
+ * first value and feed it to the SDK as `{ answer, wasFreeform }`.
541
+ * `wasFreeform` is derived by checking whether the answer matches one
542
+ * of the predefined `choices` captured when the callback was parked.
543
+ */
544
+ resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
545
+ const pending = this.pendingUserAnswers.get(toolUseId);
546
+ if (!pending) {
547
+ debug.warn('engine', 'Copilot resolveUserAnswer: no pending question for toolUseId:', toolUseId);
548
+ return false;
549
+ }
550
+
551
+ const answer = Object.values(answers)[0] ?? '';
552
+ const wasFreeform = pending.choices ? !pending.choices.includes(answer) : true;
553
+
554
+ debug.log('engine', `Copilot resolveUserAnswer (toolUseId: ${toolUseId}, wasFreeform: ${wasFreeform})`);
555
+ pending.resolve({ answer, wasFreeform });
556
+ this.pendingUserAnswers.delete(toolUseId);
557
+ return true;
558
+ }
559
+ }
560
+
561
+ // ============================================================================
562
+ // Helpers
563
+ // ============================================================================
564
+
565
+ function extractPromptText(prompt: EngineQueryOptions['prompt']): string {
566
+ const parts: string[] = [];
567
+ for (const block of prompt.content) {
568
+ if (block.type === 'text') {
569
+ parts.push(block.text);
570
+ }
571
+ }
572
+ return parts.join('\n').trim();
573
+ }