@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,68 @@
1
+ /**
2
+ * Cursor fork-on-resume.
3
+ *
4
+ * Clopen's multi-branch checkpoints require every resumed turn to fork so the
5
+ * source branch's history is never mutated (README §10.10). Cursor has no native
6
+ * fork — `Agent.resume(agentId)` continues the SAME agent in place — so we fork by
7
+ * copying the parent agent's persisted state under a fresh `agentId`:
8
+ *
9
+ * 1. read the parent agent document (metadata + `latestCheckpoint` pointer)
10
+ * 2. copy every content-addressed checkpoint blob to the new agent id
11
+ * 3. write a new agent document seeded with the parent's checkpoint pointer
12
+ *
13
+ * The conversation transcript lives in the checkpoint blobs, so the resumed agent
14
+ * replays the exact ancestor branch. Runs / run-events (the streaming log) are
15
+ * intentionally NOT copied — they are per-turn history, not conversation context.
16
+ *
17
+ * Returns the new agent id, or `undefined` when the parent is missing on disk
18
+ * (evicted / cross-restart) so the caller can gracefully start a fresh agent.
19
+ */
20
+
21
+ import type { JsonlLocalAgentStore } from '@cursor/sdk';
22
+ import { debug } from '$shared/utils/logger';
23
+
24
+ /** Page through a checkpoint blob-id listing (id-based cursor). */
25
+ async function listAllCheckpointBlobIds(store: JsonlLocalAgentStore, agentId: string): Promise<string[]> {
26
+ const ids: string[] = [];
27
+ let cursor: string | undefined;
28
+ do {
29
+ const page = await store.checkpoints.list({ filter: { agentIds: [agentId], cursor, limit: 500 } });
30
+ ids.push(...page.items);
31
+ cursor = page.nextCursor;
32
+ } while (cursor);
33
+ return ids;
34
+ }
35
+
36
+ export async function forkCursorAgent(store: JsonlLocalAgentStore, parentAgentId: string): Promise<string | undefined> {
37
+ const parent = await store.agents.get({ agentId: parentAgentId });
38
+ if (!parent) {
39
+ debug.warn('engine', `Cursor fork: parent agent ${parentAgentId} not found on disk, starting fresh`);
40
+ return undefined;
41
+ }
42
+
43
+ const newAgentId = `agent-${crypto.randomUUID()}`;
44
+
45
+ // Copy every checkpoint blob (content-addressed) to the new agent id.
46
+ const blobIds = await listAllCheckpointBlobIds(store, parentAgentId);
47
+ for (const blobId of blobIds) {
48
+ const data = await store.checkpoints.get({ agentId: parentAgentId, blobId });
49
+ if (data) await store.checkpoints.create({ agentId: newAgentId, blobId, data });
50
+ }
51
+
52
+ // Seed the new agent document with the parent's checkpoint pointer. `Date.now()`
53
+ // is fine here (backend runtime, not a workflow script).
54
+ const now = Date.now();
55
+ await store.agents.create({
56
+ agent: {
57
+ ...parent,
58
+ agentId: newAgentId,
59
+ status: 'idle',
60
+ activeRunId: null,
61
+ createdAt: now,
62
+ updatedAt: now,
63
+ },
64
+ });
65
+
66
+ debug.log('engine', `Cursor resumed agent ${parentAgentId} → fork ${newAgentId} (${blobIds.length} checkpoint blob(s))`);
67
+ return newAgentId;
68
+ }
@@ -0,0 +1,341 @@
1
+ /**
2
+ * Cursor Engine Adapter
3
+ *
4
+ * Wraps `@cursor/sdk` into the AIEngine interface. Key choices:
5
+ *
6
+ * 1. **Local agents.** `Agent.create({ local: { cwd, store } })` runs the coding
7
+ * agent in-process against the project workspace. Cloud agents (Cursor VMs +
8
+ * GitHub repos) don't fit Clopen's local-project workflow and can't take the
9
+ * in-process custom tools we need, so they're not used.
10
+ * 2. **Native async-generator stream.** `agent.send()` returns a `Run` whose
11
+ * `run.stream()` is already an `AsyncGenerator<SDKMessage>` — no subscribe
12
+ * bridge (unlike Cline/Pi). The message-converter maps each event.
13
+ * 3. **Single-account, API-key auth.** One `CURSOR_API_KEY` per account, passed
14
+ * to `Agent.create({ apiKey })`; multi-account is a pure DB `is_active` swap.
15
+ * 4. **Isolated JSONL store + fork-on-resume.** State lives in Clopen's isolated
16
+ * engine dir via a `JsonlLocalAgentStore` (never `~/.cursor`); every resume
17
+ * forks by copying the parent agent's checkpoints (README §10.10 / §10.19).
18
+ *
19
+ * MCP servers ride Cursor's native `mcpServers` config (the shared `clopen-mcp`
20
+ * bridge). AskUserQuestion is bridged as an in-process custom tool. Subagents map
21
+ * to Cursor's native `agents` config.
22
+ */
23
+
24
+ import { Agent, Cursor } from '@cursor/sdk';
25
+ import type { SDKAgent, Run, SDKUserMessage, SDKImage, AgentDefinition, SDKCustomTool } from '@cursor/sdk';
26
+ import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
27
+ import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
28
+ import { resolveOsPath } from '$backend/utils/paths';
29
+ import { debug } from '$shared/utils/logger';
30
+ import { engineQueries } from '$backend/database/queries/engine-queries';
31
+ import { syncSkills } from '$backend/skills';
32
+ import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
33
+ import { artifactFilter } from '$backend/profiles';
34
+ import { getCursorMcpConfig } from '../../../mcp';
35
+ import { subagentQueries } from '$backend/database/queries';
36
+ import { readSubagentMd } from '$backend/subagents/store';
37
+ import { buildJsonPrompt, extractJson } from '../../structured-helpers';
38
+ import { getActiveCursorAccount, resolveCursorApiKey } from './credential';
39
+ import { getCursorStore } from './environment';
40
+ import { forkCursorAgent } from './session-fork';
41
+ import { fetchCursorModels } from './models';
42
+ import { createAskUserQuestionTool, formatAnswers, type PendingAsk } from './ask-question-tool';
43
+ import { createCursorMessageConverter } from './message-converter';
44
+ import { handleStreamError } from './error-handler';
45
+
46
+ /** Strip YAML frontmatter from a subagent markdown doc, leaving the instructions. */
47
+ function stripFrontmatter(md: string): string {
48
+ const match = md.match(/^---\n[\s\S]*?\n---\n?/);
49
+ return (match ? md.slice(match[0].length) : md).trim();
50
+ }
51
+
52
+ /**
53
+ * Minimal pushable queue merging Cursor's pull stream (`run.stream()`) with the
54
+ * push emissions of the in-process AskUserQuestion custom tool into one ordered
55
+ * async generator. The ask tool fires from inside the SDK's tool executor (a
56
+ * separate async flow from the stream loop), so a plain `for await` can't carry
57
+ * its emission — the queue is the merge point.
58
+ */
59
+ class EventQueue<T> {
60
+ private buffer: T[] = [];
61
+ private wake: (() => void) | null = null;
62
+ private done = false;
63
+ private error: unknown = null;
64
+
65
+ push(value: T): void { this.buffer.push(value); this.signal(); }
66
+ close(): void { this.done = true; this.signal(); }
67
+ fail(error: unknown): void { this.error = error; this.done = true; this.signal(); }
68
+
69
+ private signal(): void {
70
+ const wake = this.wake;
71
+ this.wake = null;
72
+ wake?.();
73
+ }
74
+
75
+ async *drain(): AsyncGenerator<T, void, unknown> {
76
+ while (true) {
77
+ while (this.buffer.length) yield this.buffer.shift() as T;
78
+ if (this.error) throw this.error;
79
+ if (this.done) return;
80
+ await new Promise<void>((resolve) => { this.wake = resolve; });
81
+ }
82
+ }
83
+ }
84
+
85
+ export class CursorEngine implements AIEngine {
86
+ readonly name = 'cursor' as const;
87
+ private _isInitialized = false;
88
+ private activeController: AbortController | null = null;
89
+ private activeRun: Run | null = null;
90
+ private activeAgent: SDKAgent | null = null;
91
+ private pendingAsks = new Map<string, PendingAsk>();
92
+
93
+ get isInitialized(): boolean { return this._isInitialized; }
94
+ get isActive(): boolean { return this.activeController !== null; }
95
+
96
+ async initialize(): Promise<void> {
97
+ if (this._isInitialized) return;
98
+ this._isInitialized = true;
99
+ debug.log('engine', '✅ Cursor engine initialized');
100
+ }
101
+
102
+ async dispose(): Promise<void> {
103
+ await this.cancel();
104
+ this.pendingAsks.clear();
105
+ this._isInitialized = false;
106
+ }
107
+
108
+ async getAvailableModels(): Promise<EngineModel[]> {
109
+ return fetchCursorModels();
110
+ }
111
+
112
+ /** Build the `agents` config from Clopen's enabled subagents (Cursor-native). */
113
+ private async buildAgents(): Promise<Record<string, AgentDefinition> | undefined> {
114
+ const subagents = subagentQueries.getEnabled();
115
+ if (subagents.length === 0) return undefined;
116
+ const agents: Record<string, AgentDefinition> = {};
117
+ for (const s of subagents) {
118
+ const md = (await readSubagentMd(s.slug)) ?? '';
119
+ const prompt = stripFrontmatter(md) || `You are the ${s.name} subagent. ${s.description}`;
120
+ agents[s.slug] = { description: s.description || s.name, prompt, model: 'inherit' };
121
+ }
122
+ return agents;
123
+ }
124
+
125
+ async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
126
+ const { projectPath, prompt, resume, modelId, abortController, accountId } = options;
127
+ debug.log('chat', 'Cursor - Stream Query', { modelId, resume });
128
+
129
+ // ── Resolve account + API key ──
130
+ const account = (accountId != null ? engineQueries.getAccount(accountId) : null) ?? getActiveCursorAccount();
131
+ if (!account) {
132
+ throw new Error('Cursor is not configured. Add an API key in Settings → Engines → Cursor.');
133
+ }
134
+ const apiKey = resolveCursorApiKey(account);
135
+
136
+ this.activeController = abortController || new AbortController();
137
+ const resolvedProjectPath = resolveOsPath(projectPath);
138
+
139
+ // ── Active Profile scoping + artifact materialization ──
140
+ const profileId = options.mcpContext?.profileId;
141
+ const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
142
+ await syncSkills('cursor', profileId);
143
+ await syncEngineArtifacts('cursor', profileId);
144
+
145
+ // ── Output queue merging the pull stream with the ask tool's push emissions ──
146
+ const queue = new EventQueue<EngineOutput>();
147
+ const converterHolder: { current: ReturnType<typeof createCursorMessageConverter> | null } = { current: null };
148
+
149
+ // ── Tools: AskUserQuestion (in-process custom tool) + MCP (native config) ──
150
+ const askTool: SDKCustomTool = createAskUserQuestionTool({
151
+ register: (id, entry) => this.pendingAsks.set(id, entry),
152
+ unregister: (id) => this.pendingAsks.delete(id),
153
+ // Emit the tool_use with the COMPLETE questions from execute's args.
154
+ emit: (id, questions) => {
155
+ const c = converterHolder.current;
156
+ if (c) for (const out of c.emitAskUserQuestion(id, questions)) queue.push(out);
157
+ },
158
+ });
159
+ const customTools: Record<string, SDKCustomTool> = { AskUserQuestion: askTool };
160
+ const mcpServers = getCursorMcpConfig(mcpProfileFilter);
161
+ const agents = await this.buildAgents();
162
+
163
+ const store = getCursorStore(projectPath);
164
+ const engineMeta: MessageEngine = {
165
+ type: 'cursor',
166
+ provider: 'cursor',
167
+ model: { id: modelId, name: modelId },
168
+ account: { id: account.id, name: account.name },
169
+ };
170
+
171
+ // ── Resume / fork (branch-aware) ──
172
+ // `resume` is the parent agent id. We ALWAYS fork (copy the parent's
173
+ // checkpoints under a fresh agent id) so sibling branches stay isolated.
174
+ let forkedAgentId: string | undefined;
175
+ if (resume) {
176
+ try {
177
+ forkedAgentId = await forkCursorAgent(store, resume);
178
+ } catch (error) {
179
+ debug.warn('engine', `Cursor fork failed (${error instanceof Error ? error.message : String(error)}), starting fresh`);
180
+ }
181
+ }
182
+
183
+ const localOptions = { cwd: resolvedProjectPath, store, customTools };
184
+ let agent: SDKAgent;
185
+ try {
186
+ agent = forkedAgentId
187
+ ? await Agent.resume(forkedAgentId, {
188
+ apiKey,
189
+ model: { id: modelId },
190
+ local: localOptions,
191
+ ...(Object.keys(mcpServers).length ? { mcpServers } : {}),
192
+ ...(agents ? { agents } : {}),
193
+ })
194
+ : await Agent.create({
195
+ apiKey,
196
+ model: { id: modelId },
197
+ local: localOptions,
198
+ ...(Object.keys(mcpServers).length ? { mcpServers } : {}),
199
+ ...(agents ? { agents } : {}),
200
+ });
201
+ } catch (error) {
202
+ this.activeController = null;
203
+ handleStreamError(error);
204
+ return;
205
+ }
206
+ this.activeAgent = agent;
207
+ const sessionId = agent.agentId;
208
+
209
+ const converter = createCursorMessageConverter({ engine: engineMeta, sessionId });
210
+ converterHolder.current = converter;
211
+
212
+ // Build the user turn (text + image attachments).
213
+ const promptText = prompt.content.filter(b => b.type === 'text').map(b => (b.type === 'text' ? b.text : '')).join('\n');
214
+ const artifacts = buildArtifactsPromptContext(profileId);
215
+ const text = artifacts ? `${artifacts}\n\n${promptText}` : promptText;
216
+ const images: SDKImage[] = [];
217
+ for (const b of prompt.content) {
218
+ if (b.type === 'image') images.push({ data: b.data, mimeType: b.mediaType });
219
+ }
220
+ const userMessage: SDKUserMessage = { text, ...(images.length ? { images } : {}) };
221
+
222
+ // Cursor's `run.stream()` yields each text/thinking chunk as its own
223
+ // SDKMessage; the converter streams every chunk live as a transient
224
+ // stream_event AND accumulates it, flushing ONE consolidated reasoning /
225
+ // assistant message per block. The pull stream + the ask tool's push
226
+ // emissions are merged through the queue.
227
+ let onAbort: (() => void) | null = null;
228
+ try {
229
+ const run = await agent.send(userMessage, {
230
+ model: { id: modelId },
231
+ // Sub-agent (Task) steps aren't in `run.stream()` — they ride
232
+ // `tool-call-delta.taskUpdate` here. Stream each completed sub-agent
233
+ // tool call live as a child of the Agent block (parent.toolUseId).
234
+ onDelta: ({ update }) => {
235
+ const u = update as { type?: string; callId?: string; taskUpdate?: unknown };
236
+ if (u.type === 'tool-call-delta' && u.taskUpdate && u.callId) {
237
+ const c = converterHolder.current;
238
+ if (c) for (const out of c.emitSubagentActivity(u.callId, u.taskUpdate)) queue.push(out);
239
+ }
240
+ },
241
+ });
242
+ this.activeRun = run;
243
+
244
+ // Abort wiring: cancelling the stream cancels the Cursor run.
245
+ onAbort = () => { run.cancel().catch(() => { /* already terminal */ }); };
246
+ this.activeController.signal.addEventListener('abort', onAbort, { once: true });
247
+
248
+ // Drive the pull stream + result in the background, funnelling into the queue.
249
+ const settle = (async () => {
250
+ try {
251
+ if (run.supports('stream')) {
252
+ for await (const message of run.stream()) {
253
+ for (const out of converter.convert(message)) queue.push(out);
254
+ }
255
+ }
256
+ const result = await run.wait();
257
+ for (const out of converter.finalize(result)) queue.push(out);
258
+ queue.close();
259
+ } catch (error) {
260
+ queue.fail(error);
261
+ }
262
+ })();
263
+
264
+ for await (const out of queue.drain()) yield out;
265
+ await settle;
266
+ } catch (error) {
267
+ handleStreamError(error);
268
+ } finally {
269
+ if (onAbort) this.activeController?.signal.removeEventListener('abort', onAbort);
270
+ try { agent.close(); } catch { /* fire-and-forget */ }
271
+ this.activeRun = null;
272
+ this.activeAgent = null;
273
+ this.activeController = null;
274
+ this.pendingAsks.clear();
275
+ }
276
+ }
277
+
278
+ async cancel(): Promise<void> {
279
+ // Release any parked AskUserQuestion callbacks so a blocked run can settle.
280
+ for (const [, pending] of this.pendingAsks) {
281
+ pending.resolve('User did not answer the question.');
282
+ }
283
+ this.pendingAsks.clear();
284
+
285
+ // Abort the local controller first (cuts the for-await loop), then RPC.
286
+ if (this.activeController && !this.activeController.signal.aborted) {
287
+ this.activeController.abort();
288
+ }
289
+ this.activeController = null;
290
+
291
+ if (this.activeRun) {
292
+ try { await this.activeRun.cancel(); } catch { /* may already be terminal */ }
293
+ }
294
+ this.activeRun = null;
295
+ this.activeAgent = null;
296
+ }
297
+
298
+ async interrupt(): Promise<void> {
299
+ if (this.activeRun) {
300
+ try { await this.activeRun.cancel(); } catch { /* ignore */ }
301
+ }
302
+ }
303
+
304
+ resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
305
+ const pending = this.pendingAsks.get(toolUseId);
306
+ if (!pending) {
307
+ debug.warn('engine', `Cursor resolveUserAnswer: no pending question for ${toolUseId}`);
308
+ return false;
309
+ }
310
+ pending.resolve(formatAnswers(pending.questions, answers));
311
+ this.pendingAsks.delete(toolUseId);
312
+ return true;
313
+ }
314
+
315
+ /**
316
+ * One-shot structured JSON generation. Cursor local agents always expose the
317
+ * built-in coding tools, so we instruct the model to answer with JSON only and
318
+ * parse the final result text.
319
+ */
320
+ async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
321
+ const { prompt, modelId, schema, projectPath, accountId } = options;
322
+
323
+ const account = (accountId != null ? engineQueries.getAccount(accountId) : null) ?? getActiveCursorAccount();
324
+ if (!account) throw new Error('Cursor is not configured.');
325
+ const apiKey = resolveCursorApiKey(account);
326
+
327
+ const agent = await Agent.create({
328
+ apiKey,
329
+ model: { id: modelId },
330
+ local: { cwd: resolveOsPath(projectPath), store: getCursorStore(projectPath) },
331
+ });
332
+ try {
333
+ const run = await agent.send(buildJsonPrompt(prompt, schema));
334
+ const result = await run.wait();
335
+ if (!result.result?.trim()) throw new Error('Cursor returned no structured output');
336
+ return extractJson<T>(result.result);
337
+ } finally {
338
+ try { agent.close(); } catch { /* ignore */ }
339
+ }
340
+ }
341
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Subagent dispatch tool for Pi.
3
+ *
4
+ * Pi has no native Agent/Task primitive, so the synthetic "Available Subagents"
5
+ * preamble (materialized into AGENTS.md) is informational only — the model can
6
+ * describe subagents but can't invoke them. This custom `Agent` tool closes that
7
+ * gap: calling it spawns a fresh sub-session with the subagent's system prompt,
8
+ * runs the delegated prompt to completion, and returns the final text as the
9
+ * tool result. Sub-activity does not stream to the main UI (it runs inside the
10
+ * tool), but the delegation actually happens.
11
+ */
12
+
13
+ import { Type } from 'typebox';
14
+ import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
15
+
16
+ export interface SubagentInfo {
17
+ slug: string;
18
+ name: string;
19
+ description: string;
20
+ }
21
+
22
+ export interface AgentDispatchBindings {
23
+ /** Enabled subagents advertised to the model. */
24
+ subagents: SubagentInfo[];
25
+ /**
26
+ * Run one subagent against a prompt; resolve with its final text output.
27
+ * `toolCallId` is the parent Agent tool_use id — the runner tags the
28
+ * subagent's messages with it so they render as sub-activities.
29
+ */
30
+ run: (subagent: SubagentInfo, prompt: string, toolCallId: string, signal?: AbortSignal) => Promise<string>;
31
+ }
32
+
33
+ const AGENT_PARAMS = Type.Object({
34
+ subagentType: Type.String({ description: 'The slug of the subagent to delegate to.' }),
35
+ description: Type.String({ description: 'A short (3-5 word) description of the delegated task.' }),
36
+ prompt: Type.String({ description: 'The full, self-contained task/instructions for the subagent.' }),
37
+ });
38
+
39
+ export function createAgentDispatchTool(bindings: AgentDispatchBindings): ToolDefinition {
40
+ const catalog = bindings.subagents.map(s => `- ${s.slug}: ${s.name} — ${s.description}`).join('\n');
41
+ return {
42
+ name: 'Agent',
43
+ label: 'Agent',
44
+ description:
45
+ 'Delegate a self-contained subtask to a specialized subagent. Pass the subagent slug as `subagentType` and the task as `prompt`. Available subagents:\n' + catalog,
46
+ parameters: AGENT_PARAMS,
47
+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) => {
48
+ const p = params as { subagentType?: string; prompt?: string };
49
+ const match = bindings.subagents.find(s => s.slug === p.subagentType || s.name === p.subagentType);
50
+ if (!match) {
51
+ const names = bindings.subagents.map(s => s.slug).join(', ') || '(none configured)';
52
+ return { content: [{ type: 'text' as const, text: `No subagent named "${p.subagentType}". Available: ${names}` }], details: {} };
53
+ }
54
+ try {
55
+ const text = await bindings.run(match, p.prompt ?? '', _toolCallId, signal);
56
+ return { content: [{ type: 'text' as const, text: text.trim() || '(subagent produced no output)' }], details: {} };
57
+ } catch (error) {
58
+ return { content: [{ type: 'text' as const, text: `Subagent "${match.slug}" failed: ${error instanceof Error ? error.message : String(error)}` }], details: {} };
59
+ }
60
+ },
61
+ } as ToolDefinition;
62
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * AskUserQuestion custom tool for Pi.
3
+ *
4
+ * Pi's native `ask_question` tool has no headless answer path (it drives the
5
+ * TUI). We exclude it and register our own canonical `AskUserQuestion` tool that
6
+ * BLOCKS until the user answers through the chat UI — the same contract Claude's
7
+ * `canUseTool` provides, but modelled as a tool because Pi's block hook can't
8
+ * hold the model waiting.
9
+ *
10
+ * The tool's `execute` returns a promise the engine resolves via
11
+ * `resolveUserAnswer(toolCallId, answers)`. The converter renders the tool_use
12
+ * block (name `AskUserQuestion`) so the frontend shows the dialog; the resolved
13
+ * tool result carries the formatted answers.
14
+ */
15
+
16
+ import { Type } from 'typebox';
17
+ import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
18
+ import type { AgentToolResult } from '@earendil-works/pi-agent-core';
19
+ import type { AskUserQuestion } from '$shared/types/unified';
20
+
21
+ export interface PendingAsk {
22
+ questions: AskUserQuestion[];
23
+ resolve: (result: AgentToolResult<unknown>) => void;
24
+ }
25
+
26
+ export interface AskToolBindings {
27
+ register: (toolCallId: string, entry: PendingAsk) => void;
28
+ unregister: (toolCallId: string) => void;
29
+ }
30
+
31
+ /** Format the user's answers in the shared OpenCode/Qwen wording. */
32
+ export function formatAnswers(questions: AskUserQuestion[], answers: Record<string, string>): string {
33
+ const pairs: string[] = [];
34
+ for (const [key, value] of Object.entries(answers)) {
35
+ const idx = Number.parseInt(key, 10);
36
+ const q = Number.isFinite(idx) ? questions[idx] : undefined;
37
+ const label = q?.question ?? q?.header ?? key;
38
+ pairs.push(`"${label}"="${value}"`);
39
+ }
40
+ if (pairs.length === 0) return 'User did not provide any answers.';
41
+ return `User has answered your questions: ${pairs.join(', ')}. You can now continue with the user's answers in mind.`;
42
+ }
43
+
44
+ function cancelledResult(): AgentToolResult<unknown> {
45
+ return { content: [{ type: 'text', text: 'User did not answer the question.' }], details: {} };
46
+ }
47
+
48
+ const ASK_PARAMS = Type.Object({
49
+ questions: Type.Array(
50
+ Type.Object({
51
+ question: Type.String(),
52
+ header: Type.String(),
53
+ multiSelect: Type.Boolean(),
54
+ options: Type.Array(
55
+ Type.Object({
56
+ label: Type.String(),
57
+ description: Type.String(),
58
+ }),
59
+ ),
60
+ }),
61
+ ),
62
+ });
63
+
64
+ export function createAskUserQuestionTool(bindings: AskToolBindings): ToolDefinition {
65
+ return {
66
+ name: 'AskUserQuestion',
67
+ label: 'Ask User Question',
68
+ description:
69
+ '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.',
70
+ parameters: ASK_PARAMS,
71
+ execute: async (toolCallId: string, params: unknown, signal?: AbortSignal) => {
72
+ const questions = ((params as { questions?: AskUserQuestion[] })?.questions ?? []) as AskUserQuestion[];
73
+ return new Promise<AgentToolResult<unknown>>((resolve) => {
74
+ if (signal?.aborted) {
75
+ resolve(cancelledResult());
76
+ return;
77
+ }
78
+ const onAbort = () => {
79
+ bindings.unregister(toolCallId);
80
+ resolve(cancelledResult());
81
+ };
82
+ signal?.addEventListener('abort', onAbort, { once: true });
83
+ bindings.register(toolCallId, {
84
+ questions,
85
+ resolve: (result) => {
86
+ signal?.removeEventListener('abort', onAbort);
87
+ resolve(result);
88
+ },
89
+ });
90
+ });
91
+ },
92
+ } as ToolDefinition;
93
+ }