@myrialabs/clopen 0.4.29 → 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.
@@ -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 ensureDatabase).
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
- private async ensureDatabase(database?: string): Promise<void> {
96
- if (!this.conn) return;
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.ensureDatabase(opts?.database);
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.ensureDatabase(opts?.database);
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.ensureDatabase(opts?.database);
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
- { label: 'Database', value: this.defaultDb ?? 'postgres' },
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
- const rows = (await this.requireSql().unsafe(
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.ensureDatabase(database);
295
+ const sql = await this.acquire(database);
281
296
  const target = this.targetSchema({ schema });
282
- const tables = (await this.requireSql().unsafe(
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 this.requireSql().unsafe(
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.ensureDatabase(database);
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
- if (this.defaultDb === name) await this.ensureDatabase('postgres');
455
+ const sql = this.defaultDb === name ? await this.acquire('postgres') : this.requireSql();
442
456
  const ddl = `DROP DATABASE ${Q(name)}`;
443
- await this.requireSql().unsafe(ddl);
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
- if (this.defaultDb === name) await this.ensureDatabase('postgres');
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 this.requireSql().unsafe(ddl);
466
+ await sql.unsafe(ddl);
453
467
  return ddl;
454
468
  }
455
469
 
456
470
  async resetDatabase(opts?: SchemaOpts): Promise<string> {
457
- await this.ensureDatabase(opts?.database);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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.ensureDatabase(opts?.database);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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.ensureDatabase(opts?.database);
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 this.requireSql().unsafe(ddl);
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
 
@@ -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
- // Write the resolved allow/deny into the isolated settings.json (honesty
157
- // layer — the runtime hook below is the authoritative enforcement).
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; the canUseTool
161
- // hook consults it to actually block denied tools (Clopen otherwise
162
- // auto-allows everything, so this hook is where deny gets its teeth).
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
- // Custom permission handler: blocks on AskUserQuestion until user answers,
192
- // auto-allows everything else. Works alongside bypassPermissions.
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) {
@@ -98,7 +98,7 @@ reliably re-read per turn — the prompt is the one genuinely per-session channe
98
98
  | **Commands** (`backend/commands/`) | custom slash commands | global, project | one `.md` per command into the engine command dir, or synthetic preamble. Profile-bundled |
99
99
  | **Subagents** (`backend/subagents/`) | specialized delegated agents | global, project | one `.md` per subagent, or synthetic preamble. Profile-bundled |
100
100
  | **Instructions** (`backend/instructions/`) | a shared instruction block | global, project | marker region inside the engine memory file (`CLAUDE.md` / `QWEN.md` / `AGENTS.md`). Global set always synced in full; never profile-bundled |
101
- | **Permissions** (`backend/permissions/`) | per-engine tool allow/deny | global, project | **enforcement is a runtime hook** (`resolvePermissionsFromDb` + `isToolAllowed`) each adapter consults at its auto-approve point. The matrix only describes the optional on-disk "honesty" file, which today only Claude reads (a managed `permissions` key merged into its isolated `settings.json`) |
101
+ | **Permissions** (`backend/permissions/`) | per-engine tool allow/deny | global, project | **enforcement is a runtime check** (`resolvePermissionsFromDb` + `isToolAllowed`) each adapter runs at whichever surface fires for every tool call — for Claude a `PreToolUse` hook, since `bypassPermissions` auto-approves before `canUseTool` is consulted. The matrix only describes the optional on-disk file, which today only Claude reads (a managed `permissions` key merged into its isolated `settings.json`); its `deny` rules do bite even under `bypassPermissions`, an allowlist has no on-disk equivalent |
102
102
  | **Profiles** (`backend/profiles/`) | a named bundle of slugs | per session | not materialized. Narrows which instance-global artifacts are active: effective profile = `chat_sessions.profile_id ?? projects.default_profile_id`, resolved once at stream start and threaded down as `profileId`. Only constrains the types it references (`artifactFilter` → `null` = unconstrained), so a Commands-only profile never disables every Skill |
103
103
 
104
104
  ### 8.5 Connectors (MCP)
@@ -29,7 +29,7 @@
29
29
  | Materialize an artifact per engine (matrix) | `backend/artifacts/matrix.ts::resolveArtifact`, generic writer `backend/artifacts/sync.ts`, scanner `backend/artifacts/detect.ts` (see §8.2) |
30
30
  | Per-stream artifact sync (Commands/Subagents/Instructions) | `backend/engine/artifact-sync.ts::syncEngineArtifacts` + `buildArtifactsPromptContext` — called from each `stream.ts` after `syncSkills` (see §8.3) |
31
31
  | Profile scoping (narrow active artifacts) | `backend/profiles/service.ts::resolveActiveProfileId` + `artifactFilter` (see §8.4) |
32
- | Permission enforcement (runtime hook) | `backend/permissions/service.ts::resolvePermissionsFromDb` + `isToolAllowed` (see §8.4) |
32
+ | Permission enforcement (runtime check) | `backend/permissions/service.ts::resolvePermissionsFromDb` + `isToolAllowed` (see §8.4); Claude wires it into a `PreToolUse` hook in `claude/stream.ts` |
33
33
  | Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §10.13 |
34
34
  | Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `engines/panels/OpenCodePanel.svelte::handleRestartServer`/`forceRestartServer` |
35
35
  | `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`); `opencode` / `copilot` / `qwen` / `pi` / `cline` / `cursor` are prompt-engineered via `backend/engine/structured-helpers.ts` (`buildJsonPrompt` + `extractJson`). See §10.16 for the strict-schema + part-fallback gotchas. |
package/backend/index.ts CHANGED
@@ -27,6 +27,7 @@ import { bootstrapAfterDbInit } from './bootstrap';
27
27
  import { disposeAllEngines } from './engine';
28
28
  import { connectionManager } from './db-client/connection-manager';
29
29
  import { refreshProcessPath } from './utils/path-enrich';
30
+ import { installProcessWarningFilter } from './utils/process-warnings';
30
31
  import { debug } from '$shared/utils/logger';
31
32
  import { networkInterfaces } from 'os';
32
33
  import { resolve } from 'node:path';
@@ -381,6 +382,10 @@ globalThis.addEventListener('unhandledrejection', (event: PromiseRejectionEvent)
381
382
  reportUnhandledRejection(event.reason);
382
383
  });
383
384
 
385
+ // Owns every `process.emitWarning` line in the server log (see the module for
386
+ // why registering a listener means we must re-print what we keep).
387
+ installProcessWarningFilter();
388
+
384
389
  process.on('uncaughtException', (error) => {
385
390
  try {
386
391
  debug.error('server', 'Uncaught exception (server still running):', error);
@@ -20,6 +20,7 @@ import { notifyMemoryReadiness } from './notify';
20
20
  import { resetGraphEmptiness } from './context';
21
21
  import { reconcileVectorIndex } from './indexer';
22
22
  import { startMemoryMaintenance } from './maintenance';
23
+ import { resetGraphLayoutState, scheduleGraphLayout } from './layout';
23
24
  import { ensureMemoryModel } from './model';
24
25
  import { startExtractionRunner } from './extract';
25
26
 
@@ -42,6 +43,14 @@ export function bootstrapMemoryGraph(): void {
42
43
  vectorCache.reset();
43
44
  resetGraphEmptiness();
44
45
 
46
+ // Same reason as the caches above: "Clear All Data" wipes the database under a
47
+ // live process, so what the last pass laid out describes rows that no longer
48
+ // exist. Scheduling one here is also what places an EXISTING graph the first
49
+ // time the upgrade runs — until it lands the view falls back to the flat
50
+ // listing it always used, so nothing is missing meanwhile.
51
+ resetGraphLayoutState();
52
+ scheduleGraphLayout();
53
+
45
54
  // Duplicate collapse and retention are pure SQL and are worth running whether
46
55
  // or not the artifact ever lands, so maintenance starts independently of the
47
56
  // download. Its own first tick is minutes away, well clear of startup.