@myrialabs/clopen 0.3.12 → 0.3.14

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 (55) hide show
  1. package/backend/auth/session-invalidation.test.ts +45 -1
  2. package/backend/auth/session-invalidation.ts +35 -1
  3. package/backend/chat/stream-manager.ts +15 -0
  4. package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/engine/README.md +16 -1597
  7. package/backend/engine/adapters/claude/message-converter.ts +34 -7
  8. package/backend/engine/adapters/claude/models.ts +174 -2
  9. package/backend/engine/adapters/codex/stream.ts +54 -1
  10. package/backend/engine/adapters/copilot/stream.ts +79 -19
  11. package/backend/engine/adapters/opencode/stream.ts +23 -23
  12. package/backend/engine/adapters/qwen/stream.ts +83 -1
  13. package/backend/engine/docs/adapter-contract.md +183 -0
  14. package/backend/engine/docs/adding-an-engine.md +150 -0
  15. package/backend/engine/docs/database.md +123 -0
  16. package/backend/engine/docs/frontend-and-chat.md +176 -0
  17. package/backend/engine/docs/lessons-learned.md +715 -0
  18. package/backend/engine/docs/quick-reference.md +36 -0
  19. package/backend/engine/docs/system-tools.md +82 -0
  20. package/backend/engine/docs/websocket-routes.md +240 -0
  21. package/backend/engine/structured-helpers.ts +59 -0
  22. package/backend/files/file-archive.test.ts +131 -0
  23. package/backend/files/file-archive.ts +252 -0
  24. package/backend/files/file-operations.ts +39 -66
  25. package/backend/files/file-size-limit.test.ts +71 -15
  26. package/backend/files/file-size-limit.ts +36 -8
  27. package/backend/files/file-watcher.ts +117 -3
  28. package/backend/http/files-upload.ts +168 -0
  29. package/backend/index.ts +8 -0
  30. package/backend/mcp/servers/helper.ts +5 -1
  31. package/backend/projects/project-cleanup.ts +1 -1
  32. package/backend/terminal/pty-session-manager.ts +3 -0
  33. package/backend/terminal/stream-manager.ts +1 -1
  34. package/backend/utils/ws.ts +9 -0
  35. package/backend/ws/auth/users.ts +1 -1
  36. package/backend/ws/chat/stream.ts +46 -38
  37. package/backend/ws/files/path-access.test.ts +166 -0
  38. package/backend/ws/files/path-access.ts +56 -22
  39. package/backend/ws/files/read.ts +5 -5
  40. package/backend/ws/files/watch.ts +48 -19
  41. package/backend/ws/files/write.ts +53 -27
  42. package/backend/ws/git/commit-message.ts +12 -5
  43. package/backend/ws/terminal/session.ts +1 -0
  44. package/dist/assets/main-BqiSLc8F.css +1 -0
  45. package/dist/assets/{main-HIDO3ugS.js → main-C37-Y8f-.js} +230 -229
  46. package/dist/index.html +2 -2
  47. package/package.json +8 -7
  48. package/shared/types/git.ts +4 -2
  49. package/shared/types/stores/settings.ts +2 -0
  50. package/shared/types/unified/index.ts +6 -0
  51. package/shared/types/unified/stream.ts +15 -1
  52. package/shared/types/unified/tool.ts +41 -1
  53. package/shared/utils/ws-server.ts +6 -0
  54. package/backend/engine/adapters/copilot/session-fork.ts +0 -111
  55. package/dist/assets/main-C2JiGYnx.css +0 -1
@@ -38,6 +38,7 @@ import type {
38
38
  ErrorResultEvent,
39
39
  SystemInitEvent,
40
40
  RateLimitEvent,
41
+ NotificationEvent,
41
42
  TokenUsage,
42
43
  StopReason,
43
44
  } from '$shared/types/unified';
@@ -389,6 +390,26 @@ export function convertSystemInit(msg: SDKSystemMessage): SystemInitEvent {
389
390
  };
390
391
  }
391
392
 
