@myrialabs/clopen 0.4.15 → 0.4.17

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 (95) hide show
  1. package/README.md +8 -5
  2. package/backend/artifacts/matrix.ts +8 -0
  3. package/backend/artifacts/types.ts +2 -2
  4. package/backend/auth/permissions.ts +14 -0
  5. package/backend/chat/stream-manager.ts +5 -5
  6. package/backend/commands/detect.ts +1 -1
  7. package/backend/commands/sync.ts +1 -1
  8. package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
  9. package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
  10. package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
  11. package/backend/database/migrations/index.ts +21 -0
  12. package/backend/engine/README.md +36 -13
  13. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  14. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  15. package/backend/engine/adapters/cline/credential.ts +166 -0
  16. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  17. package/backend/engine/adapters/cline/index.ts +1 -0
  18. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  19. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  20. package/backend/engine/adapters/cline/models.ts +73 -0
  21. package/backend/engine/adapters/cline/presets.ts +128 -0
  22. package/backend/engine/adapters/cline/stream.ts +413 -0
  23. package/backend/engine/adapters/codex/credential.ts +1 -1
  24. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  25. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  26. package/backend/engine/adapters/codex/stream.ts +3 -3
  27. package/backend/engine/adapters/copilot/stream.ts +1 -1
  28. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  29. package/backend/engine/adapters/cursor/credential.ts +68 -0
  30. package/backend/engine/adapters/cursor/environment.ts +32 -0
  31. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  32. package/backend/engine/adapters/cursor/index.ts +1 -0
  33. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  34. package/backend/engine/adapters/cursor/models.ts +68 -0
  35. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  36. package/backend/engine/adapters/cursor/stream.ts +341 -0
  37. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  38. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  39. package/backend/engine/adapters/pi/credential.ts +137 -0
  40. package/backend/engine/adapters/pi/environment.ts +33 -0
  41. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  42. package/backend/engine/adapters/pi/index.ts +1 -0
  43. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  44. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  45. package/backend/engine/adapters/pi/models.ts +53 -0
  46. package/backend/engine/adapters/pi/presets.ts +133 -0
  47. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  48. package/backend/engine/adapters/pi/stream.ts +427 -0
  49. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  50. package/backend/engine/adapters/qwen/stream.ts +2 -2
  51. package/backend/engine/docs/adapter-contract.md +7 -2
  52. package/backend/engine/docs/adding-an-engine.md +70 -12
  53. package/backend/engine/docs/artifacts.md +124 -0
  54. package/backend/engine/docs/database.md +4 -4
  55. package/backend/engine/docs/frontend-and-chat.md +22 -4
  56. package/backend/engine/docs/lessons-learned.md +219 -32
  57. package/backend/engine/docs/quick-reference.md +18 -7
  58. package/backend/engine/docs/websocket-routes.md +2 -2
  59. package/backend/engine/index.ts +9 -0
  60. package/backend/mcp/README.md +3 -3
  61. package/backend/mcp/external/config.ts +11 -0
  62. package/backend/mcp/index.ts +8 -0
  63. package/backend/mcp/internal/config.ts +33 -1
  64. package/backend/permissions/service.ts +5 -2
  65. package/backend/skills/sync.ts +1 -1
  66. package/backend/subagents/detect.ts +1 -1
  67. package/backend/subagents/sync.ts +1 -1
  68. package/backend/ws/chat/stream.ts +1 -1
  69. package/backend/ws/engine/cline/accounts.ts +317 -0
  70. package/backend/ws/engine/cline/index.ts +15 -0
  71. package/backend/ws/engine/cline/presets.ts +36 -0
  72. package/backend/ws/engine/cline/status.ts +49 -0
  73. package/backend/ws/engine/codex/accounts.ts +1 -1
  74. package/backend/ws/engine/cursor/accounts.ts +162 -0
  75. package/backend/ws/engine/cursor/index.ts +13 -0
  76. package/backend/ws/engine/cursor/status.ts +55 -0
  77. package/backend/ws/engine/index.ts +6 -0
  78. package/backend/ws/engine/pi/accounts.ts +319 -0
  79. package/backend/ws/engine/pi/index.ts +15 -0
  80. package/backend/ws/engine/pi/presets.ts +34 -0
  81. package/backend/ws/engine/pi/status.ts +50 -0
  82. package/backend/ws/sessions/crud.ts +2 -2
  83. package/backend/ws/settings/crud.ts +2 -2
  84. package/dist/assets/{index-EunAFLxP.js → index-Bu5loFQE.js} +1 -1
  85. package/dist/assets/{index-ChF_jIXj.js → index-kME3THy5.js} +1 -1
  86. package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
  87. package/dist/assets/{main-CTs4NXwP.js → main-HirJLquI.js} +361 -359
  88. package/dist/index.html +2 -2
  89. package/package.json +11 -2
  90. package/shared/constants/engine-tools.ts +16 -2
  91. package/shared/constants/engines.ts +27 -0
  92. package/shared/types/unified/common.ts +1 -1
  93. package/shared/types/unified/engine.ts +82 -1
  94. package/shared/types/unified/index.ts +6 -0
  95. package/shared/types/unified/message.ts +1 -1
