@myrialabs/clopen 0.4.15 → 0.4.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +8 -5
  2. package/backend/artifacts/matrix.ts +8 -0
  3. package/backend/artifacts/types.ts +2 -2
  4. package/backend/auth/permissions.ts +14 -0
  5. package/backend/chat/stream-manager.ts +5 -5
  6. package/backend/commands/detect.ts +1 -1
  7. package/backend/commands/sync.ts +1 -1
  8. package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
  9. package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
  10. package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
  11. package/backend/database/migrations/index.ts +21 -0
  12. package/backend/engine/README.md +36 -13
  13. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  14. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  15. package/backend/engine/adapters/cline/credential.ts +166 -0
  16. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  17. package/backend/engine/adapters/cline/index.ts +1 -0
  18. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  19. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  20. package/backend/engine/adapters/cline/models.ts +73 -0
  21. package/backend/engine/adapters/cline/presets.ts +128 -0
  22. package/backend/engine/adapters/cline/stream.ts +413 -0
  23. package/backend/engine/adapters/codex/credential.ts +1 -1
  24. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  25. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  26. package/backend/engine/adapters/codex/stream.ts +3 -3
  27. package/backend/engine/adapters/copilot/stream.ts +1 -1
  28. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  29. package/backend/engine/adapters/cursor/credential.ts +68 -0
  30. package/backend/engine/adapters/cursor/environment.ts +32 -0
  31. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  32. package/backend/engine/adapters/cursor/index.ts +1 -0
  33. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  34. package/backend/engine/adapters/cursor/models.ts +68 -0
  35. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  36. package/backend/engine/adapters/cursor/stream.ts +341 -0
  37. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  38. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  39. package/backend/engine/adapters/pi/credential.ts +137 -0
  40. package/backend/engine/adapters/pi/environment.ts +33 -0
  41. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  42. package/backend/engine/adapters/pi/index.ts +1 -0
  43. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  44. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  45. package/backend/engine/adapters/pi/models.ts +53 -0
  46. package/backend/engine/adapters/pi/presets.ts +133 -0
  47. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  48. package/backend/engine/adapters/pi/stream.ts +427 -0
  49. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  50. package/backend/engine/adapters/qwen/stream.ts +2 -2
  51. package/backend/engine/docs/adapter-contract.md +7 -2
  52. package/backend/engine/docs/adding-an-engine.md +70 -12
  53. package/backend/engine/docs/artifacts.md +124 -0
  54. package/backend/engine/docs/database.md +4 -4
  55. package/backend/engine/docs/frontend-and-chat.md +22 -4
  56. package/backend/engine/docs/lessons-learned.md +219 -32
  57. package/backend/engine/docs/quick-reference.md +18 -7
  58. package/backend/engine/docs/websocket-routes.md +2 -2
  59. package/backend/engine/index.ts +9 -0
  60. package/backend/mcp/README.md +3 -3
  61. package/backend/mcp/external/config.ts +11 -0
  62. package/backend/mcp/index.ts +8 -0
  63. package/backend/mcp/internal/config.ts +33 -1
  64. package/backend/permissions/service.ts +5 -2
  65. package/backend/skills/sync.ts +1 -1
  66. package/backend/subagents/detect.ts +1 -1
  67. package/backend/subagents/sync.ts +1 -1
  68. package/backend/ws/chat/stream.ts +1 -1
  69. package/backend/ws/engine/cline/accounts.ts +317 -0
  70. package/backend/ws/engine/cline/index.ts +15 -0
  71. package/backend/ws/engine/cline/presets.ts +36 -0
  72. package/backend/ws/engine/cline/status.ts +49 -0
  73. package/backend/ws/engine/codex/accounts.ts +1 -1
  74. package/backend/ws/engine/cursor/accounts.ts +162 -0
  75. package/backend/ws/engine/cursor/index.ts +13 -0
  76. package/backend/ws/engine/cursor/status.ts +55 -0
  77. package/backend/ws/engine/index.ts +6 -0
  78. package/backend/ws/engine/pi/accounts.ts +319 -0
  79. package/backend/ws/engine/pi/index.ts +15 -0
  80. package/backend/ws/engine/pi/presets.ts +34 -0
  81. package/backend/ws/engine/pi/status.ts +50 -0
  82. package/backend/ws/sessions/crud.ts +2 -2
  83. package/backend/ws/settings/crud.ts +2 -2
  84. package/dist/assets/{index-EunAFLxP.js → index-Bu5loFQE.js} +1 -1
  85. package/dist/assets/{index-ChF_jIXj.js → index-kME3THy5.js} +1 -1
  86. package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
  87. package/dist/assets/{main-CTs4NXwP.js → main-HirJLquI.js} +361 -359
  88. package/dist/index.html +2 -2
  89. package/package.json +11 -2
  90. package/shared/constants/engine-tools.ts +16 -2
  91. package/shared/constants/engines.ts +27 -0
  92. package/shared/types/unified/common.ts +1 -1
  93. package/shared/types/unified/engine.ts +82 -1
  94. package/shared/types/unified/index.ts +6 -0
  95. package/shared/types/unified/message.ts +1 -1
@@ -0,0 +1,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
+ }