@myrialabs/clopen 0.4.45 → 0.4.46

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 (70) hide show
  1. package/backend/artifacts/project/sources.ts +2 -2
  2. package/backend/engine/adapters/claude/models.test.ts +49 -0
  3. package/backend/engine/adapters/claude/models.ts +81 -562
  4. package/backend/engine/adapters/claude/stream.ts +5 -4
  5. package/backend/engine/adapters/cline/credential.ts +42 -18
  6. package/backend/engine/adapters/cline/message-converter.ts +31 -1
  7. package/backend/engine/adapters/cline/models.test.ts +77 -0
  8. package/backend/engine/adapters/cline/models.ts +89 -3
  9. package/backend/engine/adapters/cline/presets.ts +5 -0
  10. package/backend/engine/adapters/cline/stream.ts +9 -2
  11. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  12. package/backend/engine/adapters/codex/models.ts +54 -31
  13. package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
  14. package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
  15. package/backend/engine/adapters/codex/session-fork.ts +5 -0
  16. package/backend/engine/adapters/codex/stream.ts +8 -7
  17. package/backend/engine/adapters/copilot/models.test.ts +40 -0
  18. package/backend/engine/adapters/copilot/models.ts +51 -24
  19. package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
  20. package/backend/engine/adapters/copilot/permissions.ts +72 -0
  21. package/backend/engine/adapters/copilot/stream.ts +77 -67
  22. package/backend/engine/adapters/cursor/stream.ts +8 -4
  23. package/backend/engine/adapters/pi/credential.test.ts +83 -0
  24. package/backend/engine/adapters/pi/credential.ts +68 -12
  25. package/backend/engine/adapters/pi/environment.ts +9 -5
  26. package/backend/engine/adapters/pi/mcp.test.ts +194 -0
  27. package/backend/engine/adapters/pi/mcp.ts +88 -0
  28. package/backend/engine/adapters/pi/message-converter.ts +6 -4
  29. package/backend/engine/adapters/pi/presets.ts +10 -5
  30. package/backend/engine/adapters/pi/stream.ts +42 -38
  31. package/backend/engine/adapters/qwen/environment.ts +39 -2
  32. package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
  33. package/backend/engine/adapters/qwen/message-converter.ts +40 -23
  34. package/backend/engine/adapters/qwen/models.test.ts +25 -0
  35. package/backend/engine/adapters/qwen/models.ts +42 -5
  36. package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
  37. package/backend/engine/adapters/qwen/session-store.ts +66 -0
  38. package/backend/engine/adapters/qwen/stream.ts +110 -87
  39. package/backend/engine/docs/adapter-contract.md +7 -4
  40. package/backend/engine/docs/lessons-learned.md +405 -62
  41. package/backend/engine/docs/quick-reference.md +2 -2
  42. package/backend/engine/docs/stack.md +17 -4
  43. package/backend/engine/docs/websocket-routes.md +5 -5
  44. package/backend/engine/install-recipes.test.ts +105 -5
  45. package/backend/engine/install-recipes.ts +102 -42
  46. package/backend/engine/install-runner.ts +56 -2
  47. package/backend/engine/stack-project.ts +71 -1
  48. package/backend/index.ts +5 -0
  49. package/backend/mcp/README.md +2 -2
  50. package/backend/mcp/external/config.ts +18 -0
  51. package/backend/mcp/external/proxy.ts +2 -2
  52. package/backend/mcp/index.ts +8 -0
  53. package/backend/mcp/internal/config.ts +42 -3
  54. package/backend/memory/embedding/install.ts +29 -1
  55. package/backend/utils/keyed-lock.test.ts +33 -0
  56. package/backend/utils/keyed-lock.ts +17 -0
  57. package/backend/utils/port-utils.test.ts +29 -0
  58. package/backend/utils/port-utils.ts +19 -0
  59. package/backend/ws/engine/cline/accounts.ts +26 -6
  60. package/backend/ws/engine/codex/accounts.test.ts +49 -0
  61. package/backend/ws/engine/codex/accounts.ts +17 -13
  62. package/backend/ws/engine/pi/accounts.ts +61 -6
  63. package/dist/assets/{index-D-Ad1N96.js → index-BTcR1byF.js} +1 -1
  64. package/dist/assets/{index-Am-rJRxA.js → index-CwuKQelV.js} +1 -1
  65. package/dist/assets/{main--PLCDxSy.css → main-BiDNMWb3.css} +1 -1
  66. package/dist/assets/{main-DelPm2Xt.js → main-BlhKWz2B.js} +595 -593
  67. package/dist/index.html +2 -2
  68. package/package.json +19 -15
  69. package/backend/engine/adapters/pi/mcp-tools.ts +0 -153
  70. package/backend/engine/adapters/qwen/session-fork.ts +0 -109