@@ -0,0 +1,413 @@
1
+ /**
2
+ * Cline Engine Adapter
3
+ *
4
+ * Wraps `@cline/sdk` into the AIEngine interface. Structurally close to the Pi
5
+ * adapter, with three deliberate choices:
6
+ *
7
+ * 1. **Stateless `Agent`, not `ClineCore`.** Clopen already owns session
8
+ * persistence (stream-manager + DB), and `ClineCore` derives its storage
9
+ * root from `$HOME/.cline` with no redirect env var — which would collide
10
+ * with the user's real Cline data. The stateless `Agent` writes nothing to
11
+ * disk; we bring the built-in coding tools in via `createBuiltinTools`.
12
+ * 2. **Subscribe, not async-generator.** `Agent.subscribe(listener)` +
13
+ * `agent.run()` drive output. `streamQuery` bridges that push stream into
14
+ * the required `AsyncGenerator<EngineOutput>` via a small pushable queue.
15
+ * 3. **Multi-provider, DB-backed credentials.** Each stream resolves the
16
+ * account matching the model's provider from `engine_accounts` and feeds its
17
+ * api-key (or refreshed OAuth token) into the provider-form `Agent` config.
18
+ *
19
+ * MCP tools + AskUserQuestion are bridged as in-process custom tools (Cline has
20
+ * no headless MCP/ask path for the stateless loop). Resume keeps context within
21
+ * the running server via `restore()` of the prior transcript.
22
+ */
23
+
24
+ import { Agent, createBuiltinTools, getClineDefaultSystemPrompt } from '@cline/sdk';
25
+ import type { AgentTool, ToolPolicy } from '@cline/sdk';
26
+ import type { AgentMessage, AgentMessagePart, AgentRunResult } from '@cline/agents';
27
+ import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
28
+ import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
29
+ import { resolveOsPath } from '$backend/utils/paths';
30
+ import { debug } from '$shared/utils/logger';
31
+ import { engineQueries } from '$backend/database/queries/engine-queries';
32
+ import { syncSkills } from '$backend/skills';
33
+ import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
34
+ import { artifactFilter } from '$backend/profiles';
35
+ import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
36
+ import { buildJsonPrompt, extractJson } from '../../structured-helpers';
37
+ import { subagentQueries } from '$backend/database/queries';
38
+ import { readSubagentMd } from '$backend/subagents/store';
39
+ import { getClineAccountForProvider, parseClineCredential, resolveClineAuth } from './credential';
40
+ import { fetchClineModels } from './models';
41
+ import { buildClineMcpTools } from './mcp-tools';
42
+ import { createAskUserQuestionTool, formatAnswers, type PendingAsk } from './ask-question-tool';
43
+ import { createAgentDispatchTool, type SubagentInfo } from './agent-tool';
44
+ import { createClineMessageConverter } from './message-converter';
45
+ import { handleStreamError } from './error-handler';
46
+
47
+ /** Cline built-in coding tools (createBuiltinTools defaults; ask/submit are off). */
48
+ const CLINE_BUILTIN_TOOLS = ['read_files', 'search_codebase', 'run_commands', 'fetch_web_content', 'apply_patch', 'editor', 'skills'];
49
+
50
+ /** Max per-turn transcripts kept in memory before FIFO eviction (branch history). */
51
+ const MAX_TRACKED_SESSIONS = 500;
52
+
53
+ type ClineAgent = InstanceType<typeof Agent>;
54
+
55
+ /** Strip YAML frontmatter from a subagent markdown doc, leaving the instructions. */
56
+ function stripFrontmatter(md: string): string {
57
+ const match = md.match(/^---\n[\s\S]*?\n---\n?/);
58
+ return (match ? md.slice(match[0].length) : md).trim();
59
+ }
60
+
61
+ /** Minimal pushable queue bridging Cline's subscribe stream → an async generator. */
62
+ class EventQueue<T> {
63
+ private buffer: T[] = [];
64
+ private wake: (() => void) | null = null;
65
+ private done = false;
66
+ private error: unknown = null;
67
+
68
+ push(value: T): void { this.buffer.push(value); this.signal(); }
69
+ close(): void { this.done = true; this.signal(); }
70
+ fail(error: unknown): void { this.error = error; this.done = true; this.signal(); }
71
+
72
+ private signal(): void {
73
+ const wake = this.wake;
74
+ this.wake = null;
75
+ wake?.();
76
+ }
77
+
78
+ async *drain(): AsyncGenerator<T, void, unknown> {
79
+ while (true) {
80
+ while (this.buffer.length) yield this.buffer.shift() as T;
81
+ if (this.error) throw this.error;
82
+ if (this.done) return;
83
+ await new Promise<void>((resolve) => { this.wake = resolve; });
84
+ }
85
+ }
86
+ }
87
+
88
+ export class ClineEngine implements AIEngine {
89
+ readonly name = 'cline' as const;
90
+ private _isInitialized = false;
91
+ private activeController: AbortController | null = null;
92
+ private activeAgent: ClineAgent | null = null;
93
+ private pendingAsks = new Map<string, PendingAsk>();
94
+ /**
95
+ * In-memory transcript keyed by the SDK session id EMITTED for each turn.
96
+ * Every turn stores its resulting transcript under a fresh id and never
97
+ * mutates an existing entry — so a checkpoint fork (undo + continue) resumes
98
+ * from the exact ancestor branch instead of whatever was written last. See
99
+ * the branch-awareness note in `streamQuery`.
100
+ */
101
+ private sessions = new Map<string, AgentMessage[]>();
102
+
103
+ get isInitialized(): boolean { return this._isInitialized; }
104
+ get isActive(): boolean { return this.activeController !== null; }
105
+
106
+ async initialize(): Promise<void> {
107
+ if (this._isInitialized) return;
108
+ this._isInitialized = true;
109
+ debug.log('engine', '✅ Cline engine initialized');
110
+ }
111
+
112
+ async dispose(): Promise<void> {
113
+ await this.cancel();
114
+ this.pendingAsks.clear();
115
+ this.sessions.clear();
116
+ this._isInitialized = false;
117
+ }
118
+
119
+ async getAvailableModels(): Promise<EngineModel[]> {
120
+ return fetchClineModels();
121
+ }
122
+
123
+ private buildSystemPrompt(cwd: string, providerId: string, profileId?: number): string {
124
+ let base: string;
125
+ try {
126
+ base = getClineDefaultSystemPrompt({ cwd, workspaceRoot: cwd, providerId, platform: process.platform });
127
+ } catch {
128
+ base = 'You are Cline, a highly skilled software engineer. Use the available tools to complete the user\'s coding task.';
129
+ }
130
+ const artifacts = buildArtifactsPromptContext(profileId);
131
+ return artifacts ? `${base}\n\n${artifacts}` : base;
132
+ }
133
+
134
+ async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
135
+ const { projectPath, prompt, resume, providerSlug, modelId, abortController, accountId } = options;
136
+ debug.log('chat', 'Cline - Stream Query', { providerSlug, modelId, resume });
137
+
138
+ // ── Resolve account + credential for the model's provider ──
139
+ const account = getClineAccountForProvider(providerSlug)
140
+ ?? (accountId != null ? engineQueries.getAccount(accountId) : null);
141
+ if (!account) {
142
+ throw new Error(`Cline has no account for provider "${providerSlug}". Add one in Settings → Engines → Cline.`);
143
+ }
144
+ const provider = parseClineCredential(account.credential)?.provider ?? providerSlug;
145
+ const auth = await resolveClineAuth(account);
146
+
147
+ this.activeController = abortController || new AbortController();
148
+ const resolvedProjectPath = resolveOsPath(projectPath);
149
+
150
+ // ── Active Profile scoping + artifact materialization ──
151
+ const profileId = options.mcpContext?.profileId;
152
+ const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
153
+ await syncSkills('cline', profileId);
154
+ await syncEngineArtifacts('cline', profileId);
155
+
156
+ // ── Permissions → toolPolicies (denied builtins are hidden from the model) ──
157
+ const permissions = resolvePermissionsFromDb('cline', options.mcpContext?.projectId, profileId);
158
+
159
+ // Late-bound handle to the stream's event queue so the subagent runner
160
+ // (built before the queue exists) can push its sub-activity messages into it.
161
+ const queueHolder: { queue: EventQueue<EngineOutput> | null } = { queue: null };
162
+
163
+ // ── Tools: builtins + AskUserQuestion + MCP bridge ──
164
+ const builtinTools = createBuiltinTools({
165
+ cwd: resolvedProjectPath,
166
+ enableAskQuestion: false,
167
+ enableSubmitAndExit: false,
168
+ });
169
+ const askTool = createAskUserQuestionTool({
170
+ register: (id, entry) => this.pendingAsks.set(id, entry),
171
+ unregister: (id) => this.pendingAsks.delete(id),
172
+ });
173
+ const mcpTools = await buildClineMcpTools(options.mcpContext, mcpProfileFilter);
174
+ const tools: AgentTool[] = [...builtinTools, askTool, ...mcpTools];
175
+
176
+ const toolPolicies: Record<string, ToolPolicy> = {};
177
+ for (const name of CLINE_BUILTIN_TOOLS) {
178
+ toolPolicies[name] = isToolAllowed(permissions, name) ? { autoApprove: true } : { enabled: false };
179
+ }
180
+ toolPolicies.AskUserQuestion = { autoApprove: true };
181
+ for (const t of mcpTools) toolPolicies[t.name] = { autoApprove: true };
182
+
183
+ // ── Subagents: Cline's stateless Agent has no native Agent/Task tool, so the
184
+ // "Available Subagents" preamble alone can't be invoked. Expose an `Agent`
185
+ // tool that actually spawns a bounded sub-`Agent` with the chosen subagent's
186
+ // system prompt and returns its final text. ──
187
+ const subagents: SubagentInfo[] = subagentQueries.getEnabled().map(s => ({ slug: s.slug, name: s.name, description: s.description }));
188
+ if (subagents.length > 0) {
189
+ const agentTool = createAgentDispatchTool({
190
+ subagents,
191
+ run: async (subagent, subPrompt, toolCallId, signal) => {
192
+ const md = (await readSubagentMd(subagent.slug)) ?? '';
193
+ const instructions = stripFrontmatter(md) || `You are the ${subagent.name} subagent. ${subagent.description}`;
194
+ // APPEND the subagent instructions to Cline's base coding prompt (a
195
+ // bare instruction strips the tool-use scaffolding). The sub-Agent gets
196
+ // the permission-filtered builtins ONLY — no AskUserQuestion, no MCP,
197
+ // and no nested Agent tool — so delegation stays bounded.
198
+ let base: string;
199
+ try {
200
+ base = getClineDefaultSystemPrompt({ cwd: resolvedProjectPath, workspaceRoot: resolvedProjectPath, providerId: provider, platform: process.platform });
201
+ } catch {
202
+ base = 'You are Cline, a highly skilled software engineer.';
203
+ }
204
+ const subAgent = new Agent({
205
+ providerId: provider,
206
+ modelId,
207
+ ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
208
+ ...(auth.baseUrl ? { baseUrl: auth.baseUrl } : {}),
209
+ ...(auth.options ? { options: auth.options } : {}),
210
+ systemPrompt: `${base}\n\n# Subagent: ${subagent.name}\n\n${instructions}`,
211
+ tools: builtinTools,
212
+ toolPolicies,
213
+ maxIterations: 30,
214
+ });
215
+
216
+ // Route the sub-agent's persisted messages into the PARENT stream as
217
+ // sub-activities: tag each with `parent.toolUseId = <Agent block id>`
218
+ // so the frontend folds them under the Agent tool. Only tool_use
219
+ // steps (+ their tool_result) are surfaced — the collapsed sub-agent
220
+ // view is a tool trail; the sub-agent's prose is already returned as
221
+ // the Agent tool's result (its `outputText`). So we drop transient
222
+ // events, reasoning, and text-only assistant messages.
223
+ const subConverter = createClineMessageConverter({
224
+ engine: { type: 'cline', provider, model: { id: modelId, name: modelId }, account: { id: account.id, name: account.name } },
225
+ sessionId: crypto.randomUUID(),
226
+ });
227
+ const unsub = subAgent.subscribe((ev) => {
228
+ for (const out of subConverter.convert(ev)) {
229
+ if (out.type === 'user') {
230
+ // tool_result messages — carry the sub-agent's tool outputs.
231
+ } else if (out.type === 'assistant' && out.content.some(b => b.type === 'tool_use')) {
232
+ // tool_use step — keep.
233
+ } else {
234
+ continue; // drop stream/result/init/notification/reasoning/text-only
235
+ }
236
+ out.parent = { messageId: null, sessionId: null, toolUseId: toolCallId };
237
+ queueHolder.queue?.push(out);
238
+ }
239
+ });
240
+
241
+ const onSubAbort = () => { try { subAgent.abort('Parent cancelled'); } catch { /* ignore */ } };
242
+ signal?.addEventListener('abort', onSubAbort, { once: true });
243
+ try {
244
+ const result = await subAgent.run(subPrompt);
245
+ return result.outputText ?? '';
246
+ } finally {
247
+ signal?.removeEventListener('abort', onSubAbort);
248
+ unsub();
249
+ }
250
+ },
251
+ });
252
+ tools.push(agentTool);
253
+ toolPolicies.Agent = { autoApprove: true };
254
+ }
255
+
256
+ const toolNames = tools.filter(t => toolPolicies[t.name]?.enabled !== false).map(t => t.name);
257
+
258
+ // ── Resume / fork (branch-aware) ──
259
+ // `resume` is the parent branch's per-turn session id (stream-manager
260
+ // derives it from the prompt's `parent.sessionId`). We ALWAYS mint a fresh
261
+ // id for this turn and copy the parent's transcript forward — so two turns
262
+ // that share the same parent (a checkpoint fork: A→B→C vs A→B1→C1) each get
263
+ // an independent history and never leak the sibling branch's messages.
264
+ const priorMessages = resume ? this.sessions.get(resume) : undefined;
265
+ const sessionId = crypto.randomUUID();
266
+
267
+ const systemPrompt = this.buildSystemPrompt(resolvedProjectPath, provider, profileId);
268
+ const agent = new Agent({
269
+ providerId: provider,
270
+ modelId,
271
+ ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
272
+ ...(auth.baseUrl ? { baseUrl: auth.baseUrl } : {}),
273
+ ...(auth.options ? { options: auth.options } : {}),
274
+ systemPrompt,
275
+ tools,
276
+ toolPolicies,
277
+ maxIterations: options.maxTurns ?? 100,
278
+ });
279
+ this.activeAgent = agent;
280
+ if (priorMessages?.length) agent.restore(priorMessages);
281
+
282
+ const engineMeta: MessageEngine = {
283
+ type: 'cline',
284
+ provider,
285
+ model: { id: modelId, name: modelId },
286
+ account: { id: account.id, name: account.name },
287
+ };
288
+ const converter = createClineMessageConverter({ engine: engineMeta, sessionId });
289
+ const queue = new EventQueue<EngineOutput>();
290
+ queueHolder.queue = queue;
291
+ const unsubscribe = agent.subscribe((event) => {
292
+ try {
293
+ for (const out of converter.convert(event)) queue.push(out);
294
+ } catch (error) {
295
+ queue.fail(error);
296
+ }
297
+ });
298
+
299
+ // Abort wiring: cancelling the stream aborts the Cline run.
300
+ const onAbort = () => { agent.abort('Cancelled'); };
301
+ this.activeController.signal.addEventListener('abort', onAbort, { once: true });
302
+
303
+ // Build the user turn (text + image attachments).
304
+ const promptText = prompt.content.filter(b => b.type === 'text').map(b => (b.type === 'text' ? b.text : '')).join('\n');
305
+ const content: AgentMessagePart[] = [{ type: 'text', text: promptText }];
306
+ for (const b of prompt.content) {
307
+ if (b.type === 'image') content.push({ type: 'image', image: `data:${b.mediaType};base64,${b.data}`, mediaType: b.mediaType });
308
+ }
309
+ const userMessage: AgentMessage = { id: crypto.randomUUID(), role: 'user', content, createdAt: Date.now() };
310
+
311
+ // system_init first — model + enabled tools (Cline bridges MCP as custom tools).
312
+ yield {
313
+ type: 'system_init',
314
+ sessionId,
315
+ model: modelId,
316
+ engine: 'cline',
317
+ tools: toolNames,
318
+ mcpServers: [],
319
+ };
320
+
321
+ const runPromise: Promise<AgentRunResult> = priorMessages?.length ? agent.continue(userMessage) : agent.run(userMessage);
322
+ const settle = runPromise
323
+ .then((result) => {
324
+ // Store this turn's full transcript under its OWN new id — never
325
+ // overwrite the parent (`resume`) entry, so sibling forks stay isolated.
326
+ this.sessions.set(sessionId, [...result.messages]);
327
+ // Bound the map so a long-lived project engine can't grow unbounded.
328
+ // FIFO eviction: forking from a very old (evicted) checkpoint simply
329
+ // starts fresh, same graceful degradation as a cross-restart resume.
330
+ while (this.sessions.size > MAX_TRACKED_SESSIONS) {
331
+ const oldest = this.sessions.keys().next().value;
332
+ if (oldest === undefined) break;
333
+ this.sessions.delete(oldest);
334
+ }
335
+ if (result.status === 'failed') {
336
+ queue.fail(result.error ?? new Error('Cline run failed'));
337
+ return;
338
+ }
339
+ queue.close();
340
+ })
341
+ .catch((error) => queue.fail(error));
342
+
343
+ try {
344
+ for await (const out of queue.drain()) yield out;
345
+ await settle;
346
+ } catch (error) {
347
+ handleStreamError(error);
348
+ } finally {
349
+ this.activeController?.signal.removeEventListener('abort', onAbort);
350
+ unsubscribe();
351
+ this.activeAgent = null;
352
+ this.activeController = null;
353
+ this.pendingAsks.clear();
354
+ }
355
+ }
356
+
357
+ async cancel(): Promise<void> {
358
+ if (this.activeController && !this.activeController.signal.aborted) {
359
+ this.activeController.abort();
360
+ }
361
+ if (this.activeAgent) {
362
+ try { this.activeAgent.abort('Cancelled'); } catch { /* may already be idle */ }
363
+ }
364
+ this.pendingAsks.clear();
365
+ this.activeAgent = null;
366
+ this.activeController = null;
367
+ }
368
+
369
+ async interrupt(): Promise<void> {
370
+ if (this.activeAgent) {
371
+ try { this.activeAgent.abort('Interrupted'); } catch { /* ignore */ }
372
+ }
373
+ }
374
+
375
+ resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
376
+ const pending = this.pendingAsks.get(toolUseId);
377
+ if (!pending) {
378
+ debug.warn('engine', `Cline resolveUserAnswer: no pending question for ${toolUseId}`);
379
+ return false;
380
+ }
381
+ pending.resolve(formatAnswers(pending.questions, answers));
382
+ this.pendingAsks.delete(toolUseId);
383
+ return true;
384
+ }
385
+
386
+ /**
387
+ * One-shot structured JSON generation via prompt engineering (no tools). Runs
388
+ * a tool-less `Agent` and parses the final assistant text.
389
+ */
390
+ async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
391
+ const { prompt, providerSlug, modelId, schema, accountId } = options;
392
+
393
+ const account = getClineAccountForProvider(providerSlug)
394
+ ?? (accountId != null ? engineQueries.getAccount(accountId) : null);
395
+ if (!account) throw new Error(`Cline has no account for provider "${providerSlug}".`);
396
+ const provider = parseClineCredential(account.credential)?.provider ?? providerSlug;
397
+ const auth = await resolveClineAuth(account);
398
+
399
+ const agent = new Agent({
400
+ providerId: provider,
401
+ modelId,
402
+ ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
403
+ ...(auth.baseUrl ? { baseUrl: auth.baseUrl } : {}),
404
+ ...(auth.options ? { options: auth.options } : {}),
405
+ systemPrompt: 'You output only valid JSON. No prose, no markdown fences.',
406
+ maxIterations: 1,
407
+ });
408
+
409
+ const result = await agent.run(buildJsonPrompt(prompt, schema));
410
+ if (!result.outputText?.trim()) throw new Error('Cline returned no structured output');
411
+ return extractJson<T>(result.outputText);
412
+ }
413
+ }
@@ -8,7 +8,7 @@
8
8
  * `~/.codex/auth.json` and refreshes it in-place.
