@myrialabs/clopen 0.4.14 → 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.
- package/backend/artifacts/matrix.ts +8 -0
- package/backend/artifacts/types.ts +2 -2
- package/backend/auth/permissions.ts +16 -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/056_support_mssql_driver.ts +137 -0
- 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 +28 -0
- package/backend/database/queries/engine-queries.ts +13 -0
- package/backend/database/queries/message-queries.ts +43 -1
- package/backend/db-client/connection-manager.ts +8 -2
- package/backend/db-client/drivers/mssql.ts +829 -0
- package/backend/db-client/drivers/mysql.ts +33 -4
- package/backend/db-client/drivers/postgres.ts +55 -5
- package/backend/db-client/drivers/sql-builders.test.ts +70 -0
- package/backend/db-client/drivers/sql-builders.ts +9 -2
- package/backend/db-client/pool-config.ts +32 -0
- package/backend/db-client/query-executor.test.ts +42 -0
- package/backend/db-client/query-executor.ts +47 -3
- 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/opencode/config.ts +9 -0
- package/backend/engine/adapters/opencode/models.ts +10 -1
- package/backend/engine/adapters/opencode/server.ts +110 -2
- 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/index.ts +6 -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/preview/browser/browser-preview-service.ts +15 -6
- package/backend/preview/browser/browser-video-capture.ts +232 -100
- package/backend/preview/browser/scripts/video-stream.ts +216 -56
- package/backend/preview/browser/types.ts +24 -12
- 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 +13 -5
- package/backend/ws/db-client/connections.ts +2 -1
- package/backend/ws/db-client/query.ts +41 -4
- package/backend/ws/db-client/schema.ts +45 -1
- package/backend/ws/engine/claude/accounts.ts +37 -13
- 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 +37 -5
- package/backend/ws/engine/copilot/accounts.ts +12 -0
- 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/opencode/providers.ts +72 -1
- 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/engine/qwen/accounts.ts +22 -0
- package/backend/ws/messages/crud.ts +13 -0
- package/backend/ws/preview/browser/interact.ts +10 -8
- package/backend/ws/preview/browser/webcodecs.ts +26 -2
- package/backend/ws/sessions/crud.ts +2 -2
- package/backend/ws/settings/crud.ts +2 -2
- package/dist/assets/{index-CDZf6lfv.js → index-BPvctwJ2.js} +1 -1
- package/dist/assets/{index-BWf-DDJN.js → index-vLKZpWQH.js} +1 -1
- package/dist/assets/{main-C15mQTCW.js → main-BtBZvCwv.js} +428 -386
- package/dist/assets/main-D7ATW8pp.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +11 -1
- package/shared/constants/engine-tools.ts +16 -2
- package/shared/constants/engines.ts +27 -0
- package/shared/types/db-client/connection.ts +1 -1
- package/shared/types/db-client/query.ts +4 -1
- 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
- package/shared/utils/db-client/split-sql.test.ts +13 -0
- package/shared/utils/db-client/split-sql.ts +38 -1
- package/shared/utils/subagent-wire-trim.ts +87 -0
- package/dist/assets/main-Ba5ZGlY4.css +0 -1
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AskUserQuestion custom tool for Cline.
|
|
3
|
+
*
|
|
4
|
+
* Cline's built-in `ask_question` drives its own UI and has no headless answer
|
|
5
|
+
* path, so we disable it (`enableAskQuestion: false`) and register our own
|
|
6
|
+
* canonical `AskUserQuestion` tool that BLOCKS until the user answers through the
|
|
7
|
+
* chat UI — the same contract Claude's `canUseTool` provides, modelled as a
|
|
8
|
+
* blocking tool because the stateless `Agent` loop resolves a tool call by its
|
|
9
|
+
* returned promise.
|
|
10
|
+
*
|
|
11
|
+
* The tool's `execute` returns a promise the engine resolves via
|
|
12
|
+
* `resolveUserAnswer(toolCallId, answers)`. The converter renders the tool_use
|
|
13
|
+
* block (name `AskUserQuestion`) so the frontend shows the dialog; the resolved
|
|
14
|
+
* tool result carries the formatted answers.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createTool } from '@cline/sdk';
|
|
18
|
+
import type { AgentTool, AgentToolContext } from '@cline/sdk';
|
|
19
|
+
import type { AskUserQuestion } from '$shared/types/unified';
|
|
20
|
+
|
|
21
|
+
export interface PendingAsk {
|
|
22
|
+
questions: AskUserQuestion[];
|
|
23
|
+
resolve: (text: string) => void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface AskToolBindings {
|
|
27
|
+
register: (toolCallId: string, entry: PendingAsk) => void;
|
|
28
|
+
unregister: (toolCallId: string) => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Format the user's answers in the shared OpenCode/Qwen/Pi wording. */
|
|
32
|
+
export function formatAnswers(questions: AskUserQuestion[], answers: Record<string, string>): string {
|
|
33
|
+
const pairs: string[] = [];
|
|
34
|
+
for (const [key, value] of Object.entries(answers)) {
|
|
35
|
+
const idx = Number.parseInt(key, 10);
|
|
36
|
+
const q = Number.isFinite(idx) ? questions[idx] : undefined;
|
|
37
|
+
const label = q?.question ?? q?.header ?? key;
|
|
38
|
+
pairs.push(`"${label}"="${value}"`);
|
|
39
|
+
}
|
|
40
|
+
if (pairs.length === 0) return 'User did not provide any answers.';
|
|
41
|
+
return `User has answered your questions: ${pairs.join(', ')}. You can now continue with the user's answers in mind.`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const ASK_INPUT_SCHEMA = {
|
|
45
|
+
type: 'object',
|
|
46
|
+
properties: {
|
|
47
|
+
questions: {
|
|
48
|
+
type: 'array',
|
|
49
|
+
description: 'One or more multiple-choice questions to ask the user.',
|
|
50
|
+
items: {
|
|
51
|
+
type: 'object',
|
|
52
|
+
properties: {
|
|
53
|
+
question: { type: 'string', description: 'The full question text.' },
|
|
54
|
+
header: { type: 'string', description: 'A short (max 12 char) label for the question.' },
|
|
55
|
+
multiSelect: { type: 'boolean', description: 'Whether multiple options may be selected.' },
|
|
56
|
+
options: {
|
|
57
|
+
type: 'array',
|
|
58
|
+
items: {
|
|
59
|
+
type: 'object',
|
|
60
|
+
properties: {
|
|
61
|
+
label: { type: 'string' },
|
|
62
|
+
description: { type: 'string' },
|
|
63
|
+
},
|
|
64
|
+
required: ['label', 'description'],
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
required: ['question', 'header', 'options'],
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
required: ['questions'],
|
|
73
|
+
} as const;
|
|
74
|
+
|
|
75
|
+
export function createAskUserQuestionTool(bindings: AskToolBindings): AgentTool {
|
|
76
|
+
return createTool({
|
|
77
|
+
name: 'AskUserQuestion',
|
|
78
|
+
description:
|
|
79
|
+
'Ask the user one or more multiple-choice questions when you need a decision only they can make. Blocks until the user answers in the UI.',
|
|
80
|
+
inputSchema: ASK_INPUT_SCHEMA,
|
|
81
|
+
async execute(input: { questions?: AskUserQuestion[] }, context: AgentToolContext) {
|
|
82
|
+
const questions = (input?.questions ?? []) as AskUserQuestion[];
|
|
83
|
+
const toolCallId = context.toolCallId ?? '';
|
|
84
|
+
const signal = context.signal;
|
|
85
|
+
return new Promise<string>((resolve) => {
|
|
86
|
+
if (!toolCallId || signal?.aborted) {
|
|
87
|
+
resolve('User did not answer the question.');
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const onAbort = () => {
|
|
91
|
+
bindings.unregister(toolCallId);
|
|
92
|
+
resolve('User did not answer the question.');
|
|
93
|
+
};
|
|
94
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
95
|
+
bindings.register(toolCallId, {
|
|
96
|
+
questions,
|
|
97
|
+
resolve: (text) => {
|
|
98
|
+
signal?.removeEventListener('abort', onAbort);
|
|
99
|
+
resolve(text);
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
},
|
|
104
|
+
}) as AgentTool;
|
|
105
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cline credential storage.
|
|
3
|
+
*
|
|
4
|
+
* Cline (`@cline/sdk`) is genuinely multi-provider and supports both API-key and
|
|
5
|
+
* OAuth (the Cline account signs in through WorkOS OAuth). Rather than let the
|
|
6
|
+
* SDK write its own `~/.cline` provider settings, Clopen OWNS the credential and
|
|
7
|
+
* feeds it to the stateless `Agent` per stream: an API key (or the OAuth access
|
|
8
|
+
* token, formatted via `formatProviderOAuthApiKey`) is passed as
|
|
9
|
+
* `AgentRuntimeConfigWithProvider.apiKey`.
|
|
10
|
+
*
|
|
11
|
+
* `engine_accounts.credential` for a Cline account stores a JSON wrapper:
|
|
12
|
+
*
|
|
13
|
+
* { "provider": "anthropic", "authMethod": "api_key", "apiKey": "sk-…", "baseUrl": "…", "fields": { … } }
|
|
14
|
+
* { "provider": "cline", "authMethod": "oauth", "oauth": { "access": …, "refresh": …, "expires": … } }
|
|
15
|
+
*
|
|
16
|
+
* Because OAuth access tokens rotate, `resolveClineAuth()` refreshes an expired
|
|
17
|
+
* token via the SDK's provider auth handler and persists the refreshed blob
|
|
18
|
+
* straight back into the account row — no dotfile swap, no `process.env`
|
|
19
|
+
* mutation (mirrors Pi's DB-backed credential contract).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { getProviderAuthHandler, formatProviderOAuthApiKey } from '@cline/sdk';
|
|
23
|
+
import type { OAuthCredentials, ProviderSettings } from '@cline/sdk';
|
|
24
|
+
import { engineQueries, type EngineAccount } from '$backend/database/queries/engine-queries';
|
|
25
|
+
import { debug } from '$shared/utils/logger';
|
|
26
|
+
|
|
27
|
+
export type ClineAuthMethod = 'api_key' | 'oauth';
|
|
28
|
+
|
|
29
|
+
export interface ClineCredential {
|
|
30
|
+
/** Cline SDK provider id (e.g. 'anthropic', 'openai', 'cline'). */
|
|
31
|
+
provider: string;
|
|
32
|
+
authMethod: ClineAuthMethod;
|
|
33
|
+
/** API key (api_key mode). */
|
|
34
|
+
apiKey?: string;
|
|
35
|
+
/** Custom base URL (OpenAI-compatible / self-hosted). */
|
|
36
|
+
baseUrl?: string;
|
|
37
|
+
/** Extra provider-scoped fields (awsRegion, gcpProjectId, …). */
|
|
38
|
+
fields?: Record<string, string>;
|
|
39
|
+
/** OAuth token blob (oauth mode). */
|
|
40
|
+
oauth?: OAuthCredentials;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The single `engine_providers` row that owns every Cline account (Pi/Qwen-style). */
|
|
44
|
+
export function getClineProvider() {
|
|
45
|
+
return engineQueries.getProviderBySlug('cline', 'cline');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Every stored Cline account (each tagged with its own Cline provider id). */
|
|
49
|
+
export function getClineAccounts(): EngineAccount[] {
|
|
50
|
+
const provider = getClineProvider();
|
|
51
|
+
return provider ? engineQueries.getAccountsByProvider(provider.id) : [];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The account backing a given Cline provider id, preferring the active one. */
|
|
55
|
+
export function getClineAccountForProvider(providerId: string): EngineAccount | null {
|
|
56
|
+
const accounts = getClineAccounts().filter(a => parseClineCredential(a.credential)?.provider === providerId);
|
|
57
|
+
if (accounts.length === 0) return null;
|
|
58
|
+
return accounts.find(a => a.is_active === 1) ?? accounts[accounts.length - 1];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Parse a stored `engine_accounts.credential` blob. Returns null if unusable. */
|
|
62
|
+
export function parseClineCredential(stored: string | null | undefined): ClineCredential | null {
|
|
63
|
+
if (!stored) return null;
|
|
64
|
+
const trimmed = stored.trim();
|
|
65
|
+
if (!trimmed.startsWith('{')) return null;
|
|
66
|
+
try {
|
|
67
|
+
const parsed = JSON.parse(trimmed) as Partial<ClineCredential>;
|
|
68
|
+
if (!parsed || typeof parsed.provider !== 'string' || !parsed.provider) return null;
|
|
69
|
+
const authMethod = parsed.authMethod === 'oauth' ? 'oauth' : 'api_key';
|
|
70
|
+
if (authMethod === 'api_key' && !parsed.apiKey) return null;
|
|
71
|
+
if (authMethod === 'oauth' && !parsed.oauth?.access) return null;
|
|
72
|
+
return {
|
|
73
|
+
provider: parsed.provider,
|
|
74
|
+
authMethod,
|
|
75
|
+
...(parsed.apiKey ? { apiKey: parsed.apiKey } : {}),
|
|
76
|
+
...(parsed.baseUrl ? { baseUrl: parsed.baseUrl } : {}),
|
|
77
|
+
...(parsed.fields && typeof parsed.fields === 'object' ? { fields: parsed.fields } : {}),
|
|
78
|
+
...(parsed.oauth ? { oauth: parsed.oauth } : {}),
|
|
79
|
+
};
|
|
80
|
+
} catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function serializeClineCredential(cred: ClineCredential): string {
|
|
86
|
+
return JSON.stringify(cred);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Non-secret display metadata for one account (auth method + provider). */
|
|
90
|
+
export function describeClineCredential(
|
|
91
|
+
stored: string | null | undefined,
|
|
92
|
+
): { provider: string; authMethod: ClineAuthMethod } | null {
|
|
93
|
+
const parsed = parseClineCredential(stored);
|
|
94
|
+
if (!parsed) return null;
|
|
95
|
+
return { provider: parsed.provider, authMethod: parsed.authMethod };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface ResolvedClineAuth {
|
|
99
|
+
provider: string;
|
|
100
|
+
apiKey?: string;
|
|
101
|
+
baseUrl?: string;
|
|
102
|
+
/** Gateway options for provider-scoped fields (awsRegion, gcpProjectId, …). */
|
|
103
|
+
options?: Record<string, unknown>;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Refresh window: refresh an OAuth token that expires within the next minute. */
|
|
107
|
+
const OAUTH_REFRESH_BUFFER_MS = 60_000;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Resolve the auth an `Agent` needs for one account. For OAuth accounts this
|
|
111
|
+
* refreshes a near-expired access token (persisting the rotated blob back to the
|
|
112
|
+
* DB) and formats it into the api-key the provider handler expects.
|
|
113
|
+
*/
|
|
114
|
+
export async function resolveClineAuth(account: EngineAccount): Promise<ResolvedClineAuth> {
|
|
115
|
+
const parsed = parseClineCredential(account.credential);
|
|
116
|
+
if (!parsed) throw new Error('Cline account has no usable credential.');
|
|
117
|
+
|
|
118
|
+
if (parsed.authMethod === 'api_key') {
|
|
119
|
+
return {
|
|
120
|
+
provider: parsed.provider,
|
|
121
|
+
...(parsed.apiKey ? { apiKey: parsed.apiKey } : {}),
|
|
122
|
+
...(parsed.baseUrl ? { baseUrl: parsed.baseUrl } : {}),
|
|
123
|
+
...(parsed.fields && Object.keys(parsed.fields).length ? { options: { ...parsed.fields } } : {}),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// OAuth: refresh if near-expiry, then format the access token as an api key.
|
|
128
|
+
let creds = parsed.oauth as OAuthCredentials;
|
|
129
|
+
const handler = getProviderAuthHandler(parsed.provider);
|
|
130
|
+
const nearExpiry = typeof creds.expires === 'number' && creds.expires <= Date.now() + OAUTH_REFRESH_BUFFER_MS;
|
|
131
|
+
if (handler && creds.refresh && nearExpiry) {
|
|
132
|
+
try {
|
|
133
|
+
const settings = {
|
|
134
|
+
auth: {
|
|
135
|
+
accessToken: creds.access,
|
|
136
|
+
refreshToken: creds.refresh,
|
|
137
|
+
expiresAt: creds.expires,
|
|
138
|
+
...(creds.accountId ? { accountId: creds.accountId } : {}),
|
|
139
|
+
},
|
|
140
|
+
} as ProviderSettings;
|
|
141
|
+
const refreshed = await handler.refresh({ settings, credentials: creds });
|
|
142
|
+
if (refreshed?.access) {
|
|
143
|
+
creds = refreshed;
|
|
144
|
+
engineQueries.updateAccountCredential(
|
|
145
|
+
account.id,
|
|
146
|
+
serializeClineCredential({ ...parsed, oauth: refreshed }),
|
|
147
|
+
);
|
|
148
|
+
debug.log('engine', `Cline: refreshed OAuth token for provider "${parsed.provider}" (account ${account.id})`);
|
|
149
|
+
}
|
|
150
|
+
} catch (error) {
|
|
151
|
+
debug.warn('engine', `Cline OAuth refresh failed for "${parsed.provider}" (using stored token): ${error instanceof Error ? error.message : String(error)}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
let apiKey: string;
|
|
156
|
+
try {
|
|
157
|
+
apiKey = formatProviderOAuthApiKey(parsed.provider, { access: creds.access });
|
|
158
|
+
} catch {
|
|
159
|
+
apiKey = creds.access;
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
provider: parsed.provider,
|
|
163
|
+
apiKey,
|
|
164
|
+
...(parsed.baseUrl ? { baseUrl: parsed.baseUrl } : {}),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
@@ -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
|
+
}
|