@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.
- package/backend/artifacts/project/bridge.ts +218 -0
- package/backend/artifacts/project/edit.ts +243 -0
- package/backend/artifacts/project/index.ts +38 -0
- package/backend/artifacts/project/project.test.ts +181 -0
- package/backend/artifacts/project/scan.ts +368 -0
- package/backend/artifacts/project/sources.ts +100 -0
- package/backend/artifacts/sync.ts +1 -1
- package/backend/auth/permissions.ts +15 -0
- package/backend/chat/stream-manager.ts +20 -3
- package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
- package/backend/engine/adapters/claude/models.test.ts +49 -0
- package/backend/engine/adapters/claude/models.ts +81 -562
- package/backend/engine/adapters/claude/stream.ts +32 -5
- package/backend/engine/adapters/cline/credential.ts +42 -18
- package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
- package/backend/engine/adapters/cline/message-converter.ts +31 -1
- package/backend/engine/adapters/cline/models.test.ts +77 -0
- package/backend/engine/adapters/cline/models.ts +89 -3
- package/backend/engine/adapters/cline/presets.ts +5 -0
- package/backend/engine/adapters/cline/stream.ts +29 -8
- package/backend/engine/adapters/codex/message-converter.ts +1 -1
- package/backend/engine/adapters/codex/models.ts +54 -31
- package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
- package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
- package/backend/engine/adapters/codex/session-fork.ts +5 -0
- package/backend/engine/adapters/codex/stream.ts +29 -11
- package/backend/engine/adapters/copilot/models.test.ts +40 -0
- package/backend/engine/adapters/copilot/models.ts +51 -24
- package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
- package/backend/engine/adapters/copilot/permissions.ts +72 -0
- package/backend/engine/adapters/copilot/stream.ts +83 -70
- package/backend/engine/adapters/cursor/stream.ts +27 -12
- package/backend/engine/adapters/opencode/server.ts +14 -4
- package/backend/engine/adapters/opencode/stream.ts +18 -3
- package/backend/engine/adapters/pi/credential.test.ts +83 -0
- package/backend/engine/adapters/pi/credential.ts +68 -12
- package/backend/engine/adapters/pi/environment.ts +9 -5
- package/backend/engine/adapters/pi/mcp.test.ts +194 -0
- package/backend/engine/adapters/pi/mcp.ts +88 -0
- package/backend/engine/adapters/pi/message-converter.ts +6 -4
- package/backend/engine/adapters/pi/presets.ts +10 -5
- package/backend/engine/adapters/pi/stream.ts +77 -41
- package/backend/engine/adapters/qwen/environment.ts +39 -2
- package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
- package/backend/engine/adapters/qwen/message-converter.ts +40 -23
- package/backend/engine/adapters/qwen/models.test.ts +25 -0
- package/backend/engine/adapters/qwen/models.ts +42 -5
- package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
- package/backend/engine/adapters/qwen/session-store.ts +66 -0
- package/backend/engine/adapters/qwen/stream.ts +118 -87
- package/backend/engine/artifact-sync.ts +12 -5
- package/backend/engine/docs/adapter-contract.md +7 -4
- package/backend/engine/docs/lessons-learned.md +405 -62
- package/backend/engine/docs/quick-reference.md +2 -2
- package/backend/engine/docs/stack.md +17 -4
- package/backend/engine/docs/websocket-routes.md +5 -5
- package/backend/engine/install-recipes.test.ts +105 -5
- package/backend/engine/install-recipes.ts +102 -42
- package/backend/engine/install-runner.ts +56 -2
- package/backend/engine/stack-project.ts +71 -1
- package/backend/files/file-watcher.test.ts +77 -0
- package/backend/files/file-watcher.ts +92 -60
- package/backend/files/watch-ignore.test.ts +182 -0
- package/backend/files/watch-ignore.ts +244 -0
- package/backend/git/git-executor.ts +14 -4
- package/backend/index.ts +16 -1
- package/backend/instructions/service.ts +5 -3
- package/backend/instructions/sync.ts +10 -27
- package/backend/mcp/README.md +2 -2
- package/backend/mcp/external/config.ts +83 -23
- package/backend/mcp/external/project.ts +124 -0
- package/backend/mcp/external/proxy.ts +65 -11
- package/backend/mcp/index.ts +22 -9
- package/backend/mcp/internal/config.ts +42 -3
- package/backend/mcp/internal/remote-server.ts +11 -1
- package/backend/memory/embedding/install.ts +29 -1
- package/backend/skills/marketplace.ts +1 -1
- package/backend/snapshot/blob-store.ts +9 -5
- package/backend/snapshot/git-attribution.test.ts +42 -0
- package/backend/snapshot/git-attribution.ts +306 -0
- package/backend/snapshot/gitignore.test.ts +62 -0
- package/backend/snapshot/gitignore.ts +158 -78
- package/backend/snapshot/snapshot-service.test.ts +270 -0
- package/backend/snapshot/snapshot-service.ts +412 -136
- package/backend/snapshot/turn-activity.test.ts +52 -0
- package/backend/snapshot/turn-activity.ts +83 -0
- package/backend/snapshot/turn-changes.test.ts +58 -1
- package/backend/snapshot/turn-changes.ts +66 -0
- package/backend/utils/keyed-lock.test.ts +33 -0
- package/backend/utils/keyed-lock.ts +17 -0
- package/backend/utils/port-utils.test.ts +29 -0
- package/backend/utils/port-utils.ts +19 -0
- package/backend/worktrees/tree.ts +1 -1
- package/backend/ws/chat/composer.ts +504 -0
- package/backend/ws/chat/index.ts +3 -1
- package/backend/ws/chat/stream.ts +252 -440
- package/backend/ws/engine/cline/accounts.ts +26 -6
- package/backend/ws/engine/codex/accounts.test.ts +49 -0
- package/backend/ws/engine/codex/accounts.ts +17 -13
- package/backend/ws/engine/pi/accounts.ts +61 -6
- package/backend/ws/index.ts +4 -0
- package/backend/ws/project-artifacts/index.ts +236 -0
- package/backend/ws/snapshot/changes.ts +66 -31
- package/dist/assets/{index-DX5OwLOc.js → index-BTcR1byF.js} +1 -1
- package/dist/assets/{index-BWyhqUi5.js → index-CwuKQelV.js} +1 -1
- package/dist/assets/main-BiDNMWb3.css +1 -0
- package/dist/assets/main-BlhKWz2B.js +1241 -0
- package/dist/index.html +2 -2
- package/package.json +19 -15
- package/shared/types/stores/settings.ts +5 -0
- package/shared/types/unified/message.ts +2 -0
- package/backend/engine/adapters/pi/mcp-tools.ts +0 -131
- package/backend/engine/adapters/qwen/session-fork.ts +0 -109
- package/dist/assets/main-DOkwqXRU.js +0 -1215
- 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. **
|
|
17
|
-
*
|
|
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 {
|
|
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
|
-
|
|
173
|
-
|
|
174
|
-
|
|
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
|
|
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
|
|
191
|
-
const
|
|
192
|
-
const
|
|
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
|
-
|
|
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
|
|
203
|
-
const
|
|
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({
|
|
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 +
|
|
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:
|
|
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.
|
|
334
|
-
//
|
|
335
|
-
|
|
336
|
-
|
|
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-
|
|
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
|
|
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: `
|
|
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
|
|
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
|
|
93
|
-
|
|
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
|
|
530
|
-
*
|
|
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:
|
|
671
|
-
// the
|
|
672
|
-
//
|
|
673
|
-
//
|
|
674
|
-
// `qwen/stream.ts::resolveUserAnswer`
|
|
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
|
-
* `
|
|
865
|
+
* `emitSystemMessage("task_notification", …)` in the SDK's bundled CLI
|
|
866
|
+
* (`node_modules/@qwen-code/sdk/dist/cli/chunks/`).
|
|
850
867
|
*
|
|
851
|
-
* `data` shape (
|
|
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(
|
|
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: {
|
|
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
|
+
});
|