393
+ /**
394
+ * Convert SDKTaskNotificationMessage (terminal background-task event) →
395
+ * NotificationEvent. Fires when a backgrounded Agent/teammate finishes
396
+ * (status completed | failed | stopped). The non-terminal task_started /
397
+ * task_progress / task_updated messages are intentionally not surfaced —
398
+ * they would spam the toast and there is no dedicated tasks panel.
399
+ */
400
+ function convertTaskNotification(
401
+ msg: { session_id: string; status: string; summary?: string; task_id: string },
402
+ ): NotificationEvent {
403
+ const completed = msg.status === 'completed';
404
+ return {
405
+ type: 'notification',
406
+ sessionId: msg.session_id,
407
+ level: completed ? 'info' : 'warning',
408
+ title: completed ? 'Background task completed' : `Background task ${msg.status}`,
409
+ message: msg.summary || `Task ${msg.task_id} ${msg.status}`,
410
+ };
411
+ }
412
+
392
413
  /** Convert SDKCompactBoundaryMessage → CompactBoundaryMessage */
393
414
  export function convertCompactBoundary(msg: SDKCompactBoundaryMessage): CompactBoundaryMessage {
394
415
  return {
@@ -476,14 +497,20 @@ function* dispatchSdkMessage(msg: SDKMessage, state: StreamConverterState): Gene
476
497
  break;
477
498
 
478
499
  case 'system': {
479
- const systemMsg = msg as SDKSystemMessage | SDKCompactBoundaryMessage;
480
- if ('subtype' in systemMsg) {
481
- if (systemMsg.subtype === 'init') {
482
- yield convertSystemInit(systemMsg as SDKSystemMessage);
483
- } else if (systemMsg.subtype === 'compact_boundary') {
484
- yield convertCompactBoundary(systemMsg as SDKCompactBoundaryMessage);
485
- }
500
+ // Read subtype as a plain string: the SDKMessage `system` arm covers
501
+ // more subtypes (task_*, etc.) than the SDKSystemMessage |
502
+ // SDKCompactBoundaryMessage union, so narrowing on that union would
503
+ // collapse the task branch to `never`.
504
+ const subtype = (msg as { subtype?: string }).subtype;
505
+ if (subtype === 'init') {
506
+ yield convertSystemInit(msg as SDKSystemMessage);
507
+ } else if (subtype === 'compact_boundary') {
508
+ yield convertCompactBoundary(msg as SDKCompactBoundaryMessage);
509
+ } else if (subtype === 'task_notification') {
510
+ yield convertTaskNotification(msg as unknown as Parameters<typeof convertTaskNotification>[0]);
486
511
  }
512
+ // task_started / task_progress / task_updated: background-task
513
+ // progress noise — intentionally not surfaced (no tasks panel).
487
514
  break;
488
515
  }
489
516
 
@@ -23,7 +23,7 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
23
23
  },
24
24
  },
25
25
  limit: {
26
- input: 200_000,
26
+ input: 1_000_000,
27
27
  output: 128_000,
28
28
  },
29
29
  modalities: {
@@ -66,7 +66,7 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
66
66
  },
67
67
  },
68
68
  limit: {
69
- input: 200_000,
69
+ input: 1_000_000,
70
70
  output: 64_000,
71
71
  },
72
72
  modalities: {
@@ -138,4 +138,176 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
138
138
  output: 5,
139
139
  },
140
140
  },