9
9
  *
10
10
  * Multi-account ChatGPT support uses the **auth-blob swap** pattern (see
11
- * backend/engine/README.md §9.13): we snapshot `~/.codex/auth.json` content
11
+ * backend/engine/README.md §10.13): we snapshot `~/.codex/auth.json` content
12
12
  * into `engine_accounts.credential` after login, and write the active
13
13
  * account's snapshot back to the shared file on switch / stream-start.
14
14
  *
@@ -254,7 +254,7 @@ export function convertTurnCompleted(event: TurnCompletedEvent, state: CodexStre
254
254
  // Note: the per-turn `usage` aggregate is NOT attached to individual
255
255
  // assistant messages here — they were already saved live during the turn
256
256
  // (with usage:null). The stream-manager backfills usage after the result
257
- // event by looking up each saved row's DB id. See README §9.4.
257
+ // event by looking up each saved row's DB id. See README §10.4.
258
258
 
259
259
  const stopLifecycle: StreamLifecycleEvent = {
260
260
  type: 'stream_event',
@@ -439,7 +439,7 @@ function buildToolResultUserMessage(
439
439
  createdAt: new Date().toISOString(),
440
440
  messageId: crypto.randomUUID(),
441
441
  sessionId: state.sessionId,
442
- // IMPORTANT: parent.toolUseId stays null (README §9.5 sharp edge).
442
+ // IMPORTANT: parent.toolUseId stays null (README §10.5 sharp edge).
443
443
  parent: { messageId: null, sessionId: null, toolUseId: null },
444
444
  engine: buildEngine(state.modelId),
445
445
  sender: { id: '', name: '' },
@@ -463,7 +463,7 @@ function buildCommandExecutionPair(item: CommandExecutionItem, state: CodexStrea
463
463
  }
464
464
 
465
465
  function buildFileChangePair(item: FileChangeItem, state: CodexStreamState): EngineOutput[] {
466
- // Codex bundles N file changes per item. Per README §9.3 we split into N
466
+ // Codex bundles N file changes per item. Per README §10.3 we split into N
467
467
  // separate AssistantMessages so each shows up as its own tool block.
468
468
  const out: EngineOutput[] = [];
469
469
  const baseId = item.id;
@@ -557,7 +557,7 @@ function buildWebSearchPair(item: WebSearchItem, state: CodexStreamState): Engin
557
557
  const block = buildToolUseBlock('WebSearch', input as unknown as Record<string, unknown>, item.id);
558
558
  const assistant = createAssistantToolUseMessage(state, block, item.id);
559
559
  // Synthetic tool_result so the frontend grouper attaches a non-null
560
- // result at render time (README §9.5). Without it `tool_use.result`
560
+ // result at render time (README §10.5). Without it `tool_use.result`
561
561
  // stays null forever.
562
562
  const result = buildToolResultUserMessage(
563
563
  item.id,
@@ -18,7 +18,7 @@
18
18
  * Earlier versions of this helper assumed a directory layout
19
19
  * (`~/.codex/sessions/<thread_id>/`) and so `sessionStateExists()` always
20
20
  * returned false — the fork block was silently skipped and resume reused
21
- * the source thread id, breaking multi-branch checkpoints (README §9.10
21
+ * the source thread id, breaking multi-branch checkpoints (README §10.10
22
22
  * sharp edge: "reusing the same id across turns is the symptom that
23
23
  * forking is gated or skipped").
24
24
  *
@@ -6,7 +6,7 @@
6
6
  * instance, the `Thread` lifecycle, and an `AbortController` for cancellation.
7
7
  *
8
8
  * Auth: dual mode (API key + ChatGPT browser OAuth). See ./auth.ts and
9
- * backend/engine/README.md §9.13 for the auth-blob swap pattern.
9
+ * backend/engine/README.md §10.13 for the auth-blob swap pattern.
10
10
  *
11
11
  * MCP: reuses the existing remote MCP HTTP server at /mcp via
12
12
  * getCodexMcpConfig() in backend/mcp/config.ts. No new MCP infrastructure.
@@ -208,7 +208,7 @@ export class CodexEngine implements AIEngine {
208
208
 
209
209
  if (resume) {
210
210
  // Fork-by-copy on EVERY resume — same semantics as Copilot
211
- // (README §9.10 sharp edge: never gate on options.forkSession).
211
+ // (README §10.10 sharp edge: never gate on options.forkSession).
212
212
  let resumeId = resume;
213
213
  if (sessionStateExists(resume)) {
214
214
  const forkId = crypto.randomUUID();
@@ -279,7 +279,7 @@ export class CodexEngine implements AIEngine {
279
279
  handleStreamError(error);
280
280
  } finally {
281
281
  // Snapshot the (possibly token-refreshed) auth.json back to DB so
282
- // refreshes survive across account switches (README §9.13 step 4).
282
+ // refreshes survive across account switches (README §10.13 step 4).
283
283
  try {
284
284
  snapshotAuthJsonToActiveAccount();
285
285
  } catch (snapshotErr) {
@@ -356,7 +356,7 @@ export class CopilotEngine implements AIEngine {
356
356
  includeSubAgentStreamingEvents: false,
357
357
  // Custom MCP tools served from Clopen's in-process remote MCP HTTP
358
358
  // endpoint (`/mcp`). Same `clopen-mcp` namespace and URL Open Code
359
- // and Codex consume — see backend/engine/README.md §9.12.
359
+ // and Codex consume — see backend/engine/README.md §10.12.
360
360
  ...(Object.keys(mcpConfig).length > 0 && { mcpServers: mcpConfig }),
361
361
  };
362
362
 
@@ -0,0 +1,98 @@
1
+ /**
2
+ * AskUserQuestion custom tool for Cursor.
3
+ *
4
+ * Cursor exposes in-process callback tools via `local.customTools` (surfaced to
5
+ * the model as the `custom-user-tools` MCP server). We register a canonical
6
+ * `AskUserQuestion` tool whose `execute` BLOCKS until the user answers through the
7
+ * chat UI — the same contract Claude's `canUseTool` / Cline's custom ask tool
8
+ * provide.
9
+ *
10
+ * The Cursor custom-tool context carries no abort signal, so a parked question is
11
+ * released either by `resolveUserAnswer(toolCallId, answers)` (the user answered)
12
+ * or by the engine's `cancel()` sweep over `pendingAsks`.
13
+ */
14
+
15
+ import type { SDKCustomTool, SDKJsonValue } from '@cursor/sdk';
16
+ import type { AskUserQuestion } from '$shared/types/unified';
17
+
18
+ export interface PendingAsk {
19
+ questions: AskUserQuestion[];
20
+ resolve: (text: string) => void;
21
+ }
22
+
23
+ export interface AskToolBindings {
24
+ register: (toolCallId: string, entry: PendingAsk) => void;
25
+ unregister: (toolCallId: string) => void;
26
+ /**
27
+ * Surface the AskUserQuestion tool_use into the stream with the COMPLETE
28
+ * questions. Sourced from `execute`'s args (always fully populated) rather
29
+ * than the stream's `tool_call` args, which can arrive empty/partial for large
30
+ * question sets — the bug behind `questions: []` in the UI.
31
+ */
32
+ emit: (toolCallId: string, questions: AskUserQuestion[]) => void;
33
+ }
34
+
35
+ /** Format the user's answers in the shared OpenCode/Qwen/Pi/Cline wording. */
36
+ export function formatAnswers(questions: AskUserQuestion[], answers: Record<string, string>): string {
37
+ const pairs: string[] = [];
38
+ for (const [key, value] of Object.entries(answers)) {
39
+ const idx = Number.parseInt(key, 10);
40
+ const q = Number.isFinite(idx) ? questions[idx] : undefined;
41
+ const label = q?.question ?? q?.header ?? key;
42
+ pairs.push(`"${label}"="${value}"`);
43
+ }
44
+ if (pairs.length === 0) return 'User did not provide any answers.';
45
+ return `User has answered your questions: ${pairs.join(', ')}. You can now continue with the user's answers in mind.`;
46
+ }
47
+
48
+ const ASK_INPUT_SCHEMA: Record<string, SDKJsonValue> = {
49
+ type: 'object',
50
+ properties: {
51
+ questions: {
52
+ type: 'array',
53
+ description: 'One or more multiple-choice questions to ask the user.',
54
+ items: {
55
+ type: 'object',
56
+ properties: {
57
+ question: { type: 'string', description: 'The full question text.' },
58
+ header: { type: 'string', description: 'A short (max 12 char) label for the question.' },
59
+ multiSelect: { type: 'boolean', description: 'Whether multiple options may be selected.' },
60
+ options: {
61
+ type: 'array',
62
+ items: {
63
+ type: 'object',
64
+ properties: {
65
+ label: { type: 'string' },
66
+ description: { type: 'string' },
67
+ },
68
+ required: ['label', 'description'],
69
+ },
70
+ },
71
+ },
72
+ required: ['question', 'header', 'options'],
73
+ },
74
+ },
75
+ },
76
+ required: ['questions'],
77
+ };
78
+
79
+ export function createAskUserQuestionTool(bindings: AskToolBindings): SDKCustomTool {
80
+ return {
81
+ description:
82
+ 'Ask the user one or more multiple-choice questions when you need a decision only they can make. Blocks until the user answers in the UI.',
83
+ inputSchema: ASK_INPUT_SCHEMA,
84
+ execute(args, context) {
85
+ const questions = (Array.isArray(args?.questions) ? args.questions : []) as unknown as AskUserQuestion[];
86
+ const toolCallId = context.toolCallId ?? '';
87
+ return new Promise<string>((resolve) => {
88
+ if (!toolCallId) {
89
+ resolve('User did not answer the question.');
90
+ return;
91
+ }
92
+ // Emit the tool_use with the complete questions from THIS call's args.
93
+ bindings.emit(toolCallId, questions);
94
+ bindings.register(toolCallId, { questions, resolve });
95
+ });
96
+ },
97
+ };
98
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Cursor credential storage.
3
+ *
4
+ * Cursor authenticates with a single `CURSOR_API_KEY` (a user API key from the
5
+ * Cursor dashboard, or a team service-account key). Unlike the multi-provider
6
+ * engines (Cline/Qwen), a Cursor account is single-provider: one `engine_providers`
7
+ * row (`slug = 'cursor'`) owns every stored account, and the account's
8
+ * `credential` carries just the key.
9
+ *
10
+ * The key is passed to `Agent.create({ apiKey })` per stream — there is no shared
11
+ * dotfile to swap, so multi-account within Clopen is a pure DB `is_active` switch
12
+ * (see `backend/engine/README.md` §10.13). Stored as a JSON wrapper
13
+ * (`{ "apiKey": "…" }`) for forward-compatibility, but a raw key string is also
14
+ * accepted.
15
+ */
16
+
17
+ import { engineQueries, type EngineAccount } from '$backend/database/queries/engine-queries';
18
+
19
+ export interface CursorCredential {
20
+ apiKey: string;
21
+ }
22
+
23
+ /** The single `engine_providers` row that owns every Cursor account. */
24
+ export function getCursorProvider() {
25
+ return engineQueries.getProviderBySlug('cursor', 'cursor');
26
+ }
27
+
28
+ /** Every stored Cursor account. */
29
+ export function getCursorAccounts(): EngineAccount[] {
30
+ const provider = getCursorProvider();
31
+ return provider ? engineQueries.getAccountsByProvider(provider.id) : [];
32
+ }
33
+
34
+ /** The active Cursor account (or the most recently added one as a fallback). */
35
+ export function getActiveCursorAccount(): EngineAccount | null {
36
+ const active = engineQueries.getActiveAccountForEngine('cursor');
37
+ if (active) return active;
38
+ const accounts = getCursorAccounts();
39
+ return accounts.length ? accounts[accounts.length - 1] : null;
40
+ }
41
+
42
+ /** Parse a stored `engine_accounts.credential` blob into a Cursor credential. */
43
+ export function parseCursorCredential(stored: string | null | undefined): CursorCredential | null {
44
+ if (!stored) return null;
45
+ const trimmed = stored.trim();
46
+ if (!trimmed) return null;
47
+ if (trimmed.startsWith('{')) {
48
+ try {
49
+ const parsed = JSON.parse(trimmed) as Partial<CursorCredential>;
50
+ return parsed?.apiKey ? { apiKey: parsed.apiKey } : null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ // Raw API key.
56
+ return { apiKey: trimmed };
57
+ }
58
+
59
+ export function serializeCursorCredential(cred: CursorCredential): string {
60
+ return JSON.stringify(cred);
61
+ }
62
+
63
+ /** Resolve the API key for an account, throwing if it is unusable. */
64
+ export function resolveCursorApiKey(account: EngineAccount): string {
65
+ const parsed = parseCursorCredential(account.credential);
66
+ if (!parsed) throw new Error('Cursor account has no usable API key.');
67
+ return parsed.apiKey;
68
+ }