@@ -0,0 +1,64 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { SDKMessage } from '@qwen-code/sdk';
3
+ import type { AskUserQuestion } from '$shared/types/unified';
4
+ import { createSdkMessageConverter, toQwenAnswers } from './message-converter';
5
+
6
+ const questions: AskUserQuestion[] = [
7
+ { question: 'Which scope?', header: 'Scope', options: [{ label: 'All', description: 'a' }, { label: 'Some', description: 's' }], multiSelect: false },
8
+ { question: 'Which approach?', header: 'Approach', options: [{ label: 'Safe', description: 's' }, { label: 'Bold', description: 'b' }], multiSelect: false },
9
+ ];
10
+
11
+ const askMessage = (id: string) => ({
12
+ type: 'assistant',
13
+ uuid: `a-${id}`,
14
+ session_id: 's1',
15
+ parent_tool_use_id: null,
16
+ message: { role: 'assistant', content: [{ type: 'tool_use', id, name: 'ask_user_question', input: { questions } }] },
17
+ }) as unknown as SDKMessage;
18
+
19
+ const resultMessage = (id: string, content: string, isError: boolean) => ({
20
+ type: 'user',
21
+ session_id: 's1',
22
+ parent_tool_use_id: null,
23
+ message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content, is_error: isError }] },
24
+ }) as unknown as SDKMessage;
25
+
26
+ function toolResults(outputs: unknown[]) {
27
+ return outputs.flatMap((o) => {
28
+ const msg = o as { type: string; content?: Array<{ type: string; content?: string; isError?: boolean }> };
29
+ return msg.type === 'user' ? (msg.content ?? []).filter(b => b.type === 'tool_result') : [];
30
+ });
31
+ }
32
+
33
+ describe('toQwenAnswers', () => {
34
+ // The CLI drops every non-index key and tells the model "No valid answers
35
+ // were provided." — the frontend sends question-text keys.
36
+ test('re-keys question-text answers by question index', () => {
37
+ expect(toQwenAnswers(questions, { 'Which scope?': 'Some', 'Which approach?': 'Bold' })).toEqual({ '0': 'Some', '1': 'Bold' });
38
+ });
39
+
40
+ test('keeps index keys and skips unanswered questions', () => {
41
+ expect(toQwenAnswers(questions, { '1': 'Safe' })).toEqual({ '1': 'Safe' });
42
+ });
43
+ });
44
+
45
+ describe('AskUserQuestion tool_result', () => {
46
+ test('an answered question renders as "<question>"="<answer>" pairs the UI card parses', () => {
47
+ const converter = createSdkMessageConverter('m');
48
+ [...converter.convert(askMessage('call_1'))];
49
+ converter.recordUserAnswer('call_1', { 'Which scope?': 'Some', 'Which approach?': 'Bold' });
50
+ const [result] = toolResults([...converter.convert(resultMessage('call_1', 'User has provided the following answers:\n\n**Scope**: Some', false))]);
51
+ expect(result.isError).toBe(false);
52
+ expect(result.content).toBe('User has answered your questions: "Which scope?"="Some", "Which approach?"="Bold". You can now continue with the user\'s answers in mind.');
53
+ });
54
+
55
+ test('a question the CLI cancelled stays an error, even if an answer arrived late', () => {
56
+ const converter = createSdkMessageConverter('m');
57
+ [...converter.convert(askMessage('call_2'))];
58
+ converter.recordUserAnswer('call_2', { 'Which scope?': 'Some' });
59
+ const cancelled = '[Operation Cancelled] Reason: The host could not present the required approval for "ask_user_question".';
60
+ const [result] = toolResults([...converter.convert(resultMessage('call_2', cancelled, true))]);
61
+ expect(result.isError).toBe(true);
62
+ expect(result.content).toBe(cancelled);
63
+ });
64
+ });
@@ -60,10 +60,11 @@ import { resolveOpenCodeToolName } from '../../../mcp';
60
60
  // has only just been spawned — its real output is still pending":
