@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.
- package/README.md +22 -19
- package/backend/auth/auth-service.ts +56 -1
- package/backend/auth/permissions.ts +66 -2
- package/backend/auth/session-cleanup.ts +58 -0
- package/backend/chat/stream-manager.ts +143 -13
- package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
- package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
- package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
- package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
- package/backend/database/migrations/index.ts +29 -1
- package/backend/database/queries/db-client-connection-queries.ts +160 -54
- package/backend/database/queries/engine-queries.ts +12 -0
- package/backend/database/queries/project-queries.ts +10 -5
- package/backend/db-client/connection-manager.ts +9 -3
- package/backend/engine/README.md +1702 -0
- package/backend/engine/adapters/claude/models.ts +141 -0
- package/backend/engine/adapters/claude/stream.ts +1 -1
- package/backend/engine/adapters/codex/credential.ts +179 -0
- package/backend/engine/adapters/codex/error-handler.ts +65 -0
- package/backend/engine/adapters/codex/index.ts +1 -0
- package/backend/engine/adapters/codex/message-converter.ts +646 -0
- package/backend/engine/adapters/codex/models.ts +105 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
- package/backend/engine/adapters/codex/session-fork.ts +149 -0
- package/backend/engine/adapters/codex/stream.ts +310 -0
- package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
- package/backend/engine/adapters/copilot/error-handler.ts +94 -0
- package/backend/engine/adapters/copilot/index.ts +1 -0
- package/backend/engine/adapters/copilot/message-converter.ts +973 -0
- package/backend/engine/adapters/copilot/models.ts +92 -0
- package/backend/engine/adapters/copilot/session-fork.ts +111 -0
- package/backend/engine/adapters/copilot/stream.ts +570 -0
- package/backend/engine/adapters/opencode/config.ts +56 -104
- package/backend/engine/adapters/opencode/error-handler.ts +71 -0
- package/backend/engine/adapters/opencode/models.ts +79 -0
- package/backend/engine/adapters/opencode/presets.ts +91 -0
- package/backend/engine/adapters/opencode/stream.ts +8 -114
- package/backend/engine/adapters/qwen/credential.ts +78 -0
- package/backend/engine/adapters/qwen/environment.ts +84 -0
- package/backend/engine/adapters/qwen/error-handler.ts +71 -0
- package/backend/engine/adapters/qwen/index.ts +1 -0
- package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
- package/backend/engine/adapters/qwen/models.ts +81 -0
- package/backend/engine/adapters/qwen/presets.ts +51 -0
- package/backend/engine/adapters/qwen/session-fork.ts +97 -0
- package/backend/engine/adapters/qwen/stream.ts +379 -0
- package/backend/engine/index.ts +35 -0
- package/backend/engine/install-recipes.ts +80 -1
- package/backend/engine/install-runner.ts +4 -0
- package/backend/files/path-browsing.ts +20 -0
- package/backend/git/git-service.ts +81 -11
- package/backend/git/git-spawn-validation.test.ts +75 -0
- package/backend/git/git-spawn-validation.ts +77 -0
- package/backend/index.ts +5 -0
- package/backend/mcp/README.md +84 -14
- package/backend/mcp/config.ts +218 -17
- package/backend/mcp/index.ts +2 -0
- package/backend/mcp/project-context.ts +55 -0
- package/backend/mcp/servers/browser-automation/actions.ts +6 -1
- package/backend/mcp/servers/helper.ts +13 -0
- package/backend/middleware/error-handler.ts +16 -2
- package/backend/preview/browser/browser-preview-service.ts +4 -4
- package/backend/preview/browser/browser-tab-manager.ts +23 -3
- package/backend/snapshot/gitignore.ts +4 -9
- package/backend/tunnel/cloudflared/binary.ts +2 -2
- package/backend/tunnel/global-tunnel-manager.ts +9 -3
- package/backend/utils/ws.ts +5 -1
- package/backend/ws/README.md +128 -3
- package/backend/ws/access.ts +56 -0
- package/backend/ws/auth/index.ts +14 -0
- package/backend/ws/auth/login.ts +3 -0
- package/backend/ws/auth/users.ts +61 -1
- package/backend/ws/chat/stream.ts +139 -22
- package/backend/ws/db-client/access.ts +19 -0
- package/backend/ws/db-client/connections.ts +31 -17
- package/backend/ws/db-client/io.ts +7 -9
- package/backend/ws/db-client/query.ts +86 -32
- package/backend/ws/db-client/schema.ts +9 -4
- package/backend/ws/db-client/structure.ts +22 -10
- package/backend/ws/engine/access.ts +39 -0
- package/backend/ws/engine/claude/accounts.ts +15 -10
- package/backend/ws/engine/codex/accounts.ts +516 -0
- package/backend/ws/engine/codex/index.ts +14 -0
- package/backend/ws/engine/codex/status.ts +87 -0
- package/backend/ws/engine/copilot/accounts.ts +122 -0
- package/backend/ws/engine/copilot/index.ts +13 -0
- package/backend/ws/engine/copilot/status.ts +54 -0
- package/backend/ws/engine/index.ts +7 -1
- package/backend/ws/engine/opencode/providers.ts +1 -1
- package/backend/ws/engine/qwen/accounts.ts +137 -0
- package/backend/ws/engine/qwen/index.ts +15 -0
- package/backend/ws/engine/qwen/presets.ts +40 -0
- package/backend/ws/engine/qwen/status.ts +54 -0
- package/backend/ws/files/path-access.ts +101 -0
- package/backend/ws/files/read.ts +26 -11
- package/backend/ws/files/search.ts +10 -6
- package/backend/ws/files/state.ts +3 -0
- package/backend/ws/files/watch.ts +7 -1
- package/backend/ws/files/write.ts +109 -15
- package/backend/ws/git/branch.ts +13 -19
- package/backend/ws/git/commit-message.ts +3 -4
- package/backend/ws/git/commit.ts +5 -7
- package/backend/ws/git/conflict.ts +7 -10
- package/backend/ws/git/diff.ts +7 -10
- package/backend/ws/git/log.ts +3 -4
- package/backend/ws/git/remote.ts +30 -43
- package/backend/ws/git/staging.ts +13 -19
- package/backend/ws/git/status.ts +7 -11
- package/backend/ws/messages/crud.ts +7 -13
- package/backend/ws/preview/access.ts +45 -0
- package/backend/ws/preview/browser/cleanup.ts +3 -11
- package/backend/ws/preview/browser/console.ts +7 -42
- package/backend/ws/preview/browser/interact.ts +2 -6
- package/backend/ws/preview/browser/native-ui.ts +5 -18
- package/backend/ws/preview/browser/stats.ts +2 -12
- package/backend/ws/preview/browser/tab-info.ts +4 -20
- package/backend/ws/preview/browser/tab.ts +4 -27
- package/backend/ws/preview/browser/webcodecs.ts +6 -47
- package/backend/ws/projects/crud.ts +15 -16
- package/backend/ws/projects/status.ts +5 -1
- package/backend/ws/sessions/crud.ts +31 -36
- package/backend/ws/settings/crud.ts +13 -13
- package/backend/ws/snapshot/restore.ts +5 -2
- package/backend/ws/snapshot/timeline.ts +3 -1
- package/backend/ws/system-tools/access.ts +28 -0
- package/backend/ws/system-tools/install.ts +13 -4
- package/backend/ws/system-tools/status.ts +5 -2
- package/backend/ws/terminal/access.ts +56 -0
- package/backend/ws/terminal/persistence.ts +13 -7
- package/backend/ws/terminal/session.ts +35 -14
- package/backend/ws/terminal/stream.ts +4 -1
- package/dist/assets/{index-DqAGCTFT.js → index-C1afGwHY.js} +2 -2
- package/dist/assets/main-CZb3Y_Z_.js +315 -0
- package/dist/assets/main-Cn8cX2DY.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +5 -1
- package/shared/constants/engines.ts +45 -140
- package/shared/types/database/schema.ts +1 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +29 -1
- package/shared/types/unified/index.ts +2 -0
- package/shared/types/unified/message.ts +1 -1
- package/shared/types/unified/tool.ts +17 -2
- package/shared/utils/ws-server.ts +14 -0
- package/dist/assets/main-DsED0rLr.js +0 -304
- package/dist/assets/main-eWY9R8g9.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,379 @@
|
|
|
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
|
+
throw new Error('Qwen Code is not configured. Add an API key in Settings → Engines → Qwen Code.');
|
|
111
|
+
}
|
|
112
|
+
const dynamic = await fetchQwenModels(env);
|
|
113
|
+
debug.log('engine', `Qwen getAvailableModels: ${dynamic.length} models from ${env.preset}`);
|
|
114
|
+
return dynamic;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
|
|
118
|
+
const {
|
|
119
|
+
projectPath,
|
|
120
|
+
prompt,
|
|
121
|
+
resume,
|
|
122
|
+
maxTurns,
|
|
123
|
+
modelId,
|
|
124
|
+
includePartialMessages = true,
|
|
125
|
+
abortController,
|
|
126
|
+
accountId,
|
|
127
|
+
} = options;
|
|
128
|
+
|
|
129
|
+
debug.log('chat', 'Qwen Code - Stream Query', { modelId, resume });
|
|
130
|
+
|
|
131
|
+
const resolution = getEngineEnv(accountId);
|
|
132
|
+
if (!resolution) {
|
|
133
|
+
throw new Error('Qwen Code is not configured. Add an API key in Settings → Engines → Qwen Code.');
|
|
134
|
+
}
|
|
135
|
+
const { env } = resolution;
|
|
136
|
+
|
|
137
|
+
this.activeController = abortController || new AbortController();
|
|
138
|
+
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
139
|
+
const mcpConfig = getQwenMcpConfig();
|
|
140
|
+
|
|
141
|
+
// Fork-by-copy on EVERY resume — same semantics as Claude
|
|
142
|
+
// (`forkSession: true`), OpenCode (`client.session.fork()`),
|
|
143
|
+
// Copilot, and Codex (README §9.10): each turn must produce a
|
|
144
|
+
// brand-new session id so the original branch's history is never
|
|
145
|
+
// mutated and the multi-branch checkpoint tree stays consistent.
|
|
146
|
+
// Falls through to a plain resume only when the source chat can't
|
|
147
|
+
// be found on disk (best-effort recovery).
|
|
148
|
+
//
|
|
149
|
+
// TODO: replace with a native SDK fork call when @qwen-code/sdk
|
|
150
|
+
// adds one. The block is the same one-liner Claude/OpenCode use.
|
|
151
|
+
let resumeId = resume;
|
|
152
|
+
if (resume && sessionStateExists(resolvedProjectPath, resume)) {
|
|
153
|
+
const forkId = crypto.randomUUID();
|
|
154
|
+
if (forkQwenSessionState(resolvedProjectPath, resume, forkId)) {
|
|
155
|
+
resumeId = forkId;
|
|
156
|
+
debug.log('engine', `Qwen resumed session: ${forkId} (forked from ${resume})`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Capture the last few stderr lines from the bundled CLI so we can
|
|
161
|
+
// surface them when the SDK reports a generic "CLI process exited
|
|
162
|
+
// with code N" error. Otherwise the underlying cause (bad model,
|
|
163
|
+
// bad endpoint, MCP timeout, …) is invisible to the user.
|
|
164
|
+
const stderrLines: string[] = [];
|
|
165
|
+
const STDERR_KEEP = 20;
|
|
166
|
+
|
|
167
|
+
// Optional verbose SDK logging when CLOPEN_DEBUG_QWEN is set — useful
|
|
168
|
+
// when shipping a build with sticky symptoms but no obvious cause.
|
|
169
|
+
const verbose = !!process.env.CLOPEN_DEBUG_QWEN;
|
|
170
|
+
|
|
171
|
+
try {
|
|
172
|
+
const sdkOptions: QueryOptions = {
|
|
173
|
+
cwd: resolvedProjectPath,
|
|
174
|
+
model: modelId,
|
|
175
|
+
env,
|
|
176
|
+
// Force the bundled CLI onto the OpenAI-compatible auth path.
|
|
177
|
+
// Without this the CLI falls back to `qwen-oauth` whenever it
|
|
178
|
+
// finds residual OAuth state on disk (~/.qwen) and reports
|
|
179
|
+
// "Qwen OAuth free tier was discontinued" even though we've
|
|
180
|
+
// supplied OPENAI_API_KEY / OPENAI_BASE_URL.
|
|
181
|
+
authType: 'openai',
|
|
182
|
+
abortController: this.activeController,
|
|
183
|
+
includePartialMessages,
|
|
184
|
+
stderr: (msg: string) => {
|
|
185
|
+
const trimmed = msg.replace(/\s+$/, '');
|
|
186
|
+
if (!trimmed) return;
|
|
187
|
+
stderrLines.push(trimmed);
|
|
188
|
+
if (stderrLines.length > STDERR_KEEP) stderrLines.shift();
|
|
189
|
+
debug.warn('engine', 'qwen stderr:', trimmed);
|
|
190
|
+
},
|
|
191
|
+
...(verbose ? { logLevel: 'debug' as const, debug: true } : {}),
|
|
192
|
+
// Lift the SDK's defaults: AskUserQuestion may legitimately
|
|
193
|
+
// block the SDK indefinitely while the user thinks (Claude's
|
|
194
|
+
// behaviour). MCP requests get a longer ceiling for slow
|
|
195
|
+
// browser-automation calls. Other timeouts keep the default.
|
|
196
|
+
//
|
|
197
|
+
// `canUseTool` is the cap on how long we can hold the SDK
|
|
198
|
+
// waiting for the user. The SDK feeds this to `setTimeout`,
|
|
199
|
+
// which silently clamps any value > 2^31-1 ms down to 1 ms
|
|
200
|
+
// (Node's TimeoutOverflowWarning) — that would auto-reject the
|
|
201
|
+
// AUQ before the user could even see the dialog. ~24.8 days is
|
|
202
|
+
// the practical maximum and is effectively unbounded for AUQ.
|
|
203
|
+
timeout: {
|
|
204
|
+
canUseTool: 2_147_483_647,
|
|
205
|
+
mcpRequest: 600_000,
|
|
206
|
+
},
|
|
207
|
+
// 'default' lets `canUseTool` decide; non-write tools auto-execute.
|
|
208
|
+
permissionMode: 'default',
|
|
209
|
+
// Block `ask_user_question` at the SDK level — `excludeTools` has
|
|
210
|
+
// the highest permission priority (see QueryOptions docs in the
|
|
211
|
+
// SDK), so the tool is never advertised to the model and
|
|
212
|
+
// `canUseTool` is never invoked for it.
|
|
213
|
+
//
|
|
214
|
+
// Why excluded: the Qwen SDK's stream-json
|
|
215
|
+
// `handleOutgoingPermissionRequest` (cli.js:486478-486485) calls
|
|
216
|
+
// `onConfirm(ProceedOnce)` WITHOUT forwarding the `updatedInput`
|
|
217
|
+
// payload we resolve `canUseTool` with — so the user's `answers`
|
|
218
|
+
// are dropped and the AUQ tool executes with `userAnswers: {}`,
|
|
219
|
+
// emitting `"User has provided the following answers:\n\n"` and
|
|
220
|
+
// closing the UI dialog before the user can respond. The
|
|
221
|
+
// converter has a rewrite workaround (recordUserAnswer +
|
|
222
|
+
// convertUserMessage interception) but it depends on a race
|
|
223
|
+
// between the empty tool_result and `resolveUserAnswer` landing —
|
|
224
|
+
// not reliable enough for production use.
|
|
225
|
+
//
|
|
226
|
+
// TODO(qwen-sdk): re-enable AUQ once the upstream SDK forwards
|
|
227
|
+
// `updatedInput` from `canUseTool` into the tool execution
|
|
228
|
+
// payload. Verify by checking `handleOutgoingPermissionRequest`
|
|
229
|
+
// in the bundled CLI — when it stops calling
|
|
230
|
+
// `onConfirm(ProceedOnce)` without the payload (or starts
|
|
231
|
+
// passing the resolved `updatedInput`), drop this excludeTools
|
|
232
|
+
// entry. The AUQ flow code (canUseTool handler, converter
|
|
233
|
+
// state, resolveUserAnswer, recordUserAnswer) is intentionally
|
|
234
|
+
// kept in place so reverting is a one-line change.
|
|
235
|
+
excludeTools: ['ask_user_question'],
|
|
236
|
+
canUseTool: async (toolName, input, ctx) => {
|
|
237
|
+
// Qwen SDK passes the registered (snake_case) tool name here —
|
|
238
|
+
// `ToolNames.ASK_USER_QUESTION = "ask_user_question"` — NOT the
|
|
239
|
+
// canonical PascalCase form Claude uses. Comparing against
|
|
240
|
+
// `'AskUserQuestion'` would silently fall through to auto-allow,
|
|
241
|
+
// the SDK would then call `onConfirm(ProceedOnce)` without a
|
|
242
|
+
// payload, and the AUQ tool would emit
|
|
243
|
+
// `"User has provided the following answers:\n\n"` immediately
|
|
244
|
+
// (empty `userAnswers`), closing the UI dialog before the user
|
|
245
|
+
// has a chance to respond.
|
|
246
|
+
if (toolName === 'ask_user_question') {
|
|
247
|
+
return new Promise<PermissionResult>((resolve) => {
|
|
248
|
+
if (ctx.signal.aborted) {
|
|
249
|
+
resolve({ behavior: 'deny', message: 'Cancelled' });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const onAbort = () => {
|
|
253
|
+
// Drop the slot WITHOUT resolving — same pattern as
|
|
254
|
+
// Claude (see claude/stream.ts cancel()). Resolving
|
|
255
|
+
// would prompt the SDK to write the result to a
|
|
256
|
+
// subprocess that's about to die.
|
|
257
|
+
this.pendingAskUserQuestion = null;
|
|
258
|
+
};
|
|
259
|
+
ctx.signal.addEventListener('abort', onAbort, { once: true });
|
|
260
|
+
|
|
261
|
+
this.pendingAskUserQuestion = {
|
|
262
|
+
resolve: (result) => {
|
|
263
|
+
ctx.signal.removeEventListener('abort', onAbort);
|
|
264
|
+
resolve(result);
|
|
265
|
+
},
|
|
266
|
+
removeAbortListener: () => ctx.signal.removeEventListener('abort', onAbort),
|
|
267
|
+
input,
|
|
268
|
+
toolUseId: null,
|
|
269
|
+
};
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
// Auto-allow everything else.
|
|
273
|
+
return { behavior: 'allow' as const, updatedInput: input };
|
|
274
|
+
},
|
|
275
|
+
...(maxTurns !== undefined ? { maxSessionTurns: maxTurns } : {}),
|
|
276
|
+
...(resumeId ? { resume: resumeId } : {}),
|
|
277
|
+
...(Object.keys(mcpConfig).length > 0 ? { mcpServers: mcpConfig } : {}),
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
const sdkPrompt = toSdkUserMessage(prompt);
|
|
281
|
+
const promptIterable = (async function* (): AsyncIterable<SDKUserMessage> {
|
|
282
|
+
yield sdkPrompt;
|
|
283
|
+
})();
|
|
284
|
+
|
|
285
|
+
const queryInstance = query({ prompt: promptIterable, options: sdkOptions });
|
|
286
|
+
this.activeQuery = queryInstance;
|
|
287
|
+
|
|
288
|
+
const converter = createSdkMessageConverter(modelId, {
|
|
289
|
+
onAskUserQuestionEmitted: (toolUseId: string) => {
|
|
290
|
+
// canUseTool may fire before OR after the assistant message
|
|
291
|
+
// containing the tool_use block — record either way. Keying
|
|
292
|
+
// the pending slot here unblocks `resolveUserAnswer` even
|
|
293
|
+
// when the frontend gets the toolUseId before our slot was
|
|
294
|
+
// populated (rare but possible if the SDK queues events).
|
|
295
|
+
if (this.pendingAskUserQuestion && this.pendingAskUserQuestion.toolUseId === null) {
|
|
296
|
+
this.pendingAskUserQuestion.toolUseId = toolUseId;
|
|
297
|
+
}
|
|
298
|
+
},
|
|
299
|
+
});
|
|
300
|
+
this.activeConverter = converter;
|
|
301
|
+
for await (const sdkMessage of queryInstance) {
|
|
302
|
+
yield* converter.convert(sdkMessage);
|
|
303
|
+
}
|
|
304
|
+
} catch (error) {
|
|
305
|
+
handleStreamError(error, stderrLines.join('\n'));
|
|
306
|
+
} finally {
|
|
307
|
+
this.activeController = null;
|
|
308
|
+
this.activeQuery = null;
|
|
309
|
+
this.activeConverter = null;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async cancel(): Promise<void> {
|
|
314
|
+
// Drop the pending AskUserQuestion handler — same pattern as Claude
|
|
315
|
+
// (don't resolve, just abandon, otherwise the SDK tries to write to
|
|
316
|
+
// a subprocess that's about to die).
|
|
317
|
+
if (this.pendingAskUserQuestion) {
|
|
318
|
+
this.pendingAskUserQuestion.removeAbortListener();
|
|
319
|
+
this.pendingAskUserQuestion = null;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (this.activeQuery && typeof this.activeQuery.close === 'function') {
|
|
323
|
+
try {
|
|
324
|
+
await this.activeQuery.close();
|
|
325
|
+
} catch {
|
|
326
|
+
/* subprocess may already be dead */
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (this.activeController && !this.activeController.signal.aborted) {
|
|
331
|
+
this.activeController.abort();
|
|
332
|
+
}
|
|
333
|
+
this.activeController = null;
|
|
334
|
+
this.activeQuery = null;
|
|
335
|
+
this.activeConverter = null;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async interrupt(): Promise<void> {
|
|
339
|
+
if (this.activeQuery && typeof this.activeQuery.interrupt === 'function') {
|
|
340
|
+
try {
|
|
341
|
+
await this.activeQuery.interrupt();
|
|
342
|
+
} catch {
|
|
343
|
+
/* fall through to cancel */
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
|
|
349
|
+
const pending = this.pendingAskUserQuestion;
|
|
350
|
+
if (!pending) {
|
|
351
|
+
debug.warn('engine', 'Qwen resolveUserAnswer: no pending question');
|
|
352
|
+
return false;
|
|
353
|
+
}
|
|
354
|
+
// Verify the toolUseId matches the one we recorded from the converter.
|
|
355
|
+
// If we haven't seen the tool_use block yet (canUseTool fired first),
|
|
356
|
+
// accept the answer and trust the frontend — only one question can be
|
|
357
|
+
// pending at a time per SDK contract.
|
|
358
|
+
if (pending.toolUseId !== null && pending.toolUseId !== toolUseId) {
|
|
359
|
+
debug.warn('engine', `Qwen resolveUserAnswer: toolUseId mismatch (got ${toolUseId}, expected ${pending.toolUseId})`);
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Push the answers into converter state FIRST so the rewrite is in
|
|
364
|
+
// place by the time the SDK's broken AUQ tool_result arrives. The
|
|
365
|
+
// SDK's `handleOutgoingPermissionRequest` calls `onConfirm(ProceedOnce)`
|
|
366
|
+
// without a payload — `userAnswers` always ends up `{}` and the
|
|
367
|
+
// tool_result body is `"User has provided the following answers:\n\n"`
|
|
368
|
+
// (empty). The converter intercepts that tool_result and replaces its
|
|
369
|
+
// content with the proper formatted answers we just stored.
|
|
370
|
+
this.activeConverter?.recordUserAnswer(toolUseId, answers);
|
|
371
|
+
|
|
372
|
+
pending.resolve({
|
|
373
|
+
behavior: 'allow',
|
|
374
|
+
updatedInput: { ...pending.input, answers },
|
|
375
|
+
});
|
|
376
|
+
this.pendingAskUserQuestion = null;
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
}
|
package/backend/engine/index.ts
CHANGED
|
@@ -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
|
*/
|