@myrialabs/clopen 0.4.15 → 0.4.16

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 (94) hide show
  1. package/backend/artifacts/matrix.ts +8 -0
  2. package/backend/artifacts/types.ts +2 -2
  3. package/backend/auth/permissions.ts +14 -0
  4. package/backend/chat/stream-manager.ts +5 -5
  5. package/backend/commands/detect.ts +1 -1
  6. package/backend/commands/sync.ts +1 -1
  7. package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
  8. package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
  9. package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
  10. package/backend/database/migrations/index.ts +21 -0
  11. package/backend/engine/README.md +36 -13
  12. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  13. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  14. package/backend/engine/adapters/cline/credential.ts +166 -0
  15. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  16. package/backend/engine/adapters/cline/index.ts +1 -0
  17. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  18. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  19. package/backend/engine/adapters/cline/models.ts +73 -0
  20. package/backend/engine/adapters/cline/presets.ts +128 -0
  21. package/backend/engine/adapters/cline/stream.ts +413 -0
  22. package/backend/engine/adapters/codex/credential.ts +1 -1
  23. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  24. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  25. package/backend/engine/adapters/codex/stream.ts +3 -3
  26. package/backend/engine/adapters/copilot/stream.ts +1 -1
  27. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  28. package/backend/engine/adapters/cursor/credential.ts +68 -0
  29. package/backend/engine/adapters/cursor/environment.ts +32 -0
  30. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  31. package/backend/engine/adapters/cursor/index.ts +1 -0
  32. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  33. package/backend/engine/adapters/cursor/models.ts +68 -0
  34. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  35. package/backend/engine/adapters/cursor/stream.ts +341 -0
  36. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  37. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  38. package/backend/engine/adapters/pi/credential.ts +137 -0
  39. package/backend/engine/adapters/pi/environment.ts +33 -0
  40. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  41. package/backend/engine/adapters/pi/index.ts +1 -0
  42. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  44. package/backend/engine/adapters/pi/models.ts +53 -0
  45. package/backend/engine/adapters/pi/presets.ts +133 -0
  46. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  47. package/backend/engine/adapters/pi/stream.ts +427 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  49. package/backend/engine/adapters/qwen/stream.ts +2 -2
  50. package/backend/engine/docs/adapter-contract.md +7 -2
  51. package/backend/engine/docs/adding-an-engine.md +70 -12
  52. package/backend/engine/docs/artifacts.md +124 -0
  53. package/backend/engine/docs/database.md +4 -4
  54. package/backend/engine/docs/frontend-and-chat.md +22 -4
  55. package/backend/engine/docs/lessons-learned.md +219 -32
  56. package/backend/engine/docs/quick-reference.md +18 -7
  57. package/backend/engine/docs/websocket-routes.md +2 -2
  58. package/backend/engine/index.ts +9 -0
  59. package/backend/mcp/README.md +3 -3
  60. package/backend/mcp/external/config.ts +11 -0
  61. package/backend/mcp/index.ts +8 -0
  62. package/backend/mcp/internal/config.ts +33 -1
  63. package/backend/permissions/service.ts +5 -2
  64. package/backend/skills/sync.ts +1 -1
  65. package/backend/subagents/detect.ts +1 -1
  66. package/backend/subagents/sync.ts +1 -1
  67. package/backend/ws/chat/stream.ts +1 -1
  68. package/backend/ws/engine/cline/accounts.ts +317 -0
  69. package/backend/ws/engine/cline/index.ts +15 -0
  70. package/backend/ws/engine/cline/presets.ts +36 -0
  71. package/backend/ws/engine/cline/status.ts +49 -0
  72. package/backend/ws/engine/codex/accounts.ts +1 -1
  73. package/backend/ws/engine/cursor/accounts.ts +162 -0
  74. package/backend/ws/engine/cursor/index.ts +13 -0
  75. package/backend/ws/engine/cursor/status.ts +55 -0
  76. package/backend/ws/engine/index.ts +6 -0
  77. package/backend/ws/engine/pi/accounts.ts +319 -0
  78. package/backend/ws/engine/pi/index.ts +15 -0
  79. package/backend/ws/engine/pi/presets.ts +34 -0
  80. package/backend/ws/engine/pi/status.ts +50 -0
  81. package/backend/ws/sessions/crud.ts +2 -2
  82. package/backend/ws/settings/crud.ts +2 -2
  83. package/dist/assets/{index-EunAFLxP.js → index-BPvctwJ2.js} +1 -1
  84. package/dist/assets/{index-ChF_jIXj.js → index-vLKZpWQH.js} +1 -1
  85. package/dist/assets/{main-CTs4NXwP.js → main-BtBZvCwv.js} +359 -357
  86. package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
  87. package/dist/index.html +2 -2
  88. package/package.json +7 -1
  89. package/shared/constants/engine-tools.ts +16 -2
  90. package/shared/constants/engines.ts +27 -0
  91. package/shared/types/unified/common.ts +1 -1
  92. package/shared/types/unified/engine.ts +82 -1
  93. package/shared/types/unified/index.ts +6 -0
  94. package/shared/types/unified/message.ts +1 -1