61
61
  //
62
62
  // 1. FORK_PLACEHOLDER_RESULT — fire-and-forget fork (no `subagent_type`,
63
- // no `run_in_background`). Source: `node_modules/@qwen-code/sdk/dist/cli/cli.js:277525`.
63
+ // no `run_in_background`). Source: `FORK_PLACEHOLDER_RESULT` in the SDK's
64
+ // bundled CLI (`node_modules/@qwen-code/sdk/dist/cli/chunks/`).
64
65
  // 2. The "Background agent launched successfully…" multiline blob —
65
66
  // `run_in_background: true` mode that emits a `task_notification` later.
66
- // Source: same file around line 281616.
67
+ // Source: same chunk directory.
67
68
  //
68
69
  // We intercept these so the Agent block stays in the "pending" state in the
69
70
  // UI while sub-activities accumulate, then emit a synthetic tool_result with
@@ -78,24 +79,32 @@ function isQwenAgentPlaceholderResult(content: string): boolean {
78
79
  || trimmed.startsWith(QWEN_BACKGROUND_LAUNCH_PREFIX);
79
80
  }
80
81
 
82
+ /**
83
+ * Re-key the user's AskUserQuestion answers by question INDEX ("0", "1", …),
84
+ * the only shape Qwen's CLI accepts (`parseAnswerQuestionIndex` in the SDK's
85
+ * bundled CLI drops every other key, then tells the model "No valid answers
86
+ * were provided."). The frontend keys answers by question TEXT, the shape
87
+ * Claude uses; index keys are accepted too so either side can change.
88
+ */
89
+ export function toQwenAnswers(questions: AskUserQuestion[], answers: Record<string, string>): Record<string, string> {
90
+ const indexed: Record<string, string> = {};
91
+ questions.forEach((q, i) => {
92
+ const value = answers[q.question] ?? answers[String(i)];
93
+ if (typeof value === 'string') indexed[String(i)] = value;
94
+ });
95
+ return indexed;
96
+ }
97
+
81
98
  /**
82
99
  * Format the user's answers to AskUserQuestion in OpenCode's wording so the
83
100
  * downstream model sees a consistent payload regardless of which engine ran.
84
- * Mirrors the OpenCode adapter's output:
101
+ * Mirrors the OpenCode adapter's output — and it is the exact shape the
102
+ * frontend's AskUserQuestion card parses (`"<question>"="<answer>"`):
85
103
  * `User has answered your questions: "Q1"="A1", "Q2"="A2". You can now continue with the user's answers in mind.`
86
- *
87
- * Qwen's `answers` map is keyed by question INDEX (string number), not by
88
- * question text — see `node_modules/@qwen-code/sdk/dist/cli/cli.js:284219-284222`.
89
- * We dereference each index against the original questions array.
90
104
  */