141
+ {
142
+ engine: {
143
+ type: 'claude-code',
144
+ provider: 'anthropic',
145
+ model: {
146
+ id: 'claude-opus-4-6',
147
+ name: 'Claude Opus 4.6',
148
+ },
149
+ account: {
150
+ id: 0,
151
+ name: '',
152
+ },
153
+ },
154
+ limit: {
155
+ input: 1_000_000,
156
+ output: 128_000,
157
+ },
158
+ modalities: {
159
+ input: {
160
+ text: true,
161
+ image: true,
162
+ audio: false,
163
+ video: false,
164
+ pdf: true,
165
+ },
166
+ output: {
167
+ text: true,
168
+ image: false,
169
+ audio: false,
170
+ video: false,
171
+ pdf: false,
172
+ },
173
+ },
174
+ capabilities: {
175
+ reasoning: true,
176
+ tools: true,
177
+ structuredOutput: true,
178
+ },
179
+ cost: {
180
+ input: 5,
181
+ output: 25,
182
+ },
183
+ },
184
+ {
185
+ engine: {
186
+ type: 'claude-code',
187
+ provider: 'anthropic',
188
+ model: {
189
+ id: 'claude-sonnet-4-5',
190
+ name: 'Claude Sonnet 4.5',
191
+ },
192
+ account: {
193
+ id: 0,
194
+ name: '',
195
+ },
196
+ },
197
+ limit: {
198
+ input: 200_000,
199
+ output: 64_000,
200
+ },
201
+ modalities: {
202
+ input: {
203
+ text: true,
204
+ image: true,
205
+ audio: false,
206
+ video: false,
207
+ pdf: true,
208
+ },
209
+ output: {
210
+ text: true,
211
+ image: false,
212
+ audio: false,
213
+ video: false,
214
+ pdf: false,
215
+ },
216
+ },
217
+ capabilities: {
218
+ reasoning: true,
219
+ tools: true,
220
+ structuredOutput: true,
221
+ },
222
+ cost: {
223
+ input: 3,
224
+ output: 15,
225
+ },
226
+ },
227
+ {
228
+ engine: {
229
+ type: 'claude-code',
230
+ provider: 'anthropic',
231
+ model: {
232
+ id: 'claude-opus-4-5',
233
+ name: 'Claude Opus 4.5',
234
+ },
235
+ account: {
236
+ id: 0,
237
+ name: '',
238
+ },
239
+ },
240
+ limit: {
241
+ input: 200_000,
242
+ output: 64_000,
243
+ },
244
+ modalities: {
245
+ input: {
246
+ text: true,
247
+ image: true,
248
+ audio: false,
249
+ video: false,
250
+ pdf: true,
251
+ },
252
+ output: {
253
+ text: true,
254
+ image: false,
255
+ audio: false,
256
+ video: false,
257
+ pdf: false,
258
+ },
259
+ },
260
+ capabilities: {
261
+ reasoning: true,
262
+ tools: true,
263
+ structuredOutput: true,
264
+ },
265
+ cost: {
266
+ input: 5,
267
+ output: 25,
268
+ },
269
+ },
270
+ {
271
+ engine: {
272
+ type: 'claude-code',
273
+ provider: 'anthropic',
274
+ model: {
275
+ id: 'claude-opus-4-1',
276
+ name: 'Claude Opus 4.1',
277
+ },
278
+ account: {
279
+ id: 0,
280
+ name: '',
281
+ },
282
+ },
283
+ limit: {
284
+ input: 200_000,
285
+ output: 32_000,
286
+ },
287
+ modalities: {
288
+ input: {
289
+ text: true,
290
+ image: true,
291
+ audio: false,
292
+ video: false,
293
+ pdf: true,
294
+ },
295
+ output: {
296
+ text: true,
297
+ image: false,
298
+ audio: false,
299
+ video: false,
300
+ pdf: false,
301
+ },
302
+ },
303
+ capabilities: {
304
+ reasoning: true,
305
+ tools: true,
306
+ structuredOutput: true,
307
+ },
308
+ cost: {
309
+ input: 15,
310
+ output: 75,
311
+ },
312
+ },
141
313
  ];
@@ -21,7 +21,8 @@
21
21
 
22
22
  import { Codex, type Thread, type ThreadOptions, type Input as CodexInput } from '@openai/codex-sdk';
23
23
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
24
- import type { AIEngine, EngineQueryOptions } from '../../types';
24
+ import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
25
+ import { extractJson } from '../../structured-helpers';
25
26
  import { engineQueries } from '$backend/database/queries/engine-queries';
26
27
  import { resolveOsPath } from '$backend/utils/paths';
27
28
  import { resolveBinary } from '$backend/utils/cli';
@@ -266,6 +267,58 @@ export class CodexEngine implements AIEngine {
266
267
  async interrupt(): Promise<void> {
267
268
  await this.cancel();
268
269
  }
270
+
271
+ /**
272
+ * One-shot structured JSON generation via the SDK's native `outputSchema`.
273
+ * The CLI returns the JSON-serialised object as `Turn.finalResponse` (and
274
+ * as the text of the trailing `agent_message` item) — see codex-sdk
275
+ * `TurnOptions.outputSchema` in `dist/index.d.ts`.
276
+ */
277
+ async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
278
+ const {
279
+ prompt,
280
+ modelId,
281
+ schema,
282
+ projectPath,
283
+ abortController,
284
+ accountId,
285
+ } = options;
286
+
287
+ if (!this._isInitialized || !this.codex || (accountId != null && accountId !== this.currentAccountId)) {
288
+ if (this._isInitialized) {
289
+ await this.dispose();
290
+ }
291
+ await this.initialize(accountId);
292
+ }
293
+ if (!this.codex) {
294
+ throw new Error('Codex client unavailable.');
295
+ }
296
+
297
+ const controller = abortController || new AbortController();
298
+ const resolvedProjectPath = resolveOsPath(projectPath);
299
+
300
+ const thread = this.codex.startThread({
301
+ model: modelId,
302
+ workingDirectory: resolvedProjectPath,
303
+ skipGitRepoCheck: true,
304
+ sandboxMode: 'read-only',
305
+ approvalPolicy: 'never',
306
+ modelReasoningEffort: 'low',
307
+ });
308
+
309
+ debug.log('engine', `[codex structured] running with model=${modelId}`);
310
+
311
+ const turn = await thread.run(prompt, {
312
+ outputSchema: schema,
313
+ signal: controller.signal,
314
+ });
315
+
316
+ if (!turn.finalResponse) {
317
+ throw new Error('Codex returned empty response');
318
+ }
319
+
320
+ return extractJson<T>(turn.finalResponse);
321
+ }
269
322
  }
