@myrialabs/clopen 0.3.7 → 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 (149) hide show
  1. package/backend/auth/permissions.ts +41 -2
  2. package/backend/chat/stream-manager.ts +71 -0
  3. package/backend/database/migrations/030_add_files_panel_state_to_user_projects.ts +34 -0
  4. package/backend/database/migrations/031_create_db_client_tables.ts +74 -0
  5. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  6. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  7. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  8. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  9. package/backend/database/migrations/index.ts +43 -1
  10. package/backend/database/queries/db-client-connection-queries.ts +343 -0
  11. package/backend/database/queries/db-client-query-history-queries.ts +113 -0
  12. package/backend/database/queries/engine-queries.ts +12 -0
  13. package/backend/database/queries/index.ts +3 -1
  14. package/backend/database/queries/project-queries.ts +28 -0
  15. package/backend/db-client/connection-manager.ts +257 -0
  16. package/backend/db-client/drivers/bun-sql-helpers.ts +41 -0
  17. package/backend/db-client/drivers/mongodb.ts +358 -0
  18. package/backend/db-client/drivers/mysql.ts +385 -0
  19. package/backend/db-client/drivers/postgres.ts +446 -0
  20. package/backend/db-client/drivers/redis.ts +267 -0
  21. package/backend/db-client/drivers/sql-builders.ts +215 -0
  22. package/backend/db-client/drivers/sqlite.ts +346 -0
  23. package/backend/db-client/drivers/types.ts +92 -0
  24. package/backend/db-client/query-executor.ts +126 -0
  25. package/backend/db-client/ssh-tunnel.ts +122 -0
  26. package/backend/engine/README.md +1702 -0
  27. package/backend/engine/adapters/claude/models.ts +141 -0
  28. package/backend/engine/adapters/claude/stream.ts +1 -1
  29. package/backend/engine/adapters/codex/credential.ts +179 -0
  30. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  31. package/backend/engine/adapters/codex/index.ts +1 -0
  32. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  33. package/backend/engine/adapters/codex/models.ts +105 -0
  34. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  35. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  36. package/backend/engine/adapters/codex/stream.ts +310 -0
  37. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  38. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  39. package/backend/engine/adapters/copilot/index.ts +1 -0
  40. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  41. package/backend/engine/adapters/copilot/models.ts +92 -0
  42. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  43. package/backend/engine/adapters/copilot/stream.ts +573 -0
  44. package/backend/engine/adapters/opencode/config.ts +56 -104
  45. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  46. package/backend/engine/adapters/opencode/models.ts +79 -0
  47. package/backend/engine/adapters/opencode/presets.ts +91 -0
  48. package/backend/engine/adapters/opencode/stream.ts +5 -115
  49. package/backend/engine/adapters/qwen/credential.ts +78 -0
  50. package/backend/engine/adapters/qwen/environment.ts +84 -0
  51. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  52. package/backend/engine/adapters/qwen/index.ts +1 -0
  53. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  54. package/backend/engine/adapters/qwen/models.ts +81 -0
  55. package/backend/engine/adapters/qwen/presets.ts +51 -0
  56. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  57. package/backend/engine/adapters/qwen/stream.ts +380 -0
  58. package/backend/engine/index.ts +35 -0
  59. package/backend/engine/install-recipes.ts +80 -1
  60. package/backend/engine/install-runner.ts +4 -0
  61. package/backend/git/git-service.ts +12 -0
  62. package/backend/mcp/README.md +84 -14
  63. package/backend/mcp/config.ts +218 -17
  64. package/backend/mcp/index.ts +2 -0
  65. package/backend/mcp/project-context.ts +55 -0
  66. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  67. package/backend/mcp/servers/helper.ts +13 -0
  68. package/backend/middleware/error-handler.ts +16 -2
  69. package/backend/preview/browser/browser-preview-service.ts +4 -4
  70. package/backend/preview/browser/scripts/video-stream.ts +9 -3
  71. package/backend/ws/README.md +128 -3
  72. package/backend/ws/access.ts +56 -0
  73. package/backend/ws/chat/stream.ts +36 -12
  74. package/backend/ws/db-client/access.ts +19 -0
  75. package/backend/ws/db-client/connections.ts +194 -0
  76. package/backend/ws/db-client/index.ts +17 -0
  77. package/backend/ws/db-client/io.ts +456 -0
  78. package/backend/ws/db-client/query.ts +214 -0
  79. package/backend/ws/db-client/schema.ts +81 -0
  80. package/backend/ws/db-client/structure.ts +230 -0
  81. package/backend/ws/engine/access.ts +39 -0
  82. package/backend/ws/engine/claude/accounts.ts +15 -10
  83. package/backend/ws/engine/codex/accounts.ts +516 -0
  84. package/backend/ws/engine/codex/index.ts +14 -0
  85. package/backend/ws/engine/codex/status.ts +87 -0
  86. package/backend/ws/engine/copilot/accounts.ts +122 -0
  87. package/backend/ws/engine/copilot/index.ts +13 -0
  88. package/backend/ws/engine/copilot/status.ts +54 -0
  89. package/backend/ws/engine/index.ts +7 -1
  90. package/backend/ws/engine/opencode/providers.ts +1 -1
  91. package/backend/ws/engine/qwen/accounts.ts +137 -0
  92. package/backend/ws/engine/qwen/index.ts +15 -0
  93. package/backend/ws/engine/qwen/presets.ts +40 -0
  94. package/backend/ws/engine/qwen/status.ts +54 -0
  95. package/backend/ws/files/index.ts +5 -1
  96. package/backend/ws/files/read.ts +34 -0
  97. package/backend/ws/files/state.ts +42 -0
  98. package/backend/ws/files/watch.ts +7 -1
  99. package/backend/ws/git/branch.ts +13 -19
  100. package/backend/ws/git/commit-message.ts +3 -4
  101. package/backend/ws/git/commit.ts +5 -7
  102. package/backend/ws/git/conflict.ts +7 -10
  103. package/backend/ws/git/diff.ts +7 -10
  104. package/backend/ws/git/log.ts +3 -4
  105. package/backend/ws/git/remote.ts +30 -43
  106. package/backend/ws/git/staging.ts +13 -19
  107. package/backend/ws/git/status.ts +7 -11
  108. package/backend/ws/index.ts +5 -1
  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 +5 -40
  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 +4 -10
  120. package/backend/ws/projects/status.ts +2 -0
  121. package/backend/ws/sessions/crud.ts +22 -33
  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 +12 -6
  130. package/backend/ws/terminal/session.ts +35 -14
  131. package/backend/ws/terminal/stream.ts +4 -1
  132. package/dist/assets/{index-C86jwBxR.js → index-D8V2wj9B.js} +2 -2
  133. package/dist/assets/{main-DhLx8wD1.js → main-C9nYVmnw.js} +222 -195
  134. package/dist/assets/main-hspyFOoK.css +1 -0
  135. package/dist/index.html +2 -2
  136. package/package.json +7 -1
  137. package/shared/constants/engines.ts +45 -140
  138. package/shared/types/database/schema.ts +49 -1
  139. package/shared/types/db-client/connection.ts +60 -0
  140. package/shared/types/db-client/index.ts +6 -0
  141. package/shared/types/db-client/query.ts +77 -0
  142. package/shared/types/unified/common.ts +1 -1
  143. package/shared/types/unified/engine.ts +29 -1
  144. package/shared/types/unified/index.ts +2 -0
  145. package/shared/types/unified/message.ts +1 -1
  146. package/shared/types/unified/tool.ts +17 -2
  147. package/shared/utils/logger.ts +1 -0
  148. package/shared/utils/ws-server.ts +14 -0
  149. package/dist/assets/main-jTnmAoXS.css +0 -1
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Qwen Code dynamic model discovery.
3
+ *
4
+ * Each preset (DashScope CN/INTL, OpenRouter, Fireworks) exposes the
5
+ * OpenAI-compatible `/models` endpoint. We hit it with the active account's
6
+ * API key and translate the response into `EngineModel[]` with conservative
7
+ * default metadata — the SDK only needs the model id to dispatch a stream,
8
+ * so anything beyond that is best-effort UI hinting.
9
+ *
10
+ * Returns `[]` on any failure (network, auth, malformed body) so the caller
11
+ * can surface an empty picker rather than a stale curated list — same shape
12
+ * as OpenCode's `fetchOpenCodeModels` (see README §4.5).
13
+ */
14
+
15
+ import type { EngineModel } from '$shared/types/unified';
16
+ import { debug } from '$shared/utils/logger';
17
+ import type { QwenEnvResolution } from './environment';
18
+
19
+ const MODELS_FETCH_TIMEOUT_MS = 10_000;
20
+
21
+ interface OpenAiModelsResponse {
22
+ data?: Array<{
23
+ id?: string;
24
+ name?: string;
25
+ context_length?: number;
26
+ [key: string]: unknown;
27
+ }>;
28
+ }
29
+
30
+ export async function fetchQwenModels(env: QwenEnvResolution): Promise<EngineModel[]> {
31
+ const apiKey = env.env['OPENAI_API_KEY'];
32
+ if (!apiKey) return [];
33
+
34
+ const url = `${env.baseUrl.replace(/\/+$/, '')}/models`;
35
+ try {
36
+ const res = await fetch(url, {
37
+ headers: {
38
+ Authorization: `Bearer ${apiKey}`,
39
+ Accept: 'application/json',
40
+ },
41
+ signal: AbortSignal.timeout(MODELS_FETCH_TIMEOUT_MS),
42
+ });
43
+ if (!res.ok) {
44
+ debug.warn('engine', `Qwen /models fetch failed: ${res.status} ${res.statusText}`);
45
+ return [];
46
+ }
47
+ const json = (await res.json()) as OpenAiModelsResponse;
48
+ const entries = Array.isArray(json.data) ? json.data : [];
49
+ const mapped: EngineModel[] = [];
50
+ for (const entry of entries) {
51
+ if (!entry || typeof entry.id !== 'string' || !entry.id) continue;
52
+ mapped.push(mapQwenIdToEngineModel(entry.id, entry.name, entry.context_length));
53
+ }
54
+ return mapped;
55
+ } catch (error) {
56
+ debug.warn('engine', `Qwen /models fetch error: ${error instanceof Error ? error.message : String(error)}`);
57
+ return [];
58
+ }
59
+ }
60
+
61
+ function mapQwenIdToEngineModel(id: string, name?: string, contextLength?: number): EngineModel {
62
+ const slashIdx = id.indexOf('/');
63
+ const provider = slashIdx > 0 ? id.slice(0, slashIdx) : 'qwen';
64
+ const displayName = name ?? (slashIdx > 0 ? id.slice(slashIdx + 1) : id);
65
+
66
+ return {
67
+ engine: {
68
+ type: 'qwen',
69
+ provider,
70
+ model: { id, name: displayName },
71
+ account: { id: 0, name: '' },
72
+ },
73
+ limit: { input: contextLength ?? 0, output: 0 },
74
+ modalities: {
75
+ input: { text: true, image: false, audio: false, video: false, pdf: false },
76
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
77
+ },
78
+ capabilities: { reasoning: false, tools: true, structuredOutput: true },
79
+ cost: { input: 0, output: 0 },
80
+ };
81
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Qwen Code Provider Presets
3
+ *
4
+ * Each Qwen account picks one preset. The preset bundles a default base URL
5
+ * used both for the streaming endpoint and for the OpenAI-compatible
6
+ * `/models` discovery call (see `./models.ts`).
7
+ *
8
+ * The wire-format types (`QwenProviderPresetId`, `QwenProviderPreset`) live in
9
+ * `shared/types/unified/engine.ts` so the frontend stays typed without
10
+ * importing from `$backend`. Runtime values are exposed to the frontend via
11
+ * the `engine:qwen-presets-list` WS endpoint.
12
+ */
13
+
14
+ import type {
15
+ QwenProviderPresetId,
16
+ QwenProviderPreset,
17
+ } from '$shared/types/unified';
18
+
19
+ export type { QwenProviderPresetId, QwenProviderPreset };
20
+
21
+ export const QWEN_PROVIDER_PRESETS: QwenProviderPreset[] = [
22
+ {
23
+ id: 'dashscope-intl',
24
+ name: 'DashScope (International)',
25
+ defaultBaseUrl: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
26
+ docsUrl: 'https://www.alibabacloud.com/help/en/model-studio/get-api-key',
27
+ },
28
+ {
29
+ id: 'dashscope-cn',
30
+ name: 'DashScope (China)',
31
+ defaultBaseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
32
+ docsUrl: 'https://help.aliyun.com/zh/model-studio/get-api-key',
33
+ },
34
+ {
35
+ id: 'openrouter',
36
+ name: 'OpenRouter',
37
+ defaultBaseUrl: 'https://openrouter.ai/api/v1',
38
+ docsUrl: 'https://openrouter.ai/keys',
39
+ },
40
+ {
41
+ id: 'fireworks',
42
+ name: 'Fireworks AI',
43
+ defaultBaseUrl: 'https://api.fireworks.ai/inference/v1',
44
+ docsUrl: 'https://fireworks.ai/account/api-keys',
45
+ },
46
+ ];
47
+
48
+ export const DEFAULT_QWEN_PRESET: QwenProviderPresetId = 'dashscope-intl';
49
+
50
+ export const getQwenPreset = (id: QwenProviderPresetId | string): QwenProviderPreset | undefined =>
51
+ QWEN_PROVIDER_PRESETS.find(p => p.id === id);
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Qwen Code Session Fork (workaround)
3
+ *
4
+ * The Qwen Code SDK / CLI does not yet expose a native fork primitive. To
5
+ * support Clopen's multi-branch checkpoints feature — which lets the user
6
+ * replay an earlier point in the conversation as a sibling branch — we
7
+ * copy the on-disk chat file to a fresh session id and patch the embedded
8
+ * id references.
9
+ *
10
+ * On-disk layout (`~/.qwen/projects/<sanitized-cwd>/chats/<sessionId>.jsonl`):
11
+ *
12
+ * - `<sanitized-cwd>` is `cwd.replace(/[^a-zA-Z0-9]/g, '-')` (with a
13
+ * `toLowerCase()` first on win32). Mirror of the SDK's `sanitizeCwd()`
14
+ * in `node_modules/@qwen-code/sdk/dist/cli/cli.js` so we resolve to the
15
+ * same directory the bundled CLI writes to.
16
+ * - Each chat is a SINGLE JSONL file. Every record carries a
17
+ * `sessionId` field equal to the file's basename (without `.jsonl`).
18
+ * Per-record `uuid` / `parentUuid` reference the previous record's
19
+ * `uuid` and are unrelated to the session id, so a blanket replace
20
+ * of the source session id is safe.
21
+ *
22
+ * After copy + patch, `query({ ..., resume: <forkId> })` makes the bundled
23
+ * CLI pick the new file up as a resumed session whose id is `forkId`. The
24
+ * source file is left untouched so the original branch's history stays
25
+ * replayable.
26
+ *
27
+ * TODO: when @qwen-code/sdk gains a native `forkSession()` (or an
28
+ * equivalent flag the CLI honours, e.g. `--resume <id> --fork`), delete
29
+ * this helper and switch `QwenEngine.streamQuery` to use the SDK API
30
+ * directly. The migration is one line — same shape as Claude
31
+ * (`forkSession: true`) and OpenCode (`client.session.fork()`).
32
+ */
33
+
34
+ import fs from 'node:fs';
35
+ import path from 'node:path';
36
+ import os from 'node:os';
37
+ import { debug } from '$shared/utils/logger';
38
+
39
+ const QWEN_PROJECTS_DIR = path.join(os.homedir(), '.qwen', 'projects');
40
+
41
+ /**
42
+ * Mirror of `sanitizeCwd` in @qwen-code/sdk's bundled CLI
43
+ * (cli.js::sanitizeCwd). Lower-case on Windows then collapse every
44
+ * non-alphanumeric character to `-`. Drift from this would point to a
45
+ * different project directory and the fork would land in a directory the
46
+ * CLI never reads.
47
+ */
48
+ function sanitizeCwd(cwd: string): string {
49
+ const normalized = os.platform() === 'win32' ? cwd.toLowerCase() : cwd;
50
+ return normalized.replace(/[^a-zA-Z0-9]/g, '-');
51
+ }
52
+
53
+ function getChatsDir(projectPath: string): string {
54
+ return path.join(QWEN_PROJECTS_DIR, sanitizeCwd(projectPath), 'chats');
55
+ }
56
+
57
+ export function getSessionStatePath(projectPath: string, sessionId: string): string {
58
+ return path.join(getChatsDir(projectPath), `${sessionId}.jsonl`);
59
+ }
60
+
61
+ export function sessionStateExists(projectPath: string, sessionId: string): boolean {
62
+ return fs.existsSync(getSessionStatePath(projectPath, sessionId));
63
+ }
64
+
65
+ /**
66
+ * Copy `sourceSessionId`'s chat file to a new file keyed by
67
+ * `forkSessionId` (in the same project's `chats/` directory) and patch
68
+ * the embedded session ids. Returns true on success, false if the source
69
+ * file is missing (caller falls back to a fresh chat).
70
+ *
71
+ * The destination is removed first if it already exists so a re-fork
72
+ * from the same source produces a clean copy.
73
+ */
74
+ export function forkQwenSessionState(
75
+ projectPath: string,
76
+ sourceSessionId: string,
77
+ forkSessionId: string,
78
+ ): boolean {
79
+ const srcPath = getSessionStatePath(projectPath, sourceSessionId);
80
+ if (!fs.existsSync(srcPath)) {
81
+ debug.warn('engine', `Qwen fork: source chat ${sourceSessionId} not found at ${srcPath}`);
82
+ return false;
83
+ }
84
+
85
+ const dstPath = getSessionStatePath(projectPath, forkSessionId);
86
+ fs.mkdirSync(path.dirname(dstPath), { recursive: true });
87
+ if (fs.existsSync(dstPath)) {
88
+ fs.rmSync(dstPath, { force: true });
89
+ }
90
+
91
+ const content = fs.readFileSync(srcPath, 'utf-8');
92
+ const patched = content.split(sourceSessionId).join(forkSessionId);
93
+ fs.writeFileSync(dstPath, patched);
94
+
95
+ debug.log('engine', `Qwen fork: ${sourceSessionId} → ${forkSessionId}`);
96
+ return true;
97
+ }
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Qwen Code Engine Adapter
3
+ *
4
+ * Wraps `@qwen-code/sdk` into the AIEngine interface. The SDK manages a
5
+ * `qwen` subprocess per `query()` call (CLI is bundled with the SDK from
6
+ * v0.1.1+). We only own the per-project `Query` lifecycle, an
7
+ * `AbortController`, and the single-slot `pendingAskUserQuestion` for the
8
+ * blocking AskUserQuestion flow.
9
+ *
10
+ * Auth: paste-token only. `engine_accounts.credential` stores the
11
+ * OpenAI-compatible API key; the active account is read on every stream
12
+ * (env-var SDK pattern, no client construction state — no Restart-Server
13
+ * UX needed).
14
+ *
15
+ * MCP: reuses the existing remote MCP HTTP server at `/mcp` via
16
+ * `getQwenMcpConfig()`. Tool handlers run in-process in the Clopen backend
17
+ * (README §9.12).
18
+ *
19
+ * AskUserQuestion: Qwen's `canUseTool` callback signature does NOT include
20
+ * the tool_use_id (see `node_modules/@qwen-code/sdk/dist/index.d.ts:406-409`),
21
+ * so we cannot key pending answers by id at the moment the SDK invokes the
22
+ * callback. The SDK serialises AskUserQuestion — only one can be pending at
23
+ * a time — so we keep a single slot and recover the real tool_use_id from
24
+ * the converter (which sees the `assistant` message that carries the block
25
+ * id) and stamp it onto the slot. `resolveUserAnswer(toolUseId, …)` then
26
+ * accepts answers either matching that recorded id or for the slot when no
27
+ * id has been recorded yet (race on which lands first).
28
+ */
29
+
30
+ import {
31
+ query,
32
+ type Query,
33
+ type QueryOptions,
34
+ type SDKMessage,
35
+ type SDKUserMessage,
36
+ type PermissionResult,
37
+ type ToolInput,
38
+ } from '@qwen-code/sdk';
39
+ import type { EngineOutput, EngineModel } from '$shared/types/unified';
40
+ import type { AIEngine, EngineQueryOptions } from '../../types';
41
+ import { resolveOsPath } from '$backend/utils/paths';
42
+ import { debug } from '$shared/utils/logger';
43
+ import { getEngineEnv } from './environment';
44
+ import { handleStreamError } from './error-handler';
45
+ import { createSdkMessageConverter, toSdkUserMessage, type SdkMessageConverter } from './message-converter';
46
+ import { fetchQwenModels } from './models';
47
+ import { getQwenMcpConfig } from '../../../mcp/config';
48
+ import { forkQwenSessionState, sessionStateExists } from './session-fork';
49
+
50
+ interface PendingAskUserQuestion {
51
+ resolve: (result: PermissionResult) => void;
52
+ removeAbortListener: () => void;
53
+ input: ToolInput;
54
+ /**
55
+ * The tool_use_id the frontend will send back when answering, learned
56
+ * from the converter when it sees the `ask_user_question` tool_use block.
57
+ * Null until the assistant message arrives (canUseTool can fire either
58
+ * before or after that on the wire).
59
+ */
60
+ toolUseId: string | null;
61
+ }
62
+
63
+ export class QwenEngine implements AIEngine {
64
+ readonly name = 'qwen' as const;
65
+
66
+ private _isInitialized = false;
67
+ private activeController: AbortController | null = null;
68
+ private activeQuery: Query | null = null;
69
+ private pendingAskUserQuestion: PendingAskUserQuestion | null = null;
70
+ /**
71
+ * Live converter for the current stream — used by `resolveUserAnswer` to
72
+ * push the user's answers into the converter state so the eventual AUQ
73
+ * tool_result can be rewritten with the actual answers (the Qwen SDK's
74
+ * `canUseTool` → AUQ tool execution path drops `answers` on the floor; see
75
+ * the comment block at the top of `message-converter.ts` and the analysis
76
+ * in `qwen/stream.ts::canUseTool` for AskUserQuestion).
77
+ */
78
+ private activeConverter: SdkMessageConverter | null = null;
79
+
80
+ get isInitialized(): boolean {
81
+ return this._isInitialized;
82
+ }
83
+
84
+ get isActive(): boolean {
85
+ return this.activeController !== null;
86
+ }
87
+
88
+ async initialize(): Promise<void> {
89
+ if (this._isInitialized) return;
90
+ this._isInitialized = true;
91
+ debug.log('engine', '✅ Qwen Code engine initialized');
92
+ }
93
+
94
+ async dispose(): Promise<void> {
95
+ await this.cancel();
96
+ this.pendingAskUserQuestion = null;
97
+ this._isInitialized = false;
98
+ }
99
+
100
+ /**
101
+ * Discover models dynamically against the active account's
102
+ * OpenAI-compatible `/models` endpoint. There is no static catalog —
103
+ * if no account is configured or the endpoint is unreachable, the
104
+ * picker shows an empty list (same contract Copilot follows on auth
105
+ * failure).
106
+ */
107
+ async getAvailableModels(): Promise<EngineModel[]> {
108
+ const env = getEngineEnv();
109
+ if (!env) {
110
+ debug.log('engine', 'Qwen getAvailableModels: no active account configured');
111
+ return [];
112
+ }
113
+ const dynamic = await fetchQwenModels(env);
114
+ debug.log('engine', `Qwen getAvailableModels: ${dynamic.length} models from ${env.preset}`);
115
+ return dynamic;
116
+ }
117
+
118
+ async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
119
+ const {
120
+ projectPath,
121
+ prompt,
122
+ resume,
123
+ maxTurns,
124
+ modelId,
125
+ includePartialMessages = true,
126
+ abortController,
127
+ accountId,
128
+ } = options;
129
+
130
+ debug.log('chat', 'Qwen Code - Stream Query', { modelId, resume });
131
+
132
+ const resolution = getEngineEnv(accountId);
133
+ if (!resolution) {
134
+ throw new Error('Qwen Code is not configured. Add an API key in Settings → Engines → Qwen Code.');
135
+ }
136
+ const { env } = resolution;
137
+
138
+ this.activeController = abortController || new AbortController();
139
+ const resolvedProjectPath = resolveOsPath(projectPath);
140
+ const mcpConfig = getQwenMcpConfig();
141
+
142
+ // Fork-by-copy on EVERY resume — same semantics as Claude
143
+ // (`forkSession: true`), OpenCode (`client.session.fork()`),
144
+ // Copilot, and Codex (README §9.10): each turn must produce a
145
+ // brand-new session id so the original branch's history is never
146
+ // mutated and the multi-branch checkpoint tree stays consistent.
147
+ // Falls through to a plain resume only when the source chat can't
148
+ // be found on disk (best-effort recovery).
149
+ //
150
+ // TODO: replace with a native SDK fork call when @qwen-code/sdk
151
+ // adds one. The block is the same one-liner Claude/OpenCode use.
152
+ let resumeId = resume;
153
+ if (resume && sessionStateExists(resolvedProjectPath, resume)) {
154
+ const forkId = crypto.randomUUID();
155
+ if (forkQwenSessionState(resolvedProjectPath, resume, forkId)) {
156
+ resumeId = forkId;
157
+ debug.log('engine', `Qwen resumed session: ${forkId} (forked from ${resume})`);
158
+ }
159
+ }
160
+
161
+ // Capture the last few stderr lines from the bundled CLI so we can
162
+ // surface them when the SDK reports a generic "CLI process exited
163
+ // with code N" error. Otherwise the underlying cause (bad model,
164
+ // bad endpoint, MCP timeout, …) is invisible to the user.
165
+ const stderrLines: string[] = [];
166
+ const STDERR_KEEP = 20;
167
+
168
+ // Optional verbose SDK logging when CLOPEN_DEBUG_QWEN is set — useful
169
+ // when shipping a build with sticky symptoms but no obvious cause.
170
+ const verbose = !!process.env.CLOPEN_DEBUG_QWEN;
171
+
172
+ try {
173
+ const sdkOptions: QueryOptions = {
174
+ cwd: resolvedProjectPath,
175
+ model: modelId,
176
+ env,
177
+ // Force the bundled CLI onto the OpenAI-compatible auth path.
178
+ // Without this the CLI falls back to `qwen-oauth` whenever it
179
+ // finds residual OAuth state on disk (~/.qwen) and reports
180
+ // "Qwen OAuth free tier was discontinued" even though we've
181
+ // supplied OPENAI_API_KEY / OPENAI_BASE_URL.
182
+ authType: 'openai',
183
+ abortController: this.activeController,
184
+ includePartialMessages,
185
+ stderr: (msg: string) => {
186
+ const trimmed = msg.replace(/\s+$/, '');
187
+ if (!trimmed) return;
188
+ stderrLines.push(trimmed);
189
+ if (stderrLines.length > STDERR_KEEP) stderrLines.shift();
190
+ debug.warn('engine', 'qwen stderr:', trimmed);
191
+ },
192
+ ...(verbose ? { logLevel: 'debug' as const, debug: true } : {}),
193
+ // Lift the SDK's defaults: AskUserQuestion may legitimately
194
+ // block the SDK indefinitely while the user thinks (Claude's
195
+ // behaviour). MCP requests get a longer ceiling for slow
196
+ // browser-automation calls. Other timeouts keep the default.
197
+ //
198
+ // `canUseTool` is the cap on how long we can hold the SDK
199
+ // waiting for the user. The SDK feeds this to `setTimeout`,
200
+ // which silently clamps any value > 2^31-1 ms down to 1 ms
201
+ // (Node's TimeoutOverflowWarning) — that would auto-reject the
202
+ // AUQ before the user could even see the dialog. ~24.8 days is
203
+ // the practical maximum and is effectively unbounded for AUQ.
204
+ timeout: {
205
+ canUseTool: 2_147_483_647,
206
+ mcpRequest: 600_000,
207
+ },
208
+ // 'default' lets `canUseTool` decide; non-write tools auto-execute.
209
+ permissionMode: 'default',
210
+ // Block `ask_user_question` at the SDK level — `excludeTools` has
211
+ // the highest permission priority (see QueryOptions docs in the
212
+ // SDK), so the tool is never advertised to the model and
213
+ // `canUseTool` is never invoked for it.
214
+ //
215
+ // Why excluded: the Qwen SDK's stream-json
216
+ // `handleOutgoingPermissionRequest` (cli.js:486478-486485) calls
217
+ // `onConfirm(ProceedOnce)` WITHOUT forwarding the `updatedInput`
218
+ // payload we resolve `canUseTool` with — so the user's `answers`
219
+ // are dropped and the AUQ tool executes with `userAnswers: {}`,
220
+ // emitting `"User has provided the following answers:\n\n"` and
221
+ // closing the UI dialog before the user can respond. The
222
+ // converter has a rewrite workaround (recordUserAnswer +
223
+ // convertUserMessage interception) but it depends on a race
224
+ // between the empty tool_result and `resolveUserAnswer` landing —
225
+ // not reliable enough for production use.
226
+ //
227
+ // TODO(qwen-sdk): re-enable AUQ once the upstream SDK forwards
228
+ // `updatedInput` from `canUseTool` into the tool execution
229
+ // payload. Verify by checking `handleOutgoingPermissionRequest`
230
+ // in the bundled CLI — when it stops calling
231
+ // `onConfirm(ProceedOnce)` without the payload (or starts
232
+ // passing the resolved `updatedInput`), drop this excludeTools
233
+ // entry. The AUQ flow code (canUseTool handler, converter
234
+ // state, resolveUserAnswer, recordUserAnswer) is intentionally
235
+ // kept in place so reverting is a one-line change.
236
+ excludeTools: ['ask_user_question'],
237
+ canUseTool: async (toolName, input, ctx) => {
238
+ // Qwen SDK passes the registered (snake_case) tool name here —
239
+ // `ToolNames.ASK_USER_QUESTION = "ask_user_question"` — NOT the
240
+ // canonical PascalCase form Claude uses. Comparing against
241
+ // `'AskUserQuestion'` would silently fall through to auto-allow,
242
+ // the SDK would then call `onConfirm(ProceedOnce)` without a
243
+ // payload, and the AUQ tool would emit
244
+ // `"User has provided the following answers:\n\n"` immediately
245
+ // (empty `userAnswers`), closing the UI dialog before the user
246
+ // has a chance to respond.
247
+ if (toolName === 'ask_user_question') {
248
+ return new Promise<PermissionResult>((resolve) => {
249
+ if (ctx.signal.aborted) {
250
+ resolve({ behavior: 'deny', message: 'Cancelled' });
251
+ return;
252
+ }
253
+ const onAbort = () => {
254
+ // Drop the slot WITHOUT resolving — same pattern as
255
+ // Claude (see claude/stream.ts cancel()). Resolving
256
+ // would prompt the SDK to write the result to a
257
+ // subprocess that's about to die.
258
+ this.pendingAskUserQuestion = null;
259
+ };
260
+ ctx.signal.addEventListener('abort', onAbort, { once: true });
261
+
262
+ this.pendingAskUserQuestion = {
263
+ resolve: (result) => {
264
+ ctx.signal.removeEventListener('abort', onAbort);
265
+ resolve(result);
266
+ },
267
+ removeAbortListener: () => ctx.signal.removeEventListener('abort', onAbort),
268
+ input,
269
+ toolUseId: null,
270
+ };
271
+ });
272
+ }
273
+ // Auto-allow everything else.
274
+ return { behavior: 'allow' as const, updatedInput: input };
275
+ },
276
+ ...(maxTurns !== undefined ? { maxSessionTurns: maxTurns } : {}),
277
+ ...(resumeId ? { resume: resumeId } : {}),
278
+ ...(Object.keys(mcpConfig).length > 0 ? { mcpServers: mcpConfig } : {}),
279
+ };
280
+
281
+ const sdkPrompt = toSdkUserMessage(prompt);
282
+ const promptIterable = (async function* (): AsyncIterable<SDKUserMessage> {
283
+ yield sdkPrompt;
284
+ })();
285
+
286
+ const queryInstance = query({ prompt: promptIterable, options: sdkOptions });
287
+ this.activeQuery = queryInstance;
288
+
289
+ const converter = createSdkMessageConverter(modelId, {
290
+ onAskUserQuestionEmitted: (toolUseId: string) => {
291
+ // canUseTool may fire before OR after the assistant message
292
+ // containing the tool_use block — record either way. Keying
293
+ // the pending slot here unblocks `resolveUserAnswer` even
294
+ // when the frontend gets the toolUseId before our slot was
295
+ // populated (rare but possible if the SDK queues events).
296
+ if (this.pendingAskUserQuestion && this.pendingAskUserQuestion.toolUseId === null) {
297
+ this.pendingAskUserQuestion.toolUseId = toolUseId;
298
+ }
299
+ },
300
+ });
301
+ this.activeConverter = converter;
302
+ for await (const sdkMessage of queryInstance) {
303
+ yield* converter.convert(sdkMessage);
304
+ }
305
+ } catch (error) {
306
+ handleStreamError(error, stderrLines.join('\n'));
307
+ } finally {
308
+ this.activeController = null;
309
+ this.activeQuery = null;
310
+ this.activeConverter = null;
311
+ }
312
+ }
313
+
314
+ async cancel(): Promise<void> {
315
+ // Drop the pending AskUserQuestion handler — same pattern as Claude
316
+ // (don't resolve, just abandon, otherwise the SDK tries to write to
317
+ // a subprocess that's about to die).
318
+ if (this.pendingAskUserQuestion) {
319
+ this.pendingAskUserQuestion.removeAbortListener();
320
+ this.pendingAskUserQuestion = null;
321
+ }
322
+
323
+ if (this.activeQuery && typeof this.activeQuery.close === 'function') {
324
+ try {
325
+ await this.activeQuery.close();
326
+ } catch {
327
+ /* subprocess may already be dead */
328
+ }
329
+ }
330
+
331
+ if (this.activeController && !this.activeController.signal.aborted) {
332
+ this.activeController.abort();
333
+ }
334
+ this.activeController = null;
335
+ this.activeQuery = null;
336
+ this.activeConverter = null;
337
+ }
338
+
339
+ async interrupt(): Promise<void> {
340
+ if (this.activeQuery && typeof this.activeQuery.interrupt === 'function') {
341
+ try {
342
+ await this.activeQuery.interrupt();
343
+ } catch {
344
+ /* fall through to cancel */
345
+ }
346
+ }
347
+ }
348
+
349
+ resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
350
+ const pending = this.pendingAskUserQuestion;
351
+ if (!pending) {
352
+ debug.warn('engine', 'Qwen resolveUserAnswer: no pending question');
353
+ return false;
354
+ }
355
+ // Verify the toolUseId matches the one we recorded from the converter.
356
+ // If we haven't seen the tool_use block yet (canUseTool fired first),
357
+ // accept the answer and trust the frontend — only one question can be
358
+ // pending at a time per SDK contract.
359
+ if (pending.toolUseId !== null && pending.toolUseId !== toolUseId) {
360
+ debug.warn('engine', `Qwen resolveUserAnswer: toolUseId mismatch (got ${toolUseId}, expected ${pending.toolUseId})`);
361
+ return false;
362
+ }
363
+
364
+ // Push the answers into converter state FIRST so the rewrite is in
365
+ // place by the time the SDK's broken AUQ tool_result arrives. The
366
+ // SDK's `handleOutgoingPermissionRequest` calls `onConfirm(ProceedOnce)`
367
+ // without a payload — `userAnswers` always ends up `{}` and the
368
+ // tool_result body is `"User has provided the following answers:\n\n"`
369
+ // (empty). The converter intercepts that tool_result and replaces its
370
+ // content with the proper formatted answers we just stored.
371
+ this.activeConverter?.recordUserAnswer(toolUseId, answers);
372
+
373
+ pending.resolve({
374
+ behavior: 'allow',
375
+ updatedInput: { ...pending.input, answers },
376
+ });
377
+ this.pendingAskUserQuestion = null;
378
+ return true;
379
+ }
380
+ }
@@ -17,6 +17,9 @@
17
17
  import type { AIEngine, EngineType } from './types';
