@myrialabs/clopen 0.3.8 → 0.3.10

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