@myrialabs/clopen 0.4.14 → 0.4.15
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/auth/permissions.ts +2 -0
- package/backend/database/migrations/056_support_mssql_driver.ts +137 -0
- package/backend/database/migrations/index.ts +7 -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/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/index.ts +6 -0
- 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/ws/chat/stream.ts +12 -4
- 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/codex/accounts.ts +36 -4
- package/backend/ws/engine/copilot/accounts.ts +12 -0
- package/backend/ws/engine/opencode/providers.ts +72 -1
- 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/dist/assets/{index-BWf-DDJN.js → index-ChF_jIXj.js} +1 -1
- package/dist/assets/{index-CDZf6lfv.js → index-EunAFLxP.js} +1 -1
- package/dist/assets/{main-C15mQTCW.js → main-CTs4NXwP.js} +407 -367
- package/dist/assets/main-moCAkEwm.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +5 -1
- package/shared/types/db-client/connection.ts +1 -1
- package/shared/types/db-client/query.ts +4 -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 });
|
|
@@ -67,6 +67,15 @@ export function generateOpenCodeProviderConfig(): OpenCodeProviderConfigResult {
|
|
|
67
67
|
|
|
68
68
|
for (const provider of providers) {
|
|
69
69
|
const activeAccount = engineQueries.getActiveAccount(provider.id);
|
|
70
|
+
|
|
71
|
+
// Custom providers (api_url set) are OpenAI-compatible endpoints that
|
|
72
|
+
// don't need env-var management — the config injection in server.ts
|
|
73
|
+
// handles npm + baseURL + model discovery from /v1/models.
|
|
74
|
+
if (provider.api_url) {
|
|
75
|
+
enabledProviders.push(provider.slug);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
|
|
70
79
|
if (!activeAccount) continue;
|
|
71
80
|
|
|
72
81
|
enabledProviders.push(provider.slug);
|
|
@@ -22,8 +22,17 @@ export async function fetchOpenCodeModels(client: OpencodeClient): Promise<Engin
|
|
|
22
22
|
|
|
23
23
|
for (const provider of providers) {
|
|
24
24
|
const providerModels: Record<string, Model> = provider.models ?? {};
|
|
25
|
+
const modelOrder = (provider.options._modelOrder as string[]) ?? [];
|
|
25
26
|
|
|
26
|
-
|
|
27
|
+
const entries = modelOrder.length > 0
|
|
28
|
+
? [...Object.entries(providerModels)].sort((a, b) => {
|
|
29
|
+
const ai = modelOrder.indexOf(a[0]);
|
|
30
|
+
const bi = modelOrder.indexOf(b[0]);
|
|
31
|
+
return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi);
|
|
32
|
+
})
|
|
33
|
+
: Object.entries(providerModels);
|
|
34
|
+
|
|
35
|
+
for (const [, model] of entries) {
|
|
27
36
|
models.push({
|
|
28
37
|
engine: {
|
|
29
38
|
type: 'opencode',
|
|
@@ -25,8 +25,8 @@ import { join } from 'path';
|
|
|
25
25
|
import type { OpencodeClient } from '@opencode-ai/sdk';
|
|
26
26
|
import type { Subprocess } from 'bun';
|
|
27
27
|
import { getOpenCodeMcpConfig } from '../../../mcp';
|
|
28
|
-
import { settingsQueries } from '../../../database/queries';
|
|
29
|
-
import { generateOpenCodeProviderConfig } from './config';
|
|
28
|
+
import { engineQueries, settingsQueries } from '../../../database/queries';
|
|
29
|
+
import { generateOpenCodeProviderConfig, parseCredentialMap } from './config';
|
|
30
30
|
import type { OpenCodeInlineAgent } from '$backend/subagents';
|
|
31
31
|
import { resolveBinaryWithRefresh } from '$backend/utils/cli';
|
|
32
32
|
import { getEngineUserConfigDir } from '$backend/utils/paths';
|
|
@@ -195,6 +195,114 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
|
|
|
195
195
|
if (Object.keys(mcpConfig).length > 0) mergedConfig.mcp = mcpConfig;
|
|
196
196
|
if (providerConfig.enabledProviders.length > 0) mergedConfig.enabled_providers = providerConfig.enabledProviders;
|
|
197
197
|
if (spec.inlineAgents && Object.keys(spec.inlineAgents).length > 0) mergedConfig.agent = spec.inlineAgents;
|
|
198
|
+
|
|
199
|
+
// Inject provider definitions for custom OpenAI-compatible providers
|
|
200
|
+
// (those with api_url set). Unlike models.dev catalog providers, custom
|
|
201
|
+
// providers need their npm + baseURL passed explicitly so the opencode
|
|
202
|
+
// server can discover models from their /v1/models endpoint.
|
|
203
|
+
const providerSection: Record<string, unknown> = {};
|
|
204
|
+
const opencodeProviders = engineQueries.getEnabledProviders('opencode');
|
|
205
|
+
for (const provider of opencodeProviders) {
|
|
206
|
+
if (!provider.api_url) continue;
|
|
207
|
+
|
|
208
|
+
// Resolve the active account's credential so we can (a) authenticate the
|
|
209
|
+
// endpoint and (b) substitute `${VAR}` placeholders in the base URL.
|
|
210
|
+
// Multi-secret providers (e.g. Cloudflare Workers AI, whose URL embeds
|
|
211
|
+
// ${CLOUDFLARE_ACCOUNT_ID} and whose bearer is CLOUDFLARE_API_KEY) store
|
|
212
|
+
// every secret as a JSON bundle; single-key providers store a raw string.
|
|
213
|
+
const activeAccount = engineQueries.getActiveAccount(provider.id);
|
|
214
|
+
let baseURL = provider.api_url;
|
|
215
|
+
let apiKey: string | undefined;
|
|
216
|
+
if (activeAccount?.credential) {
|
|
217
|
+
const credMap = parseCredentialMap(activeAccount.credential);
|
|
218
|
+
if (credMap) {
|
|
219
|
+
baseURL = baseURL.replace(/\$\{(\w+)\}/g, (_m, name) => credMap[name] ?? '');
|
|
220
|
+
const keys = Object.keys(credMap);
|
|
221
|
+
const tokenKey = keys.find(k => /API[_-]?(?:KEY|TOKEN)$/i.test(k)) ?? keys.find(k => /(?:KEY|TOKEN)$/i.test(k));
|
|
222
|
+
if (tokenKey) apiKey = credMap[tokenKey];
|
|
223
|
+
} else {
|
|
224
|
+
apiKey = activeAccount.credential;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const models: Record<string, { name: string; limit: { context: number; output: number } }> = {};
|
|
229
|
+
// Per-model limits live in `modelLimits`; legacy provider-level
|
|
230
|
+
// contextLimit/outputLimit remain a fallback for older rows.
|
|
231
|
+
let defaultContext = 128000;
|
|
232
|
+
let defaultOutput = 16384;
|
|
233
|
+
let modelLimits: Record<string, { context?: number; output?: number }> = {};
|
|
234
|
+
let modelNames: Record<string, string> = {};
|
|
235
|
+
let hiddenSet = new Set<string>();
|
|
236
|
+
try {
|
|
237
|
+
const opts = JSON.parse(provider.options || '{}') as {
|
|
238
|
+
models?: string[];
|
|
239
|
+
modelNames?: Record<string, string>;
|
|
240
|
+
hiddenModels?: string[];
|
|
241
|
+
modelLimits?: Record<string, { context?: number; output?: number }>;
|
|
242
|
+
contextLimit?: number;
|
|
243
|
+
outputLimit?: number;
|
|
244
|
+
};
|
|
245
|
+
if (opts.contextLimit) defaultContext = opts.contextLimit;
|
|
246
|
+
if (opts.outputLimit) defaultOutput = opts.outputLimit;
|
|
247
|
+
if (opts.modelLimits) modelLimits = opts.modelLimits;
|
|
248
|
+
if (opts.modelNames) modelNames = opts.modelNames;
|
|
249
|
+
if (opts.hiddenModels) hiddenSet = new Set(opts.hiddenModels);
|
|
250
|
+
} catch {
|
|
251
|
+
// malformed options — proceed to auto-discover
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const addModel = (id: string) => {
|
|
255
|
+
const lim = modelLimits[id];
|
|
256
|
+
models[id] = { name: modelNames[id] || id, limit: { context: lim?.context || defaultContext, output: lim?.output || defaultOutput } };
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
try {
|
|
260
|
+
const opts = JSON.parse(provider.options || '{}') as { models?: string[] };
|
|
261
|
+
if (opts.models && opts.models.length > 0) {
|
|
262
|
+
for (const id of opts.models) {
|
|
263
|
+
if (!hiddenSet.has(id)) addModel(id);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
} catch {
|
|
267
|
+
// malformed options — proceed to auto-discover
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Auto-discover models from /v1/models if none stored in options
|
|
271
|
+
if (Object.keys(models).length === 0) {
|
|
272
|
+
try {
|
|
273
|
+
const baseUrl = baseURL.replace(/\/+$/, '');
|
|
274
|
+
const res = await fetch(`${baseUrl}/models`, {
|
|
275
|
+
headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
|
|
276
|
+
signal: AbortSignal.timeout(3000),
|
|
277
|
+
});
|
|
278
|
+
if (res.ok) {
|
|
279
|
+
const body = await res.json() as { data?: { id: string }[] };
|
|
280
|
+
for (const m of body.data ?? []) {
|
|
281
|
+
addModel(m.id);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
// Provider may not be running — models will be empty.
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
let modelOrder: string[] | undefined;
|
|
290
|
+
try {
|
|
291
|
+
const o = JSON.parse(provider.options || '{}') as { models?: string[] };
|
|
292
|
+
if (o.models && o.models.length > 0) modelOrder = o.models.filter(id => !hiddenSet.has(id));
|
|
293
|
+
} catch { /* ignore */ }
|
|
294
|
+
const providerOptions: Record<string, unknown> = { baseURL };
|
|
295
|
+
if (apiKey) providerOptions.apiKey = apiKey;
|
|
296
|
+
if (modelOrder) providerOptions._modelOrder = modelOrder;
|
|
297
|
+
providerSection[provider.slug] = {
|
|
298
|
+
npm: provider.npm || '@ai-sdk/openai-compatible',
|
|
299
|
+
name: provider.name,
|
|
300
|
+
options: providerOptions,
|
|
301
|
+
models: models,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
if (Object.keys(providerSection).length > 0) mergedConfig.provider = providerSection;
|
|
305
|
+
|
|
198
306
|
const configContent = Object.keys(mergedConfig).length > 0 ? JSON.stringify(mergedConfig) : '{}';
|
|
199
307
|
|
|
200
308
|
const proc = Bun.spawn(args, {
|
package/backend/index.ts
CHANGED
|
@@ -25,6 +25,7 @@ import { loggerMiddleware } from './middleware/logger';
|
|
|
25
25
|
import { initializeDatabase, closeDatabase } from './database';
|
|
26
26
|
import { syncInternalServers } from './mcp';
|
|
27
27
|
import { disposeAllEngines } from './engine';
|
|
28
|
+
import { connectionManager } from './db-client/connection-manager';
|
|
28
29
|
import { refreshProcessPath } from './utils/path-enrich';
|
|
29
30
|
import { debug } from '$shared/utils/logger';
|
|
30
31
|
import { networkInterfaces } from 'os';
|
|
@@ -260,6 +261,11 @@ async function gracefulShutdown() {
|
|
|
260
261
|
try {
|
|
261
262
|
// Stop accepting new connections first — release the port ASAP
|
|
262
263
|
app.stop();
|
|
264
|
+
// Release DB Client pools up front so remote server sessions are freed
|
|
265
|
+
// immediately on restart (dev `bun --watch`), before the slower engine
|
|
266
|
+
// and browser teardown below — otherwise the old process keeps those
|
|
267
|
+
// sockets open long enough to overlap the new process ("too many clients").
|
|
268
|
+
await connectionManager.closeAll();
|
|
263
269
|
// Dispose rate limiter timer
|
|
264
270
|
authRateLimiter.dispose();
|
|
265
271
|
// Dispose expired session cleanup timer
|
|
@@ -366,7 +366,7 @@ export class BrowserPreviewService extends EventEmitter {
|
|
|
366
366
|
// ============================================================================
|
|
367
367
|
// WebCodecs Streaming Methods (optimized, ~20-40ms, lower bandwidth)
|
|
368
368
|
// ============================================================================
|
|
369
|
-
async startWebCodecsStreaming(tabId: string): Promise<boolean> {
|
|
369
|
+
async startWebCodecsStreaming(tabId: string, allowVp9 = true): Promise<boolean> {
|
|
370
370
|
const tab = this.getTab(tabId);
|
|
371
371
|
if (!tab) {
|
|
372
372
|
return false;
|
|
@@ -374,7 +374,8 @@ export class BrowserPreviewService extends EventEmitter {
|
|
|
374
374
|
return await this.videoCapture.startStreaming(
|
|
375
375
|
tabId,
|
|
376
376
|
tab,
|
|
377
|
-
() => this.isValidTab(tabId)
|
|
377
|
+
() => this.isValidTab(tabId),
|
|
378
|
+
allowVp9
|
|
378
379
|
);
|
|
379
380
|
}
|
|
380
381
|
|
|
@@ -383,20 +384,28 @@ export class BrowserPreviewService extends EventEmitter {
|
|
|
383
384
|
await this.videoCapture.stopStreaming(tabId, tab ?? undefined);
|
|
384
385
|
}
|
|
385
386
|
|
|
386
|
-
async
|
|
387
|
+
async refreshWebCodecsScreencast(tabId: string): Promise<boolean> {
|
|
387
388
|
const tab = this.getTab(tabId);
|
|
388
389
|
if (!tab) {
|
|
389
390
|
return false;
|
|
390
391
|
}
|
|
391
|
-
return await this.videoCapture.
|
|
392
|
+
return await this.videoCapture.refreshScreencast(tabId, tab);
|
|
392
393
|
}
|
|
393
394
|
|
|
394
|
-
async
|
|
395
|
+
async requestWebCodecsKeyframe(tabId: string): Promise<boolean> {
|
|
395
396
|
const tab = this.getTab(tabId);
|
|
396
397
|
if (!tab) {
|
|
397
398
|
return false;
|
|
398
399
|
}
|
|
399
|
-
return await this.videoCapture.
|
|
400
|
+
return await this.videoCapture.requestKeyframe(tabId, tab);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
async updateWebCodecsViewport(tabId: string, width: number, height: number): Promise<boolean> {
|
|
404
|
+
const tab = this.getTab(tabId);
|
|
405
|
+
if (!tab) {
|
|
406
|
+
return false;
|
|
407
|
+
}
|
|
408
|
+
return await this.videoCapture.updateViewport(tabId, tab, width, height);
|
|
400
409
|
}
|
|
401
410
|
|
|
402
411
|
async getWebCodecsOffer(tabId: string): Promise<RTCSessionDescriptionInit | null> {
|