18
18
  import { ClaudeCodeEngine } from './adapters/claude';
19
19
  import { OpenCodeEngine, disposeOpenCodeClient } from './adapters/opencode';
20
+ import { CopilotEngine } from './adapters/copilot';
21
+ import { CodexEngine } from './adapters/codex';
22
+ import { QwenEngine } from './adapters/qwen';
20
23
  import { debug } from '$shared/utils/logger';
21
24
 
22
25
  // ============================================================================
@@ -29,6 +32,12 @@ function createEngine(type: EngineType): AIEngine {
29
32
  return new ClaudeCodeEngine();
30
33
  case 'opencode':
31
34
  return new OpenCodeEngine();
35
+ case 'copilot':
36
+ return new CopilotEngine();
37
+ case 'codex':
38
+ return new CodexEngine();
39
+ case 'qwen':
40
+ return new QwenEngine();
32
41
  default:
33
42
  throw new Error(`Unknown engine type: ${type}`);
34
43
  }
@@ -173,6 +182,32 @@ export async function disposeProjectEngines(projectId: string): Promise<void> {
173
182
  }
174
183
  }
175
184
 
185
+ /**
186
+ * Dispose all instances of a given engine type across all projects, plus the
187
+ * global singleton. Call when an account/credential change requires every
188
+ * client to re-initialise (e.g. Copilot account switch).
189
+ */
190
+ export async function disposeAllProjectEnginesByType(type: EngineType): Promise<void> {
191
+ for (const [projectId, engines] of projectEngines) {
192
+ const engine = engines.get(type);
193
+ if (engine) {
194
+ try {
195
+ await engine.dispose();
196
+ debug.log('engine', `Project engine disposed: ${type} for project ${projectId.slice(0, 8)}`);
197
+ } catch (error) {
198
+ debug.error('engine', `Error disposing project engine ${type} for ${projectId.slice(0, 8)}:`, error);
199
+ }
200
+ engines.delete(type);
201
+ }
202
+ if (engines.size === 0) {
203
+ projectEngines.delete(projectId);
204
+ }
205
+ }
206
+
207
+ // Also drop the global singleton so the next non-streaming op rebuilds it.
208
+ await disposeEngine(type);
209
+ }
210
+
176
211
  /**
177
212
  * Dispose all project engines (used on server shutdown).
178
213
  */