270
323
 
271
324
  // ============================================================================
@@ -15,7 +15,8 @@ import type {
15
15
  ModelInfo,
16
16
  } from '@github/copilot-sdk';
17
17
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
18
- import type { AIEngine, EngineQueryOptions } from '../../types';
18
+ import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
19
+ import { buildJsonPrompt, extractJson } from '../../structured-helpers';
19
20
  import { engineQueries } from '$backend/database/queries/engine-queries';
20
21
  import { resolveOsPath } from '$backend/utils/paths';
21
22
  import { debug } from '$shared/utils/logger';
@@ -46,7 +47,6 @@ import {
46
47
  convertSubagentStarted,
47
48
  convertSubagentEnded,
48
49
  } from './message-converter';
49
- import { forkCopilotSessionState, sessionStateExists } from './session-fork';
50
50
 
51
51
  const ABORT_TIMEOUT_MS = 5000;
52
52
 
@@ -304,28 +304,23 @@ export class CopilotEngine implements AIEngine {
304
304
 
305
305
  let session: CopilotSession;
306
306
  if (resume) {
307
- // Fork-by-copy on EVERY resume — same semantics as Claude
307
+ // Fork on EVERY resume — same semantics as Claude
308
308
  // (`forkSession: true`) and OpenCode (`client.session.fork()`):
309
309
  // each turn must produce a brand-new session id so the original
310
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.
311
+ // checkpoint tree stays consistent.
315
312
  //
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.
313
+ // Uses `client.rpc.sessions.fork` (added in @github/copilot-sdk
314
+ // 1.0.0-beta.4, marked @experimental — see node_modules/
315
+ // @github/copilot-sdk/dist/generated/rpc.d.ts::SessionsForkRequest).
316
+ // Falls back to plain resume if the SDK rejects the fork (source
317
+ // session no longer on disk, server doesn't support the RPC, etc.).
323
318
  let resumeId = resume;
324
- if (sessionStateExists(resume)) {
325
- const forkId = crypto.randomUUID();
326
- if (forkCopilotSessionState(resume, forkId)) {
327
- resumeId = forkId;
328
- }
319
+ try {
320
+ const result = await this.client.rpc.sessions.fork({ sessionId: resume });
321
+ resumeId = result.sessionId;
322
+ } catch (forkErr) {
323
+ debug.warn('engine', `Copilot fork failed for ${resume}, falling back to plain resume (non-fatal):`, forkErr);
329
324
  }
330
325
 
331
326
  try {
@@ -538,6 +533,71 @@ export class CopilotEngine implements AIEngine {
538
533
  * `wasFreeform` is derived by checking whether the answer matches one
539
534
  * of the predefined `choices` captured when the callback was parked.
540
535
  */
536
+ /**
537
+ * One-shot structured JSON generation via prompt engineering.
538
+ *
539
+ * The Copilot SDK has no native `outputSchema` / `response_format`
540
+ * option, so we instruct the model to emit JSON only, disable every
541
+ * tool with `availableTools: []`, and parse the assistant's final
542
+ * message text.
543
+ */
544
+ async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
545
+ const {
546
+ prompt,
547
+ modelId,
548
+ schema,
549
+ projectPath,
550
+ abortController,
551
+ accountId,
552
+ } = options;
553
+
554
+ if (this._isInitialized && accountId != null && accountId !== this.currentAccountId) {
555
+ await this.dispose();
556
+ }
557
+ if (!this._isInitialized || !this.client) {
558
+ await this.initialize(accountId);
559
+ }
560
+ if (!this.client) {
561
+ throw new Error('Copilot client unavailable.');
562
+ }
563
+
564
+ const controller = abortController || new AbortController();
565
+ const resolvedProjectPath = resolveOsPath(projectPath);
566
+ const jsonPrompt = buildJsonPrompt(prompt, schema);
567
+
568
+ const session = await this.client.createSession({
569
+ model: modelId,
570
+ workingDirectory: resolvedProjectPath,
571
+ onPermissionRequest: approveAll,
572
+ availableTools: [],
573
+ streaming: false,
574
+ } as SessionConfig);
575
+
576
+ const onAbort = () => {
577
+ session.abort().catch((err) => {
578
+ debug.warn('engine', 'Copilot structured: abort failed (non-fatal):', err);
579
+ });
580
+ };
581
+ controller.signal.addEventListener('abort', onAbort, { once: true });
582
+
583
+ debug.log('engine', `[copilot structured] sending prompt to session ${session.sessionId}, model=${modelId}`);
584
+
585
+ try {
586
+ const final = await session.sendAndWait({ prompt: jsonPrompt });
587
+ if (!final?.data?.content) {
588
+ throw new Error('Copilot returned no assistant message content');
589
+ }
590
+ return extractJson<T>(final.data.content);
591
+ } finally {
592
+ controller.signal.removeEventListener('abort', onAbort);
593
+ try {
594
+ await session.disconnect();
595
+ } catch (error) {
596
+ debug.warn('engine', 'Copilot structured: session.disconnect failed (non-fatal):', error);
597
+ }
598
+ }
599
+ }
600
+
541
601
  resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
542
602
  const pending = this.pendingUserAnswers.get(toolUseId);
543
603
  if (!pending) {
@@ -41,6 +41,7 @@ import {
41
41
  } from './message-converter';
42
42
  import { ensureClient, getClient, getServerUrl } from './server';
43
43
  import { formatSessionError, handleStreamError } from './error-handler';
44
+ import { buildJsonPrompt, extractJson } from '../../structured-helpers';
44
45
  import { debug } from '$shared/utils/logger';
45
46
 
46
47
  // ============================================================================
@@ -940,11 +941,7 @@ export class OpenCodeEngine implements AIEngine {
940
941
  throw new Error('Failed to create OpenCode session');
941
942
  }
942
943
 
943
- // Wrap prompt with JSON instruction since v1 doesn't support format option
944
- const jsonPrompt = `${prompt}
945
-
946
- IMPORTANT: You MUST respond with ONLY a valid JSON object matching this schema, no other text:
947
- ${JSON.stringify(schema, null, 2)}`;
944
+ const jsonPrompt = buildJsonPrompt(prompt, schema);
948
945
 
949
946
  debug.log('engine', `[OC structured] Sending prompt to session ${sessionId}, provider=${providerSlug}, modelId=${modelId}`);
950
947
 
@@ -965,26 +962,29 @@ ${JSON.stringify(schema, null, 2)}`;
965
962
  throw new Error('OpenCode returned empty response');
966
963
  }
967
964
 
968
- debug.log('engine', `[OC structured] Got response with ${data.parts?.length || 0} parts`);
969
-
970
- // Extract text content from response parts and parse as JSON
971
- const textParts = (data.parts || []).filter((p: any) => p.type === 'text');
972
- const fullText = textParts.map((p: any) => p.text || '').join('');
973
-
974
- if (!fullText) {
975
- throw new Error('OpenCode returned no text content');
965
+ const parts = data.parts || [];
966
+ debug.log('engine', `[OC structured] Got response with ${parts.length} parts (${parts.map((p: any) => p.type).join(', ')})`);
967
+
968
+ // Prefer `text` parts but fall back to `reasoning` parts: some models
969
+ // (notably thinking-heavy ones) emit JSON inside reasoning when tools
970
+ // are disabled and the prompt is short. Both carry a `.text` field.
971
+ const collectText = (type: 'text' | 'reasoning') =>
972
+ parts
973
+ .filter((p: any) => p.type === type && !p.ignored)
974
+ .map((p: any) => p.text || '')
975
+ .join('');
976
+
977
+ const textContent = collectText('text');
978
+ const source = textContent || collectText('reasoning');
979
+
980
+ if (!source) {
981
+ throw new Error(
982
+ `OpenCode returned no parseable content (received parts: ${parts.map((p: any) => p.type).join(', ') || 'none'})`
983
+ );
976
984
  }
977
985
 
978
- debug.log('engine', `[OC structured] Raw text: ${fullText.slice(0, 200)}`);
986
+ debug.log('engine', `[OC structured] Raw text: ${source.slice(0, 200)}`);
979
987
 
980
- // Try to extract JSON from the response (may include markdown fences)
981
- const jsonMatch = fullText.match(/```(?:json)?\s*([\s\S]*?)```/) || fullText.match(/(\{[\s\S]*\})/);
982
- const jsonText = jsonMatch ? jsonMatch[1].trim() : fullText.trim();
983
-
984
- try {
985
- return JSON.parse(jsonText) as T;
986
- } catch {
987
- throw new Error(`OpenCode did not return valid JSON: ${jsonText.slice(0, 200)}`);
988
- }
988
+ return extractJson<T>(source);
989
989
  }
990
990
  }
@@ -37,7 +37,8 @@ import {
37
37
  type ToolInput,
38
38
  } from '@qwen-code/sdk';
39
39
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
40
- import type { AIEngine, EngineQueryOptions } from '../../types';
40
+ import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
41
+ import { buildJsonPrompt, extractJson } from '../../structured-helpers';
41
42
  import { resolveOsPath } from '$backend/utils/paths';
42
43
  import { debug } from '$shared/utils/logger';
43
44
  import { getEngineEnv } from './environment';
@@ -345,6 +346,87 @@ export class QwenEngine implements AIEngine {
345
346
  }
346
347
  }
347
348
 
349
+ /**
350
+ * One-shot structured JSON generation via prompt engineering.
351
+ *
352
+ * The Qwen SDK has no native `outputSchema` / `response_format` option,
353
+ * so we instruct the model to emit JSON only, restrict tools with
354
+ * `coreTools: []`, and parse the final `result` text returned by the
355
+ * SDK's `SDKResultMessageSuccess`.
356
+ */
357
+ async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
358
+ const {
359
+ prompt,
360
+ modelId,
361
+ schema,
362
+ projectPath,
363
+ abortController,
364
+ accountId,
365
+ } = options;
366
+
367
+ const resolution = getEngineEnv(accountId);
368
+ if (!resolution) {
369
+ throw new Error('Qwen Code is not configured. Add an API key in Settings → Engines → Qwen Code.');
370
+ }
371
+ const { env } = resolution;
372
+
373
+ const controller = abortController || new AbortController();
374
+ const resolvedProjectPath = resolveOsPath(projectPath);
375
+ const jsonPrompt = buildJsonPrompt(prompt, schema);
376
+
377
+ debug.log('engine', `[qwen structured] running with model=${modelId}`);
378
+
379
+ const sdkOptions: QueryOptions = {
380
+ cwd: resolvedProjectPath,
381
+ model: modelId,
382
+ env,
383
+ authType: 'openai',
384
+ abortController: controller,
385
+ includePartialMessages: false,
386
+ permissionMode: 'default',
387
+ coreTools: [],
388
+ maxSessionTurns: 1,
389
+ };
390
+
391
+ const sdkPrompt: SDKUserMessage = {
392
+ type: 'user',
393
+ uuid: crypto.randomUUID(),
394
+ session_id: '',
395
+ parent_tool_use_id: null,
396
+ message: { role: 'user', content: jsonPrompt },
397
+ };
398
+ const promptIterable = (async function* (): AsyncIterable<SDKUserMessage> {
399
+ yield sdkPrompt;
400
+ })();
401
+
402
+ const queryInstance = query({ prompt: promptIterable, options: sdkOptions });
403
+
404
+ let resultText = '';
405
+ let errorMessage = '';
406
+ try {
407
+ for await (const message of queryInstance) {
408
+ if (message.type === 'result') {
409
+ if (message.subtype === 'success') {
410
+ resultText = message.result || '';
411
+ } else {
412
+ errorMessage = message.error?.message || message.subtype || 'unknown error';
413
+ }
414
+ }
415
+ }
416
+ } catch (error) {
417
+ if (controller.signal.aborted) {
418
+ throw new Error('Generation was cancelled');
419
+ }
420
+ throw error;
421
+ }
422
+
423
+ if (!resultText) {
424
+ throw new Error(errorMessage || 'Qwen returned no result text');
425
+ }
426
+
427
+ return extractJson<T>(resultText);
428
+ }
429
+
348
430
  resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
349
431
  const pending = this.pendingAskUserQuestion;
350
432
  if (!pending) {