@myrialabs/clopen 0.4.44 → 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 (118) hide show
  1. package/backend/artifacts/project/bridge.ts +218 -0
  2. package/backend/artifacts/project/edit.ts +243 -0
  3. package/backend/artifacts/project/index.ts +38 -0
  4. package/backend/artifacts/project/project.test.ts +181 -0
  5. package/backend/artifacts/project/scan.ts +368 -0
  6. package/backend/artifacts/project/sources.ts +100 -0
  7. package/backend/artifacts/sync.ts +1 -1
  8. package/backend/auth/permissions.ts +15 -0
  9. package/backend/chat/stream-manager.ts +20 -3
  10. package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
  11. package/backend/database/migrations/index.ts +7 -0
  12. package/backend/database/queries/index.ts +2 -0
  13. package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
  14. package/backend/engine/adapters/claude/models.test.ts +49 -0
  15. package/backend/engine/adapters/claude/models.ts +81 -562
  16. package/backend/engine/adapters/claude/stream.ts +32 -5
  17. package/backend/engine/adapters/cline/credential.ts +42 -18
  18. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  19. package/backend/engine/adapters/cline/message-converter.ts +31 -1
  20. package/backend/engine/adapters/cline/models.test.ts +77 -0
  21. package/backend/engine/adapters/cline/models.ts +89 -3
  22. package/backend/engine/adapters/cline/presets.ts +5 -0
  23. package/backend/engine/adapters/cline/stream.ts +29 -8
  24. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  25. package/backend/engine/adapters/codex/models.ts +54 -31
  26. package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
  27. package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
  28. package/backend/engine/adapters/codex/session-fork.ts +5 -0
  29. package/backend/engine/adapters/codex/stream.ts +29 -11
  30. package/backend/engine/adapters/copilot/models.test.ts +40 -0
  31. package/backend/engine/adapters/copilot/models.ts +51 -24
  32. package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
  33. package/backend/engine/adapters/copilot/permissions.ts +72 -0
  34. package/backend/engine/adapters/copilot/stream.ts +83 -70
  35. package/backend/engine/adapters/cursor/stream.ts +27 -12
  36. package/backend/engine/adapters/opencode/server.ts +14 -4
  37. package/backend/engine/adapters/opencode/stream.ts +18 -3
  38. package/backend/engine/adapters/pi/credential.test.ts +83 -0
  39. package/backend/engine/adapters/pi/credential.ts +68 -12
  40. package/backend/engine/adapters/pi/environment.ts +9 -5
  41. package/backend/engine/adapters/pi/mcp.test.ts +194 -0
  42. package/backend/engine/adapters/pi/mcp.ts +88 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +6 -4
  44. package/backend/engine/adapters/pi/presets.ts +10 -5
  45. package/backend/engine/adapters/pi/stream.ts +77 -41
  46. package/backend/engine/adapters/qwen/environment.ts +39 -2
  47. package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +40 -23
  49. package/backend/engine/adapters/qwen/models.test.ts +25 -0
  50. package/backend/engine/adapters/qwen/models.ts +42 -5
  51. package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
  52. package/backend/engine/adapters/qwen/session-store.ts +66 -0
  53. package/backend/engine/adapters/qwen/stream.ts +118 -87
  54. package/backend/engine/artifact-sync.ts +12 -5
  55. package/backend/engine/docs/adapter-contract.md +7 -4
  56. package/backend/engine/docs/lessons-learned.md +405 -62
  57. package/backend/engine/docs/quick-reference.md +2 -2
  58. package/backend/engine/docs/stack.md +17 -4
  59. package/backend/engine/docs/websocket-routes.md +5 -5
  60. package/backend/engine/install-recipes.test.ts +105 -5
  61. package/backend/engine/install-recipes.ts +102 -42
  62. package/backend/engine/install-runner.ts +56 -2
  63. package/backend/engine/stack-project.ts +71 -1
  64. package/backend/files/file-watcher.test.ts +77 -0
  65. package/backend/files/file-watcher.ts +92 -60
  66. package/backend/files/watch-ignore.test.ts +182 -0
  67. package/backend/files/watch-ignore.ts +244 -0
  68. package/backend/git/git-executor.ts +14 -4
  69. package/backend/index.ts +16 -1
  70. package/backend/instructions/service.ts +5 -3
  71. package/backend/instructions/sync.ts +10 -27
  72. package/backend/mcp/README.md +2 -2
  73. package/backend/mcp/external/config.ts +83 -23
  74. package/backend/mcp/external/project.ts +124 -0
  75. package/backend/mcp/external/proxy.ts +65 -11
  76. package/backend/mcp/index.ts +22 -9
  77. package/backend/mcp/internal/config.ts +42 -3
  78. package/backend/mcp/internal/remote-server.ts +11 -1
  79. package/backend/memory/embedding/install.ts +29 -1
  80. package/backend/skills/marketplace.ts +1 -1
  81. package/backend/snapshot/blob-store.ts +9 -5
  82. package/backend/snapshot/git-attribution.test.ts +42 -0
  83. package/backend/snapshot/git-attribution.ts +306 -0
  84. package/backend/snapshot/gitignore.test.ts +62 -0
  85. package/backend/snapshot/gitignore.ts +158 -78
  86. package/backend/snapshot/snapshot-service.test.ts +270 -0
  87. package/backend/snapshot/snapshot-service.ts +412 -136
  88. package/backend/snapshot/turn-activity.test.ts +52 -0
  89. package/backend/snapshot/turn-activity.ts +83 -0
  90. package/backend/snapshot/turn-changes.test.ts +58 -1
  91. package/backend/snapshot/turn-changes.ts +66 -0
  92. package/backend/utils/keyed-lock.test.ts +33 -0
  93. package/backend/utils/keyed-lock.ts +17 -0
  94. package/backend/utils/port-utils.test.ts +29 -0
  95. package/backend/utils/port-utils.ts +19 -0
  96. package/backend/worktrees/tree.ts +1 -1
  97. package/backend/ws/chat/composer.ts +504 -0
  98. package/backend/ws/chat/index.ts +3 -1
  99. package/backend/ws/chat/stream.ts +252 -440
  100. package/backend/ws/engine/cline/accounts.ts +26 -6
  101. package/backend/ws/engine/codex/accounts.test.ts +49 -0
  102. package/backend/ws/engine/codex/accounts.ts +17 -13
  103. package/backend/ws/engine/pi/accounts.ts +61 -6
  104. package/backend/ws/index.ts +4 -0
  105. package/backend/ws/project-artifacts/index.ts +236 -0
  106. package/backend/ws/snapshot/changes.ts +66 -31
  107. package/dist/assets/{index-DX5OwLOc.js → index-BTcR1byF.js} +1 -1
  108. package/dist/assets/{index-BWyhqUi5.js → index-CwuKQelV.js} +1 -1
  109. package/dist/assets/main-BiDNMWb3.css +1 -0
  110. package/dist/assets/main-BlhKWz2B.js +1241 -0
  111. package/dist/index.html +2 -2
  112. package/package.json +19 -15
  113. package/shared/types/stores/settings.ts +5 -0
  114. package/shared/types/unified/message.ts +2 -0
  115. package/backend/engine/adapters/pi/mcp-tools.ts +0 -131
  116. package/backend/engine/adapters/qwen/session-fork.ts +0 -109
  117. package/dist/assets/main-DOkwqXRU.js +0 -1215
  118. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -13,8 +13,9 @@
