@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
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
TableDefinition
|
|
25
25
|
} from './types';
|
|
26
26
|
import { normalizeBunSqlResult } from './bun-sql-helpers';
|
|
27
|
+
import { BUN_SQL_POOL_OPTIONS } from '../pool-config';
|
|
27
28
|
import {
|
|
28
29
|
assertSafeIdentifier,
|
|
29
30
|
buildDelete,
|
|
@@ -61,7 +62,7 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
61
62
|
const db = conn.database ? `/${encodeURIComponent(conn.database)}` : '';
|
|
62
63
|
|
|
63
64
|
const url = `mysql://${auth}${host}:${port}${db}`;
|
|
64
|
-
this.sql = new SQL(url);
|
|
65
|
+
this.sql = new SQL(url, BUN_SQL_POOL_OPTIONS);
|
|
65
66
|
await this.sql.connect();
|
|
66
67
|
this.defaultDb = conn.database || null;
|
|
67
68
|
this.configuredDb = conn.database || null;
|
|
@@ -239,14 +240,27 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
239
240
|
async listObjects(database?: string): Promise<DbClientSchemaNode[]> {
|
|
240
241
|
const target = this.targetDb({ database });
|
|
241
242
|
if (!target) throw new Error('MySQL: database is required');
|
|
242
|
-
const
|
|
243
|
+
const tables = (await this.requireSql().unsafe(
|
|
243
244
|
'SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.tables WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME',
|
|
244
245
|
[target] as never
|
|
245
246
|
)) as Array<{ TABLE_NAME: string; TABLE_TYPE: string }>;
|
|
246
|
-
|
|
247
|
+
|
|
248
|
+
const routines = (await this.requireSql().unsafe(
|
|
249
|
+
'SELECT ROUTINE_NAME, ROUTINE_TYPE FROM information_schema.routines WHERE ROUTINE_SCHEMA = ? ORDER BY ROUTINE_NAME',
|
|
250
|
+
[target] as never
|
|
251
|
+
)) as Array<{ ROUTINE_NAME: string; ROUTINE_TYPE: string }>;
|
|
252
|
+
|
|
253
|
+
const tableNodes = tables.map((r) => ({
|
|
247
254
|
name: r.TABLE_NAME,
|
|
248
|
-
type: r.TABLE_TYPE === 'VIEW' ? 'view' as const : 'table' as const
|
|
255
|
+
type: r.TABLE_TYPE === 'VIEW' ? ('view' as const) : ('table' as const)
|
|
256
|
+
}));
|
|
257
|
+
|
|
258
|
+
const routineNodes = routines.map((r) => ({
|
|
259
|
+
name: r.ROUTINE_NAME,
|
|
260
|
+
type: r.ROUTINE_TYPE === 'FUNCTION' ? ('function' as const) : ('procedure' as const)
|
|
249
261
|
}));
|
|
262
|
+
|
|
263
|
+
return [...tableNodes, ...routineNodes];
|
|
250
264
|
}
|
|
251
265
|
|
|
252
266
|
async getObjectDetails(
|
|
@@ -258,6 +272,21 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
258
272
|
if (!target) throw new Error('MySQL: database is required');
|
|
259
273
|
const sql = this.requireSql();
|
|
260
274
|
|
|
275
|
+
if (_type === 'function' || _type === 'procedure') {
|
|
276
|
+
const query = _type === 'function'
|
|
277
|
+
? `SHOW CREATE FUNCTION ${Q(target)}.${Q(name)}`
|
|
278
|
+
: `SHOW CREATE PROCEDURE ${Q(target)}.${Q(name)}`;
|
|
279
|
+
|
|
280
|
+
const res = (await sql.unsafe(query)) as any[];
|
|
281
|
+
const field = _type === 'function' ? 'Create Function' : 'Create Procedure';
|
|
282
|
+
const definition = res[0]?.[field] ?? res[0]?.[field.toUpperCase()] ?? '';
|
|
283
|
+
return {
|
|
284
|
+
name,
|
|
285
|
+
type: _type,
|
|
286
|
+
ddl: String(definition)
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
261
290
|
const colRows = (await sql.unsafe(
|
|
262
291
|
`SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_KEY, EXTRA
|
|
263
292
|
FROM information_schema.columns
|
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
TableDefinition
|
|
25
25
|
} from './types';
|
|
26
26
|
import { normalizeBunSqlResult } from './bun-sql-helpers';
|
|
27
|
+
import { BUN_SQL_POOL_OPTIONS } from '../pool-config';
|
|
27
28
|
import {
|
|
28
29
|
assertSafeIdentifier,
|
|
29
30
|
buildDelete,
|
|
@@ -80,7 +81,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
80
81
|
async connect(conn: DbClientConnection, tunnelPort?: number): Promise<void> {
|
|
81
82
|
const url = this.buildUrl(conn, tunnelPort);
|
|
82
83
|
|
|
83
|
-
this.sql = new SQL(url);
|
|
84
|
+
this.sql = new SQL(url, BUN_SQL_POOL_OPTIONS);
|
|
84
85
|
await this.sql.connect();
|
|
85
86
|
this.hasConfiguredDb = !!conn.database;
|
|
86
87
|
this.homeDb = conn.database || 'postgres';
|
|
@@ -105,7 +106,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
105
106
|
if (target === this.defaultDb) return;
|
|
106
107
|
const newConn = { ...this.conn, database: target };
|
|
107
108
|
const url = this.buildUrl(newConn, this.tunnelPort);
|
|
108
|
-
const next = new SQL(url);
|
|
109
|
+
const next = new SQL(url, BUN_SQL_POOL_OPTIONS);
|
|
109
110
|
await next.connect();
|
|
110
111
|
const prevSql = this.sql;
|
|
111
112
|
this.sql = next;
|
|
@@ -278,15 +279,47 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
278
279
|
async listObjects(database?: string, schema?: string): Promise<DbClientSchemaNode[]> {
|
|
279
280
|
await this.ensureDatabase(database);
|
|
280
281
|
const target = this.targetSchema({ schema });
|
|
281
|
-
const
|
|
282
|
+
const tables = (await this.requireSql().unsafe(
|
|
282
283
|
`SELECT table_name, table_type FROM information_schema.tables
|
|
283
284
|
WHERE table_schema = $1 ORDER BY table_name`,
|
|
284
285
|
[target] as never
|
|
285
286
|
)) as Array<{ table_name: string; table_type: string }>;
|
|
286
|
-
|
|
287
|
+
|
|
288
|
+
// Query pg_proc directly (not information_schema.routines) so we can filter
|
|
289
|
+
// on prokind: keep plain functions ('f') and procedures ('p'), but exclude
|
|
290
|
+
// aggregates ('a') and window functions ('w') — those (e.g. avg/sum) have no
|
|
291
|
+
// pg_get_functiondef and would error when their DDL is opened.
|
|
292
|
+
const routines = (await this.requireSql().unsafe(
|
|
293
|
+
`SELECT p.proname AS routine_name, p.prokind
|
|
294
|
+
FROM pg_proc p
|
|
295
|
+
JOIN pg_namespace n ON p.pronamespace = n.oid
|
|
296
|
+
WHERE n.nspname = $1 AND p.prokind IN ('f', 'p')
|
|
297
|
+
ORDER BY p.proname`,
|
|
298
|
+
[target] as never
|
|
299
|
+
)) as Array<{ routine_name: string; prokind: string }>;
|
|
300
|
+
|
|
301
|
+
const tableNodes = tables.map((r) => ({
|
|
287
302
|
name: r.table_name,
|
|
288
|
-
type: r.table_type === 'VIEW' ? 'view' as const : 'table' as const
|
|
303
|
+
type: r.table_type === 'VIEW' ? ('view' as const) : ('table' as const)
|
|
289
304
|
}));
|
|
305
|
+
|
|
306
|
+
// Overloaded functions (e.g. the `citext` extension) appear once per
|
|
307
|
+
// signature. Collapse to one node per name since the tree browses and
|
|
308
|
+
// fetches routine details by name alone.
|
|
309
|
+
const seenRoutines = new Set<string>();
|
|
310
|
+
const routineNodes = routines
|
|
311
|
+
.filter((r) => {
|
|
312
|
+
const key = `${r.prokind}:${r.routine_name}`;
|
|
313
|
+
if (seenRoutines.has(key)) return false;
|
|
314
|
+
seenRoutines.add(key);
|
|
315
|
+
return true;
|
|
316
|
+
})
|
|
317
|
+
.map((r) => ({
|
|
318
|
+
name: r.routine_name,
|
|
319
|
+
type: r.prokind === 'p' ? ('procedure' as const) : ('function' as const)
|
|
320
|
+
}));
|
|
321
|
+
|
|
322
|
+
return [...tableNodes, ...routineNodes];
|
|
290
323
|
}
|
|
291
324
|
|
|
292
325
|
async getObjectDetails(
|
|
@@ -299,6 +332,23 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
299
332
|
const target = this.targetSchema({ schema });
|
|
300
333
|
const sql = this.requireSql();
|
|
301
334
|
|
|
335
|
+
if (_type === 'function' || _type === 'procedure') {
|
|
336
|
+
const routineRows = (await sql.unsafe(
|
|
337
|
+
`SELECT pg_get_functiondef(p.oid) AS definition
|
|
338
|
+
FROM pg_proc p
|
|
339
|
+
JOIN pg_namespace n ON p.pronamespace = n.oid
|
|
340
|
+
WHERE n.nspname = $1 AND p.proname = $2`,
|
|
341
|
+
[target, name] as never
|
|
342
|
+
)) as Array<{ definition: string }>;
|
|
343
|
+
|
|
344
|
+
const definition = routineRows[0]?.definition ?? '';
|
|
345
|
+
return {
|
|
346
|
+
name,
|
|
347
|
+
type: _type,
|
|
348
|
+
ddl: String(definition)
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
|
|
302
352
|
const colRows = (await sql.unsafe(
|
|
303
353
|
`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default,
|
|
304
354
|
EXISTS (
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { describe, it, expect } from 'bun:test';
|
|
2
|
+
import {
|
|
3
|
+
quoteMssql,
|
|
4
|
+
renderColumn,
|
|
5
|
+
renderCreateTable
|
|
6
|
+
} from './sql-builders';
|
|
7
|
+
|
|
8
|
+
describe('sql-builders mssql support', () => {
|
|
9
|
+
describe('quoteMssql', () => {
|
|
10
|
+
it('should quote simple identifier', () => {
|
|
11
|
+
expect(quoteMssql('users')).toBe('[users]');
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('should throw error for invalid character [', () => {
|
|
15
|
+
expect(() => quoteMssql('user[s')).toThrow();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('should throw error for invalid character ]', () => {
|
|
19
|
+
expect(() => quoteMssql('user]s')).toThrow();
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('should throw error for empty identifier', () => {
|
|
23
|
+
expect(() => quoteMssql('')).toThrow();
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe('renderColumn', () => {
|
|
28
|
+
it('should render standard identity column', () => {
|
|
29
|
+
const col = {
|
|
30
|
+
name: 'id',
|
|
31
|
+
type: 'INT',
|
|
32
|
+
nullable: false,
|
|
33
|
+
autoIncrement: true,
|
|
34
|
+
primary: true
|
|
35
|
+
};
|
|
36
|
+
const result = renderColumn({ quote: quoteMssql, column: col, driver: 'mssql' });
|
|
37
|
+
expect(result).toBe('[id] INT NOT NULL IDENTITY(1,1) PRIMARY KEY');
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('should render standard nullable column with default value', () => {
|
|
41
|
+
const col = {
|
|
42
|
+
name: 'name',
|
|
43
|
+
type: 'VARCHAR(255)',
|
|
44
|
+
nullable: true,
|
|
45
|
+
default: "'anonymous'"
|
|
46
|
+
};
|
|
47
|
+
const result = renderColumn({ quote: quoteMssql, column: col, driver: 'mssql' });
|
|
48
|
+
expect(result).toBe("[name] VARCHAR(255) DEFAULT 'anonymous'");
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe('renderCreateTable', () => {
|
|
53
|
+
it('should render correct DDL for simple table', () => {
|
|
54
|
+
const definition = {
|
|
55
|
+
name: 'products',
|
|
56
|
+
columns: [
|
|
57
|
+
{ name: 'id', type: 'INT', nullable: false, autoIncrement: true },
|
|
58
|
+
{ name: 'title', type: 'NVARCHAR(100)', nullable: true }
|
|
59
|
+
],
|
|
60
|
+
primaryKey: ['id']
|
|
61
|
+
};
|
|
62
|
+
const result = renderCreateTable({
|
|
63
|
+
quote: quoteMssql,
|
|
64
|
+
definition,
|
|
65
|
+
driver: 'mssql'
|
|
66
|
+
});
|
|
67
|
+
expect(result).toBe('CREATE TABLE [products] ([id] INT NOT NULL IDENTITY(1,1), [title] NVARCHAR(100), PRIMARY KEY ([id]))');
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
});
|
|
@@ -25,6 +25,12 @@ export function quoteSqlite(name: string): string {
|
|
|
25
25
|
return quotePg(name);
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
export function quoteMssql(name: string): string {
|
|
29
|
+
if (!name) throw new Error('Identifier cannot be empty');
|
|
30
|
+
if (name.includes('[') || name.includes(']')) throw new Error(`Invalid identifier: ${name}`);
|
|
31
|
+
return `[${name}]`;
|
|
32
|
+
}
|
|
33
|
+
|
|
28
34
|
export type Quoter = (name: string) => string;
|
|
29
35
|
|
|
30
36
|
export function qualified(quote: Quoter, parts: Array<string | undefined | null>): string {
|
|
@@ -142,7 +148,7 @@ export function buildDelete({
|
|
|
142
148
|
interface RenderColumnInput {
|
|
143
149
|
quote: Quoter;
|
|
144
150
|
column: ColumnDefinition;
|
|
145
|
-
driver: 'mysql' | 'postgres' | 'sqlite';
|
|
151
|
+
driver: 'mysql' | 'postgres' | 'sqlite' | 'mssql';
|
|
146
152
|
}
|
|
147
153
|
|
|
148
154
|
export function renderColumn({ quote, column, driver }: RenderColumnInput): string {
|
|
@@ -154,6 +160,7 @@ export function renderColumn({ quote, column, driver }: RenderColumnInput): stri
|
|
|
154
160
|
if (column.autoIncrement) {
|
|
155
161
|
if (driver === 'mysql') parts.push('AUTO_INCREMENT');
|
|
156
162
|
else if (driver === 'sqlite') parts.push('AUTOINCREMENT');
|
|
163
|
+
else if (driver === 'mssql') parts.push('IDENTITY(1,1)');
|
|
157
164
|
// PG handled via SERIAL/IDENTITY in the type itself; nothing to append.
|
|
158
165
|
}
|
|
159
166
|
if (column.primary) parts.push('PRIMARY KEY');
|
|
@@ -166,7 +173,7 @@ interface RenderTableInput {
|
|
|
166
173
|
definition: TableDefinition;
|
|
167
174
|
schema?: string;
|
|
168
175
|
database?: string;
|
|
169
|
-
driver: 'mysql' | 'postgres' | 'sqlite';
|
|
176
|
+
driver: 'mysql' | 'postgres' | 'sqlite' | 'mssql';
|
|
170
177
|
}
|
|
171
178
|
|
|
172
179
|
export function renderCreateTable({
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* db-client — shared connection-pool tuning.
|
|
3
|
+
*
|
|
4
|
+
* A DB browser has a low-concurrency workload: at most a running query plus a
|
|
5
|
+
* reserved transaction connection. The library defaults (Bun.sql `max: 10`,
|
|
6
|
+
* `idleTimeout: 0` = never release) let a single browsed connection hold up to
|
|
7
|
+
* 10 server-side sessions and keep them open indefinitely — so a few
|
|
8
|
+
* connections, database switches, or dev-mode restarts quickly exhaust the
|
|
9
|
+
* server's `max_connections` ("too many clients already"). These bounds keep
|
|
10
|
+
* the socket footprint small and let idle sockets drop on their own.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Max concurrent server connections a single adapter's pool may open. */
|
|
14
|
+
export const POOL_MAX = 3;
|
|
15
|
+
|
|
16
|
+
/** Seconds an idle pooled socket is kept before the driver closes it. */
|
|
17
|
+
export const POOL_IDLE_TIMEOUT_SEC = 20;
|
|
18
|
+
|
|
19
|
+
/** Seconds to wait for a new connection before failing. */
|
|
20
|
+
export const POOL_CONNECTION_TIMEOUT_SEC = 30;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Pool options for Bun.sql-based adapters (Postgres, MySQL).
|
|
24
|
+
* `maxLifetime: 0` keeps healthy connections; idle release is handled by
|
|
25
|
+
* `idleTimeout` instead.
|
|
26
|
+
*/
|
|
27
|
+
export const BUN_SQL_POOL_OPTIONS = {
|
|
28
|
+
max: POOL_MAX,
|
|
29
|
+
idleTimeout: POOL_IDLE_TIMEOUT_SEC,
|
|
30
|
+
maxLifetime: 0,
|
|
31
|
+
connectionTimeout: POOL_CONNECTION_TIMEOUT_SEC
|
|
32
|
+
} as const;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { describe, it, expect } from 'bun:test';
|
|
2
|
+
import { applyAutoLimitMssql } from './query-executor';
|
|
3
|
+
|
|
4
|
+
describe('applyAutoLimitMssql', () => {
|
|
5
|
+
it('injects TOP into a plain SELECT', () => {
|
|
6
|
+
expect(applyAutoLimitMssql('SELECT * FROM users', 500)).toBe('SELECT TOP (500) * FROM users');
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
it('injects TOP after DISTINCT', () => {
|
|
10
|
+
expect(applyAutoLimitMssql('SELECT DISTINCT name FROM users', 500)).toBe(
|
|
11
|
+
'SELECT DISTINCT TOP (500) name FROM users'
|
|
12
|
+
);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('strips a trailing semicolon before injecting', () => {
|
|
16
|
+
expect(applyAutoLimitMssql('SELECT id FROM t;', 100)).toBe('SELECT TOP (100) id FROM t');
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('leaves a query that already has TOP untouched', () => {
|
|
20
|
+
expect(applyAutoLimitMssql('SELECT TOP 10 * FROM users', 500)).toBe('SELECT TOP 10 * FROM users');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('leaves an OFFSET/FETCH paged query untouched', () => {
|
|
24
|
+
const q = 'SELECT * FROM users ORDER BY id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY';
|
|
25
|
+
expect(applyAutoLimitMssql(q, 500)).toBe(q);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('does not touch WITH / CTE queries', () => {
|
|
29
|
+
const q = 'WITH cte AS (SELECT 1 AS n) SELECT * FROM cte';
|
|
30
|
+
expect(applyAutoLimitMssql(q, 500)).toBe(q);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('does not touch non-SELECT statements', () => {
|
|
34
|
+
expect(applyAutoLimitMssql('UPDATE users SET name = 1', 500)).toBe('UPDATE users SET name = 1');
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('injects TOP even when the SELECT is preceded by a comment', () => {
|
|
38
|
+
expect(applyAutoLimitMssql('-- fetch users\nSELECT * FROM users', 500)).toBe(
|
|
39
|
+
'-- fetch users\nSELECT TOP (500) * FROM users'
|
|
40
|
+
);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
@@ -104,6 +104,50 @@ export function applyAutoLimit(query: string, limit = 500): string {
|
|
|
104
104
|
return `${trimmed} LIMIT ${limit}`;
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
/**
|
|
108
|
+
* SQL Server has no `LIMIT`; the equivalent cap is `TOP (n)` right after the
|
|
109
|
+
* `SELECT` keyword. Conservative — only touches a plain leading `SELECT`
|
|
110
|
+
* (skips `WITH`/CTE where TOP placement is ambiguous) and leaves queries that
|
|
111
|
+
* already cap or page (`TOP`, `OFFSET … ROWS`) untouched.
|
|
112
|
+
*/
|
|
113
|
+
export function applyAutoLimitMssql(query: string, limit = 500): string {
|
|
114
|
+
const trimmed = query.replace(/;\s*$/, '');
|
|
115
|
+
if (firstSqlKeyword(trimmed) !== 'SELECT') return query;
|
|
116
|
+
if (/\boffset\s+\d+\s+rows?\b/i.test(trimmed)) return query;
|
|
117
|
+
|
|
118
|
+
// Locate the leading SELECT token, skipping whitespace and comments.
|
|
119
|
+
let i = 0;
|
|
120
|
+
while (i < trimmed.length) {
|
|
121
|
+
const ch = trimmed[i];
|
|
122
|
+
if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
|
|
123
|
+
i++;
|
|
124
|
+
} else if (ch === '-' && trimmed[i + 1] === '-') {
|
|
125
|
+
const nl = trimmed.indexOf('\n', i);
|
|
126
|
+
if (nl === -1) return query;
|
|
127
|
+
i = nl + 1;
|
|
128
|
+
} else if (ch === '/' && trimmed[i + 1] === '*') {
|
|
129
|
+
const end = trimmed.indexOf('*/', i + 2);
|
|
130
|
+
if (end === -1) return query;
|
|
131
|
+
i = end + 2;
|
|
132
|
+
} else {
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const after = trimmed.slice(i);
|
|
137
|
+
const m = /^select\s+(distinct\s+|all\s+)?/i.exec(after);
|
|
138
|
+
if (!m) return query;
|
|
139
|
+
if (/^top\b/i.test(after.slice(m[0].length))) return query;
|
|
140
|
+
const insertAt = i + m[0].length;
|
|
141
|
+
return `${trimmed.slice(0, insertAt)}TOP (${limit}) ${trimmed.slice(insertAt)}`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Apply the driver-appropriate auto-limit to a read query (no-op for drivers without one). */
|
|
145
|
+
function autoLimitForDriver(driver: DbDriver, query: string, limit: number): string {
|
|
146
|
+
if (driver === 'mysql' || driver === 'postgres' || driver === 'sqlite') return applyAutoLimit(query, limit);
|
|
147
|
+
if (driver === 'mssql') return applyAutoLimitMssql(query, limit);
|
|
148
|
+
return query;
|
|
149
|
+
}
|
|
150
|
+
|
|
107
151
|
interface RunSafelyInput {
|
|
108
152
|
driver: DbDriver;
|
|
109
153
|
adapter: DbClientDriverAdapter;
|
|
@@ -118,8 +162,8 @@ export async function runSafely(input: RunSafelyInput): Promise<DbClientQueryRes
|
|
|
118
162
|
const { adapter, driver, mode, params, database, limit } = input;
|
|
119
163
|
let query = input.query;
|
|
120
164
|
|
|
121
|
-
if (mode === 'read'
|
|
122
|
-
query =
|
|
165
|
+
if (mode === 'read') {
|
|
166
|
+
query = autoLimitForDriver(driver, query, limit ?? 500);
|
|
123
167
|
}
|
|
124
168
|
|
|
125
169
|
const fn = mode === 'read' ? adapter.executeRead : adapter.executeWrite;
|
|
@@ -164,7 +208,7 @@ export async function executeBatch(input: ExecuteBatchInput): Promise<DbClientBa
|
|
|
164
208
|
}
|
|
165
209
|
try {
|
|
166
210
|
const result = queryClass === 'read'
|
|
167
|
-
? await exec.executeRead(
|
|
211
|
+
? await exec.executeRead(autoLimitForDriver(driver, query, limit ?? 500), params, { database })
|
|
168
212
|
: await exec.executeWrite(query, params, { database });
|
|
169
213
|
totalDurationMs += result.durationMs;
|
|
170
214
|
results.push({ index, query, queryClass, status: 'success', result, error: null, durationMs: result.durationMs });
|
package/backend/engine/README.md
CHANGED
|
@@ -1,12 +1,34 @@
|
|
|
1
1
|
# `backend/engine/` — End-to-End Adapter Guide
|
|
2
2
|
|
|
3
3
|
This folder is the **boundary** between Clopen and the AI SDKs that drive
|
|
4
|
-
streaming chat.
|
|
5
|
-
(`@anthropic-ai/claude-agent-sdk`), **`opencode`** (`@opencode-ai/sdk`),
|
|
6
|
-
**`copilot`** (`@github/copilot-sdk`)
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
4
|
+
streaming chat. The adapters today: **`claude`**
|
|
5
|
+
(`@anthropic-ai/claude-agent-sdk`), **`opencode`** (`@opencode-ai/sdk`),
|
|
6
|
+
**`copilot`** (`@github/copilot-sdk`), **`codex`** (`@openai/codex-sdk`),
|
|
7
|
+
**`qwen`** (`@qwen-code/qwen-code`), **`pi`**
|
|
8
|
+
(`@earendil-works/pi-coding-agent`), **`cline`** (`@cline/sdk`), and
|
|
9
|
+
**`cursor`** (`@cursor/sdk`). Every
|
|
10
|
+
adapter follows the same shape so that the rest of the system outside this
|
|
11
|
+
folder — `stream-manager`, MCP, DB, WebSocket, frontend chat, settings UI —
|
|
12
|
+
stays **agnostic** to the underlying SDK.
|
|
13
|
+
|
|
14
|
+
> **In-process, session-less SDKs are their own category.** Most adapters
|
|
15
|
+
> wrap a CLI subprocess or an SDK that owns a session store (on disk or via a
|
|
16
|
+
> server). `cline` is different: `@cline/sdk`'s stateless `Agent` holds **no**
|
|
17
|
+
> session store at all, so the adapter reconstructs branch history in memory
|
|
18
|
+
> and synthesizes the sub-agent (`Agent`) tool itself. Both were bug sources
|
|
19
|
+
> during bring-up — read **§10.10** (checkpoint forks) and **§10.15**
|
|
20
|
+
> (sub-agents) in [lessons-learned](./docs/lessons-learned.md) before adding a
|
|
21
|
+
> similar engine.
|
|
22
|
+
|
|
23
|
+
> **Delta-stream SDKs are another category.** `cursor` (`@cursor/sdk`) is
|
|
24
|
+
> in-process with an on-disk store like `pi`, but its `run.stream()` emits each
|
|
25
|
+
> text/thinking CHUNK as its own message (deltas, not snapshots), routes MCP +
|
|
26
|
+
> custom tools through a single wrapper tool, streams sub-agents only via
|
|
27
|
+
> `onDelta`, and reports no context-window metadata. If a new SDK is delta-based,
|
|
28
|
+
> tool-wrapping, or metadata-poor, read **§10.20** in
|
|
29
|
+
> [lessons-learned](./docs/lessons-learned.md) before writing the converter — and
|
|
30
|
+
> capture the SDK's real runtime shapes with a throwaway script rather than
|
|
31
|
+
> trusting its `.d.ts`.
|
|
10
32
|
|
|
11
33
|
This guide is split into focused documents — start here for the architecture
|
|
12
34
|
map, then jump to the area you need.
|
|
@@ -19,9 +41,10 @@ map, then jump to the area you need.
|
|
|
19
41
|
4. [WebSocket routes](./docs/websocket-routes.md) — `engine:*`, `system-tools:*`, `models:list`, `chat:stream`, and the Restart-Server pattern.
|
|
20
42
|
5. [Frontend & chat integration](./docs/frontend-and-chat.md) — Settings → Engines / System Tools, the model picker, the send path, reasoning/attachments/AskUserQuestion.
|
|
21
43
|
6. [System Tools](./docs/system-tools.md) — registering a binary in `install-recipes.ts` + the install runner.
|
|
22
|
-
7. [
|
|
23
|
-
8. [
|
|
24
|
-
9. [
|
|
44
|
+
7. [Artifacts & Access](./docs/artifacts.md) — the extension layer (Skills, Commands, Subagents, Instructions, Permissions, Profiles, MCP), the capability matrix, and the `artifact-sync.ts` seam adapters call at stream start.
|
|
45
|
+
8. [Adding a new engine](./docs/adding-an-engine.md) — the end-to-end, stage-by-stage checklist.
|
|
46
|
+
9. [Lessons learned](./docs/lessons-learned.md) — §10 pitfalls (tool name/input canonicalisation, fork session, MCP reuse, auth-blob swap, sub-agent routing, OpenCode v1/v2, structured output, …).
|
|
47
|
+
10. [Quick reference](./docs/quick-reference.md) — "I need X → look in file Y" table.
|
|
25
48
|
|
|
26
49
|
---
|
|
27
50
|
|
|
@@ -32,7 +55,7 @@ map, then jump to the area you need.
|
|
|
32
55
|
│ │
|
|
33
56
|
│ Settings → Engines Settings → System Tools Chat Input │
|
|
34
57
|
│ ───────────────────── ────────────────────── ────────────── │
|
|
35
|
-
│ AIEnginesSettings
|
|
58
|
+
│ AIEnginesSettings+panels/ SystemToolsSettings… EngineModel… │
|
|
36
59
|
│ │ │ │ │
|
|
37
60
|
│ ├─ claudeAccountsStore └─ ws.http( ├─ model │
|
|
38
61
|
│ ├─ copilotAccountsStore 'system-tools:…') │ Store │
|
|
@@ -104,19 +127,19 @@ Three key rules that **every** layer upholds:
|
|
|
104
127
|
> `streamable-http` MCP URL (Codex, future engines) reuses **the same
|
|
105
128
|
> URL** by adding a sibling `getXxxMcpConfig()` helper in
|
|
106
129
|
> `backend/mcp/internal/config.ts`. Do **NOT** propose a "new MCP bridge",
|
|
107
|
-
> "per-engine MCP server", or "per-stream MCP path". See §
|
|
130
|
+
> "per-engine MCP server", or "per-stream MCP path". See §10.12.
|
|
108
131
|
> 2. **Engine home dirs are isolated per-engine (Clopen vs. global), but
|
|
109
132
|
> multi-account stays DB-swap.** Two different axes — don't conflate them:
|
|
110
133
|
> - **Clopen vs. the user's global CLI usage:** every engine's home/config
|
|
111
134
|
> is redirected to `{clopenDir}/engine/{engine}/user/` via that engine's env
|
|
112
135
|
> var (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME` via
|
|
113
136
|
> `baseDirectory`, `QWEN_RUNTIME_DIR`, `XDG_*` for OpenCode) so Clopen
|
|
114
|
-
> never touches `~/.codex`, `~/.copilot`, … See §
|
|
137
|
+
> never touches `~/.codex`, `~/.copilot`, … See §10.19.
|
|
115
138
|
> - **Multiple accounts *within* Clopen:** still the auth-blob swap — one
|
|
116
139
|
> shared dotfile inside that isolated home, snapshotted to/from the DB on
|
|
117
140
|
> login/switch. Do **NOT** propose **per-account** home dirs
|
|
118
141
|
> (`CODEX_HOME=/foo/account-1/`); that splits session-state, breaks
|
|
119
|
-
> fork-by-copy, and loses token-refresh persistence. See §
|
|
142
|
+
> fork-by-copy, and loses token-refresh persistence. See §10.13.
|
|
120
143
|
|
|
121
144
|
---
|
|
122
145
|
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent dispatch tool for Cline.
|
|
3
|
+
*
|
|
4
|
+
* Cline's stateless `Agent` has no native Agent/Task primitive, so the synthetic
|
|
5
|
+
* "Available Subagents" preamble (injected into the system prompt) is
|
|
6
|
+
* informational only — the model can describe subagents but can't invoke them.
|
|
7
|
+
* This custom `Agent` tool closes that gap: calling it spawns a fresh sub-`Agent`
|
|
8
|
+
* with the subagent's system prompt, runs the delegated prompt to completion, and
|
|
9
|
+
* returns the final text as the tool result. Sub-activity does not stream to the
|
|
10
|
+
* main UI (it runs inside the tool), but the delegation actually happens.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { createTool } from '@cline/sdk';
|
|
14
|
+
import type { AgentTool, AgentToolContext } from '@cline/sdk';
|
|
15
|
+
|
|
16
|
+
export interface SubagentInfo {
|
|
17
|
+
slug: string;
|
|
18
|
+
name: string;
|
|
19
|
+
description: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface AgentDispatchBindings {
|
|
23
|
+
/** Enabled subagents advertised to the model. */
|
|
24
|
+
subagents: SubagentInfo[];
|
|
25
|
+
/**
|
|
26
|
+
* Run one subagent against a prompt; resolve with its final text output.
|
|
27
|
+
* `toolCallId` is the parent Agent tool_use id — the runner tags the
|
|
28
|
+
* subagent's messages with it so they render as sub-activities.
|
|
29
|
+
*/
|
|
30
|
+
run: (subagent: SubagentInfo, prompt: string, toolCallId: string, signal?: AbortSignal) => Promise<string>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const AGENT_INPUT_SCHEMA = {
|
|
34
|
+
type: 'object',
|
|
35
|
+
properties: {
|
|
36
|
+
subagentType: { type: 'string', description: 'The slug of the subagent to delegate to.' },
|
|
37
|
+
prompt: { type: 'string', description: 'The self-contained task for the subagent.' },
|
|
38
|
+
description: { type: 'string', description: 'A short (3-5 word) description of the delegated task.' },
|
|
39
|
+
},
|
|
40
|
+
required: ['subagentType', 'prompt', 'description'],
|
|
41
|
+
} as const;
|
|
42
|
+
|
|
43
|
+
export function createAgentDispatchTool(bindings: AgentDispatchBindings): AgentTool {
|
|
44
|
+
const catalog = bindings.subagents.map(s => `- ${s.slug}: ${s.name} — ${s.description}`).join('\n');
|
|
45
|
+
return createTool({
|
|
46
|
+
name: 'Agent',
|
|
47
|
+
description:
|
|
48
|
+
'Delegate a self-contained subtask to a specialized subagent. Pass the subagent slug as `subagentType` and the task as `prompt`. Available subagents:\n' + catalog,
|
|
49
|
+
inputSchema: AGENT_INPUT_SCHEMA,
|
|
50
|
+
async execute(input: { subagentType?: string; prompt?: string }, context: AgentToolContext) {
|
|
51
|
+
const match = bindings.subagents.find(s => s.slug === input.subagentType || s.name === input.subagentType);
|
|
52
|
+
if (!match) {
|
|
53
|
+
const names = bindings.subagents.map(s => s.slug).join(', ') || '(none configured)';
|
|
54
|
+
return `No subagent named "${input.subagentType}". Available: ${names}`;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const text = await bindings.run(match, input.prompt ?? '', context.toolCallId ?? '', context.signal);
|
|
58
|
+
return text.trim() || '(subagent produced no output)';
|
|
59
|
+
} catch (error) {
|
|
60
|
+
return `Subagent "${match.slug}" failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
}) as AgentTool;
|
|
64
|
+
}
|