91
105
  function formatAskUserQuestionResult(questions: AskUserQuestion[], answers: Record<string, string>): string {
92
- const pairs: string[] = [];
93
- for (const [key, value] of Object.entries(answers)) {
94
- const idx = Number.parseInt(key, 10);
95
- const q = Number.isFinite(idx) ? questions[idx] : undefined;
96
- const label = q?.question ?? q?.header ?? `Question ${key}`;
97
- pairs.push(`"${label}"="${value}"`);
98
- }
106
+ const pairs = Object.entries(toQwenAnswers(questions, answers))
107
+ .map(([idx, value]) => `"${questions[Number(idx)].question}"="${value}"`);
99
108
  if (pairs.length === 0) {
100
109
  return 'User did not provide any answers.';
101
110
  }
@@ -526,8 +535,8 @@ export interface QwenConverterState {
526
535
  * whose canonical name is `AskUserQuestion`. The engine wires this to the
527
536
  * pending-answer slot so `resolveUserAnswer(toolUseId, …)` can verify the
528
537
  * inbound id matches the one the frontend was shown — Qwen's `canUseTool`
529
- * callback intentionally does NOT pass the tool_use_id (line 486179 of the
530
- * bundled CLI), so the converter is the only place we can recover it.
538
+ * callback does NOT pass the tool_use_id (`CanUseTool` in the SDK's
539
+ * `dist/index.d.ts`), so the converter is the only place we can recover it.
531
540
  */
532
541
  onAskUserQuestionEmitted?: (toolUseId: string) => void;
533
542
  /**
@@ -667,12 +676,19 @@ export function convertUserMessage(msg: SDKUserMessage, state: QwenConverterStat
667
676
  continue;
668
677
  }
669
678
 
670
- // 1. AskUserQuestion: replace the SDK's broken empty-answer body with
671
- // the real answers. The Qwen SDK's stream-json `handleOutgoingPermissionRequest`
672
- // calls `onConfirm(ProceedOnce)` without a payload, dropping the
673
- // `answers` we passed via `updatedInput`. See the analysis in
674
- // `qwen/stream.ts::resolveUserAnswer` and `cli.js:486478-486485`.
679
+ // 1. AskUserQuestion: the CLI answers with its own
680
+ // `**Header**: value` body (the model already saw that). Replace it
681
+ // with the cross-engine wording so the UI renders every engine's
682
+ // answers the same way. Answers arrive via `recordUserAnswer`
683
+ // before the tool runs (see `qwen/stream.ts::resolveUserAnswer`).
684
+ // A failed call (the CLI cancelled the question) passes through
685
+ // untouched — rewriting it would show answers the model never got.
675
686
  const auq = state.askUserQuestions.get(block.toolUseId);
687
+ if (auq && block.isError) {
688
+ state.askUserQuestions.delete(block.toolUseId);
689
+ outBlocks.push(block);
690
+ continue;
691
+ }
676
692
  if (auq) {
677
693
  const content = auq.answered && auq.answers
678
694
  ? formatAskUserQuestionResult(auq.questions, auq.answers)
@@ -846,9 +862,10 @@ export function convertSystemInit(msg: SDKSystemMessage, state: QwenConverterSta
846
862
  /**
847
863
  * Handle a `task_notification` system message — emitted by the Qwen SDK when
848
864
  * a `run_in_background: true` Agent reaches a terminal status. Source:
849
- * `node_modules/@qwen-code/sdk/dist/cli/cli.js:485345-485353` and 227829.
865
+ * `emitSystemMessage("task_notification", …)` in the SDK's bundled CLI
866
+ * (`node_modules/@qwen-code/sdk/dist/cli/chunks/`).
850
867
  *
851
- * `data` shape (per `cli.js:485240-485249`):
868
+ * `data` shape (the CLI's `sdkNotification`):
852
869
  * `{ task_id, tool_use_id, status: 'completed'|'failed'|'cancelled'|'running', usage? }`
853
870
  *
854
871
  * The full sub-agent text is NOT in `data` — it's only in the SDK-internal
@@ -0,0 +1,25 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { buildQwenReasoningControl } from './models';
3
+
4
+ describe('buildQwenReasoningControl', () => {
5
+ test('a model whose endpoint lists reasoning_effort gets the effort tiers', () => {
6
+ const control = buildQwenReasoningControl({
7
+ id: 'qwen/qwen3.8-max',
8
+ supported_parameters: ['max_tokens', 'reasoning', 'reasoning_effort', 'tools'],
9
+ });
10
+ expect(control?.levels.map(l => l.value)).toEqual(['low', 'medium', 'high', 'xhigh']);
11
+ expect(control?.default).toBe('medium');
12
+ });
13
+
14
+ test('toggle-only reasoning offers no effort selector', () => {
15
+ expect(buildQwenReasoningControl({
16
+ id: 'qwen/qwen3.8-omni-flash',
17
+ supported_parameters: ['reasoning', 'include_reasoning', 'tools'],
18
+ })).toBeUndefined();
19
+ });
20
+
21
+ test('endpoints without capability data (DashScope, Fireworks) offer no selector', () => {
22
+ expect(buildQwenReasoningControl({ id: 'qwen3-coder-plus' })).toBeUndefined();
23
+ expect(buildQwenReasoningControl({ id: 'qwen3-coder-plus', supported_parameters: 'reasoning_effort' })).toBeUndefined();
24
+ });
25
+ });
@@ -5,14 +5,17 @@
5
5
  * OpenAI-compatible `/models` endpoint. We hit it with the active account's
6
6
  * API key and translate the response into `EngineModel[]` with conservative
7
7
  * default metadata — the SDK only needs the model id to dispatch a stream,
8
- * so anything beyond that is best-effort UI hinting.
8
+ * so anything beyond that is best-effort UI hinting. The one exception is the
9
+ * reasoning-effort control, which is offered only when the endpoint itself
10
+ * says the model accepts `reasoning_effort` (see `buildQwenReasoningControl`).
9
11
  *
10
12
  * Returns `[]` on any failure (network, auth, malformed body) so the caller
11
13
  * can surface an empty picker rather than a stale curated list — same shape
12
14
  * as OpenCode's `fetchOpenCodeModels` (see README §4.5).
13
15
  */
14
16
 
15
- import type { EngineModel } from '$shared/types/unified';
17
+ import type { EngineModel, ReasoningControl } from '$shared/types/unified';
18
+ import { toReasoningOptions } from '$shared/constants/engines';
16
19
  import { debug } from '$shared/utils/logger';
17
20
  import type { QwenEnvResolution } from './environment';
18
21
 
@@ -23,10 +26,34 @@ interface OpenAiModelsResponse {
23
26
  id?: string;
24
27
  name?: string;
25
28
  context_length?: number;
29
+ supported_parameters?: unknown;
26
30
  [key: string]: unknown;
27
31
  }>;
28
32
  }
29
33
 
34
+ type OpenAiModelEntry = NonNullable<OpenAiModelsResponse['data']>[number];
35
+
36
+ /**
37
+ * Tiers the bundled CLI sends to an OpenAI-compatible endpoint
38
+ * (`OPENAI_COMPATIBLE_EFFORTS` in the SDK's CLI). The CLI clamps a tier the
39
+ * endpoint rejects to the nearest accepted one, so offering the full set is safe.
40
+ */
41
+ const QWEN_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh'] as const;
42
+
43
+ /**
44
+ * Qwen's knob is the SDK `effort` option, which the CLI turns into the
45
+ * provider's own wire field. Whether a model honours it is only knowable from
46
+ * the endpoint: OpenRouter lists `reasoning_effort` in `supported_parameters`.
47
+ * DashScope and Fireworks publish no capability data on `/models`, so their
48
+ * models get no selector and the provider default applies — sending an effort
49
+ * to a model that can't reason would be dropped or rejected anyway.
50
+ */
51
+ export function buildQwenReasoningControl(entry: OpenAiModelEntry): ReasoningControl | undefined {
52
+ const params = entry.supported_parameters;
53
+ if (!Array.isArray(params) || !params.includes('reasoning_effort')) return undefined;
54
+ return { levels: toReasoningOptions(QWEN_EFFORT_LEVELS), default: 'medium' };
55
+ }
56
+
30
57
  export async function fetchQwenModels(env: QwenEnvResolution): Promise<EngineModel[]> {
31
58
  const apiKey = env.env['OPENAI_API_KEY'];
32
59
  if (!apiKey) return [];
@@ -49,7 +76,7 @@ export async function fetchQwenModels(env: QwenEnvResolution): Promise<EngineMod
49
76
  const mapped: EngineModel[] = [];
50
77
  for (const entry of entries) {
51
78
  if (!entry || typeof entry.id !== 'string' || !entry.id) continue;
52
- mapped.push(mapQwenIdToEngineModel(entry.id, entry.name, entry.context_length));
79
+ mapped.push(mapQwenIdToEngineModel(entry.id, entry.name, entry.context_length, buildQwenReasoningControl(entry)));
53
80
  }
54
81
  return mapped;
55
82
  } catch (error) {
@@ -58,7 +85,12 @@ export async function fetchQwenModels(env: QwenEnvResolution): Promise<EngineMod
58
85
  }
59
86
  }