13
13
  * `ModelRuntime` whose `CredentialStore` is served from `engine_accounts`
14
14
  * (see ./credential.ts). OAuth refresh persists straight back to the DB — no
15
15
  * dotfile swap, no `process.env` mutation.
16
- * 3. **No native MCP.** Clopen's MCP tools are bridged in-process as Pi custom
17
- * tools (./mcp-tools.ts). AskUserQuestion is a custom blocking tool
16
+ * 3. **Pi's own MCP client, Clopen's servers.** Pi's MCP extension connects to
17
+ * the same `/mcp` bridges the other engines use, fed a Clopen-built config
18
+ * (./mcp.ts). AskUserQuestion is a custom blocking tool
18
19
  * (./ask-question-tool.ts) since Pi's native `ask_question` has no headless
19
20
  * answer path.
20
21
  */
@@ -36,16 +37,20 @@ import { subagentQueries } from '$backend/database/queries';
36
37
  import { readSubagentMd } from '$backend/subagents/store';
37
38
  import { syncSkills } from '$backend/skills';
38
39
  import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
40
+ import { resolveProjectBridge, buildProjectPromptContext } from '$backend/artifacts/project';
41
+ import { homedir } from 'node:os';
42
+ import { join, sep } from 'node:path';
39
43
  import { artifactFilter } from '$backend/profiles';
