@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,49 @@
1
+ /**
2
+ * Cline SDK error handler.
3
+ *
4
+ * Mirrors the Pi/Qwen pattern: swallow abort errors, normalise the common
5
+ * categories (missing auth, quota, bad model) and otherwise surface a sanitised
6
+ * message. Cline runs in-process (stateless `Agent`), so there is no CLI stderr
7
+ * tail to fold in.
8
+ */
9
+
10
+ export function handleStreamError(error: unknown): void {
11
+ if (!(error instanceof Error)) {
12
+ throw error;
13
+ }
14
+
15
+ if (
16
+ error.name === 'AbortError'
17
+ || error.name === 'AgentRuntimeAbortError'
18
+ || error.message.includes('aborted')
19
+ || error.message.includes('abort')
20
+ || error.message === 'Operation aborted'
21
+ ) {
22
+ return;
23
+ }
24
+
25
+ const lower = error.message.toLowerCase();
26
+
27
+ if (
28
+ lower.includes('no api key')
29
+ || lower.includes('not authenticated')
30
+ || lower.includes('unauthorized')
31
+ || lower.includes('401')
32
+ || lower.includes('no auth')
33
+ || lower.includes('invalid api key')
34
+ || lower.includes('not subscribed')
35
+ ) {
36
+ throw new Error('Cline is not authenticated for the selected provider. Add or re-authenticate the account in Settings → Engines → Cline.');
37
+ }
38
+
39
+ if (lower.includes('quota') || lower.includes('insufficient_quota') || lower.includes('429') || lower.includes('rate limit')) {
40
+ throw new Error('Cline provider quota/rate limit exceeded. Check your balance or switch account.');
41
+ }
42
+
43
+ if (lower.includes('model not found') || lower.includes('does not exist') || lower.includes('unsupported model') || lower.includes('no model')) {
44
+ throw new Error('Cline could not resolve the selected model for this account. Pick a model your provider supports.');
45
+ }
46
+
47
+ const message = error.message.replace(/^Error:\s*/, '') || error.name || 'Unknown error';
48
+ throw new Error(message);
49
+ }
@@ -0,0 +1 @@
1
+ export { ClineEngine } from './stream';
@@ -0,0 +1,119 @@
1
+ /**
2
+ * MCP → Cline custom-tool bridge.
3
+ *
4
+ * We drive Cline through the stateless `Agent`, which runs IN-PROCESS, so we
5
+ * don't need the `/mcp` HTTP bridge the subprocess engines use: we expose each
6
+ * enabled Clopen MCP tool directly as a Cline custom tool (`createTool`) whose
7
+ * `execute` calls the tool handler in-process.
8
+ *
9
+ * - INTERNAL servers (`defineServer()` — e.g. browser-automation): the handler
10
+ * runs bound to the stream's project context (AsyncLocalStorage) with an
11
+ * abort short-circuit, exactly like Claude's in-process path.
12
+ * - EXTERNAL servers (user-installed, `mcp_servers` table): proxied to the
13
+ * upstream server via `callExternalServerTool`.
14
+ *
15
+ * Tool names use the canonical `mcp__<namespace>__<tool>` form so the unified UI
16
+ * + `toCanonicalToolName()` render them identically to the other engines.
17
+ */
18
+
19
+ import { createTool } from '@cline/sdk';
20
+ import type { AgentTool, AgentToolContext } from '@cline/sdk';
21
+ import type { McpExecutionContext } from '../../types';
22
+ import {
23
+ getEnabledServerNames,
24
+ isToolEnabled,
25
+ getEnabledExternalServers,
26
+ listExternalServerTools,
27
+ callExternalServerTool,
28
+ projectContextService,
29
+ serverMetadata,
30
+ } from '../../../mcp';
31
+ import { debug } from '$shared/utils/logger';
32
+
33
+ type McpContentItem = { type: string; text?: string; data?: string; mimeType?: string };
34
+
35
+ /** Permissive object schema — arguments are validated by the tool handler. */
36
+ const OPEN_PARAMS = { type: 'object', additionalProperties: true } as const;
37
+
38
+ /** Extract plain text from an MCP content array for the model to read. */
39
+ function toResultText(raw: unknown): string {
40
+ const items = Array.isArray(raw) ? (raw as McpContentItem[]) : [];
41
+ const parts: string[] = [];
42
+ for (const item of items) {
43
+ if (typeof item?.text === 'string') {
44
+ parts.push(item.text);
45
+ } else if (item?.type === 'image') {
46
+ parts.push('[image]');
47
+ } else if (item != null) {
48
+ parts.push(JSON.stringify(item));
49
+ }
50
+ }
51
+ return parts.join('\n');
52
+ }
53
+
54
+ /**
55
+ * Build the set of Cline custom tools mirroring every enabled internal + external
56
+ * MCP tool. Scoped to the active Profile via `profileFilter` (server ids).
57
+ */
58
+ export async function buildClineMcpTools(
59
+ context: McpExecutionContext | undefined,
60
+ profileFilter: Set<string> | undefined,
61
+ ): Promise<AgentTool[]> {
62
+ const tools: AgentTool[] = [];
63
+
64
+ // ── Internal servers (in-process handlers) ──
65
+ for (const serverName of getEnabledServerNames()) {
66
+ if (profileFilter && !profileFilter.has(serverName)) continue;
67
+ const meta = (serverMetadata as Record<string, { tools: readonly string[]; toolDefs: Record<string, { description: string; schema: Record<string, unknown>; handler: (args: unknown) => Promise<{ content: McpContentItem[]; isError?: boolean }> }> }>)[serverName];
68
+ if (!meta) continue;
69
+
70
+ for (const toolName of meta.tools) {
71
+ if (!isToolEnabled(serverName, toolName)) continue;
72
+ const def = meta.toolDefs[toolName];
73
+ if (!def) continue;
74
+ const fullName = `mcp__${serverName}__${toolName}`;
75
+ const argKeys = Object.keys(def.schema ?? {});
76
+ tools.push(createTool({
77
+ name: fullName,
78
+ description: `${def.description}${argKeys.length ? `\n\nArguments: ${argKeys.join(', ')}` : ''}`,
79
+ inputSchema: OPEN_PARAMS,
80
+ async execute(params: unknown) {
81
+ const run = async () => {
82
+ const signal = projectContextService.getCurrentSignal();
83
+ if (signal?.aborted) return `Tool ${fullName} was cancelled.`;
84
+ const result = await def.handler(params ?? {});
85
+ return toResultText(result?.content);
86
+ };
87
+ return context ? projectContextService.runWithContextAsync(context, run) : run();
88
+ },
89
+ }) as AgentTool);
90
+ }
91
+ }
92
+
93
+ // ── External servers (proxied upstream) ──
94
+ for (const server of getEnabledExternalServers(profileFilter)) {
95
+ let externalTools;
96
+ try {
97
+ externalTools = await listExternalServerTools(server.slug);
98
+ } catch (error) {
99
+ debug.warn('mcp', `Cline MCP bridge: could not list tools for "${server.slug}" (skipping):`, error);
100
+ continue;
101
+ }
102
+ for (const tool of externalTools) {
103
+ const fullName = `mcp__${server.namespace}__${tool.name}`;
104
+ const schemaText = tool.inputSchema ? `\n\nInput JSON schema:\n${JSON.stringify(tool.inputSchema)}` : '';
105
+ tools.push(createTool({
106
+ name: fullName,
107
+ description: `${tool.description ?? tool.name}${schemaText}`,
108
+ inputSchema: OPEN_PARAMS,
109
+ async execute(params: unknown) {
110
+ const result = (await callExternalServerTool(server.slug, tool.name, params ?? {})) as { content?: unknown } | undefined;
111
+ return toResultText(result?.content);
112
+ },
113
+ }) as AgentTool);
114
+ }
115
+ }
116
+
117
+ debug.log('mcp', `Cline MCP bridge: ${tools.length} tool(s) exposed`);
118
+ return tools;
119
+ }
@@ -0,0 +1,396 @@
1
+ /**
2
+ * Cline SDK → Unified Type Converter.
3
+ *
4
+ * Translates `AgentRuntimeEvent`s (the `Agent`/`AgentRuntime` subscribe stream)
5
+ * into `EngineOutput`. Cline is push/subscribe rather than an async generator, so
6
+ * the engine bridges subscribe → generator and feeds each event through
7
+ * `convert()` here (see ./stream.ts).
8
+ *
9
+ * Event mapping:
10
+ * - `assistant-text-delta` / `assistant-reasoning-delta` → live `stream_event`s
11
+ * - `assistant-message` → ReasoningMessage + AssistantMessage(s)
12
+ * - `tool-finished` → tool_result UserMessage
13
+ * - `usage-updated` → accumulate totals
14
+ * - `run-finished` → success ResultEvent
15
+ *
16
+ * Cline built-in tool names are snake_case (`read_files`, `run_commands`, …); we
17
+ * canonicalise them to the unified PascalCase names + normalise input field names
18
+ * so the shared tool UI renders identically to Claude/Codex. MCP tools already
19
+ * arrive as `mcp__<server>__<tool>` from the bridge (see ./mcp-tools.ts).
20
+ */
21
+
22
+ import type {
23
+ AgentRuntimeEvent,
24
+ AgentMessage,
25
+ AgentMessagePart,
26
+ AgentToolCallPart,
27
+ AgentUsage,
28
+ AgentModelFinishReason,
29
+ } from '@cline/agents';
30
+ import type {
31
+ MessageEngine,
32
+ EngineOutput,
33
+ UserMessage,
34
+ AssistantMessage,
35
+ ReasoningMessage,
36
+ AssistantContentBlock,
37
+ ToolUseBlock,
38
+ TextDeltaEvent,
39
+ StreamLifecycleEvent,
40
+ SuccessResultEvent,
41
+ NotificationEvent,
42
+ TokenUsage,
43
+ StopReason,
44
+ } from '$shared/types/unified';
45
+ import { toCanonicalToolName } from '$shared/types/unified';
46
+
47
+ // ============================================================
48
+ // Tool name + input normalisation
49
+ // ============================================================
50
+
51
+ const CLINE_TOOL_NAME_MAP: Record<string, string> = {
52
+ read_files: 'Read',
53
+ editor: 'Edit',
54
+ run_commands: 'Bash',
55
+ search_codebase: 'Grep',
56
+ fetch_web_content: 'WebFetch',
57
+ apply_patch: 'Patch',
58
+ skills: 'Skill',
59
+ ask_question: 'AskUserQuestion',
60
+ };
61
+
62
+ function canonicaliseToolName(rawName: string): string {
63
+ if (rawName.startsWith('mcp__')) return rawName;
64
+ return CLINE_TOOL_NAME_MAP[rawName] ?? rawName;
65
+ }
66
+
67
+ function snakeToCamel(str: string): string {
68
+ return str.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
69
+ }
70
+
71
+ /** Pull the first file path out of Cline's flexible read/edit file shapes. */
72
+ function firstPath(raw: Record<string, unknown>): string | undefined {
73
+ const direct = (raw.filePath ?? raw.file_path ?? raw.path) as string | undefined;
74
+ if (direct) return direct;
75
+ const files = (raw.files ?? raw.paths) as unknown;
76
+ if (Array.isArray(files) && files.length) {
77
+ const f = files[0];
78
+ if (typeof f === 'string') return f;
79
+ if (f && typeof f === 'object') return ((f as Record<string, unknown>).path ?? (f as Record<string, unknown>).file_path ?? (f as Record<string, unknown>).filePath) as string | undefined;
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ function normaliseToolInput(canonical: string, raw: Record<string, unknown>): Record<string, unknown> {
85
+ switch (canonical) {
86
+ case 'Read': {
87
+ const path = firstPath(raw);
88
+ return { ...(path !== undefined ? { filePath: path } : {}) };
89
+ }
90
+ case 'Edit': {
91
+ const path = firstPath(raw);
92
+ const oldString = (raw.oldString ?? raw.old_text ?? raw.old_string ?? raw.oldText) as string | undefined;
93
+ const newString = (raw.newString ?? raw.new_text ?? raw.new_string ?? raw.newText) as string | undefined;
94
+ return {
95
+ ...(path !== undefined ? { filePath: path } : {}),
96
+ ...(oldString !== undefined && oldString !== null ? { oldString } : {}),
97
+ ...(newString !== undefined ? { newString } : {}),
98
+ };
99
+ }
100
+ case 'Bash': {
101
+ const commands = raw.commands as unknown;
102
+ let command: string | undefined;
103
+ if (Array.isArray(commands)) command = commands.filter(c => typeof c === 'string').join(' && ');
104
+ else command = (raw.command ?? raw.cmd) as string | undefined;
105
+ return { ...(command ? { command } : {}) };
106
+ }
107
+ case 'Grep': {
108
+ const queries = raw.queries as unknown;
109
+ let pattern: string | undefined;
110
+ if (Array.isArray(queries)) pattern = queries.filter(q => typeof q === 'string').join('|');
111
+ else pattern = (raw.pattern ?? raw.query ?? raw.regex) as string | undefined;
112
+ const path = (raw.path ?? raw.directory) as string | undefined;
113
+ return { ...(pattern ? { pattern } : {}), ...(path !== undefined ? { path } : {}) };
114
+ }
115
+ case 'WebFetch': {
116
+ const requests = raw.requests as unknown;
117
+ let url: string | undefined;
118
+ let prompt: string | undefined;
119
+ if (Array.isArray(requests) && requests.length && typeof requests[0] === 'object') {
120
+ const r = requests[0] as Record<string, unknown>;
121
+ url = r.url as string | undefined;
122
+ prompt = r.prompt as string | undefined;
123
+ } else {
124
+ url = raw.url as string | undefined;
125
+ prompt = raw.prompt as string | undefined;
126
+ }
127
+ return { ...(url ? { url } : {}), ...(prompt ? { prompt } : {}) };
128
+ }
129
+ case 'Patch': {
130
+ const patch = (raw.input ?? raw.patch ?? raw.diff) as string | undefined;
131
+ const path = firstPath(raw);
132
+ return { filePath: path ?? '', ...(patch ? { patch } : {}) };
133
+ }
134
+ case 'Skill': {
135
+ const skill = (raw.skill ?? raw.name) as string | undefined;
136
+ const args = (raw.args ?? undefined) as string | undefined;
137
+ return { ...(skill ? { skill } : {}), ...(args ? { args } : {}) };
138
+ }
139
+ case 'AskUserQuestion': {
140
+ return { questions: Array.isArray(raw.questions) ? raw.questions : [] };
141
+ }
142
+ default: {
143
+ const out: Record<string, unknown> = {};
144
+ for (const [k, v] of Object.entries(raw)) out[snakeToCamel(k)] = v;
145
+ return out;
146
+ }
147
+ }
148
+ }
149
+
150
+ // ============================================================
151
+ // Helper mappers
152
+ // ============================================================
153
+
154
+ function mapFinishReason(raw: AgentModelFinishReason | null | undefined): StopReason | null {
155
+ switch (raw) {
156
+ case 'stop': return 'end_turn';
157
+ case 'tool-calls': return 'tool_use';
158
+ case 'max-tokens': return 'max_tokens';
159
+ case 'aborted': return 'interrupted';
160
+ case 'error': return 'end_turn';
161
+ default: return null;
162
+ }
163
+ }
164
+
165
+ function mapUsage(raw: Partial<AgentUsage> | null | undefined): TokenUsage {
166
+ return {
167
+ inputTokens: raw?.inputTokens ?? 0,
168
+ outputTokens: raw?.outputTokens ?? 0,
169
+ cacheCreationInputTokens: raw?.cacheWriteTokens ?? 0,
170
+ cacheReadInputTokens: raw?.cacheReadTokens ?? 0,
171
+ };
172
+ }
173
+
174
+ /** Extract plain text from a tool-result part output (string / MCP content / object). */
175
+ function extractResultText(output: unknown): string {
176
+ if (output == null) return '';
177
+ if (typeof output === 'string') return output;
178
+ const r = output as { content?: unknown; text?: unknown };
179
+ if (typeof r.text === 'string') return r.text;
180
+ if (Array.isArray(r.content)) {
181
+ return r.content
182
+ .map((c: unknown) => {
183
+ const item = c as { type?: string; text?: string };
184
+ return item?.type === 'text' && typeof item.text === 'string' ? item.text : '';
185
+ })
186
+ .filter(Boolean)
187
+ .join('\n');
188
+ }
189
+ try {
190
+ return JSON.stringify(output);
191
+ } catch {
192
+ return String(output);
193
+ }
194
+ }
195
+
196
+ // ============================================================
197
+ // Converter
198
+ // ============================================================
199
+
200
+ export interface ClineConverterOptions {
201
+ engine: MessageEngine;
202
+ sessionId: string;
203
+ }
204
+
205
+ export interface ClineMessageConverter {
206
+ convert(event: AgentRuntimeEvent): EngineOutput[];
207
+ readonly totalUsage: TokenUsage;
208
+ readonly totalCostUsd: number;
209
+ readonly turns: number;
210
+ }
211
+
212
+ export function createClineMessageConverter(options: ClineConverterOptions): ClineMessageConverter {
213
+ const { engine, sessionId } = options;
214
+ let totalUsage: TokenUsage = { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0 };
215
+ let totalCostUsd = 0;
216
+ let turns = 0;
217
+ let emittedContent = false;
218
+ // Live-typing lifecycle flags — which delta stream is currently open.
219
+ let textOpen = false;
220
+ let reasoningOpen = false;
221
+
222
+ function closeStreams(): StreamLifecycleEvent[] {
223
+ const out: StreamLifecycleEvent[] = [];
224
+ if (textOpen) { out.push({ type: 'stream_event', event: 'stop', sessionId, reasoning: false }); textOpen = false; }
225
+ if (reasoningOpen) { out.push({ type: 'stream_event', event: 'stop', sessionId, reasoning: true }); reasoningOpen = false; }
226
+ return out;
227
+ }
228
+
229
+ function mapAssistantContent(parts: readonly AgentMessagePart[]): { reasoning: string; blocks: AssistantContentBlock[] } {
230
+ let reasoning = '';
231
+ const blocks: AssistantContentBlock[] = [];
232
+ for (const part of parts) {
233
+ if (part.type === 'reasoning') {
234
+ if (part.text) reasoning += (reasoning ? '\n' : '') + part.text;
235
+ } else if (part.type === 'text') {
236
+ if (part.text.trim()) blocks.push({ type: 'text', text: part.text });
237
+ } else if (part.type === 'tool-call') {
238
+ const call = part as AgentToolCallPart;
239
+ const canonical = canonicaliseToolName(call.toolName);
240
+ const finalName = toCanonicalToolName(canonical);
241
+ const rawInput = (call.input && typeof call.input === 'object' ? call.input : {}) as Record<string, unknown>;
242
+ blocks.push({
243
+ type: 'tool_use',
244
+ id: call.toolCallId,
245
+ name: finalName,
246
+ input: normaliseToolInput(canonical, rawInput),
247
+ result: null,
248
+ subActivities: [],
249
+ skillPrompt: null,
250
+ interrupted: false,
251
+ } as ToolUseBlock);
252
+ }
253
+ }
254
+ return { reasoning, blocks };
255
+ }
256
+
257
+ function convertAssistantMessage(msg: AgentMessage, finishReason: AgentModelFinishReason): EngineOutput[] {
258
+ const outputs: EngineOutput[] = [];
259
+ const { reasoning, blocks } = mapAssistantContent(msg.content);
260
+ const usage = msg.metrics ? mapUsage(msg.metrics) : null;
261
+
262
+ if (reasoning.trim()) {
263
+ emittedContent = true;
264
+ outputs.push({
265
+ type: 'reasoning',
266
+ createdAt: new Date().toISOString(),
267
+ messageId: crypto.randomUUID(),
268
+ sessionId,
269
+ parent: { messageId: null, sessionId: null, toolUseId: null },
270
+ engine,
271
+ text: reasoning,
272
+ } as ReasoningMessage);
273
+ }
274
+
275
+ if (blocks.length === 0) return outputs;
276
+ emittedContent = true;
277
+
278
+ const baseId = crypto.randomUUID();
279
+ if (blocks.length === 1) {
280
+ outputs.push({
281
+ type: 'assistant',
282
+ createdAt: new Date().toISOString(),
283
+ messageId: baseId,
284
+ sessionId,
285
+ parent: { messageId: null, sessionId: null, toolUseId: null },
286
+ engine,
287
+ content: blocks,
288
+ stopReason: blocks[0].type === 'tool_use' ? 'tool_use' : mapFinishReason(finishReason),
289
+ usage,
290
+ } as AssistantMessage);
291
+ } else {
292
+ // One tool_use per AssistantMessage (README §10.3).
293
+ blocks.forEach((block, idx) => {
294
+ outputs.push({
295
+ type: 'assistant',
296
+ createdAt: new Date().toISOString(),
297
+ messageId: `${baseId}:${idx}`,
298
+ sessionId,
299
+ parent: { messageId: null, sessionId: null, toolUseId: null },
300
+ engine,
301
+ content: [block],
302
+ stopReason: block.type === 'tool_use' ? 'tool_use' : mapFinishReason(finishReason),
303
+ usage: idx === blocks.length - 1 ? usage : null,
304
+ } as AssistantMessage);
305
+ });
306
+ }
307
+ return outputs;
308
+ }
309
+
310
+ function convertToolResults(msg: AgentMessage): UserMessage[] {
311
+ const out: UserMessage[] = [];
312
+ for (const part of msg.content) {
313
+ if (part.type !== 'tool-result') continue;
314
+ emittedContent = true;
315
+ out.push({
316
+ type: 'user',
317
+ createdAt: new Date().toISOString(),
318
+ messageId: crypto.randomUUID(),
319
+ sessionId,
320
+ parent: { messageId: null, sessionId: null, toolUseId: null },
321
+ engine,
322
+ sender: { id: '', name: '' },
323
+ content: [{ type: 'tool_result', toolUseId: part.toolCallId, content: extractResultText(part.output), isError: !!part.isError }],
324
+ synthetic: true,
325
+ });
326
+ }
327
+ return out;
328
+ }
329
+
330
+ function convert(event: AgentRuntimeEvent): EngineOutput[] {
331
+ switch (event.type) {
332
+ case 'assistant-text-delta': {
333
+ const out: EngineOutput[] = [];
334
+ if (reasoningOpen) { out.push({ type: 'stream_event', event: 'stop', sessionId, reasoning: true }); reasoningOpen = false; }
335
+ if (!textOpen) { out.push({ type: 'stream_event', event: 'start', sessionId, reasoning: false } as StreamLifecycleEvent); textOpen = true; }
336
+ out.push({ type: 'stream_event', event: 'delta', sessionId, text: event.text || '', reasoning: false } as TextDeltaEvent);
337
+ return out;
338
+ }
339
+ case 'assistant-reasoning-delta': {
340
+ const out: EngineOutput[] = [];
341
+ if (textOpen) { out.push({ type: 'stream_event', event: 'stop', sessionId, reasoning: false }); textOpen = false; }
342
+ if (!reasoningOpen) { out.push({ type: 'stream_event', event: 'start', sessionId, reasoning: true } as StreamLifecycleEvent); reasoningOpen = true; }
343
+ out.push({ type: 'stream_event', event: 'delta', sessionId, text: event.text || '', reasoning: true } as TextDeltaEvent);
344
+ return out;
345
+ }
346
+ case 'assistant-message': {
347
+ turns += 1;
348
+ const out: EngineOutput[] = [...closeStreams()];
349
+ out.push(...convertAssistantMessage(event.message, event.finishReason));
350
+ return out;
351
+ }
352
+ case 'tool-finished':
353
+ return convertToolResults(event.message);
354
+ case 'usage-updated': {
355
+ totalUsage = mapUsage(event.usage);
356
+ if (typeof event.usage.totalCost === 'number') totalCostUsd = event.usage.totalCost;
357
+ return [];
358
+ }
359
+ case 'run-finished': {
360
+ const outputs: EngineOutput[] = [...closeStreams()];
361
+ if (event.result?.usage) {
362
+ totalUsage = mapUsage(event.result.usage);
363
+ if (typeof event.result.usage.totalCost === 'number') totalCostUsd = event.result.usage.totalCost;
364
+ }
365
+ if (!emittedContent) {
366
+ outputs.push({
367
+ type: 'notification',
368
+ sessionId,
369
+ level: 'warning',
370
+ title: 'Empty response',
371
+ message: 'Cline returned an empty response. Try again or rephrase your prompt.',
372
+ } as NotificationEvent);
373
+ }
374
+ outputs.push({
375
+ type: 'result',
376
+ subtype: 'success',
377
+ sessionId,
378
+ numTurns: turns,
379
+ totalCostUsd,
380
+ usage: { ...totalUsage },
381
+ stopReason: null,
382
+ } as SuccessResultEvent);
383
+ return outputs;
384
+ }
385
+ default:
386
+ return [];
387
+ }
388
+ }
389
+
390
+ return {
391
+ convert,
392
+ get totalUsage() { return totalUsage; },
393
+ get totalCostUsd() { return totalCostUsd; },
394
+ get turns() { return turns; },
395
+ };
396
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Cline dynamic model discovery.
3
+ *
4
+ * Cline resolves models from the `@cline/llms` catalog. We enumerate every
5
+ * provider that has a stored Clopen account and translate its catalog models
6
+ * into `EngineModel`s.
7
+ *
8
+ * `engine.provider` carries the Cline provider id (e.g. 'anthropic', 'openai')
9
+ * so the chat's send path can resolve the matching account by provider. Returns
10
+ * `[]` on any failure (mirrors the OpenCode/Qwen/Pi dynamic-catalog contract —
11
+ * the picker renders empty rather than a stale list).
12
+ */
13
+
14
+ import { Llms } from '@cline/sdk';
15
+ import type { EngineModel } from '$shared/types/unified';
16
+ import { debug } from '$shared/utils/logger';
17
+ import { getClineAccounts, parseClineCredential } from './credential';
18
+
19
+ type CatalogModel = Awaited<ReturnType<typeof Llms.getModelsForProvider>>[string];
20
+
21
+ export async function fetchClineModels(): Promise<EngineModel[]> {
22
+ try {
23
+ // Distinct providers that have at least one stored account.
24
+ const providers = new Set<string>();
25
+ for (const account of getClineAccounts()) {
26
+ const parsed = parseClineCredential(account.credential);
27
+ if (parsed) providers.add(parsed.provider);
28
+ }
29
+
30
+ const out: EngineModel[] = [];
31
+ for (const providerId of providers) {
32
+ let models: Record<string, CatalogModel>;
33
+ try {
34
+ models = await Llms.getModelsForProvider(providerId);
35
+ } catch (error) {
36
+ debug.warn('engine', `Cline: could not list models for provider "${providerId}": ${error instanceof Error ? error.message : String(error)}`);
37
+ continue;
38
+ }
39
+ for (const [modelId, info] of Object.entries(models)) {
40
+ out.push(mapClineModel(providerId, modelId, info));
41
+ }
42
+ }
43
+ debug.log('engine', `Cline getAvailableModels: ${out.length} models across ${providers.size} provider(s)`);
44
+ return out;
45
+ } catch (error) {
46
+ debug.warn('engine', `Cline model discovery failed: ${error instanceof Error ? error.message : String(error)}`);
47
+ return [];
48
+ }
49
+ }
50
+
51
+ function mapClineModel(providerId: string, modelId: string, info: CatalogModel): EngineModel {
52
+ const caps = info.capabilities ?? [];
53
+ const image = caps.includes('images');
54
+ return {
55
+ engine: {
56
+ type: 'cline',
57
+ provider: providerId,
58
+ model: { id: modelId, name: info.name || modelId },
59
+ account: { id: 0, name: '' },
60
+ },
61
+ limit: { input: info.contextWindow ?? 0, output: info.maxTokens ?? 0 },
62
+ modalities: {
63
+ input: { text: true, image, audio: false, video: false, pdf: false },
64
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
65
+ },
66
+ capabilities: {
67
+ reasoning: caps.includes('reasoning'),
68
+ tools: caps.includes('tools'),
69
+ structuredOutput: caps.includes('structured_output'),
70
+ },
71
+ cost: { input: info.pricing?.input ?? 0, output: info.pricing?.output ?? 0 },
72
+ };
73
+ }