@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
|
@@ -7,6 +7,7 @@ import { createRouter } from '$shared/utils/ws-server';
|
|
|
7
7
|
import { connectionManager } from '../../db-client/connection-manager';
|
|
8
8
|
import type { DbClientSchemaNodeType } from '$shared/types/db-client';
|
|
9
9
|
import { requireDbClientConnectionAccess } from './access';
|
|
10
|
+
import { debug } from '$shared/utils/logger';
|
|
10
11
|
|
|
11
12
|
const nodeTypeSchema = t.Union([
|
|
12
13
|
t.Literal('database'),
|
|
@@ -16,7 +17,9 @@ const nodeTypeSchema = t.Union([
|
|
|
16
17
|
t.Literal('collection'),
|
|
17
18
|
t.Literal('index'),
|
|
18
19
|
t.Literal('key'),
|
|
19
|
-
t.Literal('column')
|
|
20
|
+
t.Literal('column'),
|
|
21
|
+
t.Literal('function'),
|
|
22
|
+
t.Literal('procedure')
|
|
20
23
|
]);
|
|
21
24
|
|
|
22
25
|
export const schemaHandler = createRouter()
|
|
@@ -92,4 +95,45 @@ export const schemaHandler = createRouter()
|
|
|
92
95
|
data.database,
|
|
93
96
|
data.schema
|
|
94
97
|
);
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
.http('db-client:get-er-schema', {
|
|
101
|
+
data: t.Object({
|
|
102
|
+
connectionId: t.String({ minLength: 1 }),
|
|
103
|
+
database: t.Optional(t.String()),
|
|
104
|
+
schema: t.Optional(t.String())
|
|
105
|
+
}),
|
|
106
|
+
response: t.Any()
|
|
107
|
+
}, async ({ data, conn }) => {
|
|
108
|
+
requireDbClientConnectionAccess(conn, data.connectionId);
|
|
109
|
+
const adapter = await connectionManager.get(data.connectionId);
|
|
110
|
+
if (!adapter.listObjects || !adapter.getObjectDetails) {
|
|
111
|
+
return { tables: [] };
|
|
112
|
+
}
|
|
113
|
+
const getDetails = adapter.getObjectDetails.bind(adapter);
|
|
114
|
+
const objects = await adapter.listObjects(data.database, data.schema);
|
|
115
|
+
const tableNodes = objects.filter(o => o.type === 'table');
|
|
116
|
+
const tables: any[] = [];
|
|
117
|
+
await Promise.all(tableNodes.map(async (node) => {
|
|
118
|
+
try {
|
|
119
|
+
const details = await getDetails(node.name, 'table', data.database, data.schema);
|
|
120
|
+
tables.push({
|
|
121
|
+
name: node.name,
|
|
122
|
+
columns: details.columns?.map(c => ({
|
|
123
|
+
name: c.name,
|
|
124
|
+
type: c.type,
|
|
125
|
+
isPrimary: c.isPrimary ?? false,
|
|
126
|
+
isUnique: c.isUnique ?? false
|
|
127
|
+
})) ?? [],
|
|
128
|
+
foreignKeys: details.foreignKeys?.map(fk => ({
|
|
129
|
+
column: fk.column,
|
|
130
|
+
refTable: fk.refTable,
|
|
131
|
+
refColumn: fk.refColumn
|
|
132
|
+
})) ?? []
|
|
133
|
+
});
|
|
134
|
+
} catch (e) {
|
|
135
|
+
debug.warn('db-client', `Failed to get ER schema details for table ${node.name}:`, e);
|
|
136
|
+
}
|
|
137
|
+
}));
|
|
138
|
+
return { tables };
|
|
95
139
|
});
|
|
@@ -90,9 +90,34 @@ interface SetupProcess {
|
|
|
90
90
|
disposed: boolean;
|
|
91
91
|
phase: SetupPhase;
|
|
92
92
|
accountName: string;
|
|
93
|
+
/** When set, re-authenticate this existing account in place instead of creating a new one. */
|
|
94
|
+
reauthAccountId: number | null;
|
|
93
95
|
urlEmitted: boolean;
|
|
94
96
|
}
|
|
95
97
|
|
|
98
|
+
/**
|
|
99
|
+
* Persist a freshly captured OAuth token — either updating an existing account
|
|
100
|
+
* in place (re-authentication) or creating a new one. Always resets the Claude
|
|
101
|
+
* environment so the next stream reads the new credential.
|
|
102
|
+
*/
|
|
103
|
+
function persistClaudeAccount(entry: SetupProcess, token: string): { ok: true; accountId: number } | { ok: false; error: string } {
|
|
104
|
+
const provider = engineQueries.getProviderBySlug('claude-code', 'anthropic');
|
|
105
|
+
if (!provider) return { ok: false, error: 'Anthropic provider not found in DB' };
|
|
106
|
+
|
|
107
|
+
if (entry.reauthAccountId != null) {
|
|
108
|
+
const existing = engineQueries.getAccount(entry.reauthAccountId);
|
|
109
|
+
if (!existing) return { ok: false, error: 'Account to re-authenticate not found' };
|
|
110
|
+
engineQueries.updateAccountCredential(entry.reauthAccountId, token);
|
|
111
|
+
if (entry.accountName) engineQueries.renameAccount(entry.reauthAccountId, entry.accountName);
|
|
112
|
+
resetEnvironment();
|
|
113
|
+
return { ok: true, accountId: entry.reauthAccountId };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const account = engineQueries.createAccount(provider.id, entry.accountName, token);
|
|
117
|
+
resetEnvironment();
|
|
118
|
+
return { ok: true, accountId: account.id };
|
|
119
|
+
}
|
|
120
|
+
|
|
96
121
|
const setupProcesses = new Map<string, SetupProcess>();
|
|
97
122
|
const userSetups = new Map<string, string>();
|
|
98
123
|
|
|
@@ -226,6 +251,7 @@ export const accountsHandler = createRouter()
|
|
|
226
251
|
disposed: false,
|
|
227
252
|
phase: 'waiting-url',
|
|
228
253
|
accountName: '',
|
|
254
|
+
reauthAccountId: null,
|
|
229
255
|
urlEmitted: false
|
|
230
256
|
};
|
|
231
257
|
setupProcesses.set(setupId, entry);
|
|
@@ -262,21 +288,19 @@ export const accountsHandler = createRouter()
|
|
|
262
288
|
entry.phase = 'done';
|
|
263
289
|
debug.log('engine', `[${setupId}] Token captured`);
|
|
264
290
|
|
|
265
|
-
const
|
|
266
|
-
if (!
|
|
291
|
+
const result = persistClaudeAccount(entry, token);
|
|
292
|
+
if (!result.ok) {
|
|
267
293
|
ws.emit.user(userId, 'engine:claude-account-setup-error', {
|
|
268
294
|
setupId,
|
|
269
|
-
message:
|
|
295
|
+
message: result.error
|
|
270
296
|
});
|
|
271
297
|
cleanupSetup(setupId);
|
|
272
298
|
return;
|
|
273
299
|
}
|
|
274
|
-
const account = engineQueries.createAccount(provider.id, entry.accountName, token);
|
|
275
|
-
resetEnvironment();
|
|
276
300
|
|
|
277
301
|
ws.emit.user(userId, 'engine:claude-account-setup-complete', {
|
|
278
302
|
setupId,
|
|
279
|
-
accountId:
|
|
303
|
+
accountId: result.accountId
|
|
280
304
|
});
|
|
281
305
|
|
|
282
306
|
cleanupSetup(setupId);
|
|
@@ -316,20 +340,18 @@ export const accountsHandler = createRouter()
|
|
|
316
340
|
const token = extractOAuthToken(clean);
|
|
317
341
|
if (token) {
|
|
318
342
|
debug.log('engine', `[${setupId}] Token found in final buffer`);
|
|
319
|
-
const
|
|
320
|
-
if (!
|
|
343
|
+
const result = persistClaudeAccount(entry, token);
|
|
344
|
+
if (!result.ok) {
|
|
321
345
|
ws.emit.user(userId, 'engine:claude-account-setup-error', {
|
|
322
346
|
setupId,
|
|
323
|
-
message:
|
|
347
|
+
message: result.error
|
|
324
348
|
});
|
|
325
349
|
cleanupSetup(setupId);
|
|
326
350
|
return;
|
|
327
351
|
}
|
|
328
|
-
const account = engineQueries.createAccount(provider.id, entry.accountName, token);
|
|
329
|
-
resetEnvironment();
|
|
330
352
|
ws.emit.user(userId, 'engine:claude-account-setup-complete', {
|
|
331
353
|
setupId,
|
|
332
|
-
accountId:
|
|
354
|
+
accountId: result.accountId
|
|
333
355
|
});
|
|
334
356
|
} else {
|
|
335
357
|
// Try to extract a meaningful error message
|
|
@@ -350,7 +372,8 @@ export const accountsHandler = createRouter()
|
|
|
350
372
|
data: t.Object({
|
|
351
373
|
setupId: t.String(),
|
|
352
374
|
code: t.String(),
|
|
353
|
-
name: t.String({ minLength: 1 })
|
|
375
|
+
name: t.String({ minLength: 1 }),
|
|
376
|
+
reauthAccountId: t.Optional(t.Number())
|
|
354
377
|
})
|
|
355
378
|
}, async ({ data, conn }) => {
|
|
356
379
|
const userId = ws.getUserId(conn);
|
|
@@ -371,6 +394,7 @@ export const accountsHandler = createRouter()
|
|
|
371
394
|
entry.buffer = '';
|
|
372
395
|
entry.phase = 'waiting-token';
|
|
373
396
|
entry.accountName = data.name;
|
|
397
|
+
entry.reauthAccountId = data.reauthAccountId ?? null;
|
|
374
398
|
|
|
375
399
|
// Write auth code to PTY, then press Enter after a short delay
|
|
376
400
|
// The delay ensures the PTY input buffer has processed the code before receiving Enter
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cline Account Management Handlers
|
|
3
|
+
*
|
|
4
|
+
* Cline is multi-provider (Anthropic, OpenAI, Google, the Cline account, …).
|
|
5
|
+
*
|
|
6
|
+
* - **API-key** providers: a simple all-fields-at-once form (`…-accounts-save`)
|
|
7
|
+
* that writes `{ provider, authMethod: 'api_key', apiKey, baseUrl?, fields? }`.
|
|
8
|
+
* - **OAuth** providers (the Cline account, Claude sign-in, …): an event-driven
|
|
9
|
+
* flow (`…-account-login-start`) driven by the SDK's provider auth handler.
|
|
10
|
+
* The handler owns its own local callback server; Clopen relays the auth URL
|
|
11
|
+
* and any interactive prompts to the client over WS (mirroring Pi's login).
|
|
12
|
+
* The returned OAuth credentials are stored as
|
|
13
|
+
* `{ provider, authMethod: 'oauth', oauth: { access, refresh, expires, … } }`.
|
|
14
|
+
*
|
|
15
|
+
* Every account's `engine_accounts.credential` is a JSON wrapper (see
|
|
16
|
+
* `backend/engine/adapters/cline/credential.ts`).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { t } from 'elysia';
|
|
20
|
+
import { getProviderAuthHandler, isOAuthProvider } from '@cline/sdk';
|
|
21
|
+
import type { OAuthLoginCallbacks, OAuthPrompt, OAuthCredentials } from '@cline/sdk';
|
|
22
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
23
|
+
import { ws } from '$backend/utils/ws';
|
|
24
|
+
import { engineQueries } from '../../../database/queries';
|
|
25
|
+
import { disposeAllProjectEnginesByType } from '../../../engine';
|
|
26
|
+
import { getClineProviderFields } from '../../../engine/adapters/cline/presets';
|
|
27
|
+
import {
|
|
28
|
+
getClineProvider,
|
|
29
|
+
parseClineCredential,
|
|
30
|
+
serializeClineCredential,
|
|
31
|
+
type ClineCredential,
|
|
32
|
+
} from '../../../engine/adapters/cline/credential';
|
|
33
|
+
import { requireSetupSessionAccess } from '../access';
|
|
34
|
+
import { debug } from '$shared/utils/logger';
|
|
35
|
+
|
|
36
|
+
async function disposeClineEngines(): Promise<void> {
|
|
37
|
+
try {
|
|
38
|
+
await disposeAllProjectEnginesByType('cline');
|
|
39
|
+
} catch {
|
|
40
|
+
/* engine may not be initialised — ignore */
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ── Interactive OAuth login sessions ──
|
|
45
|
+
|
|
46
|
+
interface ClineLoginSession {
|
|
47
|
+
userId: string;
|
|
48
|
+
disposed: boolean;
|
|
49
|
+
name: string;
|
|
50
|
+
provider: string;
|
|
51
|
+
/** When set, re-authenticate this existing account in place instead of creating one. */
|
|
52
|
+
reauthAccountId: number | null;
|
|
53
|
+
pendingPrompt: { resolve: (value: string) => void; reject: (error: Error) => void } | null;
|
|
54
|
+
timer: ReturnType<typeof setTimeout>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const loginSessions = new Map<string, ClineLoginSession>();
|
|
58
|
+
const LOGIN_TIMEOUT_MS = 15 * 60 * 1000;
|
|
59
|
+
|
|
60
|
+
function cleanupLogin(loginId: string): void {
|
|
61
|
+
const entry = loginSessions.get(loginId);
|
|
62
|
+
if (!entry || entry.disposed) return;
|
|
63
|
+
entry.disposed = true;
|
|
64
|
+
clearTimeout(entry.timer);
|
|
65
|
+
entry.pendingPrompt?.reject(new Error('Login session closed'));
|
|
66
|
+
entry.pendingPrompt = null;
|
|
67
|
+
loginSessions.delete(loginId);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const clineAccountsHandler = createRouter()
|
|
71
|
+
|
|
72
|
+
// ═══ CRUD ═══
|
|
73
|
+
|
|
74
|
+
.http('engine:cline-accounts-list', {
|
|
75
|
+
data: t.Object({}),
|
|
76
|
+
response: t.Object({
|
|
77
|
+
accounts: t.Array(t.Object({
|
|
78
|
+
id: t.Number(),
|
|
79
|
+
name: t.String(),
|
|
80
|
+
isActive: t.Boolean(),
|
|
81
|
+
createdAt: t.String(),
|
|
82
|
+
provider: t.String(),
|
|
83
|
+
authMethod: t.Union([t.Literal('api_key'), t.Literal('oauth')]),
|
|
84
|
+
/** Non-secret provider-scoped fields (base url, region, …) for edit prefill. */
|
|
85
|
+
fields: t.Record(t.String(), t.String()),
|
|
86
|
+
})),
|
|
87
|
+
})
|
|
88
|
+
}, async () => {
|
|
89
|
+
const provider = getClineProvider();
|
|
90
|
+
if (!provider) return { accounts: [] };
|
|
91
|
+
const accounts = engineQueries.getAccountsByProvider(provider.id);
|
|
92
|
+
return {
|
|
93
|
+
accounts: accounts
|
|
94
|
+
.map(a => {
|
|
95
|
+
const parsed = parseClineCredential(a.credential);
|
|
96
|
+
if (!parsed) return null;
|
|
97
|
+
const fields: Record<string, string> = { ...(parsed.fields ?? {}) };
|
|
98
|
+
if (parsed.baseUrl) fields.baseUrl = parsed.baseUrl;
|
|
99
|
+
return {
|
|
100
|
+
id: a.id,
|
|
101
|
+
name: a.name,
|
|
102
|
+
isActive: a.is_active === 1,
|
|
103
|
+
createdAt: a.created_at,
|
|
104
|
+
provider: parsed.provider,
|
|
105
|
+
authMethod: parsed.authMethod,
|
|
106
|
+
fields,
|
|
107
|
+
};
|
|
108
|
+
})
|
|
109
|
+
.filter((x): x is NonNullable<typeof x> => x !== null),
|
|
110
|
+
};
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
// Add or edit an API-key account from an all-fields-at-once form. A blank
|
|
114
|
+
// secret field on edit keeps the stored value; blank fields keep theirs.
|
|
115
|
+
.http('engine:cline-accounts-save', {
|
|
116
|
+
data: t.Object({
|
|
117
|
+
accountId: t.Optional(t.Number()),
|
|
118
|
+
name: t.String({ minLength: 1 }),
|
|
119
|
+
provider: t.String({ minLength: 1 }),
|
|
120
|
+
values: t.Record(t.String(), t.String()),
|
|
121
|
+
}),
|
|
122
|
+
response: t.Object({ success: t.Boolean(), accountId: t.Number() })
|
|
123
|
+
}, async ({ data }) => {
|
|
124
|
+
const providerRow = getClineProvider();
|
|
125
|
+
if (!providerRow) throw new Error('Cline provider not found in database');
|
|
126
|
+
|
|
127
|
+
const fieldDefs = getClineProviderFields(data.provider);
|
|
128
|
+
const keyField = fieldDefs.find(f => f.role === 'apiKey');
|
|
129
|
+
const baseUrlField = fieldDefs.find(f => f.role === 'baseUrl');
|
|
130
|
+
const extraFields = fieldDefs.filter(f => f.role === 'field');
|
|
131
|
+
|
|
132
|
+
const existing = data.accountId != null
|
|
133
|
+
? parseClineCredential(engineQueries.getAccount(data.accountId)?.credential)
|
|
134
|
+
: null;
|
|
135
|
+
|
|
136
|
+
const providedKey = keyField ? (data.values[keyField.key] ?? '').trim() : '';
|
|
137
|
+
const apiKey = providedKey || existing?.apiKey || '';
|
|
138
|
+
if (!apiKey) throw new Error('API key is required');
|
|
139
|
+
|
|
140
|
+
const providedBaseUrl = baseUrlField ? (data.values[baseUrlField.key] ?? '').trim() : '';
|
|
141
|
+
const baseUrl = providedBaseUrl || existing?.baseUrl;
|
|
142
|
+
|
|
143
|
+
const fields: Record<string, string> = { ...(existing?.fields ?? {}) };
|
|
144
|
+
for (const field of extraFields) {
|
|
145
|
+
const value = (data.values[field.key] ?? '').trim();
|
|
146
|
+
if (value) fields[field.key] = value;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const credential: ClineCredential = {
|
|
150
|
+
provider: data.provider,
|
|
151
|
+
authMethod: 'api_key',
|
|
152
|
+
apiKey,
|
|
153
|
+
...(baseUrl ? { baseUrl } : {}),
|
|
154
|
+
...(Object.keys(fields).length ? { fields } : {}),
|
|
155
|
+
};
|
|
156
|
+
const serialized = serializeClineCredential(credential);
|
|
157
|
+
|
|
158
|
+
let accountId: number;
|
|
159
|
+
if (data.accountId != null && engineQueries.getAccount(data.accountId)) {
|
|
160
|
+
engineQueries.updateAccountCredential(data.accountId, serialized);
|
|
161
|
+
engineQueries.renameAccount(data.accountId, data.name.trim());
|
|
162
|
+
accountId = data.accountId;
|
|
163
|
+
} else {
|
|
164
|
+
accountId = engineQueries.createAccount(providerRow.id, data.name.trim(), serialized).id;
|
|
165
|
+
}
|
|
166
|
+
await disposeClineEngines();
|
|
167
|
+
return { success: true, accountId };
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
.http('engine:cline-accounts-switch', {
|
|
171
|
+
data: t.Object({ id: t.Number() }),
|
|
172
|
+
response: t.Object({ success: t.Boolean() })
|
|
173
|
+
}, async ({ data }) => {
|
|
174
|
+
engineQueries.switchAccount(data.id);
|
|
175
|
+
await disposeClineEngines();
|
|
176
|
+
return { success: true };
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
.http('engine:cline-accounts-delete', {
|
|
180
|
+
data: t.Object({ id: t.Number() }),
|
|
181
|
+
response: t.Object({ success: t.Boolean() })
|
|
182
|
+
}, async ({ data }) => {
|
|
183
|
+
const active = engineQueries.getActiveAccountForEngine('cline');
|
|
184
|
+
engineQueries.deleteAccount(data.id);
|
|
185
|
+
if (active?.id === data.id) await disposeClineEngines();
|
|
186
|
+
return { success: true };
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
.http('engine:cline-accounts-rename', {
|
|
190
|
+
data: t.Object({ id: t.Number(), name: t.String({ minLength: 1 }) }),
|
|
191
|
+
response: t.Object({ success: t.Boolean() })
|
|
192
|
+
}, async ({ data }) => {
|
|
193
|
+
engineQueries.renameAccount(data.id, data.name.trim());
|
|
194
|
+
return { success: true };
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
// ═══ OAuth login (event-driven) ═══
|
|
198
|
+
|
|
199
|
+
.on('engine:cline-account-login-start', {
|
|
200
|
+
data: t.Object({
|
|
201
|
+
name: t.String({ minLength: 1 }),
|
|
202
|
+
provider: t.String({ minLength: 1 }),
|
|
203
|
+
reauthAccountId: t.Optional(t.Number()),
|
|
204
|
+
})
|
|
205
|
+
}, async ({ data, conn }) => {
|
|
206
|
+
const userId = ws.getUserId(conn);
|
|
207
|
+
const loginId = crypto.randomUUID();
|
|
208
|
+
|
|
209
|
+
const handler = getProviderAuthHandler(data.provider);
|
|
210
|
+
if (!handler || !isOAuthProvider(data.provider)) {
|
|
211
|
+
ws.emit.user(userId, 'engine:cline-account-login-error', { loginId, message: `Provider "${data.provider}" does not support OAuth sign-in.` });
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const entry: ClineLoginSession = {
|
|
216
|
+
userId, disposed: false,
|
|
217
|
+
name: data.name.trim(), provider: data.provider,
|
|
218
|
+
reauthAccountId: data.reauthAccountId ?? null,
|
|
219
|
+
pendingPrompt: null,
|
|
220
|
+
timer: setTimeout(() => {
|
|
221
|
+
ws.emit.user(userId, 'engine:cline-account-login-error', { loginId, message: 'Login timed out after 15 minutes' });
|
|
222
|
+
cleanupLogin(loginId);
|
|
223
|
+
}, LOGIN_TIMEOUT_MS),
|
|
224
|
+
};
|
|
225
|
+
loginSessions.set(loginId, entry);
|
|
226
|
+
ws.emit.user(userId, 'engine:cline-account-login-started', { loginId });
|
|
227
|
+
|
|
228
|
+
const awaitPrompt = (message: string): Promise<string> =>
|
|
229
|
+
new Promise<string>((resolve, reject) => {
|
|
230
|
+
entry.pendingPrompt = { resolve, reject };
|
|
231
|
+
ws.emit.user(userId, 'engine:cline-account-login-prompt', { loginId, message });
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
const callbacks: OAuthLoginCallbacks = {
|
|
235
|
+
onAuth: (info: { url: string; instructions?: string }) => {
|
|
236
|
+
ws.emit.user(userId, 'engine:cline-account-login-event', {
|
|
237
|
+
loginId, kind: 'auth_url', message: info.instructions, url: info.url,
|
|
238
|
+
});
|
|
239
|
+
},
|
|
240
|
+
onPrompt: (prompt: OAuthPrompt) => awaitPrompt(prompt.message),
|
|
241
|
+
onProgress: (message: string) => {
|
|
242
|
+
ws.emit.user(userId, 'engine:cline-account-login-event', { loginId, kind: 'progress', message });
|
|
243
|
+
},
|
|
244
|
+
onManualCodeInput: () => awaitPrompt('Paste the authorization code from your browser:'),
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
try {
|
|
248
|
+
const credential = (await handler.login({ callbacks })) as OAuthCredentials;
|
|
249
|
+
if (entry.disposed) return;
|
|
250
|
+
|
|
251
|
+
const serialized = serializeClineCredential({ provider: data.provider, authMethod: 'oauth', oauth: credential });
|
|
252
|
+
let accountId: number;
|
|
253
|
+
if (entry.reauthAccountId != null && engineQueries.getAccount(entry.reauthAccountId)) {
|
|
254
|
+
engineQueries.updateAccountCredential(entry.reauthAccountId, serialized);
|
|
255
|
+
engineQueries.renameAccount(entry.reauthAccountId, entry.name);
|
|
256
|
+
accountId = entry.reauthAccountId;
|
|
257
|
+
} else {
|
|
258
|
+
const providerRow = getClineProvider();
|
|
259
|
+
if (!providerRow) throw new Error('Cline provider not found in database');
|
|
260
|
+
accountId = engineQueries.createAccount(providerRow.id, entry.name, serialized).id;
|
|
261
|
+
}
|
|
262
|
+
await disposeClineEngines();
|
|
263
|
+
|
|
264
|
+
ws.emit.user(userId, 'engine:cline-account-login-complete', { loginId, accountId });
|
|
265
|
+
cleanupLogin(loginId);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (!entry.disposed) {
|
|
268
|
+
debug.warn('engine', `Cline login failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
269
|
+
ws.emit.user(userId, 'engine:cline-account-login-error', {
|
|
270
|
+
loginId,
|
|
271
|
+
message: error instanceof Error ? error.message : 'Login failed',
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
cleanupLogin(loginId);
|
|
275
|
+
}
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
.on('engine:cline-account-login-submit', {
|
|
279
|
+
data: t.Object({ loginId: t.String(), value: t.String() })
|
|
280
|
+
}, async ({ data, conn }) => {
|
|
281
|
+
let entry: ClineLoginSession;
|
|
282
|
+
try {
|
|
283
|
+
entry = requireSetupSessionAccess(conn, data.loginId, loginSessions);
|
|
284
|
+
} catch {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
const pending = entry.pendingPrompt;
|
|
288
|
+
entry.pendingPrompt = null;
|
|
289
|
+
pending?.resolve(data.value);
|
|
290
|
+
})
|
|
291
|
+
|
|
292
|
+
.on('engine:cline-account-login-cancel', {
|
|
293
|
+
data: t.Object({ loginId: t.String() })
|
|
294
|
+
}, async ({ data, conn }) => {
|
|
295
|
+
try {
|
|
296
|
+
requireSetupSessionAccess(conn, data.loginId, loginSessions);
|
|
297
|
+
} catch {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
cleanupLogin(data.loginId);
|
|
301
|
+
})
|
|
302
|
+
|
|
303
|
+
// ═══ Event declarations (Server → Client) ═══
|
|
304
|
+
|
|
305
|
+
.emit('engine:cline-account-login-started', t.Object({ loginId: t.String() }))
|
|
306
|
+
.emit('engine:cline-account-login-event', t.Object({
|
|
307
|
+
loginId: t.String(),
|
|
308
|
+
kind: t.String(),
|
|
309
|
+
message: t.Optional(t.String()),
|
|
310
|
+
url: t.Optional(t.String()),
|
|
311
|
+
}))
|
|
312
|
+
.emit('engine:cline-account-login-prompt', t.Object({
|
|
313
|
+
loginId: t.String(),
|
|
314
|
+
message: t.String(),
|
|
315
|
+
}))
|
|
316
|
+
.emit('engine:cline-account-login-complete', t.Object({ loginId: t.String(), accountId: t.Number() }))
|
|
317
|
+
.emit('engine:cline-account-login-error', t.Object({ loginId: t.String(), message: t.String() }));
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cline Engine Router
|
|
3
|
+
*
|
|
4
|
+
* Combines status detection, account/login management, and provider presets.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
8
|
+
import { clineStatusHandler } from './status';
|
|
9
|
+
import { clineAccountsHandler } from './accounts';
|
|
10
|
+
import { clinePresetsHandler } from './presets';
|
|
11
|
+
|
|
12
|
+
export const clineEngineRouter = createRouter()
|
|
13
|
+
.merge(clineStatusHandler)
|
|
14
|
+
.merge(clineAccountsHandler)
|
|
15
|
+
.merge(clinePresetsHandler);
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cline Provider Presets Handler
|
|
3
|
+
*
|
|
4
|
+
* Exposes the Cline provider catalog (id, name, supported auth modes, credential
|
|
5
|
+
* fields) to the frontend so the login picker can render the right flow per
|
|
6
|
+
* provider without importing backend modules directly. Built from the `@cline/llms`
|
|
7
|
+
* catalog + `getProviderConfigFields`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { t } from 'elysia';
|
|
11
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
12
|
+
import { getClineProviderPresets } from '../../../engine/adapters/cline/presets';
|
|
13
|
+
|
|
14
|
+
export const clinePresetsHandler = createRouter()
|
|
15
|
+
.http('engine:cline-presets-list', {
|
|
16
|
+
data: t.Object({}),
|
|
17
|
+
response: t.Object({
|
|
18
|
+
presets: t.Array(t.Object({
|
|
19
|
+
id: t.String(),
|
|
20
|
+
name: t.String(),
|
|
21
|
+
authModes: t.Array(t.Union([t.Literal('api_key'), t.Literal('oauth')])),
|
|
22
|
+
fields: t.Optional(t.Array(t.Object({
|
|
23
|
+
key: t.String(),
|
|
24
|
+
label: t.String(),
|
|
25
|
+
secret: t.Boolean(),
|
|
26
|
+
role: t.Union([t.Literal('apiKey'), t.Literal('baseUrl'), t.Literal('field')]),
|
|
27
|
+
placeholder: t.Optional(t.String()),
|
|
28
|
+
optional: t.Optional(t.Boolean()),
|
|
29
|
+
}))),
|
|
30
|
+
oauthLabel: t.Optional(t.String()),
|
|
31
|
+
apiKeyUrl: t.Optional(t.String()),
|
|
32
|
+
})),
|
|
33
|
+
})
|
|
34
|
+
}, async () => {
|
|
35
|
+
return { presets: await getClineProviderPresets() };
|
|
36
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cline Engine Status Handler
|
|
3
|
+
*
|
|
4
|
+
* Cline is an in-process SDK (`@cline/sdk`) — there is no CLI to install, so
|
|
5
|
+
* `installed` is always true. Reports the SDK version and active account state.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { t } from 'elysia';
|
|
9
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
10
|
+
import { engineQueries } from '../../../database/queries';
|
|
11
|
+
import { debug } from '$shared/utils/logger';
|
|
12
|
+
import { getBackendOS } from '../../../utils/os';
|
|
13
|
+
|
|
14
|
+
function readSdkVersion(): string | null {
|
|
15
|
+
try {
|
|
16
|
+
const path = require.resolve('@cline/sdk/package.json');
|
|
17
|
+
const pkg = require(path) as { version?: string };
|
|
18
|
+
return pkg.version ?? null;
|
|
19
|
+
} catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const clineStatusHandler = createRouter()
|
|
25
|
+
.http('engine:cline-status', {
|
|
26
|
+
data: t.Object({}),
|
|
27
|
+
response: t.Object({
|
|
28
|
+
installed: t.Boolean(),
|
|
29
|
+
version: t.Union([t.String(), t.Null()]),
|
|
30
|
+
activeAccount: t.Union([
|
|
31
|
+
t.Object({ id: t.Number(), name: t.String() }),
|
|
32
|
+
t.Null()
|
|
33
|
+
]),
|
|
34
|
+
accountsCount: t.Number(),
|
|
35
|
+
backendOS: t.Union([t.Literal('windows'), t.Literal('macos'), t.Literal('linux')])
|
|
36
|
+
})
|
|
37
|
+
}, async () => {
|
|
38
|
+
debug.log('engine', 'Checking Cline status...');
|
|
39
|
+
const provider = engineQueries.getProviderBySlug('cline', 'cline');
|
|
40
|
+
const accounts = provider ? engineQueries.getAccountsByProvider(provider.id) : [];
|
|
41
|
+
const activeAccount = engineQueries.getActiveAccountForEngine('cline');
|
|
42
|
+
return {
|
|
43
|
+
installed: true,
|
|
44
|
+
version: readSdkVersion(),
|
|
45
|
+
activeAccount: activeAccount ? { id: activeAccount.id, name: activeAccount.name } : null,
|
|
46
|
+
accountsCount: accounts.length,
|
|
47
|
+
backendOS: getBackendOS()
|
|
48
|
+
};
|
|
49
|
+
});
|