@myrialabs/clopen 0.4.28 → 0.4.30
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/auth-service.ts +45 -25
- package/backend/auth/onboarding.test.ts +106 -0
- package/backend/auth/permissions.ts +1 -1
- package/backend/database/migrations/067_add_memory_graph_layout.ts +91 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/graph-queries.ts +417 -32
- package/backend/database/utils/connection.ts +7 -31
- package/backend/db-client/drivers/mssql.ts +57 -22
- package/backend/db-client/drivers/mysql.ts +69 -48
- package/backend/db-client/drivers/postgres.ts +65 -53
- package/backend/engine/README.md +8 -3
- package/backend/engine/adapters/claude/message-converter.ts +51 -0
- package/backend/engine/adapters/claude/stream.ts +81 -15
- package/backend/engine/adapters/codex/message-converter.ts +8 -2
- package/backend/engine/adapters/codex/models.ts +85 -98
- package/backend/engine/adapters/codex/stream.ts +5 -7
- package/backend/engine/adapters/codex/usage-rollout.ts +7 -0
- package/backend/engine/adapters/copilot/stream.ts +24 -0
- package/backend/engine/docs/artifacts.md +1 -1
- package/backend/engine/docs/lessons-learned.md +78 -1
- package/backend/engine/docs/quick-reference.md +1 -1
- package/backend/engine/docs/stack.md +8 -0
- package/backend/engine/install-recipes.ts +19 -2
- package/backend/files/file-size-limit.ts +5 -14
- package/backend/files/file-watcher.test.ts +160 -0
- package/backend/files/file-watcher.ts +276 -58
- package/backend/git/git-executor.ts +8 -0
- package/backend/git/git-service.test.ts +136 -0
- package/backend/git/git-service.ts +113 -17
- package/backend/index.ts +16 -4
- package/backend/mcp/internal/remote-server.test.ts +8 -3
- package/backend/mcp/internal/remote-server.ts +1 -1
- package/backend/memory/bootstrap.ts +9 -0
- package/backend/memory/layout.ts +985 -0
- package/backend/memory/notify.ts +33 -7
- package/backend/memory/view.ts +375 -69
- package/backend/permissions/index.ts +4 -2
- package/backend/permissions/resolve.ts +7 -5
- package/backend/settings/system-settings.ts +97 -0
- package/backend/tunnel/public-origin.ts +5 -13
- package/backend/utils/env.ts +29 -0
- package/backend/utils/paths.ts +9 -3
- package/backend/utils/process-warnings.ts +41 -0
- package/backend/ws/auth/login.test.ts +8 -1
- package/backend/ws/auth/login.ts +22 -15
- package/backend/ws/auth/status.ts +24 -1
- package/backend/ws/chat/stream.ts +1 -0
- package/backend/ws/files/watch.ts +9 -0
- package/backend/ws/memory/crud.ts +50 -2
- package/backend/ws/settings/crud.ts +14 -22
- package/dist/assets/{index-BujQYGBm.js → index-DUc5T21e.js} +1 -1
- package/dist/assets/{index-DRMOgS9y.js → index-DYwQ5bP8.js} +1 -1
- package/dist/assets/main-VgdjTBLR.css +1 -0
- package/dist/assets/main-r0iv2PDz.js +1044 -0
- package/dist/index.html +2 -2
- package/package.json +14 -14
- package/shared/constants/engines.ts +1 -0
- package/shared/types/memory.ts +70 -0
- package/shared/types/stores/settings.ts +11 -1
- package/shared/types/unified/stream.ts +10 -4
- package/dist/assets/main-BrYtWn-4.js +0 -1036
- package/dist/assets/main-BrqMMMRX.css +0 -1
|
@@ -47,7 +47,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
47
47
|
private sql: SQL | null = null;
|
|
48
48
|
private alive = false;
|
|
49
49
|
// The database the active connection currently points at (switched by
|
|
50
|
-
// reconnecting in
|
|
50
|
+
// reconnecting in acquire).
|
|
51
51
|
private defaultDb: string | null = null;
|
|
52
52
|
// The connection's home database — what we revert to when no specific
|
|
53
53
|
// database is requested, so a connection-level overview doesn't keep
|
|
@@ -92,10 +92,19 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
92
92
|
this.alive = true;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
-
|
|
96
|
-
|
|
95
|
+
/**
|
|
96
|
+
* Return the client connected to `database`, switching if needed.
|
|
97
|
+
*
|
|
98
|
+
* Postgres cannot cross databases within a session, so a switch means a new
|
|
99
|
+
* client on a rewritten URL. Callers must run their statement on the client
|
|
100
|
+
* this returns rather than re-reading `this.sql`: a concurrent switch can
|
|
101
|
+
* land between the two, and the query would then silently run against
|
|
102
|
+
* whichever database the shared field points at by then.
|
|
103
|
+
*/
|
|
104
|
+
private async acquire(database?: string): Promise<SQL> {
|
|
105
|
+
if (!this.conn) return this.requireSql();
|
|
97
106
|
const target = database || this.homeDb;
|
|
98
|
-
if (target === this.defaultDb) return;
|
|
107
|
+
if (target === this.defaultDb) return this.requireSql();
|
|
99
108
|
|
|
100
109
|
let release: () => void;
|
|
101
110
|
const prev = this.ensureLock;
|
|
@@ -103,7 +112,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
103
112
|
await prev;
|
|
104
113
|
|
|
105
114
|
try {
|
|
106
|
-
if (target === this.defaultDb) return;
|
|
115
|
+
if (target === this.defaultDb) return this.requireSql();
|
|
107
116
|
const newConn = { ...this.conn, database: target };
|
|
108
117
|
const url = this.buildUrl(newConn, this.tunnelPort);
|
|
109
118
|
const next = new SQL(url, BUN_SQL_POOL_OPTIONS);
|
|
@@ -113,7 +122,10 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
113
122
|
this.defaultDb = target;
|
|
114
123
|
this.conn = newConn;
|
|
115
124
|
this.alive = true;
|
|
125
|
+
// The old client closes gracefully, so queries already running on it
|
|
126
|
+
// finish before its sockets go away.
|
|
116
127
|
if (prevSql) await prevSql.close().catch((err) => debug.warn('db-client', 'pg switch close error:', err));
|
|
128
|
+
return next;
|
|
117
129
|
} finally {
|
|
118
130
|
release!();
|
|
119
131
|
}
|
|
@@ -173,8 +185,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
173
185
|
}
|
|
174
186
|
|
|
175
187
|
async executeRead(q: string, params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {
|
|
176
|
-
await this.
|
|
177
|
-
const sql = this.requireSql();
|
|
188
|
+
const sql = await this.acquire(opts?.database);
|
|
178
189
|
const start = performance.now();
|
|
179
190
|
const raw = await sql.unsafe(q, params as never);
|
|
180
191
|
return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
|
|
@@ -189,8 +200,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
189
200
|
}
|
|
190
201
|
|
|
191
202
|
async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T> {
|
|
192
|
-
await this.
|
|
193
|
-
const sql = this.requireSql();
|
|
203
|
+
const sql = await this.acquire(opts?.database);
|
|
194
204
|
// Bun.sql reserves a single connection for the duration of `begin`, so
|
|
195
205
|
// every statement below shares one transaction. Postgres wraps DDL in
|
|
196
206
|
// the transaction too, so a mid-batch failure rolls everything back.
|
|
@@ -210,8 +220,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
210
220
|
// ── Overview ──────────────────────────────────────────────────────────
|
|
211
221
|
|
|
212
222
|
async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
|
|
213
|
-
await this.
|
|
214
|
-
const sql = this.requireSql();
|
|
223
|
+
const sql = await this.acquire(opts?.database);
|
|
215
224
|
const start = performance.now();
|
|
216
225
|
const verRows = (await sql.unsafe('SELECT version() AS v')) as Array<{ v: string }>;
|
|
217
226
|
const latencyMs = Math.round(performance.now() - start);
|
|
@@ -252,7 +261,9 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
252
261
|
tableCount: c.tables === undefined ? null : Number(c.tables),
|
|
253
262
|
viewCount: c.views === undefined ? null : Number(c.views),
|
|
254
263
|
extra: [
|
|
255
|
-
|
|
264
|
+
// Report what was asked for, not the shared "currently connected"
|
|
265
|
+
// field — a switch for another panel could have moved it by now.
|
|
266
|
+
{ label: 'Database', value: opts?.database || this.homeDb },
|
|
256
267
|
{ label: 'Schema', value: schema }
|
|
257
268
|
]
|
|
258
269
|
};
|
|
@@ -267,8 +278,12 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
267
278
|
return rows.map((r) => ({ name: r.datname, type: 'database' as const }));
|
|
268
279
|
}
|
|
269
280
|
|
|
270
|
-
async listSchemas(): Promise<DbClientSchemaNode[]> {
|
|
271
|
-
|
|
281
|
+
async listSchemas(database?: string): Promise<DbClientSchemaNode[]> {
|
|
282
|
+
// Schemas live inside a database, so this has to run on the browsed one —
|
|
283
|
+
// the caller passes it and the tree would otherwise show the home
|
|
284
|
+
// database's schemas under every database node.
|
|
285
|
+
const sql = await this.acquire(database);
|
|
286
|
+
const rows = (await sql.unsafe(
|
|
272
287
|
`SELECT schema_name FROM information_schema.schemata
|
|
273
288
|
WHERE schema_name NOT IN ('pg_catalog','information_schema','pg_toast')
|
|
274
289
|
ORDER BY schema_name`
|
|
@@ -277,9 +292,9 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
277
292
|
}
|
|
278
293
|
|
|
279
294
|
async listObjects(database?: string, schema?: string): Promise<DbClientSchemaNode[]> {
|
|
280
|
-
await this.
|
|
295
|
+
const sql = await this.acquire(database);
|
|
281
296
|
const target = this.targetSchema({ schema });
|
|
282
|
-
const tables = (await
|
|
297
|
+
const tables = (await sql.unsafe(
|
|
283
298
|
`SELECT table_name, table_type FROM information_schema.tables
|
|
284
299
|
WHERE table_schema = $1 ORDER BY table_name`,
|
|
285
300
|
[target] as never
|
|
@@ -289,7 +304,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
289
304
|
// on prokind: keep plain functions ('f') and procedures ('p'), but exclude
|
|
290
305
|
// aggregates ('a') and window functions ('w') — those (e.g. avg/sum) have no
|
|
291
306
|
// pg_get_functiondef and would error when their DDL is opened.
|
|
292
|
-
const routines = (await
|
|
307
|
+
const routines = (await sql.unsafe(
|
|
293
308
|
`SELECT p.proname AS routine_name, p.prokind
|
|
294
309
|
FROM pg_proc p
|
|
295
310
|
JOIN pg_namespace n ON p.pronamespace = n.oid
|
|
@@ -328,9 +343,8 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
328
343
|
database?: string,
|
|
329
344
|
schema?: string
|
|
330
345
|
): Promise<DbClientObjectDetails> {
|
|
331
|
-
await this.
|
|
346
|
+
const sql = await this.acquire(database);
|
|
332
347
|
const target = this.targetSchema({ schema });
|
|
333
|
-
const sql = this.requireSql();
|
|
334
348
|
|
|
335
349
|
if (_type === 'function' || _type === 'procedure') {
|
|
336
350
|
const routineRows = (await sql.unsafe(
|
|
@@ -438,25 +452,24 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
438
452
|
assertSafeIdentifier(name);
|
|
439
453
|
// Postgres refuses to drop the database the session is connected to —
|
|
440
454
|
// hop to the maintenance database first when needed.
|
|
441
|
-
|
|
455
|
+
const sql = this.defaultDb === name ? await this.acquire('postgres') : this.requireSql();
|
|
442
456
|
const ddl = `DROP DATABASE ${Q(name)}`;
|
|
443
|
-
await
|
|
457
|
+
await sql.unsafe(ddl);
|
|
444
458
|
return ddl;
|
|
445
459
|
}
|
|
446
460
|
|
|
447
461
|
async renameDatabase(name: string, newName: string): Promise<string> {
|
|
448
462
|
assertSafeIdentifier(name);
|
|
449
463
|
assertSafeIdentifier(newName);
|
|
450
|
-
|
|
464
|
+
const sql = this.defaultDb === name ? await this.acquire('postgres') : this.requireSql();
|
|
451
465
|
const ddl = `ALTER DATABASE ${Q(name)} RENAME TO ${Q(newName)}`;
|
|
452
|
-
await
|
|
466
|
+
await sql.unsafe(ddl);
|
|
453
467
|
return ddl;
|
|
454
468
|
}
|
|
455
469
|
|
|
456
470
|
async resetDatabase(opts?: SchemaOpts): Promise<string> {
|
|
457
|
-
await this.
|
|
471
|
+
const sql = await this.acquire(opts?.database);
|
|
458
472
|
const target = this.targetSchema(opts);
|
|
459
|
-
const sql = this.requireSql();
|
|
460
473
|
const rows = (await sql.unsafe(
|
|
461
474
|
`SELECT table_name FROM information_schema.tables
|
|
462
475
|
WHERE table_schema = $1 AND table_type = 'BASE TABLE' ORDER BY table_name`,
|
|
@@ -471,21 +484,20 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
471
484
|
}
|
|
472
485
|
|
|
473
486
|
async resetTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
474
|
-
await this.
|
|
487
|
+
const sql = await this.acquire(opts?.database);
|
|
475
488
|
assertSafeIdentifier(name);
|
|
476
489
|
const ddl = `TRUNCATE TABLE ${qualified(Q, [this.targetSchema(opts), name])} RESTART IDENTITY`;
|
|
477
|
-
await
|
|
490
|
+
await sql.unsafe(ddl);
|
|
478
491
|
return ddl;
|
|
479
492
|
}
|
|
480
493
|
|
|
481
494
|
async duplicateTable(name: string, newName: string, opts?: (SchemaOpts & { withData?: boolean })): Promise<string> {
|
|
482
|
-
await this.
|
|
495
|
+
const sql = await this.acquire(opts?.database);
|
|
483
496
|
assertSafeIdentifier(name);
|
|
484
497
|
assertSafeIdentifier(newName);
|
|
485
498
|
const schema = this.targetSchema(opts);
|
|
486
499
|
const src = qualified(Q, [schema, name]);
|
|
487
500
|
const dst = qualified(Q, [schema, newName]);
|
|
488
|
-
const sql = this.requireSql();
|
|
489
501
|
const create = `CREATE TABLE ${dst} (LIKE ${src} INCLUDING ALL)`;
|
|
490
502
|
await sql.unsafe(create);
|
|
491
503
|
const statements = [create];
|
|
@@ -515,7 +527,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
515
527
|
}
|
|
516
528
|
|
|
517
529
|
async createTable(definition: TableDefinition, opts?: SchemaOpts): Promise<string> {
|
|
518
|
-
await this.
|
|
530
|
+
const sql = await this.acquire(opts?.database);
|
|
519
531
|
assertSafeIdentifier(definition.name);
|
|
520
532
|
const ddl = renderCreateTable({
|
|
521
533
|
quote: Q,
|
|
@@ -523,12 +535,12 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
523
535
|
schema: this.targetSchema(opts),
|
|
524
536
|
driver: 'postgres'
|
|
525
537
|
});
|
|
526
|
-
await
|
|
538
|
+
await sql.unsafe(ddl);
|
|
527
539
|
return ddl;
|
|
528
540
|
}
|
|
529
541
|
|
|
530
542
|
async alterTable(name: string, operations: AlterOperation[], opts?: SchemaOpts): Promise<string> {
|
|
531
|
-
await this.
|
|
543
|
+
const sql = await this.acquire(opts?.database);
|
|
532
544
|
assertSafeIdentifier(name);
|
|
533
545
|
const fqt = qualified(Q, [this.targetSchema(opts), name]);
|
|
534
546
|
const parts: string[] = [];
|
|
@@ -554,73 +566,75 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
554
566
|
}
|
|
555
567
|
}
|
|
556
568
|
const ddl = `ALTER TABLE ${fqt} ${parts.join(', ')}`;
|
|
557
|
-
await
|
|
569
|
+
await sql.unsafe(ddl);
|
|
558
570
|
return ddl;
|
|
559
571
|
}
|
|
560
572
|
|
|
561
573
|
async dropTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
562
|
-
await this.
|
|
574
|
+
const sql = await this.acquire(opts?.database);
|
|
563
575
|
assertSafeIdentifier(name);
|
|
564
576
|
const ddl = `DROP TABLE ${qualified(Q, [this.targetSchema(opts), name])}`;
|
|
565
|
-
await
|
|
577
|
+
await sql.unsafe(ddl);
|
|
566
578
|
return ddl;
|
|
567
579
|
}
|
|
568
580
|
|
|
569
581
|
async truncateTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
570
|
-
await this.
|
|
582
|
+
const sql = await this.acquire(opts?.database);
|
|
571
583
|
assertSafeIdentifier(name);
|
|
572
584
|
const ddl = `TRUNCATE TABLE ${qualified(Q, [this.targetSchema(opts), name])}`;
|
|
573
|
-
await
|
|
585
|
+
await sql.unsafe(ddl);
|
|
574
586
|
return ddl;
|
|
575
587
|
}
|
|
576
588
|
|
|
577
589
|
async renameTable(name: string, newName: string, opts?: SchemaOpts): Promise<string> {
|
|
578
|
-
await this.
|
|
590
|
+
const sql = await this.acquire(opts?.database);
|
|
579
591
|
assertSafeIdentifier(name);
|
|
580
592
|
assertSafeIdentifier(newName);
|
|
581
593
|
const ddl = `ALTER TABLE ${qualified(Q, [this.targetSchema(opts), name])} RENAME TO ${Q(newName)}`;
|
|
582
|
-
await
|
|
594
|
+
await sql.unsafe(ddl);
|
|
583
595
|
return ddl;
|
|
584
596
|
}
|
|
585
597
|
|
|
586
598
|
async createIndex(tableName: string, def: IndexDefinition, opts?: SchemaOpts): Promise<string> {
|
|
587
|
-
await this.
|
|
599
|
+
const sql = await this.acquire(opts?.database);
|
|
588
600
|
assertSafeIdentifier(tableName);
|
|
589
601
|
assertSafeIdentifier(def.name);
|
|
590
602
|
def.columns.forEach(assertSafeIdentifier);
|
|
591
603
|
const ddl = renderCreateIndex({ quote: Q, tableName, def, schema: this.targetSchema(opts) });
|
|
592
|
-
await
|
|
604
|
+
await sql.unsafe(ddl);
|
|
593
605
|
return ddl;
|
|
594
606
|
}
|
|
595
607
|
|
|
596
608
|
async dropIndex(_tableName: string, indexName: string, opts?: SchemaOpts): Promise<string> {
|
|
597
|
-
await this.
|
|
609
|
+
const sql = await this.acquire(opts?.database);
|
|
598
610
|
assertSafeIdentifier(indexName);
|
|
599
611
|
const ddl = `DROP INDEX ${qualified(Q, [this.targetSchema(opts), indexName])}`;
|
|
600
|
-
await
|
|
612
|
+
await sql.unsafe(ddl);
|
|
601
613
|
return ddl;
|
|
602
614
|
}
|
|
603
615
|
|
|
604
616
|
async createView(name: string, query: string, opts?: SchemaOpts): Promise<string> {
|
|
605
|
-
await this.
|
|
617
|
+
const sql = await this.acquire(opts?.database);
|
|
606
618
|
assertSafeIdentifier(name);
|
|
607
619
|
const ddl = `CREATE VIEW ${qualified(Q, [this.targetSchema(opts), name])} AS ${query}`;
|
|
608
|
-
await
|
|
620
|
+
await sql.unsafe(ddl);
|
|
609
621
|
return ddl;
|
|
610
622
|
}
|
|
611
623
|
|
|
612
624
|
async dropView(name: string, opts?: SchemaOpts): Promise<string> {
|
|
613
|
-
await this.
|
|
625
|
+
const sql = await this.acquire(opts?.database);
|
|
614
626
|
assertSafeIdentifier(name);
|
|
615
627
|
const ddl = `DROP VIEW ${qualified(Q, [this.targetSchema(opts), name])}`;
|
|
616
|
-
await
|
|
628
|
+
await sql.unsafe(ddl);
|
|
617
629
|
return ddl;
|
|
618
630
|
}
|
|
619
631
|
|
|
620
632
|
// ── Data CRUD ─────────────────────────────────────────────────────────
|
|
621
633
|
|
|
634
|
+
// Postgres statements can only be schema-qualified, never database-qualified,
|
|
635
|
+
// so the target database has to ride along to `executeWrite` — without it the
|
|
636
|
+
// write resolves against the connection's home database instead.
|
|
622
637
|
async insertRow(table: string, row: Record<string, unknown>, opts?: SchemaOpts): Promise<DbClientQueryResult> {
|
|
623
|
-
await this.ensureDatabase(opts?.database);
|
|
624
638
|
assertSafeIdentifier(table);
|
|
625
639
|
Object.keys(row).forEach(assertSafeIdentifier);
|
|
626
640
|
const { sql, params } = buildInsert({
|
|
@@ -630,7 +644,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
630
644
|
schema: this.targetSchema(opts),
|
|
631
645
|
placeholder: PG_PLACEHOLDER
|
|
632
646
|
});
|
|
633
|
-
return this.executeWrite(sql, params);
|
|
647
|
+
return this.executeWrite(sql, params, { database: opts?.database });
|
|
634
648
|
}
|
|
635
649
|
|
|
636
650
|
async updateRow(
|
|
@@ -639,7 +653,6 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
639
653
|
changes: Record<string, unknown>,
|
|
640
654
|
opts?: SchemaOpts
|
|
641
655
|
): Promise<DbClientQueryResult> {
|
|
642
|
-
await this.ensureDatabase(opts?.database);
|
|
643
656
|
assertSafeIdentifier(table);
|
|
644
657
|
[...Object.keys(pk), ...Object.keys(changes)].forEach(assertSafeIdentifier);
|
|
645
658
|
const { sql, params } = buildUpdate({
|
|
@@ -650,11 +663,10 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
650
663
|
schema: this.targetSchema(opts),
|
|
651
664
|
placeholder: PG_PLACEHOLDER
|
|
652
665
|
});
|
|
653
|
-
return this.executeWrite(sql, params);
|
|
666
|
+
return this.executeWrite(sql, params, { database: opts?.database });
|
|
654
667
|
}
|
|
655
668
|
|
|
656
669
|
async deleteRows(table: string, pks: Record<string, unknown>[], opts?: SchemaOpts): Promise<DbClientQueryResult> {
|
|
657
|
-
await this.ensureDatabase(opts?.database);
|
|
658
670
|
assertSafeIdentifier(table);
|
|
659
671
|
if (pks.length > 0) Object.keys(pks[0]).forEach(assertSafeIdentifier);
|
|
660
672
|
const { sql, params } = buildDelete({
|
|
@@ -664,7 +676,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
664
676
|
schema: this.targetSchema(opts),
|
|
665
677
|
placeholder: PG_PLACEHOLDER
|
|
666
678
|
});
|
|
667
|
-
return this.executeWrite(sql, params);
|
|
679
|
+
return this.executeWrite(sql, params, { database: opts?.database });
|
|
668
680
|
}
|
|
669
681
|
}
|
|
670
682
|
|
package/backend/engine/README.md
CHANGED
|
@@ -23,8 +23,13 @@ stays **agnostic** to the underlying SDK.
|
|
|
23
23
|
> `EngineNotReadyError` (`reason: 'not-installed' | 'needs-update'`) — the
|
|
24
24
|
> engine must first be installed/updated in **Settings → Stack**. This is
|
|
25
25
|
> what fixed `bun add -g @myrialabs/clopen` aborting mid-install (it used to
|
|
26
|
-
> drag 200–300 MB of native CLI binaries).
|
|
27
|
-
>
|
|
26
|
+
> drag 200–300 MB of native CLI binaries). The pin covers an SDK's unbundled
|
|
27
|
+
> **peer** dependencies too (`ENGINE_PACKAGES` in
|
|
28
|
+
> [`install-recipes.ts`](./install-recipes.ts)) — without that they resolve at
|
|
29
|
+
> `@latest` in the stack dir and clopen runs a version it never type-checked
|
|
30
|
+
> against; read **§10.25** in [lessons-learned](./docs/lessons-learned.md)
|
|
31
|
+
> before bumping any SDK. Future Stack work (runtimes, services, per-project
|
|
32
|
+
> versioning) is specced in
|
|
28
33
|
> [`docs/stack-roadmap.md`](../../docs/stack-roadmap.md).
|
|
29
34
|
|
|
30
35
|
> **Adapters load on first use, and that rule is now mechanical.** The registry
|
|
@@ -85,7 +90,7 @@ map, then jump to the area you need.
|
|
|
85
90
|
6. [Stack](./docs/stack.md) — registering a host tool or on-demand engine SDK in `install-recipes.ts` + the install runner.
|
|
86
91
|
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.
|
|
87
92
|
8. [Adding a new engine](./docs/adding-an-engine.md) — the end-to-end, stage-by-stage checklist.
|
|
88
|
-
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, cross-engine handoff, …).
|
|
93
|
+
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, cross-engine handoff, SDK upgrades, …).
|
|
89
94
|
10. [Quick reference](./docs/quick-reference.md) — "I need X → look in file Y" table.
|
|
90
95
|
|
|
91
96
|
---
|
|
@@ -18,6 +18,8 @@ import type {
|
|
|
18
18
|
SDKSystemMessage,
|
|
19
19
|
SDKCompactBoundaryMessage,
|
|
20
20
|
SDKRateLimitEvent,
|
|
21
|
+
SDKModelRefusalFallbackMessage,
|
|
22
|
+
SDKModelRefusalNoFallbackMessage,
|
|
21
23
|
} from '@anthropic-ai/claude-agent-sdk';
|
|
22
24
|
// Infer block/usage types from the agent SDK so we stay in sync with whichever
|
|
23
25
|
// @anthropic-ai/sdk version claude-agent-sdk bundles internally.
|
|
@@ -38,6 +40,7 @@ import type {
|
|
|
38
40
|
ErrorResultEvent,
|
|
39
41
|
SystemInitEvent,
|
|
40
42
|
RateLimitEvent,
|
|
43
|
+
NotificationEvent,
|
|
41
44
|
TokenUsage,
|
|
42
45
|
StopReason,
|
|
43
46
|
} from '$shared/types/unified';
|
|
@@ -426,6 +429,50 @@ export function convertCompactBoundary(msg: SDKCompactBoundaryMessage): CompactB
|
|
|
426
429
|
};
|
|
427
430
|
}
|
|
428
431
|
|
|
432
|
+
/**
|
|
433
|
+
* Convert a model-refusal banner → NotificationEvent.
|
|
434
|
+
*
|
|
435
|
+
* Both subtypes arrived in @anthropic-ai/claude-agent-sdk 0.3.229 and were
|
|
436
|
+
* previously dropped by the `default` arm, which is the worst outcome for the
|
|
437
|
+
* two cases users actually notice: a turn answered by a *different* model than
|
|
438
|
+
* the one they picked, and a turn that produced nothing at all. Neither is an
|
|
439
|
+
* error the stream should abort on, so they surface as toasts.
|
|
440
|
+
*
|
|
441
|
+
* NOT handled: `retracted_message_uuids`, the fallback's list of already-
|
|
442
|
+
* delivered messages the CLI has retracted. Honouring it means deleting
|
|
443
|
+
* persisted messages by id across adapter → stream-manager → WS → UI, so the
|
|
444
|
+
* refused partial currently stays in the transcript above the fallback answer.
|
|
445
|
+
* See docs/lessons-learned.md §10.25.
|
|
446
|
+
*/
|
|
447
|
+
function convertModelRefusalFallback(msg: SDKModelRefusalFallbackMessage): NotificationEvent {
|
|
448
|
+
// 'local' means only this response came from the fallback (a subagent or a
|
|
449
|
+
// side question); 'session' means the session's model itself was swapped.
|
|
450
|
+
const scope = msg.scope ?? 'session';
|
|
451
|
+
const swapped = scope === 'session'
|
|
452
|
+
? `The session model is now ${msg.fallback_model}.`
|
|
453
|
+
: `Only this response came from ${msg.fallback_model}; the session model is unchanged.`;
|
|
454
|
+
return {
|
|
455
|
+
type: 'notification',
|
|
456
|
+
sessionId: msg.session_id,
|
|
457
|
+
level: 'warning',
|
|
458
|
+
title: 'Model refused — answered by a fallback',
|
|
459
|
+
message: `${msg.original_model} declined this request${msg.api_refusal_category ? ` (${msg.api_refusal_category})` : ''}. ${swapped}`,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** Convert SDKModelRefusalNoFallbackMessage → NotificationEvent (no retry ran). */
|
|
464
|
+
function convertModelRefusalNoFallback(msg: SDKModelRefusalNoFallbackMessage): NotificationEvent {
|
|
465
|
+
return {
|
|
466
|
+
type: 'notification',
|
|
467
|
+
sessionId: msg.session_id,
|
|
468
|
+
level: 'error',
|
|
469
|
+
title: 'Model refused this request',
|
|
470
|
+
// `content` is the CLI's own human-readable banner; explanation is
|
|
471
|
+
// unstable prose meant for display only.
|
|
472
|
+
message: msg.api_refusal_explanation || msg.content,
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
|
|
429
476
|
/** Convert SDKRateLimitEvent → RateLimitEvent (returns null for non-actionable 'allowed' status) */
|
|
430
477
|
export function convertRateLimit(msg: SDKRateLimitEvent): RateLimitEvent | null {
|
|
431
478
|
const info = msg.rate_limit_info;
|
|
@@ -508,6 +555,10 @@ function* dispatchSdkMessage(msg: SDKMessage, state: StreamConverterState): Gene
|
|
|
508
555
|
yield convertSystemInit(msg as SDKSystemMessage);
|
|
509
556
|
} else if (subtype === 'compact_boundary') {
|
|
510
557
|
yield convertCompactBoundary(msg as SDKCompactBoundaryMessage);
|
|
558
|
+
} else if (subtype === 'model_refusal_fallback') {
|
|
559
|
+
yield convertModelRefusalFallback(msg as SDKModelRefusalFallbackMessage);
|
|
560
|
+
} else if (subtype === 'model_refusal_no_fallback') {
|
|
561
|
+
yield convertModelRefusalNoFallback(msg as SDKModelRefusalNoFallbackMessage);
|
|
511
562
|
} else if (subtype === 'task_started') {
|
|
512
563
|
const task = msg as unknown as { session_id: string; uuid?: string; task_id: string; tool_use_id?: string; task_type?: string; workflow_name?: string; description?: string };
|
|
513
564
|
if (task.task_type === 'local_workflow' && task.tool_use_id) {
|
|
@@ -20,6 +20,8 @@ import type {
|
|
|
20
20
|
PermissionMode,
|
|
21
21
|
PermissionResult,
|
|
22
22
|
EffortLevel,
|
|
23
|
+
HookInput,
|
|
24
|
+
HookJSONOutput,
|
|
23
25
|
} from '@anthropic-ai/claude-agent-sdk';
|
|
24
26
|
import type { EngineOutput } from '$shared/types/unified';
|
|
25
27
|
import type { StructuredGenerationOptions } from '../../types';
|
|
@@ -32,7 +34,7 @@ import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
|
|
|
32
34
|
import { syncSkills } from '$backend/skills';
|
|
33
35
|
import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
|
|
34
36
|
import { artifactFilter } from '$backend/profiles';
|
|
35
|
-
import { resolvePermissionsFromDb, isToolAllowed, syncPermissions } from '$backend/permissions';
|
|
37
|
+
import { resolvePermissionsFromDb, isToolAllowed, hasAnyRestriction, syncPermissions } from '$backend/permissions';
|
|
36
38
|
import type { AIEngine, EngineQueryOptions } from '../../types';
|
|
37
39
|
import type { EngineModel } from '$shared/types/unified';
|
|
38
40
|
import { CLAUDE_CODE_MODELS } from './models';
|
|
@@ -139,6 +141,9 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
139
141
|
debug.log('chat', { prompt });
|
|
140
142
|
|
|
141
143
|
this.activeController = abortController || new AbortController();
|
|
144
|
+
// Held locally: cancel() nulls the field, and the checks below still need to
|
|
145
|
+
// know whether this stream ended because the user cancelled it.
|
|
146
|
+
const streamController = this.activeController;
|
|
142
147
|
|
|
143
148
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
144
149
|
|
|
@@ -153,14 +158,22 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
153
158
|
await syncSkills('claude', profileId);
|
|
154
159
|
// Commands, Subagents, and global Instructions share the same trigger.
|
|
155
160
|
await syncEngineArtifacts('claude', profileId);
|
|
156
|
-
//
|
|
157
|
-
//
|
|
161
|
+
// Mirror the resolved allow/deny into the isolated settings.json so the
|
|
162
|
+
// rules are visible to anyone inspecting the config. Deny rules there do
|
|
163
|
+
// bite even under bypassPermissions, but an allowlist has no on-disk
|
|
164
|
+
// equivalent — the PreToolUse hook below is the authoritative enforcement.
|
|
158
165
|
await syncPermissions('claude');
|
|
159
166
|
|
|
160
|
-
// Resolve the effective permission policy once per stream
|
|
161
|
-
//
|
|
162
|
-
//
|
|
167
|
+
// Resolve the effective permission policy once per stream. Enforcement
|
|
168
|
+
// lives in the PreToolUse hook, NOT in canUseTool: under
|
|
169
|
+
// permissionMode 'bypassPermissions' the CLI auto-approves a tool call
|
|
170
|
+
// before the permission callback is consulted (the SDK says so itself via
|
|
171
|
+
// the CLAUDE_SDK_CAN_USE_TOOL_SHADOWED warning), so a callback-side check
|
|
172
|
+
// would be a no-op. A PreToolUse hook sees every call regardless of mode.
|
|
163
173
|
const permissions = resolvePermissionsFromDb('claude-code', options.mcpContext?.projectId, profileId);
|
|
174
|
+
// Registering the hook costs one control round-trip per tool call, so only
|
|
175
|
+
// pay it when there is actually a rule to enforce.
|
|
176
|
+
const enforcePermissions = hasAnyRestriction(permissions);
|
|
164
177
|
|
|
165
178
|
// Get custom MCP servers and allowed tools
|
|
166
179
|
// Pass mcpContext so tool handlers are bound to the correct project
|
|
@@ -171,6 +184,25 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
171
184
|
debug.log('mcp', `Enabled servers: ${Object.keys(mcpServers).length}`);
|
|
172
185
|
debug.log('mcp', `Allowed tools: ${allowedMcpTools.length}`);
|
|
173
186
|
|
|
187
|
+
// AskUserQuestion safety net. The CLI still routes that tool through
|
|
188
|
+
// canUseTool even under bypassPermissions, but the SDK explicitly
|
|
189
|
+
// documents the callback as shadowed in that mode — so we rely on
|
|
190
|
+
// behaviour upstream has not promised. If a future SDK stops routing it,
|
|
191
|
+
// the question would never reach the user and the failure would be
|
|
192
|
+
// silent; comparing what the model asked against what the callback parked
|
|
193
|
+
// turns that into a log line instead of a frozen chat.
|
|
194
|
+
const questionsAsked = new Set<string>();
|
|
195
|
+
const questionsParked = new Set<string>();
|
|
196
|
+
const observeAskUserQuestion = (sdkMessage: unknown): void => {
|
|
197
|
+
const message = sdkMessage as { type?: string; message?: { content?: unknown } };
|
|
198
|
+
if (message.type !== 'assistant' || !Array.isArray(message.message?.content)) return;
|
|
199
|
+
for (const block of message.message.content as Array<{ type?: string; name?: string; id?: string }>) {
|
|
200
|
+
if (block.type === 'tool_use' && block.name === 'AskUserQuestion' && block.id) {
|
|
201
|
+
questionsAsked.add(block.id);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
|
|
174
206
|
// SDK uses cwd from options — no process.chdir() needed.
|
|
175
207
|
// Environment is passed via env option — no process.env mutation.
|
|
176
208
|
// When accountId is specified, the env overrides the OAuth token
|
|
@@ -188,11 +220,17 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
188
220
|
// thinking_delta events; 'off' disables it, an explicit level adds effort.
|
|
189
221
|
thinking: thinkingConfig,
|
|
190
222
|
...effortOption,
|
|
191
|
-
//
|
|
192
|
-
//
|
|
223
|
+
// Tool gating that must survive every permission mode lives in the
|
|
224
|
+
// PreToolUse hook below. This callback is kept for one job only: park
|
|
225
|
+
// the SDK on AskUserQuestion until the user answers. It waits without a
|
|
226
|
+
// deadline on purpose — a hook would be bounded by its `timeout`
|
|
227
|
+
// (default 600000 ms, and values above 2^31-1 ms overflow setTimeout and
|
|
228
|
+
// fire immediately), while a parked promise simply waits until the user
|
|
229
|
+
// answers or the stream is cancelled.
|
|
193
230
|
canUseTool: async (_toolName, input, canUseToolOptions) => {
|
|
194
231
|
if (_toolName === 'AskUserQuestion') {
|
|
195
232
|
debug.log('engine', `AskUserQuestion detected (toolUseID: ${canUseToolOptions.toolUseID}), waiting for user input...`);
|
|
233
|
+
questionsParked.add(canUseToolOptions.toolUseID);
|
|
196
234
|
return new Promise<PermissionResult>((resolve) => {
|
|
197
235
|
// Handle abort (stream cancelled while waiting)
|
|
198
236
|
if (canUseToolOptions.signal.aborted) {
|
|
@@ -217,15 +255,35 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
217
255
|
});
|
|
218
256
|
});
|
|
219
257
|
}
|
|
220
|
-
// Enforce the resolved permission policy: deny blocks the tool, an
|
|
221
|
-
// allowlist (when set) blocks anything not on it. Everything else is
|
|
222
|
-
// auto-allowed as before.
|
|
223
|
-
if (!isToolAllowed(permissions, _toolName)) {
|
|
224
|
-
debug.log('permissions', `⛔ Blocked tool "${_toolName}" (Clopen permission policy)`);
|
|
225
|
-
return { behavior: 'deny' as const, message: `Blocked by Clopen permission policy: ${_toolName}` };
|
|
226
|
-
}
|
|
227
258
|
return { behavior: 'allow' as const, updatedInput: input };
|
|
228
259
|
},
|
|
260
|
+
// Enforce the resolved permission policy: deny blocks the tool, an
|
|
261
|
+
// allowlist (when set) blocks anything not on it. Returning an empty
|
|
262
|
+
// result leaves the decision alone, so unrestricted tools fall through
|
|
263
|
+
// to the mode's own auto-approve without an extra round-trip.
|
|
264
|
+
...(enforcePermissions && {
|
|
265
|
+
hooks: {
|
|
266
|
+
PreToolUse: [{
|
|
267
|
+
hooks: [async (hookInput: HookInput): Promise<HookJSONOutput> => {
|
|
268
|
+
if (hookInput.hook_event_name !== 'PreToolUse') return {};
|
|
269
|
+
// AskUserQuestion is Clopen's own interaction channel, not a
|
|
270
|
+
// capability the policy is about — it was exempt while the check
|
|
271
|
+
// lived in canUseTool (that branch returned first), so an
|
|
272
|
+
// allowlist must not start silencing questions now.
|
|
273
|
+
if (hookInput.tool_name === 'AskUserQuestion') return {};
|
|
274
|
+
if (isToolAllowed(permissions, hookInput.tool_name)) return {};
|
|
275
|
+
debug.log('permissions', `⛔ Blocked tool "${hookInput.tool_name}" (Clopen permission policy)`);
|
|
276
|
+
return {
|
|
277
|
+
hookSpecificOutput: {
|
|
278
|
+
hookEventName: 'PreToolUse',
|
|
279
|
+
permissionDecision: 'deny',
|
|
280
|
+
permissionDecisionReason: `Blocked by Clopen permission policy: ${hookInput.tool_name}`
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
}]
|
|
284
|
+
}]
|
|
285
|
+
}
|
|
286
|
+
}),
|
|
229
287
|
...(modelId && { model: modelId }),
|
|
230
288
|
...(resume && { resume }),
|
|
231
289
|
...(maxTurns && { maxTurns }),
|
|
@@ -260,6 +318,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
260
318
|
const sdkProducer = (async () => {
|
|
261
319
|
try {
|
|
262
320
|
for await (const sdkMessage of queryInstance) {
|
|
321
|
+
observeAskUserQuestion(sdkMessage);
|
|
263
322
|
// Register Workflow launches after queueing the corresponding parent
|
|
264
323
|
// and tool result, preserving their ordering ahead of child records.
|
|
265
324
|
for (const output of convertSdkMessage(sdkMessage)) events.push(output);
|
|
@@ -292,6 +351,13 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
292
351
|
await producers;
|
|
293
352
|
} finally {
|
|
294
353
|
workflowTranscripts.dispose();
|
|
354
|
+
// A cancelled stream legitimately leaves questions unparked.
|
|
355
|
+
if (!streamController.signal.aborted) {
|
|
356
|
+
const unrouted = [...questionsAsked].filter(id => !questionsParked.has(id));
|
|
357
|
+
if (unrouted.length > 0) {
|
|
358
|
+
debug.error('engine', `AskUserQuestion never reached canUseTool (${unrouted.length}: ${unrouted.join(', ')}). The SDK likely stopped routing that tool through the permission callback under bypassPermissions — interactive questions are now unanswerable and must move to a PreToolUse hook.`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
295
361
|
}
|
|
296
362
|
|
|
297
363
|
} catch (error) {
|
|
@@ -627,6 +627,11 @@ function buildErrorUserMessage(item: ErrorItem, state: CodexStreamState): UserMe
|
|
|
627
627
|
* `cacheReadInputTokens`. Subtract here, otherwise the frontend's context
|
|
628
628
|
* window indicator (which sums input + cacheCreate + cacheRead) would
|
|
629
629
|
* double-count the cached prefix and appear to fill up far too quickly.
|
|
630
|
+
*
|
|
631
|
+
* `cache_write_input_tokens` (added in SDK 0.147) is the slice of that same
|
|
632
|
+
* prompt written INTO the cache this turn, so it is subtracted for the same
|
|
633
|
+
* reason and reported as `cacheCreationInputTokens`. The three parts still sum
|
|
634
|
+
* back to `input_tokens`, which is what the indicator expects.
|
|
630
635
|
*/
|
|
631
636
|
function mapUsage(raw: Usage | null): TokenUsage {
|
|
632
637
|
if (!raw) {
|
|
@@ -634,10 +639,11 @@ function mapUsage(raw: Usage | null): TokenUsage {
|
|
|
634
639
|
}
|
|
635
640
|
const totalInput = raw.input_tokens ?? 0;
|
|
636
641
|
const cached = raw.cached_input_tokens ?? 0;
|
|
642
|
+
const cacheWrite = raw.cache_write_input_tokens ?? 0;
|
|
637
643
|
return {
|
|
638
|
-
inputTokens: Math.max(0, totalInput - cached),
|
|
644
|
+
inputTokens: Math.max(0, totalInput - cached - cacheWrite),
|
|
639
645
|
outputTokens: (raw.output_tokens ?? 0) + (raw.reasoning_output_tokens ?? 0),
|
|
640
|
-
cacheCreationInputTokens:
|
|
646
|
+
cacheCreationInputTokens: cacheWrite,
|
|
641
647
|
cacheReadInputTokens: cached,
|
|
642
648
|
};
|
|
643
649
|
}
|