60
87
 
61
- function mapQwenIdToEngineModel(id: string, name?: string, contextLength?: number): EngineModel {
88
+ function mapQwenIdToEngineModel(
89
+ id: string,
90
+ name?: string,
91
+ contextLength?: number,
92
+ reasoningControl?: ReasoningControl,
93
+ ): EngineModel {
62
94
  const slashIdx = id.indexOf('/');
63
95
  const provider = slashIdx > 0 ? id.slice(0, slashIdx) : 'qwen';
64
96
  const displayName = name ?? (slashIdx > 0 ? id.slice(slashIdx + 1) : id);
@@ -75,7 +107,12 @@ function mapQwenIdToEngineModel(id: string, name?: string, contextLength?: numbe
75
107
  input: { text: true, image: false, audio: false, video: false, pdf: false },
76
108
  output: { text: true, image: false, audio: false, video: false, pdf: false },
77
109
  },
78
- capabilities: { reasoning: false, tools: true, structuredOutput: true },
110
+ capabilities: {
111
+ reasoning: !!reasoningControl,
112
+ tools: true,
113
+ structuredOutput: true,
114
+ ...(reasoningControl && { reasoningControl }),
115
+ },
79
116
  cost: { input: 0, output: 0 },
80
117
  };
81
118
  }