@@ -0,0 +1,615 @@
1
+ /**
2
+ * Cursor SDK → Unified Type Converter.
3
+ *
4
+ * `run.stream()` yields discrete `SDKMessage`s (Cursor's stream carries complete
5
+ * messages; token-level deltas ride the optional `onDelta` callback, not used
6
+ * here). We translate each into `EngineOutput`:
7
+ *
8
+ * system → SystemInitEvent (model + tool names)
9
+ * user → dropped (echoes the prompt; stream-manager persists the real one)
10
+ * assistant → AssistantMessage(s): one per text / tool_use block
11
+ * thinking → ReasoningMessage
12
+ * tool_call → tool_use AssistantMessage (running, if not already surfaced) +
13
+ * tool_result UserMessage (completed / error)
14
+ * usage → captured for the final ResultEvent
15
+ *
16
+ * Cursor built-in tool names (`read`, `edit`, `shell`, …) are canonicalised to the
17
+ * unified PascalCase names so the shared tool UI renders identically to the other
18
+ * engines. MCP tools route through `resolveOpenCodeToolName()` to recover their
19
+ * `mcp__<server>__<tool>` form.
20
+ */
21
+
22
+ import type {
23
+ MessageEngine,
24
+ EngineOutput,
25
+ UserMessage,
26
+ AssistantMessage,
27
+ ReasoningMessage,
28
+ ToolUseBlock,
29
+ UserContentBlock,
30
+ StreamLifecycleEvent,
31
+ TextDeltaEvent,
32
+ SuccessResultEvent,
33
+ SystemInitEvent,
34
+ TokenUsage,
35
+ AskUserQuestion,
36
+ } from '$shared/types/unified';
37
+ import { toCanonicalToolName } from '$shared/types/unified';
38
+ import type { SDKMessage, RunResult, TokenUsage as CursorTokenUsage } from '@cursor/sdk';
39
+ import { resolveOpenCodeToolName } from '../../../mcp';
40
+
41
+ // ============================================================
42
+ // Tool name + input normalisation
43
+ // ============================================================
44
+
45
+ const CURSOR_TOOL_NAME_MAP: Record<string, string> = {
46
+ read: 'Read',
47
+ write: 'Write',
48
+ edit: 'Edit',
49
+ ls: 'List',
50
+ glob: 'Glob',
51
+ grep: 'Grep',
52
+ shell: 'Bash',
53
+ task: 'Agent',
54
+ update_todos: 'TodoWrite',
55
+ updatetodos: 'TodoWrite',
56
+ // Cursor's `create_plan` records a markdown plan; the ExitPlanMode tool
57
+ // component renders `input.plan`, so it's the right unified home.
58
+ create_plan: 'ExitPlanMode',
59
+ createplan: 'ExitPlanMode',
60
+ web_search: 'WebSearch',
61
+ fetch: 'WebFetch',
62
+ };
63
+
64
+ function mapCursorToolName(rawName: string): string {
65
+ if (rawName.startsWith('mcp__')) return rawName;
66
+ const resolved = resolveOpenCodeToolName(rawName);
67
+ if (resolved) return resolved;
68
+ const mapped = CURSOR_TOOL_NAME_MAP[rawName.toLowerCase()] ?? rawName;
69
+ return toCanonicalToolName(mapped);
70
+ }
71
+
72
+ /**
73
+ * Cursor routes BOTH real MCP servers AND our in-process `customTools` through a
74
+ * single wrapper tool named `mcp`, with args `{ providerIdentifier, toolName, args }`:
75
+ * - real MCP → `{ providerIdentifier: 'clopen-mcp', toolName: 'open_new_tab', args: {…} }`
76
+ * - customTool→ `{ providerIdentifier: 'custom-user-tools', toolName: 'AskUserQuestion', args: {…} }`
77
+ * Unwrap it so the UI renders the proper `mcp__<server>__<tool>` / `AskUserQuestion`
78
+ * component instead of an `Unknown:mcp` block.
79
+ */
80
+ function isMcpWrapper(name: string, args: Record<string, unknown>): args is { toolName: string; args?: unknown } {
81
+ return name === 'mcp' && typeof args.toolName === 'string';
82
+ }
83
+
84
+ function canonicalCursorTool(name: string, args: Record<string, unknown>): string {
85
+ if (isMcpWrapper(name, args)) {
86
+ const bare = args.toolName;
87
+ return resolveOpenCodeToolName(bare) ?? toCanonicalToolName(bare);
88
+ }
89
+ return mapCursorToolName(name);
90
+ }
91
+
92
+ function cursorToolInput(name: string, args: Record<string, unknown>, result?: unknown): Record<string, unknown> {
93
+ if (isMcpWrapper(name, args)) {
94
+ const inner = (args.args && typeof args.args === 'object' ? args.args : {}) as Record<string, unknown>;
95
+ // Real MCP tools pass their args through unchanged; custom/unknown tools
96
+ // (e.g. AskUserQuestion) go through the per-tool normaliser.
97
+ return resolveOpenCodeToolName(args.toolName) ? inner : normaliseToolInput(toCanonicalToolName(args.toolName), inner, result);
98
+ }
99
+ return normaliseToolInput(mapCursorToolName(name), args, result);
100
+ }
101
+
102
+ function snakeToCamel(str: string): string {
103
+ return str.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
104
+ }
105
+
106
+ /** Map a Cursor todo status (`inProgress`/`cancelled`/…) to the unified UI status. */
107
+ function mapTodoStatus(status: unknown): 'pending' | 'in_progress' | 'completed' {
108
+ switch (status) {
109
+ case 'inProgress':
110
+ case 'in_progress':
111
+ return 'in_progress';
112
+ case 'completed':
113
+ case 'cancelled':
114
+ return 'completed';
115
+ default:
116
+ return 'pending';
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Freeze a snapshot of tool args. Cursor mutates some arg objects in place across
122
+ * a tool's streaming lifecycle (notably the `update_todos` list, whose statuses
123
+ * flip to "completed" as work progresses) — persisting a live reference captures
124
+ * that later state, so a just-created todo renders as already done. A structural
125
+ * clone at emit time pins the args to the moment the tool_use is surfaced.
126
+ */
127
+ function cloneArgs(raw: unknown): Record<string, unknown> {
128
+ if (!raw || typeof raw !== 'object') return {};
129
+ try {
130
+ return structuredClone(raw) as Record<string, unknown>;
131
+ } catch {
132
+ try {
133
+ return JSON.parse(JSON.stringify(raw)) as Record<string, unknown>;
134
+ } catch {
135
+ return raw as Record<string, unknown>;
136
+ }
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Extract a unified-diff string from a Cursor tool result (`edit` success carries
142
+ * `value.diffString`).
143
+ */
144
+ function extractDiffString(result: unknown): string | null {
145
+ const value = (result as { value?: { diffString?: unknown } })?.value;
146
+ return typeof value?.diffString === 'string' ? value.diffString : null;
147
+ }
148
+
149
+ /**
150
+ * Parse a unified diff into before/after text. Context lines (leading space)
151
+ * appear in BOTH sides; `-` lines are the old side, `+` lines the new side.
152
+ * File headers (`---`/`+++`) and hunk headers (`@@`) are skipped.
153
+ */
154
+ function parseUnifiedDiff(diff: string): { oldString: string; newString: string } {
155
+ const oldLines: string[] = [];
156
+ const newLines: string[] = [];
157
+ for (const line of diff.split('\n')) {
158
+ if (line.startsWith('---') || line.startsWith('+++') || line.startsWith('@@')) continue;
159
+ if (line.startsWith('-')) oldLines.push(line.slice(1));
160
+ else if (line.startsWith('+')) newLines.push(line.slice(1));
161
+ else if (line.startsWith(' ')) { oldLines.push(line.slice(1)); newLines.push(line.slice(1)); }
162
+ }
163
+ return { oldString: oldLines.join('\n'), newString: newLines.join('\n') };
164
+ }
165
+
166
+ /**
167
+ * Light per-tool input normalisation into the shared canonical shape. `result`
168
+ * (present at tool completion) is used for tools whose ARGS don't carry the
169
+ * user-visible payload — Cursor's `edit` args hold only `path`; the before/after
170
+ * lives in the result's `diffString`.
171
+ */
172
+ function normaliseToolInput(canonical: string, raw: Record<string, unknown>, result?: unknown): Record<string, unknown> {
173
+ switch (canonical) {
174
+ case 'Read':
175
+ return { filePath: String(raw.path ?? raw.file_path ?? raw.filePath ?? '') };
176
+ case 'Write':
177
+ return {
178
+ filePath: String(raw.path ?? raw.file_path ?? raw.filePath ?? ''),
179
+ content: String(raw.fileText ?? raw.contents ?? raw.content ?? raw.text ?? ''),
180
+ };
181
+ case 'Edit': {
182
+ const filePath = String(raw.path ?? raw.file_path ?? raw.filePath ?? '');
183
+ // Cursor edit args carry only `path`; recover old/new from the result diff.
184
+ const diff = extractDiffString(result);
185
+ if (diff) return { filePath, ...parseUnifiedDiff(diff) };
186
+ return {
187
+ filePath,
188
+ oldString: String(raw.old_string ?? raw.oldString ?? raw.old_str ?? ''),
189
+ newString: String(raw.new_string ?? raw.newString ?? raw.new_str ?? ''),
190
+ };
191
+ }
192
+ case 'Bash':
193
+ return { command: String(raw.command ?? raw.cmd ?? '') };
194
+ case 'Grep':
195
+ return {
196
+ pattern: String(raw.pattern ?? raw.query ?? raw.regex ?? ''),
197
+ ...(raw.path != null ? { path: String(raw.path) } : {}),
198
+ };
199
+ case 'Glob':
200
+ return { pattern: String(raw.globPattern ?? raw.pattern ?? raw.glob ?? raw.query ?? '') };
201
+ case 'Agent': {
202
+ // Cursor's `task` args carry `subagentType` as an OBJECT
203
+ // (`{ kind: 'custom', name: 'code-reviewer' }`); the unified AgentInput
204
+ // wants a plain string.
205
+ const st = raw.subagentType;
206
+ let subagentType = 'general-purpose';
207
+ if (typeof st === 'string') subagentType = st;
208
+ else if (st && typeof st === 'object') {
209
+ const o = st as { kind?: string; name?: string };
210
+ subagentType = o.name || o.kind || 'general-purpose';
211
+ }
212
+ return {
213
+ prompt: String(raw.prompt ?? ''),
214
+ description: String(raw.description ?? ''),
215
+ subagentType,
216
+ };
217
+ }
218
+ case 'List':
219
+ return {
220
+ ...(raw.path != null ? { path: String(raw.path) } : {}),
221
+ ...(Array.isArray(raw.ignore) ? { ignore: raw.ignore.map(String) } : {}),
222
+ };
223
+ case 'ExitPlanMode':
224
+ return { plan: String(raw.plan ?? '') };
225
+ case 'TodoWrite': {
226
+ // Cursor todo statuses are `pending | inProgress | completed | cancelled`;
227
+ // the unified/UI shape wants `pending | in_progress | completed`.
228
+ const todos = (Array.isArray(raw.todos) ? raw.todos : []).map((t) => {
229
+ const o = (t && typeof t === 'object' ? t : {}) as Record<string, unknown>;
230
+ const content = String(o.content ?? '');
231
+ return {
232
+ content,
233
+ status: mapTodoStatus(o.status),
234
+ activeForm: typeof o.activeForm === 'string' ? o.activeForm : content,
235
+ };
236
+ });
237
+ return { todos };
238
+ }
239
+ case 'AskUserQuestion':
240
+ return { questions: Array.isArray(raw.questions) ? raw.questions : [] };
241
+ default: {
242
+ const out: Record<string, unknown> = {};
243
+ for (const [k, v] of Object.entries(raw)) out[snakeToCamel(k)] = v;
244
+ return out;
245
+ }
246
+ }
247
+ }
248
+
249
+ // ============================================================
250
+ // Helper mappers
251
+ // ============================================================
252
+
253
+ function mapUsage(raw: CursorTokenUsage | null | undefined): TokenUsage {
254
+ return {
255
+ inputTokens: raw?.inputTokens ?? 0,
256
+ outputTokens: raw?.outputTokens ?? 0,
257
+ cacheCreationInputTokens: raw?.cacheWriteTokens ?? 0,
258
+ cacheReadInputTokens: raw?.cacheReadTokens ?? 0,
259
+ };
260
+ }
261
+
262
+ /** Read the text out of one Cursor/MCP content item (`{type:'text',text}`, Cursor's `{text:{text}}`, image → placeholder). */
263
+ function contentItemText(item: unknown): string {
264
+ if (typeof item === 'string') return item;
265
+ const it = item as { type?: string; text?: unknown; image?: unknown };
266
+ if (it?.type === 'text' && typeof it.text === 'string') return it.text;
267
+ if (it?.text && typeof it.text === 'object' && typeof (it.text as { text?: unknown }).text === 'string') return (it.text as { text: string }).text;
268
+ if (typeof it?.text === 'string') return it.text;
269
+ if (it?.image) return '[image]';
270
+ return '';
271
+ }
272
+
273
+ /**
274
+ * Extract plain text from a tool-call result. Cursor wraps results as
275
+ * `{ status, value }`, where `value` is `{ content: [...] }` (text/image items,
276
+ * incl. the nested `{text:{text}}` shape), `{ text }`, or `{ diffString }` (edit).
277
+ * Falls back to MCP-standard `{content:[{type:'text',text}]}` and JSON.
278
+ */
279
+ function extractResultText(result: unknown): string {
280
+ if (result == null) return '';
281
+ if (typeof result === 'string') return result;
282
+ const r = result as { value?: unknown; success?: unknown; content?: unknown; text?: unknown };
283
+ // Cursor wraps top-level tool results as `{status,value}` and sub-agent tool
284
+ // results as `{success:{…}}`; unwrap either.
285
+ const value = (r.value ?? r.success ?? r) as { content?: unknown; text?: unknown; diffString?: unknown };
286
+
287
+ if (Array.isArray(value.content)) {
288
+ const joined = value.content.map(contentItemText).filter(Boolean).join('\n').trim();
289
+ if (joined) return joined;
290
+ }
291
+ if (typeof value.content === 'string') return value.content;
292
+ if (typeof value.text === 'string') return value.text;
293
+ if (typeof value.diffString === 'string') return value.diffString;
294
+ if (typeof r.text === 'string') return r.text;
295
+ if (Array.isArray(r.content)) {
296
+ const joined = r.content.map(contentItemText).filter(Boolean).join('\n').trim();
297
+ if (joined) return joined;
298
+ }
299
+ try {
300
+ return JSON.stringify(result);
301
+ } catch {
302
+ return String(result);
303
+ }
304
+ }
305
+
306
+ // ============================================================
307
+ // Converter
308
+ // ============================================================
309
+
310
+ export interface CursorConverterOptions {
311
+ engine: MessageEngine;
312
+ sessionId: string;
313
+ }
314
+
315
+ export interface CursorMessageConverter {
316
+ convert(message: SDKMessage): EngineOutput[];
317
+ finalize(result: RunResult): EngineOutput[];
318
+ /** Surface an AskUserQuestion tool_use with complete questions (from the custom tool's execute). */
319
+ emitAskUserQuestion(toolCallId: string, questions: AskUserQuestion[]): EngineOutput[];
320
+ /** Stream ONE sub-agent step live (from a `tool-call-delta.taskUpdate`) as a child of the Agent block. */
321
+ emitSubagentActivity(agentToolId: string, taskUpdate: unknown): EngineOutput[];
322
+ }
323
+
324
+ export function createCursorMessageConverter(options: CursorConverterOptions): CursorMessageConverter {
325
+ const { engine, sessionId } = options;
326
+ /** Tool-call ids already surfaced as a tool_use block (avoid duplicates). */
327
+ const emittedToolUse = new Set<string>();
328
+ /** Agent (task) tool ids whose sub-agent steps were streamed live via onDelta. */
329
+ const streamedSubagents = new Set<string>();
330
+ let lastUsage: TokenUsage | null = null;
331
+ let turns = 0;
332
+ // ── Live-typing + accumulation state ──
333
+ // Cursor's `run.stream()` yields each text/thinking CHUNK as its own
334
+ // `assistant`/`thinking` SDKMessage (deltas, not snapshots). We stream each
335
+ // chunk live as a transient `stream_event` AND accumulate it into a buffer,
336
+ // flushing ONE consolidated `reasoning` / `assistant` message per block at a
337
+ // boundary (block switch, tool call, or turn end). Persisting each chunk
338
+ // separately was the bug behind dozens of fragmented one-word messages.
339
+ let textOpen = false;
340
+ let reasoningOpen = false;
341
+ let textBuffer = '';
342
+ let reasoningBuffer = '';
343
+
344
+ /** Flush the accumulated reasoning buffer as ONE ReasoningMessage (+ close its live stream). */
345
+ function flushReasoning(): EngineOutput[] {
346
+ const out: EngineOutput[] = [];
347
+ if (reasoningOpen) { out.push({ type: 'stream_event', event: 'stop', sessionId, reasoning: true }); reasoningOpen = false; }
348
+ const text = reasoningBuffer.trim();
349
+ reasoningBuffer = '';
350
+ if (text) {
351
+ out.push({
352
+ type: 'reasoning',
353
+ createdAt: new Date().toISOString(),
354
+ messageId: crypto.randomUUID(),
355
+ sessionId,
356
+ parent: { messageId: null, sessionId: null, toolUseId: null },
357
+ engine,
358
+ text,
359
+ } as ReasoningMessage);
360
+ }
361
+ return out;
362
+ }
363
+
364
+ /** Flush the accumulated text buffer as ONE AssistantMessage (+ close its live stream). */
365
+ function flushText(): EngineOutput[] {
366
+ const out: EngineOutput[] = [];
367
+ if (textOpen) { out.push({ type: 'stream_event', event: 'stop', sessionId, reasoning: false }); textOpen = false; }
368
+ const text = textBuffer;
369
+ textBuffer = '';
370
+ if (text.trim()) out.push(assistantMessage({ type: 'text', text }, false));
371
+ return out;
372
+ }
373
+
374
+ /** Flush both buffers (reasoning first, then text). */
375
+ function flushAll(): EngineOutput[] {
376
+ return [...flushReasoning(), ...flushText()];
377
+ }
378
+
379
+ /** Append a live text chunk: flush any open reasoning, stream the delta, accumulate. */
380
+ function appendText(chunk: string): EngineOutput[] {
381
+ const out: EngineOutput[] = flushReasoning();
382
+ if (!textOpen) { out.push({ type: 'stream_event', event: 'start', sessionId, reasoning: false } as StreamLifecycleEvent); textOpen = true; }
383
+ out.push({ type: 'stream_event', event: 'delta', sessionId, text: chunk, reasoning: false } as TextDeltaEvent);
384
+ textBuffer += chunk;
385
+ return out;
386
+ }
387
+
388
+ /** Append a live reasoning chunk: flush any open text, stream the delta, accumulate. */
389
+ function appendReasoning(chunk: string): EngineOutput[] {
390
+ const out: EngineOutput[] = flushText();
391
+ if (!reasoningOpen) { out.push({ type: 'stream_event', event: 'start', sessionId, reasoning: true } as StreamLifecycleEvent); reasoningOpen = true; }
392
+ out.push({ type: 'stream_event', event: 'delta', sessionId, text: chunk, reasoning: true } as TextDeltaEvent);
393
+ reasoningBuffer += chunk;
394
+ return out;
395
+ }
396
+
397
+ function assistantMessage(block: ToolUseBlock | { type: 'text'; text: string }, isTool: boolean, parentToolUseId: string | null = null): AssistantMessage {
398
+ return {
399
+ type: 'assistant',
400
+ createdAt: new Date().toISOString(),
401
+ messageId: crypto.randomUUID(),
402
+ sessionId,
403
+ parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId },
404
+ engine,
405
+ content: [block],
406
+ stopReason: isTool ? 'tool_use' : 'end_turn',
407
+ usage: null,
408
+ } as AssistantMessage;
409
+ }
410
+
411
+ function toolUseBlock(id: string, name: string, input: Record<string, unknown>): ToolUseBlock {
412
+ return {
413
+ type: 'tool_use',
414
+ id,
415
+ name,
416
+ input,
417
+ result: null,
418
+ subActivities: [],
419
+ skillPrompt: null,
420
+ interrupted: false,
421
+ } as ToolUseBlock;
422
+ }
423
+
424
+ function toolResultMessage(toolUseId: string, content: string, isError: boolean, parentToolUseId: string | null = null): UserMessage {
425
+ const block: UserContentBlock = { type: 'tool_result', toolUseId, content, isError };
426
+ return {
427
+ type: 'user',
428
+ createdAt: new Date().toISOString(),
429
+ messageId: crypto.randomUUID(),
430
+ sessionId,
431
+ parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId },
432
+ engine,
433
+ sender: { id: '', name: '' },
434
+ content: [block],
435
+ synthetic: true,
436
+ };
437
+ }
438
+
439
+ /**
440
+ * Cursor's `task` (Agent) tool runs the sub-agent internally and returns its
441
+ * FULL transcript in `result.value.conversationSteps[]` — the parent stream
442
+ * never sees the sub-agent's individual steps. We replay those steps as child
443
+ * messages tagged with `parent.toolUseId = <Agent block id>` so the frontend
444
+ * grouper folds them into the Agent block's `subActivities` (README §10.15).
445
+ * The sub-agent's final assistant text becomes the Agent tool's result.
446
+ */
447
+ function replaySubagent(result: unknown, agentToolId: string): { children: EngineOutput[]; finalText: string } {
448
+ const steps = (result as { value?: { conversationSteps?: unknown } })?.value?.conversationSteps;
449
+ if (!Array.isArray(steps)) return { children: [], finalText: extractResultText(result) };
450
+ const children: EngineOutput[] = [];
451
+ let finalText = '';
452
+ for (const step of steps as Array<Record<string, unknown>>) {
453
+ const asst = step.assistantMessage as { text?: unknown } | undefined;
454
+ if (asst && typeof asst.text === 'string' && asst.text.trim()) {
455
+ finalText = asst.text; // last assistant text = the sub-agent's answer (Agent result)
456
+ continue;
457
+ }
458
+ const tc = step.toolCall as Record<string, unknown> | undefined;
459
+ if (tc) {
460
+ const key = Object.keys(tc).find(k => k.endsWith('ToolCall'));
461
+ const inner = (key ? tc[key] : undefined) as { args?: unknown; result?: unknown } | undefined;
462
+ const toolCallId = String(tc.toolCallId ?? crypto.randomUUID());
463
+ const bare = key ? key.replace(/ToolCall$/, '') : 'tool';
464
+ const canonical = mapCursorToolName(bare);
465
+ const input = normaliseToolInput(canonical, (inner?.args && typeof inner.args === 'object' ? inner.args : {}) as Record<string, unknown>, inner?.result);
466
+ children.push(assistantMessage(toolUseBlock(toolCallId, canonical, input), true, agentToolId));
467
+ children.push(toolResultMessage(toolCallId, extractResultText(inner?.result), false, agentToolId));
468
+ }
469
+ }
470
+ return { children, finalText: finalText || extractResultText(result) };
471
+ }
472
+
473
+ function convert(message: SDKMessage): EngineOutput[] {
474
+ switch (message.type) {
475
+ case 'system': {
476
+ const init: SystemInitEvent = {
477
+ type: 'system_init',
478
+ sessionId,
479
+ model: message.model?.id ?? engine.model.id,
480
+ engine: 'cursor',
481
+ tools: message.tools ?? [],
482
+ mcpServers: [],
483
+ };
484
+ return [init];
485
+ }
486
+
487
+ case 'user':
488
+ // Echo of the prompt — the stream-manager persists the real user message.
489
+ return [];
490
+
491
+ case 'assistant': {
492
+ const out: EngineOutput[] = [];
493
+ let countedTurn = false;
494
+ for (const block of message.message.content) {
495
+ if (block.type === 'text') {
496
+ if (!countedTurn) { turns += 1; countedTurn = true; }
497
+ // Stream the chunk live + accumulate into ONE assistant message.
498
+ if (block.text) out.push(...appendText(block.text));
499
+ } else if (block.type === 'tool_use') {
500
+ // A tool call ends the current text/reasoning block — flush first.
501
+ out.push(...flushAll());
502
+ const canonical = mapCursorToolName(block.name);
503
+ emittedToolUse.add(block.id);
504
+ const input = normaliseToolInput(canonical, (block.input && typeof block.input === 'object' ? block.input : {}) as Record<string, unknown>);
505
+ out.push(assistantMessage(toolUseBlock(block.id, canonical, input), true));
506
+ }
507
+ }
508
+ return out;
509
+ }
510
+
511
+ case 'thinking':
512
+ // Stream the reasoning chunk live + accumulate into ONE reasoning message.
513
+ return message.text ? appendReasoning(message.text) : [];
514
+
515
+ case 'tool_call': {
516
+ // A tool call ends the current text/reasoning block — flush first.
517
+ const out: EngineOutput[] = flushAll();
518
+ // Freeze the args now — Cursor mutates some in place (e.g. update_todos).
519
+ const args = cloneArgs(message.args);
520
+ const canonical = canonicalCursorTool(message.name, args);
521
+ const terminal = message.status === 'completed' || message.status === 'error';
522
+
523
+ // `create_plan` proposes a plan FOR THE USER TO READ. Render it as normal
524
+ // assistant markdown (not an internal-looking tool card) so it's legible.
525
+ if (canonical === 'ExitPlanMode') {
526
+ if (terminal) {
527
+ const plan = String((args as { plan?: unknown }).plan ?? '');
528
+ if (plan.trim()) out.push(assistantMessage({ type: 'text', text: plan }, false));
529
+ }
530
+ return out;
531
+ }
532
+
533
+ // Surface the tool_use block ONCE. `edit` carries its before/after only
534
+ // in the result diff, so defer its tool_use to completion; all other
535
+ // tools emit on first sighting so the "running" state shows live.
536
+ // AskUserQuestion is emitted separately via emitAskUserQuestion() with
537
+ // the complete question set (stream args can arrive empty), so skip it here.
538
+ const deferForResult = canonical === 'Edit';
539
+ const skipToolUse = canonical === 'AskUserQuestion';
540
+ if (!emittedToolUse.has(message.call_id) && !skipToolUse && (!deferForResult || terminal)) {
541
+ emittedToolUse.add(message.call_id);
542
+ const input = cursorToolInput(message.name, args, terminal ? message.result : undefined);
543
+ out.push(assistantMessage(toolUseBlock(message.call_id, canonical, input), true));
544
+ }
545
+
546
+ if (terminal) {
547
+ if (canonical === 'Agent') {
548
+ // The sub-agent's steps stream live via onDelta taskUpdates
549
+ // (emitSubagentActivity). Only replay from the result as a FALLBACK
550
+ // when nothing was streamed. Always attach its final answer as the
551
+ // Agent tool's result.
552
+ const { children, finalText } = replaySubagent(message.result, message.call_id);
553
+ if (!streamedSubagents.has(message.call_id)) out.push(...children);
554
+ out.push(toolResultMessage(message.call_id, finalText, message.status === 'error'));
555
+ } else {
556
+ out.push(toolResultMessage(message.call_id, extractResultText(message.result), message.status === 'error'));
557
+ }
558
+ }
559
+ return out;
560
+ }
561
+
562
+ case 'usage':
563
+ lastUsage = mapUsage(message.usage);
564
+ return [];
565
+
566
+ default:
567
+ return [];
568
+ }
569
+ }
570
+
571
+ function finalize(result: RunResult): EngineOutput[] {
572
+ // Flush any buffered reasoning/text as their consolidated messages.
573
+ const out: EngineOutput[] = flushAll();
574
+ if (result.usage) lastUsage = mapUsage(result.usage);
575
+ const event: SuccessResultEvent = {
576
+ type: 'result',
577
+ subtype: 'success',
578
+ sessionId,
579
+ numTurns: turns,
580
+ totalCostUsd: 0,
581
+ usage: lastUsage ?? { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0 },
582
+ stopReason: result.status === 'cancelled' ? 'interrupted' : 'end_turn',
583
+ };
584
+ out.push(event);
585
+ return out;
586
+ }
587
+
588
+ function emitAskUserQuestion(toolCallId: string, questions: AskUserQuestion[]): EngineOutput[] {
589
+ const out: EngineOutput[] = flushAll();
590
+ emittedToolUse.add(toolCallId);
591
+ out.push(assistantMessage(toolUseBlock(toolCallId, 'AskUserQuestion', { questions: Array.isArray(questions) ? questions : [] }), true));
592
+ return out;
593
+ }
594
+
595
+ function emitSubagentActivity(agentToolId: string, taskUpdate: unknown): EngineOutput[] {
596
+ const tu = taskUpdate as { type?: string; callId?: string; toolCall?: { type?: string; args?: unknown; result?: unknown } };
597
+ // Surface completed sub-agent tool calls (they carry both args + result) as
598
+ // child tool_use + tool_result tagged with the Agent block id, so the
599
+ // frontend folds them into subActivities as they happen.
600
+ if (tu.type !== 'tool-call-completed' || !tu.toolCall) return [];
601
+ streamedSubagents.add(agentToolId);
602
+ const tc = tu.toolCall;
603
+ const innerId = String(tu.callId ?? crypto.randomUUID());
604
+ const args = (tc.args && typeof tc.args === 'object' ? tc.args : {}) as Record<string, unknown>;
605
+ const name = tc.type ?? 'tool';
606
+ const canonical = canonicalCursorTool(name, args);
607
+ const input = cursorToolInput(name, args, tc.result);
608
+ return [
609
+ assistantMessage(toolUseBlock(innerId, canonical, input), true, agentToolId),
610
+ toolResultMessage(innerId, extractResultText(tc.result), false, agentToolId),
611
+ ];
612
+ }
613
+
614
+ return { convert, finalize, emitAskUserQuestion, emitSubagentActivity };
615
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Cursor dynamic model discovery.
3
+ *
4
+ * `Cursor.models.list({ apiKey })` returns the models available to the
5
+ * authenticated key (e.g. `composer-2.5`). We translate each into an
6
+ * `EngineModel`. Returns `[]` on any failure (no account, bad key, network) —
7
+ * the shared dynamic-catalog contract (the picker renders empty rather than a
8
+ * stale list; mirrors OpenCode/Qwen/Cline).
9
+ *
10
+ * Per-model parameter variants (e.g. a `fast` toggle) are not surfaced yet — the
11
+ * base model id is exposed and the SDK resolves the default variant.
12
+ *
13
+ * `Cursor.models.list()` is a cloud endpoint that 403s with `plan_required` for
14
+ * free-tier keys. Rather than strand those users with an empty picker, we fall
15
+ * back to a small static catalog of known Cursor models when the listing is
16
+ * unavailable (empty or errored). Only a missing account/key returns `[]`.
17
+ */
18
+
19
+ import { Cursor } from '@cursor/sdk';
20
+ import type { EngineModel } from '$shared/types/unified';
21
+ import { debug } from '$shared/utils/logger';
22
+ import { getActiveCursorAccount, parseCursorCredential } from './credential';
23
+
24
+ /** Known Cursor model ids used when `Cursor.models.list()` is unavailable. */
25
+ const CURSOR_FALLBACK_MODEL_IDS = ['composer-2.5'];
26
+
27
+ export async function fetchCursorModels(): Promise<EngineModel[]> {
28
+ const account = getActiveCursorAccount();
29
+ if (!account) return [];
30
+ const apiKey = parseCursorCredential(account.credential)?.apiKey;
31
+ if (!apiKey) return [];
32
+
33
+ try {
34
+ const models = await Cursor.models.list({ apiKey });
35
+ if (models.length) {
36
+ debug.log('engine', `Cursor getAvailableModels: ${models.length} models`);
37
+ return models.map(m => makeModel(m.id, m.displayName || m.id));
38
+ }
39
+ debug.warn('engine', 'Cursor models.list returned empty — using fallback catalog');
40
+ } catch (error) {
41
+ debug.warn('engine', `Cursor model discovery failed (${error instanceof Error ? error.message : String(error)}) — using fallback catalog`);
42
+ }
43
+ return CURSOR_FALLBACK_MODEL_IDS.map(id => makeModel(id, id));
44
+ }
45
+
46
+ function makeModel(id: string, name: string): EngineModel {
47
+ return {
48
+ engine: {
49
+ type: 'cursor',
50
+ provider: 'cursor',
51
+ model: { id, name },
52
+ account: { id: 0, name: '' },
53
+ },
54
+ // Cursor's models.list() does NOT report a context window; leave 0 so the
55
+ // UI shows "unknown" (a "?") rather than a fabricated/hardcoded max.
56
+ limit: { input: 0, output: 0 },
57
+ modalities: {
58
+ input: { text: true, image: true, audio: false, video: false, pdf: false },
59
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
60
+ },
61
+ capabilities: {
62
+ reasoning: true,
63
+ tools: true,
64
+ structuredOutput: false,
65
+ },
66
+ cost: { input: 0, output: 0 },
67
+ };
68
+ }