@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.
- package/README.md +8 -5
- package/backend/artifacts/matrix.ts +8 -0
- package/backend/artifacts/types.ts +2 -2
- package/backend/auth/permissions.ts +14 -0
- package/backend/chat/stream-manager.ts +5 -5
- package/backend/commands/detect.ts +1 -1
- package/backend/commands/sync.ts +1 -1
- package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
- package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
- package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
- package/backend/database/migrations/index.ts +21 -0
- package/backend/engine/README.md +36 -13
- package/backend/engine/adapters/cline/agent-tool.ts +64 -0
- package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
- package/backend/engine/adapters/cline/credential.ts +166 -0
- package/backend/engine/adapters/cline/error-handler.ts +49 -0
- package/backend/engine/adapters/cline/index.ts +1 -0
- package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
- package/backend/engine/adapters/cline/message-converter.ts +396 -0
- package/backend/engine/adapters/cline/models.ts +73 -0
- package/backend/engine/adapters/cline/presets.ts +128 -0
- package/backend/engine/adapters/cline/stream.ts +413 -0
- package/backend/engine/adapters/codex/credential.ts +1 -1
- package/backend/engine/adapters/codex/message-converter.ts +4 -4
- package/backend/engine/adapters/codex/session-fork.ts +1 -1
- package/backend/engine/adapters/codex/stream.ts +3 -3
- package/backend/engine/adapters/copilot/stream.ts +1 -1
- package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
- package/backend/engine/adapters/cursor/credential.ts +68 -0
- package/backend/engine/adapters/cursor/environment.ts +32 -0
- package/backend/engine/adapters/cursor/error-handler.ts +60 -0
- package/backend/engine/adapters/cursor/index.ts +1 -0
- package/backend/engine/adapters/cursor/message-converter.ts +615 -0
- package/backend/engine/adapters/cursor/models.ts +68 -0
- package/backend/engine/adapters/cursor/session-fork.ts +68 -0
- package/backend/engine/adapters/cursor/stream.ts +341 -0
- package/backend/engine/adapters/pi/agent-tool.ts +62 -0
- package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
- package/backend/engine/adapters/pi/credential.ts +137 -0
- package/backend/engine/adapters/pi/environment.ts +33 -0
- package/backend/engine/adapters/pi/error-handler.ts +46 -0
- package/backend/engine/adapters/pi/index.ts +1 -0
- package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
- package/backend/engine/adapters/pi/message-converter.ts +446 -0
- package/backend/engine/adapters/pi/models.ts +53 -0
- package/backend/engine/adapters/pi/presets.ts +133 -0
- package/backend/engine/adapters/pi/session-fork.ts +46 -0
- package/backend/engine/adapters/pi/stream.ts +427 -0
- package/backend/engine/adapters/qwen/message-converter.ts +5 -5
- package/backend/engine/adapters/qwen/stream.ts +2 -2
- package/backend/engine/docs/adapter-contract.md +7 -2
- package/backend/engine/docs/adding-an-engine.md +70 -12
- package/backend/engine/docs/artifacts.md +124 -0
- package/backend/engine/docs/database.md +4 -4
- package/backend/engine/docs/frontend-and-chat.md +22 -4
- package/backend/engine/docs/lessons-learned.md +219 -32
- package/backend/engine/docs/quick-reference.md +18 -7
- package/backend/engine/docs/websocket-routes.md +2 -2
- package/backend/engine/index.ts +9 -0
- package/backend/mcp/README.md +3 -3
- package/backend/mcp/external/config.ts +11 -0
- package/backend/mcp/index.ts +8 -0
- package/backend/mcp/internal/config.ts +33 -1
- package/backend/permissions/service.ts +5 -2
- package/backend/skills/sync.ts +1 -1
- package/backend/subagents/detect.ts +1 -1
- package/backend/subagents/sync.ts +1 -1
- package/backend/ws/chat/stream.ts +1 -1
- package/backend/ws/engine/cline/accounts.ts +317 -0
- package/backend/ws/engine/cline/index.ts +15 -0
- package/backend/ws/engine/cline/presets.ts +36 -0
- package/backend/ws/engine/cline/status.ts +49 -0
- package/backend/ws/engine/codex/accounts.ts +1 -1
- package/backend/ws/engine/cursor/accounts.ts +162 -0
- package/backend/ws/engine/cursor/index.ts +13 -0
- package/backend/ws/engine/cursor/status.ts +55 -0
- package/backend/ws/engine/index.ts +6 -0
- package/backend/ws/engine/pi/accounts.ts +319 -0
- package/backend/ws/engine/pi/index.ts +15 -0
- package/backend/ws/engine/pi/presets.ts +34 -0
- package/backend/ws/engine/pi/status.ts +50 -0
- package/backend/ws/sessions/crud.ts +2 -2
- package/backend/ws/settings/crud.ts +2 -2
- package/dist/assets/{index-EunAFLxP.js → index-Bu5loFQE.js} +1 -1
- package/dist/assets/{index-ChF_jIXj.js → index-kME3THy5.js} +1 -1
- package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
- package/dist/assets/{main-CTs4NXwP.js → main-HirJLquI.js} +361 -359
- package/dist/index.html +2 -2
- package/package.json +11 -2
- package/shared/constants/engine-tools.ts +16 -2
- package/shared/constants/engines.ts +27 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +82 -1
- package/shared/types/unified/index.ts +6 -0
- package/shared/types/unified/message.ts +1 -1
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cline provider catalog.
|
|
3
|
+
*
|
|
4
|
+
* Cline ships a built-in provider catalog (Anthropic, OpenAI, Google, Bedrock,
|
|
5
|
+
* Mistral, the Cline account, OpenAI-compatible, …). Rather than hardcode them,
|
|
6
|
+
* we enumerate the catalog from `@cline/llms` (`getAllProviders`) and derive each
|
|
7
|
+
* provider's auth shape from `getProviderConfigFields` + `isOAuthProvider`, then
|
|
8
|
+
* expose the result to the login picker via `engine:cline-presets-list`.
|
|
9
|
+
*
|
|
10
|
+
* The wire types (`ClineProviderPreset`, `ClineAuthMode`, `ClineCredentialField`)
|
|
11
|
+
* live in `shared/types/unified/engine.ts` so the frontend stays typed without
|
|
12
|
+
* importing `$backend`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { Llms, getProviderConfigFields, isOAuthProvider } from '@cline/sdk';
|
|
16
|
+
import type { ClineAuthMode, ClineCredentialField, ClineProviderPreset } from '$shared/types/unified';
|
|
17
|
+
import { debug } from '$shared/utils/logger';
|
|
18
|
+
|
|
19
|
+
export type { ClineAuthMode, ClineCredentialField, ClineProviderPreset };
|
|
20
|
+
|
|
21
|
+
/** Where to obtain an API key, keyed by Cline provider id (best-effort hints). */
|
|
22
|
+
const API_KEY_URLS: Record<string, string> = {
|
|
23
|
+
anthropic: 'https://console.anthropic.com/settings/keys',
|
|
24
|
+
openai: 'https://platform.openai.com/api-keys',
|
|
25
|
+
'openai-native': 'https://platform.openai.com/api-keys',
|
|
26
|
+
gemini: 'https://aistudio.google.com/apikey',
|
|
27
|
+
google: 'https://aistudio.google.com/apikey',
|
|
28
|
+
mistral: 'https://console.mistral.ai/api-keys',
|
|
29
|
+
deepseek: 'https://platform.deepseek.com/api_keys',
|
|
30
|
+
openrouter: 'https://openrouter.ai/keys',
|
|
31
|
+
groq: 'https://console.groq.com/keys',
|
|
32
|
+
xai: 'https://console.x.ai',
|
|
33
|
+
together: 'https://api.together.ai/settings/api-keys',
|
|
34
|
+
fireworks: 'https://fireworks.ai/account/api-keys',
|
|
35
|
+
cerebras: 'https://cloud.cerebras.ai',
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Human labels for the OAuth (sign-in) option, keyed by provider id. */
|
|
39
|
+
const OAUTH_LABELS: Record<string, string> = {
|
|
40
|
+
cline: 'Sign in with Cline',
|
|
41
|
+
anthropic: 'Sign in with Claude Pro/Max',
|
|
42
|
+
'claude-code': 'Sign in with Claude Code',
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** Human-readable field labels, keyed by the Cline config-field key. */
|
|
46
|
+
const FIELD_LABELS: Record<string, string> = {
|
|
47
|
+
apiKey: 'API key',
|
|
48
|
+
baseUrl: 'Base URL',
|
|
49
|
+
azureApiVersion: 'Azure API version',
|
|
50
|
+
awsRegion: 'AWS region',
|
|
51
|
+
awsProfile: 'AWS profile',
|
|
52
|
+
gcpProjectId: 'GCP project ID',
|
|
53
|
+
gcpRegion: 'GCP region',
|
|
54
|
+
sapClientId: 'SAP client ID',
|
|
55
|
+
sapClientSecret: 'SAP client secret',
|
|
56
|
+
sapTokenUrl: 'SAP token URL',
|
|
57
|
+
sapResourceGroup: 'SAP resource group',
|
|
58
|
+
sapDeploymentId: 'SAP deployment ID',
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const SECRET_FIELDS = new Set(['apiKey', 'sapClientSecret']);
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Map a provider's `getProviderConfigFields` shape into the wire
|
|
65
|
+
* `ClineCredentialField[]` the account form renders.
|
|
66
|
+
*/
|
|
67
|
+
export function getClineProviderFields(providerId: string): ClineCredentialField[] {
|
|
68
|
+
const config = getProviderConfigFields(providerId);
|
|
69
|
+
const out: ClineCredentialField[] = [];
|
|
70
|
+
for (const [key, req] of Object.entries(config.fields ?? {})) {
|
|
71
|
+
if (!req) continue;
|
|
72
|
+
const role: ClineCredentialField['role'] = key === 'apiKey' ? 'apiKey' : key === 'baseUrl' ? 'baseUrl' : 'field';
|
|
73
|
+
out.push({
|
|
74
|
+
key,
|
|
75
|
+
label: req.label ?? FIELD_LABELS[key] ?? key,
|
|
76
|
+
secret: SECRET_FIELDS.has(key),
|
|
77
|
+
role,
|
|
78
|
+
...(req.placeholder ? { placeholder: req.placeholder } : {}),
|
|
79
|
+
...(req.optional ? { optional: true } : {}),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
// Providers with no declared fields still accept an API key.
|
|
83
|
+
if (out.length === 0) {
|
|
84
|
+
out.push({ key: 'apiKey', label: 'API key', secret: true, role: 'apiKey', placeholder: 'sk-…' });
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let presetsCache: ClineProviderPreset[] | null = null;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Enumerate Cline's providers and their supported auth modes. Cached — the
|
|
93
|
+
* catalog is static per process. Returns `[]` on any failure (mirrors the
|
|
94
|
+
* dynamic-catalog `[]`-on-failure contract so the picker renders empty rather
|
|
95
|
+
* than a stale list).
|
|
96
|
+
*/
|
|
97
|
+
export async function getClineProviderPresets(): Promise<ClineProviderPreset[]> {
|
|
98
|
+
if (presetsCache) return presetsCache;
|
|
99
|
+
try {
|
|
100
|
+
const presets: ClineProviderPreset[] = [];
|
|
101
|
+
for (const provider of await Llms.getAllProviders()) {
|
|
102
|
+
const config = getProviderConfigFields(provider.id);
|
|
103
|
+
const oauth = isOAuthProvider(provider.id) || config.authMethod === 'oauth';
|
|
104
|
+
const fields = getClineProviderFields(provider.id);
|
|
105
|
+
const hasApiKey = config.authMethod === 'api-key' || config.authMethod === 'local' || fields.some(f => f.role === 'apiKey');
|
|
106
|
+
|
|
107
|
+
const authModes: ClineAuthMode[] = [];
|
|
108
|
+
if (hasApiKey) authModes.push('api_key');
|
|
109
|
+
if (oauth) authModes.push('oauth');
|
|
110
|
+
if (authModes.length === 0) authModes.push('api_key');
|
|
111
|
+
|
|
112
|
+
presets.push({
|
|
113
|
+
id: provider.id,
|
|
114
|
+
name: provider.name || provider.id,
|
|
115
|
+
authModes,
|
|
116
|
+
...(authModes.includes('api_key') ? { fields } : {}),
|
|
117
|
+
...(OAUTH_LABELS[provider.id] ? { oauthLabel: OAUTH_LABELS[provider.id] } : {}),
|
|
118
|
+
...(API_KEY_URLS[provider.id] ? { apiKeyUrl: API_KEY_URLS[provider.id] } : {}),
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
presets.sort((a, b) => a.name.localeCompare(b.name));
|
|
122
|
+
presetsCache = presets;
|
|
123
|
+
return presets;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
debug.warn('engine', `Cline presets: failed to enumerate providers: ${error instanceof Error ? error.message : String(error)}`);
|
|
126
|
+
return [];
|
|
127
|
+
}
|
|
128
|
+
}
|