40
44
  import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
41
45
  import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
42
46
  import { EngineRuns } from '../run-registry';
43
- import { DbCredentialStore, getPiAccountForProvider, parsePiCredential } from './credential';
47
+ import { DbCredentialStore, canonicalPiProviderId, getPiAccountForProvider, parsePiCredential } from './credential';
44
48
  import { createPiRuntime } from './presets';
45
49
  import { getPiAgentDir } from './environment';
46
50
  import { fetchPiModels } from './models';
47
51
  import { resolvePiSessionManager } from './session-fork';
48
- import { buildPiMcpTools } from './mcp-tools';
52
+ import { getPiMcpConfig } from '../../../mcp';
53
+ import { createPiMcpExtension, resolvePiToolName } from './mcp';
49
54
  import { createAskUserQuestionTool, formatAnswers, type PendingAsk } from './ask-question-tool';
50
55
  import { createAgentDispatchTool, type SubagentInfo } from './agent-tool';
51
56
  import { createPiMessageConverter } from './message-converter';
@@ -146,7 +151,7 @@ export class PiEngine implements AIEngine {
146
151
  if (!account) {
147
152
  throw new Error(`Pi has no account for provider "${providerSlug}". Add one in Settings → Engines → Pi.`);
148
153
  }
149
- const provider = parsePiCredential(account.credential)?.provider ?? providerSlug;
154
+ const provider = parsePiCredential(account.credential)?.provider ?? canonicalPiProviderId(providerSlug);
150
155
  const runtime = await createPiRuntime(new DbCredentialStore([account]));
151
156
  const model = runtime.getModel(provider, modelId);
152
157
  if (!model) {
@@ -165,13 +170,22 @@ export class PiEngine implements AIEngine {
165
170
  await syncSkills('pi', profileId);
166
171
  await syncEngineArtifacts('pi', profileId);
167
172
 
173
+ // Repository artifacts Pi doesn't read natively (it reads `.pi/*`,
174
+ // `.agents/skills` and AGENTS.md itself): skills go in as extra skill
175
+ // paths, instructions as an appended system prompt, subagents join the
176
+ // dispatch tool below.
177
+ const projectBridge = await resolveProjectBridge('pi', resolvedProjectPath, options.mcpContext?.projectId);
178
+ const projectInstructions = buildProjectPromptContext(projectBridge, { instructions: true });
179
+
168
180
  // ── Permissions (enforced at the `tool_call` extension hook) ──
169
181
  const permissions = resolvePermissionsFromDb('pi', options.mcpContext?.projectId, profileId);
182
+ // MCP rules name tools canonically; Pi's own MCP names are sanitized.
170
183
  const permissionBlocker = (pi: ExtensionAPI) => {
171
184
  pi.on('tool_call', async (event: { toolName: string }) => {
172
- if (!isToolAllowed(permissions, event.toolName)) {
173
- debug.log('permissions', `⛔ Pi blocked tool "${event.toolName}" (Clopen permission policy)`);
174
- return { block: true, reason: `Blocked by Clopen permission policy: ${event.toolName}` };
185
+ const toolName = resolvePiToolName(run.session, event.toolName);
186
+ if (!isToolAllowed(permissions, toolName)) {
187
+ debug.log('permissions', `⛔ Pi blocked tool "${toolName}" (Clopen permission policy)`);
188
+ return { block: true, reason: `Blocked by Clopen permission policy: ${toolName}` };
175
189
  }
176
190
  return undefined;
177
191
  });
@@ -181,26 +195,41 @@ export class PiEngine implements AIEngine {
181
195
  // (built before the queue exists) can push sub-activity messages into it.
182
196
  const queueHolder: { queue: EventQueue<EngineOutput> | null } = { queue: null };
183
197
 
184
- // ── Tools: builtins (permission-filtered) + AskUserQuestion + MCP bridge + subagents ──
198
+ // ── Tools: builtins (permission-filtered) + AskUserQuestion + subagents; MCP via Pi's extension ──
199
+ // The builtins go in as the `defaultTools` setting, not a `tools` allowlist:
200
+ // an allowlist also filters every tool registered later, which would drop
201
+ // the MCP tools Pi registers once its servers connect.
185
202
  const allowedBuiltins = PI_BUILTIN_TOOLS.filter((name) => isToolAllowed(permissions, name));
203
+ const deniedBuiltins = PI_BUILTIN_TOOLS.filter((name) => !allowedBuiltins.includes(name));
186
204
  const askTool = createAskUserQuestionTool({
187
205
  register: (id, entry) => this.pendingAsks.set(id, { ...entry, owner: run }),
188
206
  unregister: (id) => this.pendingAsks.delete(id),
189
207
  });
190
- const mcpTools = await buildPiMcpTools(options.mcpContext, mcpProfileFilter);
191
- const customTools: ToolDefinition[] = [askTool, ...mcpTools];
192
- const toolAllowlist = [...allowedBuiltins, 'AskUserQuestion', ...mcpTools.map((t) => t.name)];
208
+ const customTools: ToolDefinition[] = [askTool];
209
+ const mcpServers = getPiMcpConfig(mcpProfileFilter, options.mcpContext);
210
+ const mcpExtension = await createPiMcpExtension(mcpServers);
193
211
 
194
212
  // Subagent dispatch — Pi has no native Agent tool, so materialising the
195
213
  // "Available Subagents" preamble isn't enough; expose a tool that actually
196
214
  // spawns a sub-session with the chosen subagent's system prompt.
197
- const subagents: SubagentInfo[] = subagentQueries.getEnabled().map((s) => ({ slug: s.slug, name: s.name, description: s.description }));
215
+ // Project subagents Pi can't read natively (`.agents/agents`, `.claude/agents`,
216
+ // …) join the same dispatch tool; an installed subagent wins a slug clash.
217
+ const installedSubagents = subagentQueries.getEnabled();
218
+ const installedSlugs = new Set(installedSubagents.map((s) => s.slug));
219
+ const projectSubagents = new Map(projectBridge.subagents.filter((s) => !installedSlugs.has(s.slug)).map((s) => [s.slug, s]));
220
+ const subagents: SubagentInfo[] = [
221
+ ...installedSubagents.map((s) => ({ slug: s.slug, name: s.name, description: s.description })),
222
+ ...[...projectSubagents.values()].map((s) => ({ slug: s.slug, name: s.name, description: s.description })),
223
+ ];
198
224
  if (subagents.length > 0) {
199
225
  const agentTool = createAgentDispatchTool({
200
226
  subagents,
201
227
  run: async (subagent, subPrompt, toolCallId, signal) => {
202
- const md = (await readSubagentMd(subagent.slug)) ?? '';
203
- const instructions = stripFrontmatter(md) || `You are the ${subagent.name} subagent. ${subagent.description}`;
228
+ const projectSubagent = projectSubagents.get(subagent.slug);
229
+ const md = projectSubagent ? '' : ((await readSubagentMd(subagent.slug)) ?? '');
230
+ const instructions = projectSubagent?.prompt
231
+ || stripFrontmatter(md)
232
+ || `You are the ${subagent.name} subagent. ${subagent.description}`;
204
233
  // APPEND the subagent instructions to Pi's base coding prompt —
205
234
  // replacing it wholesale strips the tool-use scaffolding and the
206
235
  // sub-agent then produces nothing. Keep the sub-session bounded:
@@ -260,14 +289,24 @@ export class PiEngine implements AIEngine {
260
289
  },
261
290
  });
262
291
  customTools.push(agentTool);
263
- toolAllowlist.push('Agent');
264
292
  }
265
293
 
266
294
  // ── Resource loader (discovers synced skills/prompts/AGENTS.md) ──
295
+ // Pi also scans the REAL `~/.agents/skills` (via $HOME, with no override),
296
+ // which leaks the user's personal CLI skills past Clopen's per-engine
297
+ // isolation. Drop anything loaded from there; project `.agents/skills`
298
+ // and Clopen's own synced dir are unaffected.
299
+ const userAgentsSkillsDir = join(process.env.HOME || homedir(), '.agents', 'skills') + sep;
267
300
  const resourceLoader = new DefaultResourceLoader({
268
301
  cwd: resolvedProjectPath,
269
302
  agentDir,
270
- extensionFactories: [permissionBlocker],
303
+ extensionFactories: [permissionBlocker, mcpExtension],
304
+ ...(projectBridge.skills.length > 0 && { additionalSkillPaths: projectBridge.skills.map((s) => s.skillMd) }),
305
+ ...(projectInstructions && { appendSystemPrompt: [projectInstructions] }),
306
+ skillsOverride: (base) => ({
307
+ ...base,
308
+ skills: base.skills.filter((skill) => !skill.filePath.startsWith(userAgentsSkillsDir)),
309
+ }),
271
310
  });
272
311
  await resourceLoader.reload();
273
312
 
@@ -282,13 +321,15 @@ export class PiEngine implements AIEngine {
282
321
  ? clampThinkingLevel(model, reasoningEffort as ModelThinkingLevel)
283
322
  : (model.reasoning ? 'medium' : 'off'),
284
323
  resourceLoader,
285
- tools: toolAllowlist,
286
324
  customTools,
287
- excludeTools: ['ask_question'],
325
+ excludeTools: ['ask_question', ...deniedBuiltins],
288
326
  sessionManager,
289
- settingsManager: SettingsManager.inMemory({ retry: PI_RETRY }),
327
+ settingsManager: SettingsManager.inMemory({ retry: PI_RETRY, defaultTools: allowedBuiltins }),
290
328
  });
291
329
  run.session = session;
330
+ // Fires `session_start`, which connects the MCP servers; the first prompt
331
+ // waits (bounded) for their tools to be declared.
332
+ await session.bindExtensions({});
292
333
 
293
334
  const engineMeta: MessageEngine = {
294
335
  type: 'pi',
@@ -296,7 +337,11 @@ export class PiEngine implements AIEngine {
296
337
  model: { id: modelId, name: model.name || modelId },
297
338
  account: { id: account.id, name: account.name },
298
339
  };
299
- const converter = createPiMessageConverter({ engine: engineMeta, sessionId: session.sessionId });
340
+ const converter = createPiMessageConverter({
341
+ engine: engineMeta,
342
+ sessionId: session.sessionId,
343
+ resolveToolName: (name) => resolvePiToolName(session, name),
344
+ });
300
345
  const queue = new EventQueue<EngineOutput>();
301
346
  queueHolder.queue = queue;
302
347
  const unsubscribe = session.subscribe((event) => {
@@ -319,34 +364,21 @@ export class PiEngine implements AIEngine {
319
364
  .filter((b): b is Extract<typeof b, { type: 'image' }> => b.type === 'image')
320
365
  .map((b) => ({ type: 'image', data: b.data, mimeType: b.mediaType }));
321
366
 
322
- // system_init first — model + enabled tools (Pi bridges MCP as custom tools).
367
+ // system_init first — model + tools active so far (MCP tools join as their servers connect).
323
368
  yield {
324
369
  type: 'system_init',
325
370
  sessionId: session.sessionId,
326
371
  model: modelId,
327
372
  engine: 'pi',
328
- tools: toolAllowlist,
373
+ tools: session.getActiveToolNames().map((name) => resolvePiToolName(session, name)),
329
374
  mcpServers: [],
330
375
  };
331
376
 
332
377
  // Close the queue when prompt() settles even if no `agent_end` ever fires
333
- // (e.g. a slash command Pi rejects at preflight, or an empty expansion) —
334
- // otherwise the drain loop would block forever and the stream would hang.
335
- const promptOptions = {
336
- ...(images.length ? { images } : {}),
337
- preflightResult: (success: boolean) => {
338
- if (!success) {
339
- queue.push({
340
- type: 'notification',
341
- sessionId: session.sessionId,
342
- level: 'warning',
343
- title: 'Prompt not accepted',
344
- message: 'Pi did not accept this input (unknown command or empty prompt).',
345
- });
346
- }
347
- },
348
- };
349
- const promptPromise = session.prompt(promptText, promptOptions)
378
+ // (e.g. an input an extension handled, or an empty expansion) — otherwise
379
+ // the drain loop would block forever and the stream would hang. A prompt
380
+ // Pi rejects throws, which reaches the caller through `queue.fail`.
381
+ const promptPromise = session.prompt(promptText, images.length ? { images } : undefined)
350
382
  .then(() => queue.close())
351
383
  .catch((error) => queue.fail(error));
352
384
 
@@ -358,6 +390,10 @@ export class PiEngine implements AIEngine {
358
390
  } finally {
359
391
  controller.signal.removeEventListener('abort', onAbort);
360
392
  unsubscribe();
393
+ // `dispose()` alone never emits `session_shutdown`, which is what closes
394
+ // the MCP connections — without it every turn leaks one per server.
395
+ await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'quit' })
396
+ .catch((error) => debug.warn('engine', 'Pi session shutdown hook failed:', error));
361
397
  try { session.dispose(); } catch { /* already disposed */ }
362
398
  // Retire THIS run only — another chat session of the same project may
363
399
  // still be streaming on this instance.
@@ -435,7 +471,7 @@ export class PiEngine implements AIEngine {
435
471
  const account = getPiAccountForProvider(providerSlug)
436
472
  ?? (accountId != null ? engineQueries.getAccount(accountId) : null);
437
473
  if (!account) throw new Error(`Pi has no account for provider "${providerSlug}".`);
438
- const provider = parsePiCredential(account.credential)?.provider ?? providerSlug;
474
+ const provider = parsePiCredential(account.credential)?.provider ?? canonicalPiProviderId(providerSlug);
439
475
  const runtime = await createPiRuntime(new DbCredentialStore([account]));
440
476
  const model = runtime.getModel(provider, modelId);
441
477
  if (!model) throw new Error(`Pi could not resolve model "${modelId}" for provider "${provider}".`);
@@ -16,12 +16,46 @@
16
16
  * deprecated the free-tier OAuth in April 2026.
17
17
  */
18
18
 
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
19
21
  import { engineQueries } from '$backend/database/queries/engine-queries';
20
22
  import type { EngineAccount } from '$backend/database/queries/engine-queries';
21
23
  import { getCleanSpawnEnv } from '$backend/utils/index.js';
22
24
  import { debug } from '$shared/utils/logger';
23
25
  import { parseQwenCredential, resolveQwenBaseUrl } from './credential';
24
- import { getQwenRuntimeDir } from './session-fork';
26
+ import { getQwenRuntimeDir } from './session-store';
27
+
28
+ /**
29
+ * Settings Clopen forces on every Qwen CLI run, via the CLI's system-settings
30
+ * tier (highest precedence, so neither ~/.qwen nor a repo's .qwen/ can turn
31
+ * them back on).
32
+ *
33
+ * Managed auto-memory (on by default since the 0.1.17 CLI) runs an extraction
34
+ * agent after every turn and holds the `result` back until it finishes — a
35
+ * minute or more of extra model calls on the user's key, with the chat stuck
36
+ * on "working" the whole time. It also writes memories into the CLI's own
37
+ * store, which no other engine reads; Clopen owns memory for every engine.
38
+ */
39
+ const QWEN_SYSTEM_SETTINGS = {
40
+ memory: {
41
+ enableManagedAutoMemory: false,
42
+ enableManagedAutoDream: false,
43
+ },
44
+ };
45
+
46
+ /** Write the forced settings file (only when it changed) and return its path. */
47
+ function ensureQwenSystemSettings(): string {
48
+ const file = path.join(getQwenRuntimeDir(), 'clopen-system-settings.json');
49
+ const content = `${JSON.stringify(QWEN_SYSTEM_SETTINGS, null, 2)}\n`;
50
+ try {
51
+ if (fs.readFileSync(file, 'utf-8') === content) return file;
52
+ } catch {
53
+ /* missing — written below */
54
+ }
55
+ fs.mkdirSync(path.dirname(file), { recursive: true });
56
+ fs.writeFileSync(file, content);
57
+ return file;
58
+ }
25
59
 
26
60
  export interface QwenEnvResolution {
27
61
  env: Record<string, string>;
@@ -71,10 +105,13 @@ export function getEngineEnv(accountId?: number): QwenEnvResolution | null {
71
105
  env['OPENAI_BASE_URL'] = baseUrl;
72
106
  // Isolate Qwen's runtime output (chats/sessions, history, logs, tmp) to
73
107
  // {clopenDir}/engine/qwen/user/ instead of the shared ~/.qwen. Mirrors the path
74
- // the fork helper reads from (see ./session-fork.ts). The CLI's global
108
+ // the session store reads from (see ./session-store.ts). The CLI's global
75
109
  // settings.json stays in ~/.qwen — there is no env override for it — but
76
110
  // Clopen uses paste-token auth so that file is irrelevant here.
77
111
  env['QWEN_RUNTIME_DIR'] = getQwenRuntimeDir();
112
+ // Replaces the machine-wide system settings file for these runs only
113
+ // (`/Library/Application Support/QwenCode/settings.json` and friends).
114
+ env['QWEN_CODE_SYSTEM_SETTINGS_PATH'] = ensureQwenSystemSettings();
78
115
  // Strip any inherited Qwen OAuth hints — if the host shell exports them
79
116
  // the bundled CLI prefers the OAuth path even when API-key env vars are
80
117
  // present, surfacing the "OAuth free tier discontinued" error.
@@ -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
+ });