@@ -0,0 +1,39 @@
1
+ import { afterAll, describe, expect, test } from 'bun:test';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { getQwenRuntimeDir, sessionStateExists } from './session-store';
6
+
7
+ // The CLI keys a project's chats on `sanitizeCwd(process.cwd())`, and the OS
8
+ // reports that cwd with symlinks resolved. A project opened through a symlink
9
+ // must still find its chats, or every resume silently skips the fork.
10
+ describe('sessionStateExists', () => {
11
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'clopen-qwen-store-'));
12
+ const realProject = path.join(fs.realpathSync(tmp), 'real-project');
13
+ const linkedProject = path.join(tmp, 'linked-project');
14
+ fs.mkdirSync(realProject);
15
+ fs.symlinkSync(realProject, linkedProject);
16
+
17
+ const sanitized = realProject.replace(/[^a-zA-Z0-9]/g, '-');
18
+ const chatsDir = path.join(getQwenRuntimeDir(), 'projects', sanitized, 'chats');
19
+ const sessionId = 'f0e1d2c3-0000-4000-8000-000000000001';
20
+ fs.mkdirSync(chatsDir, { recursive: true });
21
+ fs.writeFileSync(path.join(chatsDir, `${sessionId}.jsonl`), '{}\n');
22
+
23
+ afterAll(() => {
24
+ fs.rmSync(tmp, { recursive: true, force: true });
25
+ fs.rmSync(path.join(getQwenRuntimeDir(), 'projects', sanitized), { recursive: true, force: true });
26
+ });
27
+
28
+ test('finds a chat through the real project path', () => {
29
+ expect(sessionStateExists(realProject, sessionId)).toBe(true);
30
+ });
31
+
32
+ test('finds the same chat through a symlinked project path', () => {
33
+ expect(sessionStateExists(linkedProject, sessionId)).toBe(true);
34
+ });
35
+
36
+ test('reports a missing chat as missing', () => {
37
+ expect(sessionStateExists(realProject, 'f0e1d2c3-0000-4000-8000-00000000dead')).toBe(false);
38
+ });
39
+ });
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Qwen Code on-disk session store
3
+ *
4
+ * Forking is native since @qwen-code/sdk 0.1.17 (`resume` + `forkSession`,
5
+ * the CLI's `--fork-session`; see `QwenEngine.streamQuery`). This module
6
+ * only locates chats on disk so the adapter can tell whether a resume target
7
+ * still exists before asking the CLI to fork it — `--fork-session` on a
8
+ * missing source exits the CLI with code 1 instead of starting fresh.
9
+ *
10
+ * On-disk layout (`<QWEN_RUNTIME_DIR>/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 `sanitizeCwd()` in the
14
+ * SDK's bundled CLI (`dist/cli/chunks/`) so we resolve to the same
15
+ * directory the CLI writes to.
16
+ * - The `cwd` the CLI sanitizes is its own `process.cwd()`, which the OS
17
+ * reports with symlinks resolved (`/var/…` → `/private/var/…` on macOS),
18
+ * so the project path is realpath'd before sanitizing.
19
+ * - Each chat is a SINGLE JSONL file named after its session id.
20
+ */
21
+
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import os from 'node:os';
25
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
26
+
27
+ /**
28
+ * Qwen's runtime output base, forwarded to the CLI via `QWEN_RUNTIME_DIR`
29
+ * (see ./environment.ts). The bundled CLI writes chats under
30
+ * `<runtimeBase>/projects/<sanitized-cwd>/chats/` (Storage.getProjectDir →
31
+ * getRuntimeBaseDir), so lookups here must resolve to the SAME base the env
32
+ * var sets or every chat would look missing.
33
+ */
34
+ export function getQwenRuntimeDir(): string {
35
+ return getEngineUserConfigDir('qwen');
36
+ }
37
+
38
+ const QWEN_PROJECTS_DIR = path.join(getQwenRuntimeDir(), 'projects');
39
+
40
+ /**
41
+ * Mirror of `sanitizeCwd` in @qwen-code/sdk's bundled CLI. Lower-case on
42
+ * Windows then collapse every non-alphanumeric character to `-`. Drift from
43
+ * this would point to a different project directory than the one the CLI
44
+ * writes to.
45
+ */
46
+ function sanitizeCwd(cwd: string): string {
47
+ const normalized = os.platform() === 'win32' ? cwd.toLowerCase() : cwd;
48
+ return normalized.replace(/[^a-zA-Z0-9]/g, '-');
49
+ }
50
+
51
+ /** The cwd as the spawned CLI sees it: symlinks resolved, input kept if it doesn't exist. */
52
+ function resolveCliCwd(projectPath: string): string {
53
+ try {
54
+ return fs.realpathSync(projectPath);
55
+ } catch {
56
+ return projectPath;
57
+ }
58
+ }
59
+
60
+ function getSessionStatePath(projectPath: string, sessionId: string): string {
61
+ return path.join(QWEN_PROJECTS_DIR, sanitizeCwd(resolveCliCwd(projectPath)), 'chats', `${sessionId}.jsonl`);
62
+ }
63
+
64
+ export function sessionStateExists(projectPath: string, sessionId: string): boolean {
65
+ return fs.existsSync(getSessionStatePath(projectPath, sessionId));
66
+ }