@myrialabs/clopen 0.4.31 → 0.4.33

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.
Files changed (114) hide show
  1. package/backend/auth/permissions.test.ts +0 -1
  2. package/backend/auth/permissions.ts +0 -4
  3. package/backend/chat/stream-manager.ts +31 -12
  4. package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
  5. package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
  6. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  7. package/backend/database/migrations/index.ts +14 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  9. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  10. package/backend/database/queries/index.ts +3 -0
  11. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  12. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  13. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  14. package/backend/db-client/connection-manager.ts +8 -1
  15. package/backend/engine/README.md +16 -0
  16. package/backend/engine/adapters/claude/stream.ts +89 -49
  17. package/backend/engine/adapters/cline/stream.ts +62 -24
  18. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  19. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  20. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  21. package/backend/engine/adapters/codex/stream.ts +78 -22
  22. package/backend/engine/adapters/copilot/stream.ts +97 -53
  23. package/backend/engine/adapters/cursor/stream.ts +75 -35
  24. package/backend/engine/adapters/opencode/server.ts +511 -134
  25. package/backend/engine/adapters/opencode/stream.ts +131 -79
  26. package/backend/engine/adapters/pi/stream.ts +63 -24
  27. package/backend/engine/adapters/qwen/stream.ts +92 -59
  28. package/backend/engine/adapters/run-registry.test.ts +75 -0
  29. package/backend/engine/adapters/run-registry.ts +63 -0
  30. package/backend/engine/config-revision.ts +150 -0
  31. package/backend/engine/docs/adapter-contract.md +47 -9
  32. package/backend/engine/docs/adding-an-engine.md +8 -0
  33. package/backend/engine/docs/frontend-and-chat.md +39 -0
  34. package/backend/engine/docs/lessons-learned.md +70 -0
  35. package/backend/engine/docs/quick-reference.md +3 -1
  36. package/backend/engine/hot-reload.ts +99 -0
  37. package/backend/engine/index.ts +96 -24
  38. package/backend/engine/types.ts +17 -5
  39. package/backend/files/file-watcher.ts +283 -51
  40. package/backend/files/git-events.test.ts +110 -0
  41. package/backend/git/git-dirs.test.ts +132 -0
  42. package/backend/git/git-dirs.ts +0 -0
  43. package/backend/git/git-executor.ts +22 -3
  44. package/backend/git/git-service.ts +1 -1
  45. package/backend/git/nested-repos.test.ts +224 -0
  46. package/backend/git/nested-repos.ts +386 -0
  47. package/backend/http/audio.ts +5 -32
  48. package/backend/http/bearer-auth.ts +47 -0
  49. package/backend/http/files-download.test.ts +146 -0
  50. package/backend/http/files-download.ts +109 -0
  51. package/backend/http/files-upload.ts +3 -29
  52. package/backend/http/ssh-sftp.ts +133 -0
  53. package/backend/index.ts +23 -2
  54. package/backend/mcp/README.md +34 -6
  55. package/backend/mcp/index.ts +8 -8
  56. package/backend/mcp/internal/config.ts +69 -19
  57. package/backend/mcp/internal/project-context.test.ts +40 -0
  58. package/backend/mcp/internal/project-context.ts +80 -7
  59. package/backend/mcp/internal/remote-server.test.ts +17 -2
  60. package/backend/mcp/internal/remote-server.ts +36 -3
  61. package/backend/mcp/internal/servers/helper.ts +48 -18
  62. package/backend/preview/browser/browser-video-capture.ts +51 -4
  63. package/backend/snapshot/gitignore.ts +10 -174
  64. package/backend/ssh/client-pool.ts +196 -0
  65. package/backend/ssh/connect.ts +375 -0
  66. package/backend/ssh/disk-usage.test.ts +134 -0
  67. package/backend/ssh/disk-usage.ts +214 -0
  68. package/backend/ssh/forwards.ts +309 -0
  69. package/backend/ssh/health.ts +141 -0
  70. package/backend/ssh/known-hosts.ts +96 -0
  71. package/backend/ssh/pty-backend.ts +215 -0
  72. package/backend/ssh/ptykit.ts +66 -0
  73. package/backend/ssh/sftp.test.ts +242 -0
  74. package/backend/ssh/sftp.ts +967 -0
  75. package/backend/ssh/socks5.test.ts +167 -0
  76. package/backend/ssh/socks5.ts +164 -0
  77. package/backend/ssh/tunnel.ts +87 -0
  78. package/backend/ws/chat/stream.ts +24 -0
  79. package/backend/ws/db-client/connections.ts +1 -0
  80. package/backend/ws/engine/codex/accounts.ts +0 -12
  81. package/backend/ws/engine/copilot/accounts.ts +0 -10
  82. package/backend/ws/engine/cursor/accounts.ts +0 -10
  83. package/backend/ws/engine/index.ts +17 -2
  84. package/backend/ws/engine/opencode/providers.ts +0 -52
  85. package/backend/ws/files/read.ts +1 -1
  86. package/backend/ws/files/watch.ts +5 -1
  87. package/backend/ws/git/conflict.ts +1 -1
  88. package/backend/ws/git/diff.ts +1 -1
  89. package/backend/ws/git/staging.ts +1 -1
  90. package/backend/ws/git/status.ts +1 -1
  91. package/backend/ws/index.ts +4 -0
  92. package/backend/ws/ssh/access.ts +31 -0
  93. package/backend/ws/ssh/connections.ts +224 -0
  94. package/backend/ws/ssh/forwards.ts +109 -0
  95. package/backend/ws/ssh/index.ts +18 -0
  96. package/backend/ws/ssh/sftp.ts +259 -0
  97. package/backend/ws/ssh/tunnel.ts +93 -0
  98. package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
  99. package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
  100. package/dist/assets/main-BbwWLJRN.js +1057 -0
  101. package/dist/assets/main-CCvRMXlP.css +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +1 -1
  104. package/shared/types/database/schema.ts +49 -0
  105. package/shared/types/db-client/connection.ts +6 -0
  106. package/shared/types/ssh/connection.ts +80 -0
  107. package/shared/types/ssh/forward.ts +46 -0
  108. package/shared/types/ssh/index.ts +8 -0
  109. package/shared/types/ssh/known-host.ts +19 -0
  110. package/shared/types/ssh/sftp.ts +141 -0
  111. package/shared/utils/logger.ts +1 -0
  112. package/backend/ws/engine/restart.ts +0 -54
  113. package/dist/assets/main-VgdjTBLR.css +0 -1
  114. package/dist/assets/main-r0iv2PDz.js +0 -1044
@@ -7,7 +7,6 @@ describe('ADMIN_ONLY_ROUTES', () => {
7
7
  'auth:logout-all',
8
8
  'system:clear-data',
9
9
  'settings:update',
10
- 'engine:codex-restart',
11
10
  'tunnel:remote:start'
12
11
  ];
13
12
 
@@ -64,12 +64,10 @@ export const ADMIN_ONLY_ROUTES = new Set([
64
64
  'engine:codex-accounts-rename',
65
65
  'engine:codex-account-setup-start',
66
66
  'engine:codex-account-setup-cancel',
67
- 'engine:codex-restart',
68
67
  'engine:copilot-accounts-add',
69
68
  'engine:copilot-accounts-switch',
70
69
  'engine:copilot-accounts-delete',
71
70
  'engine:copilot-accounts-rename',
72
- 'engine:copilot-restart',
73
71
  'engine:qwen-accounts-add',
74
72
  'engine:qwen-accounts-switch',
75
73
  'engine:qwen-accounts-delete',
@@ -98,9 +96,7 @@ export const ADMIN_ONLY_ROUTES = new Set([
98
96
  'engine:opencode-account-switch',
99
97
  'engine:opencode-account-delete',
100
98
  'engine:opencode-account-rename',
101
- 'engine:opencode-server-restart',
102
99
  'engine:opencode-models-dev-fetch',
103
- 'engine:restart-all',
104
100
  // Tunnel — remote/local management mutates global Cloudflare credentials,
105
101
  // cloudflared auth, and ingress rules. Quick Tunnel is ephemeral and stays
106
102
  // open. Read-only routes (status, *-list, ingress, auth-status) stay open so
@@ -33,7 +33,7 @@ import type {
33
33
  } from '$shared/types/unified';
34
34
  import type { EngineType } from '$shared/types/unified';
35
35
  import type { DatabaseMessage } from '$shared/types/database/schema';
36
- import { findProjectEngine, initializeProjectEngine } from '../engine';
36
+ import { initializeProjectEngine, type AIEngine } from '../engine';
37
37
  import { messageQueries, projectQueries, sessionQueries } from '../database/queries';
38
38
  import { snapshotService } from '../snapshot/snapshot-service';
39
39
  import { snapshotQueries } from '../database/queries/snapshot-queries';
@@ -71,6 +71,17 @@ export interface StreamState {
71
71
  error?: string;
72
72
  abortController?: AbortController;
73
73
  streamPromise?: Promise<void>;
74
+ /**
75
+ * The engine instance actually running this stream.
76
+ *
77
+ * Pinned rather than looked up by (projectId, engineType), because the cache
78
+ * behind that lookup is now replaced whenever engine config changes. Looking
79
+ * it up again would hand back the REPLACEMENT: an instance with no query to
80
+ * cancel and no pending question to answer, so Stop would do nothing and an
81
+ * AskUserQuestion answer would go nowhere — and only for users unlucky enough
82
+ * to have changed a setting while a chat was running.
83
+ */
84
+ engineInstance?: AIEngine;
74
85
  sdkSessionId?: string;
75
86
  preStreamSessionId?: string | null;
76
87
  hasCompactBoundary?: boolean;
@@ -428,7 +439,10 @@ class StreamManager extends EventEmitter {
428
439
  // Register session -> projectId mapping for MCP context
429
440
  if (request.projectId) {
430
441
  projectContextService.registerSession(request.chatSessionId, request.projectId);
431
- projectContextService.registerStream(streamId, request.projectId, request.chatSessionId);
442
+ // The engine goes with it: the remote HTTP MCP bridge cannot always
443
+ // name the calling stream, and knowing which engine asked is what
444
+ // keeps a fallback from reaching across into another engine's project.
445
+ projectContextService.registerStream(streamId, request.projectId, request.chatSessionId, request.engine.type);
432
446
  }
433
447
  // Hand the AbortSignal to MCP so tool handlers can fast-fail on
434
448
  // cancellation. Without this, the engine subprocess dies on cancel
@@ -661,6 +675,7 @@ class StreamManager extends EventEmitter {
661
675
  if (chatSessionId) deferEpisodicIngest(chatSessionId);
662
676
 
663
677
  const engine = await initializeProjectEngine(projectId, requestEngine.type);
678
+ streamState.engineInstance = engine;
664
679
 
665
680
  if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
666
681
  debug.log('chat', 'Stream cancelled during engine initialization, skipping query');
@@ -1391,10 +1406,10 @@ class StreamManager extends EventEmitter {
1391
1406
  return false;
1392
1407
  }
1393
1408
 
1394
- // The stream is live, so its engine already exists. Look it up rather than
1395
- // creating one — a fresh instance holds no pending question to answer.
1396
- const pid = streamState.projectId || 'default';
1397
- const engine = findProjectEngine(pid, streamState.engine);
1409
+ // The stream is live, so it is holding the engine that owns the pending
1410
+ // question. Use that one — a replacement instance holds no question to
1411
+ // answer, and a fresh one would not even be the same process.
1412
+ const engine = streamState.engineInstance;
1398
1413
 
1399
1414
  if (!engine?.resolveUserAnswer) {
1400
1415
  debug.warn('chat', 'resolveUserAnswer: Engine does not support resolveUserAnswer');
@@ -1523,17 +1538,21 @@ class StreamManager extends EventEmitter {
1523
1538
  debug.log('mcp', `✅ Auto-released MCP tabs for session ${streamState.chatSessionId.slice(0, 8)} on stream cancellation`);
1524
1539
  }
1525
1540
 
1526
- // Cancel the per-project engine with a bounded timeout.
1527
- // engine.cancel() stops the SDK process (Claude Code: close() kills subprocess,
1541
+ // Stop this stream's run on the engine, with a bounded timeout.
1542
+ // engine.cancel() stops the SDK work (Claude Code: close() kills subprocess,
1528
1543
  // OpenCode: aborts controller + HTTP abort to server). If cancel() hangs
1529
1544
  // (e.g. unresponsive SDK), the timeout ensures we always proceed to emit
1530
1545
  // events and update presence — preventing infinite loader on the frontend.
1531
- const projectId = streamState.projectId || 'default';
1546
+ //
1547
+ // The abortController identifies WHICH run to stop. One engine instance is
1548
+ // shared by every chat session of a project, so an untargeted cancel stops
1549
+ // whichever run the instance happened to have on hand — cancelling one chat
1550
+ // would kill another chat of the same project mid-answer.
1532
1551
  try {
1533
- const engine = findProjectEngine(projectId, streamState.engine);
1534
- if (engine?.isActive) {
1552
+ const engine = streamState.engineInstance;
1553
+ if (engine && streamState.abortController) {
1535
1554
  await Promise.race([
1536
- engine.cancel(),
1555
+ engine.cancel(streamState.abortController),
1537
1556
  new Promise<void>(resolve => setTimeout(resolve, 5000))
1538
1557
  ]);
1539
1558
  }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * The revision counter is the only thing that notices a config edit now.
3
+ *
4
+ * Removing the "Restart Server" button removed the manual way to make an edit
5
+ * take effect, so a trigger that silently stops firing is no longer a small bug —
6
+ * it is config that never applies, with nothing in the UI to work around it. The
7
+ * two properties worth pinning down are that watched writes DO bump (or the
8
+ * feature is dead) and that bookkeeping writes DON'T (or every unrelated update
9
+ * respawns a server).
10
+ *
11
+ * Runs against a real in-memory SQLite rather than a mocked handle: the whole
12
+ * mechanism IS the SQL, and a mock that returns what the test expects would
13
+ * assert nothing about whether `UPDATE OF` scopes the way it is supposed to.
14
+ */
15
+
16
+ import { describe, expect, test } from 'bun:test';
17
+ import { Database } from 'bun:sqlite';
18
+ import type { DatabaseConnection } from '$shared/types/database/connection';
19
+ import { up } from './068_create_engine_config_revision';
20
+
21
+ /** Only the columns the triggers name — enough to exercise them faithfully. */
22
+ function freshDb(): Database {
23
+ const db = new Database(':memory:');
24
+ db.exec(`
25
+ CREATE TABLE mcp_servers (
26
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
27
+ slug TEXT NOT NULL,
28
+ name TEXT NOT NULL,
29
+ transport TEXT NOT NULL DEFAULT 'stdio',
30
+ command TEXT,
31
+ args TEXT NOT NULL DEFAULT '[]',
32
+ env TEXT NOT NULL DEFAULT '{}',
33
+ url TEXT,
34
+ headers TEXT NOT NULL DEFAULT '{}',
35
+ is_enabled INTEGER NOT NULL DEFAULT 1,
36
+ config_schema TEXT,
37
+ oauth TEXT,
38
+ tool_overrides TEXT,
39
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
40
+ )
41
+ `);
42
+ db.exec(`
43
+ CREATE TABLE engine_accounts (
44
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
45
+ provider_id INTEGER NOT NULL,
46
+ name TEXT NOT NULL,
47
+ credential TEXT NOT NULL,
48
+ is_active INTEGER NOT NULL DEFAULT 0
49
+ )
50
+ `);
51
+ up(db as unknown as DatabaseConnection);
52
+ return db;
53
+ }
54
+
55
+ function revision(db: Database): number {
56
+ return (db.prepare('SELECT revision FROM engine_config_revision WHERE id = 1').get() as { revision: number }).revision;
57
+ }
58
+
59
+ describe('engine config revision triggers', () => {
60
+ test('installing, toggling and removing a connector each bump the revision', () => {
61
+ const db = freshDb();
62
+ const start = revision(db);
63
+
64
+ db.exec(`INSERT INTO mcp_servers (slug, name, transport) VALUES ('playwright', 'Playwright', 'stdio')`);
65
+ const afterInsert = revision(db);
66
+ expect(afterInsert).toBeGreaterThan(start);
67
+
68
+ db.exec(`UPDATE mcp_servers SET is_enabled = 0 WHERE slug = 'playwright'`);
69
+ const afterToggle = revision(db);
70
+ expect(afterToggle).toBeGreaterThan(afterInsert);
71
+
72
+ db.exec(`DELETE FROM mcp_servers WHERE slug = 'playwright'`);
73
+ expect(revision(db)).toBeGreaterThan(afterToggle);
74
+ });
75
+
76
+ test('a refreshed OAuth token bumps, because it changes the header the connector is spawned with', () => {
77
+ const db = freshDb();
78
+ db.exec(`INSERT INTO mcp_servers (slug, name, transport) VALUES ('linear', 'Linear', 'http')`);
79
+ const before = revision(db);
80
+
81
+ db.exec(`UPDATE mcp_servers SET oauth = '{"access_token":"new"}' WHERE slug = 'linear'`);
82
+ expect(revision(db)).toBeGreaterThan(before);
83
+ });
84
+
85
+ test('bookkeeping columns do NOT bump — otherwise every unrelated write respawns a server', () => {
86
+ const db = freshDb();
87
+ db.exec(`INSERT INTO mcp_servers (slug, name, transport) VALUES ('github', 'GitHub', 'http')`);
88
+ const before = revision(db);
89
+
90
+ // `created_at` is not in the trigger's UPDATE OF list.
91
+ db.exec(`UPDATE mcp_servers SET created_at = '2020-01-01 00:00:00' WHERE slug = 'github'`);
92
+ expect(revision(db)).toBe(before);
93
+ });
94
+
95
+ test('switching the active account bumps, renaming it does not', () => {
96
+ const db = freshDb();
97
+ db.exec(`INSERT INTO engine_accounts (provider_id, name, credential, is_active) VALUES (1, 'Work', 'sk-a', 1)`);
98
+ db.exec(`INSERT INTO engine_accounts (provider_id, name, credential, is_active) VALUES (1, 'Personal', 'sk-b', 0)`);
99
+ const before = revision(db);
100
+
101
+ db.exec(`UPDATE engine_accounts SET is_active = 1 WHERE name = 'Personal'`);
102
+ const afterSwitch = revision(db);
103
+ expect(afterSwitch).toBeGreaterThan(before);
104
+
105
+ // A display name is not part of any engine's spawn config.
106
+ db.exec(`UPDATE engine_accounts SET name = 'Personal (old)' WHERE name = 'Personal'`);
107
+ expect(revision(db)).toBe(afterSwitch);
108
+ });
109
+
110
+ test('a watched table that does not exist yet is skipped, not fatal', () => {
111
+ // freshDb() creates two of the ten watched tables; `up()` already ran over
112
+ // the rest without throwing, and the counter is still usable.
113
+ const db = freshDb();
114
+ expect(revision(db)).toBeGreaterThan(0);
115
+ });
116
+
117
+ test('the counter cannot grow a second row', () => {
118
+ const db = freshDb();
119
+ expect(() => db.exec(`INSERT INTO engine_config_revision (id, revision) VALUES (2, 1)`)).toThrow();
120
+ });
121
+ });
@@ -0,0 +1,117 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create engine_config_revision counter + triggers that bump it on any engine-affecting config write';
5
+
6
+ /**
7
+ * A single counter that goes up whenever anything an engine bakes at start-up
8
+ * changes.
9
+ *
10
+ * This exists because the "Restart Server" button was removed. That button was
11
+ * a manual cache-invalidation lever: Open Code spawns `opencode serve` with its
12
+ * MCP set, provider list and agent registry frozen into the process, so editing
13
+ * any of them left the running server serving stale config until somebody
14
+ * noticed and pressed restart. With no button left, nothing may depend on a
15
+ * human noticing.
16
+ *
17
+ * The counter is maintained by TRIGGERS rather than by a `bumpConfig()` helper
18
+ * called from the write paths. A helper is one `git grep` away from being
19
+ * forgotten by the next feature that adds a config table, and the failure mode
20
+ * of forgetting it is invisible — config that silently never applies, with no
21
+ * button to work around it. A trigger cannot be forgotten by code that does not
22
+ * know it exists.
23
+ *
24
+ * Triggers are scoped with `UPDATE OF <columns>` on purpose. A blanket
25
+ * `AFTER UPDATE` would fire on bookkeeping columns (timestamps, usage counters)
26
+ * and bump the revision for writes that change nothing an engine reads, costing
27
+ * a needless config rebuild on every one of them.
28
+ *
29
+ * The revision is only ever a cache-invalidation SIGNAL. What actually decides
30
+ * whether a server is respawned is the hash of the config content itself (see
31
+ * `backend/engine/adapters/opencode/server.ts`), so a bump that turns out not to
32
+ * change any baked value — toggling a connector off and back on, editing a
33
+ * permission rule that is enforced per-prompt rather than at boot — costs one
34
+ * rebuild and reuses the running server.
35
+ */
36
+
37
+ /** Tables whose rows feed engine start-up config, with the columns that matter. */
38
+ const WATCHED: { table: string; columns: string[] }[] = [
39
+ // MCP connectors: baked into every engine's server/session config.
40
+ // `oauth` is included because a refreshed token changes the Authorization
41
+ // header the connector is spawned with.
42
+ {
43
+ table: 'mcp_servers',
44
+ columns: ['slug', 'name', 'transport', 'command', 'args', 'env', 'url', 'headers', 'is_enabled', 'config_schema', 'oauth', 'tool_overrides'],
45
+ },
46
+ // Providers + accounts: Open Code receives these as OPENCODE_CONFIG_CONTENT
47
+ // and env vars at spawn; every other engine reads them per turn.
48
+ {
49
+ table: 'engine_providers',
50
+ columns: ['slug', 'name', 'npm', 'api_url', 'options', 'is_enabled'],
51
+ },
52
+ // Deliberately NOT `name` — renaming an account changes no baked value.
53
+ {
54
+ table: 'engine_accounts',
55
+ columns: ['provider_id', 'credential', 'is_active'],
56
+ },
57
+ { table: 'skills', columns: ['slug', 'name', 'description', 'is_enabled'] },
58
+ { table: 'commands', columns: ['slug', 'name', 'description', 'argument_hint', 'is_enabled', 'model_by_engine'] },
59
+ { table: 'subagents', columns: ['slug', 'name', 'description', 'is_enabled', 'model_by_engine', 'tools_by_engine'] },
60
+ { table: 'instructions', columns: ['scope', 'project_id', 'content', 'is_enabled'] },
61
+ { table: 'permission_sets', columns: ['scope', 'project_id', 'engine', 'allow', 'deny', 'profile_id'] },
62
+ { table: 'profiles', columns: ['slug', 'name'] },
63
+ { table: 'profile_items', columns: ['profile_id', 'artifact_type', 'ref'] },
64
+ ];
65
+
66
+ const BUMP = `UPDATE engine_config_revision SET revision = revision + 1, updated_at = datetime('now') WHERE id = 1;`;
67
+
68
+ export const up = (db: DatabaseConnection): void => {
69
+ debug.log('migration', 'Creating engine_config_revision table...');
70
+
71
+ // Single-row table. The CHECK makes that a schema guarantee rather than a
72
+ // convention the triggers have to trust.
73
+ db.exec(`
74
+ CREATE TABLE IF NOT EXISTS engine_config_revision (
75
+ id INTEGER PRIMARY KEY CHECK (id = 1),
76
+ revision INTEGER NOT NULL DEFAULT 1,
77
+ updated_at DATETIME NOT NULL DEFAULT (datetime('now'))
78
+ )
79
+ `);
80
+ db.exec(`INSERT OR IGNORE INTO engine_config_revision (id, revision) VALUES (1, 1)`);
81
+
82
+ for (const { table, columns } of WATCHED) {
83
+ // A watched table may legitimately be absent on an old database that never
84
+ // ran the migration creating it; skipping keeps this migration total.
85
+ const exists = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`).get(table);
86
+ if (!exists) {
87
+ debug.warn('migration', `engine_config_revision: table ${table} not present, skipping its triggers`);
88
+ continue;
89
+ }
90
+
91
+ db.exec(`
92
+ CREATE TRIGGER IF NOT EXISTS trg_engine_config_rev_${table}_ins
93
+ AFTER INSERT ON ${table} BEGIN ${BUMP} END
94
+ `);
95
+ db.exec(`
96
+ CREATE TRIGGER IF NOT EXISTS trg_engine_config_rev_${table}_del
97
+ AFTER DELETE ON ${table} BEGIN ${BUMP} END
98
+ `);
99
+ db.exec(`
100
+ CREATE TRIGGER IF NOT EXISTS trg_engine_config_rev_${table}_upd
101
+ AFTER UPDATE OF ${columns.join(', ')} ON ${table} BEGIN ${BUMP} END
102
+ `);
103
+ }
104
+
105
+ debug.log('migration', `engine_config_revision created with triggers on ${WATCHED.length} tables`);
106
+ };
107
+
108
+ export const down = (db: DatabaseConnection): void => {
109
+ debug.log('migration', 'Dropping engine_config_revision...');
110
+ for (const { table } of WATCHED) {
111
+ db.exec(`DROP TRIGGER IF EXISTS trg_engine_config_rev_${table}_ins`);
112
+ db.exec(`DROP TRIGGER IF EXISTS trg_engine_config_rev_${table}_del`);
113
+ db.exec(`DROP TRIGGER IF EXISTS trg_engine_config_rev_${table}_upd`);
114
+ }
115
+ db.exec('DROP TABLE IF EXISTS engine_config_revision');
116
+ debug.log('migration', 'engine_config_revision dropped');
117
+ };
@@ -0,0 +1,116 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create ssh_connections, ssh_known_hosts and ssh_port_forwards tables';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating ssh_connections table...');
8
+
9
+ // `jump_connection_id` self-references: a saved host can be reached through
10
+ // another saved host (ProxyJump). ON DELETE SET NULL rather than CASCADE —
11
+ // deleting a bastion must not silently delete everything behind it.
12
+ db.exec(`
13
+ CREATE TABLE IF NOT EXISTS ssh_connections (
14
+ id TEXT PRIMARY KEY,
15
+ name TEXT NOT NULL,
16
+ host TEXT NOT NULL,
17
+ port INTEGER NOT NULL DEFAULT 22,
18
+ username TEXT NOT NULL,
19
+ auth_method TEXT NOT NULL DEFAULT 'password'
20
+ CHECK (auth_method IN ('password','key','key-file','agent')),
21
+ password TEXT,
22
+ private_key TEXT,
23
+ private_key_path TEXT,
24
+ passphrase TEXT,
25
+ agent_socket TEXT,
26
+ jump_connection_id TEXT REFERENCES ssh_connections(id) ON DELETE SET NULL,
27
+ initial_path TEXT,
28
+ keepalive_seconds INTEGER NOT NULL DEFAULT 30,
29
+ strict_host_key INTEGER NOT NULL DEFAULT 1,
30
+ color TEXT,
31
+ owner_user_id TEXT,
32
+ created_at TEXT NOT NULL,
33
+ updated_at TEXT NOT NULL,
34
+ last_used_at TEXT
35
+ )
36
+ `);
37
+
38
+ db.exec(`
39
+ CREATE INDEX IF NOT EXISTS idx_ssh_conn_last_used
40
+ ON ssh_connections(last_used_at DESC)
41
+ `);
42
+
43
+ db.exec(`
44
+ CREATE INDEX IF NOT EXISTS idx_ssh_conn_owner
45
+ ON ssh_connections(owner_user_id)
46
+ `);
47
+
48
+ debug.log('migration', 'Creating ssh_known_hosts table...');
49
+
50
+ // One trusted key per (host, port) — the same rule OpenSSH's known_hosts
51
+ // enforces, so a rotated key is an update rather than a second row.
52
+ db.exec(`
53
+ CREATE TABLE IF NOT EXISTS ssh_known_hosts (
54
+ id TEXT PRIMARY KEY,
55
+ host TEXT NOT NULL,
56
+ port INTEGER NOT NULL DEFAULT 22,
57
+ key_type TEXT NOT NULL,
58
+ fingerprint TEXT NOT NULL,
59
+ added_at TEXT NOT NULL,
60
+ last_seen_at TEXT,
61
+ UNIQUE (host, port)
62
+ )
63
+ `);
64
+
65
+ debug.log('migration', 'Creating ssh_port_forwards table...');
66
+
67
+ db.exec(`
68
+ CREATE TABLE IF NOT EXISTS ssh_port_forwards (
69
+ id TEXT PRIMARY KEY,
70
+ connection_id TEXT NOT NULL,
71
+ name TEXT NOT NULL,
72
+ type TEXT NOT NULL CHECK (type IN ('local','remote','dynamic')),
73
+ listen_host TEXT NOT NULL DEFAULT '127.0.0.1',
74
+ listen_port INTEGER NOT NULL,
75
+ dest_host TEXT,
76
+ dest_port INTEGER,
77
+ auto_start INTEGER NOT NULL DEFAULT 0,
78
+ created_at TEXT NOT NULL,
79
+ updated_at TEXT NOT NULL,
80
+ FOREIGN KEY (connection_id) REFERENCES ssh_connections(id) ON DELETE CASCADE
81
+ )
82
+ `);
83
+
84
+ db.exec(`
85
+ CREATE INDEX IF NOT EXISTS idx_ssh_forward_connection
86
+ ON ssh_port_forwards(connection_id)
87
+ `);
88
+
89
+ // Let a database connection reuse a saved SSH host instead of repeating the
90
+ // host, credentials and key inline. The inline columns stay: existing
91
+ // connections keep working untouched, and this is simply the other mode.
92
+ const dbClientColumns = db.prepare(`PRAGMA table_info(db_client_connections)`).all() as Array<{ name: string }>;
93
+ if (dbClientColumns.length > 0 && !dbClientColumns.some((column) => column.name === 'ssh_connection_id')) {
94
+ debug.log('migration', 'Adding ssh_connection_id to db_client_connections...');
95
+ db.exec(`
96
+ ALTER TABLE db_client_connections
97
+ ADD COLUMN ssh_connection_id TEXT REFERENCES ssh_connections(id) ON DELETE SET NULL
98
+ `);
99
+ }
100
+
101
+ debug.log('migration', 'ssh-client tables created');
102
+ };
103
+
104
+ export const down = (db: DatabaseConnection): void => {
105
+ debug.log('migration', 'Dropping ssh-client tables...');
106
+ db.exec('DROP INDEX IF EXISTS idx_ssh_forward_connection');
107
+ db.exec('DROP TABLE IF EXISTS ssh_port_forwards');
108
+ db.exec('DROP TABLE IF EXISTS ssh_known_hosts');
109
+ db.exec('DROP INDEX IF EXISTS idx_ssh_conn_owner');
110
+ db.exec('DROP INDEX IF EXISTS idx_ssh_conn_last_used');
111
+ db.exec('DROP TABLE IF EXISTS ssh_connections');
112
+ // db_client_connections.ssh_connection_id is deliberately left in place —
113
+ // SQLite cannot drop a column without rebuilding the table, and an orphaned
114
+ // nullable column is harmless.
115
+ debug.log('migration', 'ssh-client tables dropped');
116
+ };
@@ -66,6 +66,8 @@ import * as migration064 from './064_create_messages_fts';
66
66
  import * as migration065 from './065_add_session_reasoning_effort';
67
67
  import * as migration066 from './066_create_memory_graph';
68
68
  import * as migration067 from './067_add_memory_graph_layout';
69
+ import * as migration068 from './068_create_engine_config_revision';
70
+ import * as migration069 from './069_create_ssh_client_tables';
69
71
 
70
72
  // Export all migrations in order
71
73
  export const migrations = [
@@ -470,6 +472,18 @@ export const migrations = [
470
472
  description: migration067.description,
471
473
  up: migration067.up,
472
474
  down: migration067.down
475
+ },
476
+ {
477
+ id: '068',
478
+ description: migration068.description,
479
+ up: migration068.up,
480
+ down: migration068.down
481
+ },
482
+ {
483
+ id: '069',
484
+ description: migration069.description,
485
+ up: migration069.up,
486
+ down: migration069.down
473
487
  }
474
488
  ];
475
489
 
@@ -11,6 +11,7 @@ import type {
11
11
 
12
12
  const DEFAULT_SSH: DbClientSshConfig = {
13
13
  enabled: false,
14
+ connectionId: null,
14
15
  host: '',
15
16
  port: 22,
16
17
  username: '',
@@ -35,6 +36,7 @@ function rowToConnection(row: DBDbClientConnectionRow): DbClientConnection {
35
36
 
36
37
  const ssh: DbClientSshConfig = {
37
38
  enabled: row.ssh_enabled === 1,
39
+ connectionId: row.ssh_connection_id,
38
40
  host: row.ssh_host ?? '',
39
41
  port: row.ssh_port ?? 22,
40
42
  username: row.ssh_username ?? '',
@@ -151,7 +153,7 @@ function insertConnection(input: DbClientConnectionInput, ownerUserId: string |
151
153
  host, port, username, password, database,
152
154
  ssl_mode, ssl_ca,
153
155
  ssh_enabled, ssh_host, ssh_port, ssh_username, ssh_auth_method,
154
- ssh_password, ssh_private_key, ssh_passphrase,
156
+ ssh_password, ssh_private_key, ssh_passphrase, ssh_connection_id,
155
157
  options_json, color,
156
158
  owner_user_id,
157
159
  created_at, updated_at, last_used_at
@@ -160,7 +162,7 @@ function insertConnection(input: DbClientConnectionInput, ownerUserId: string |
160
162
  ?, ?, ?, ?, ?,
161
163
  ?, ?,
162
164
  ?, ?, ?, ?, ?,
163
- ?, ?, ?,
165
+ ?, ?, ?, ?,
164
166
  ?, ?,
165
167
  ?,
166
168
  ?, ?, ?
@@ -177,6 +179,7 @@ function insertConnection(input: DbClientConnectionInput, ownerUserId: string |
177
179
  params.ssh.password || null,
178
180
  params.ssh.privateKey || null,
179
181
  params.ssh.passphrase || null,
182
+ params.ssh.connectionId || null,
180
183
  JSON.stringify(params.options),
181
184
  params.color,
182
185
  params.ownerUserId,
@@ -275,6 +278,7 @@ export const dbClientConnectionQueries = {
275
278
  if (patch.ssh !== undefined) {
276
279
  const merged: DbClientSshConfig = {
277
280
  enabled: existing.ssh_enabled === 1,
281
+ connectionId: existing.ssh_connection_id,
278
282
  host: existing.ssh_host ?? '',
279
283
  port: existing.ssh_port ?? 22,
280
284
  username: existing.ssh_username ?? '',
@@ -296,6 +300,7 @@ export const dbClientConnectionQueries = {
296
300
  push('ssh_password', sshPassword);
297
301
  push('ssh_private_key', sshPrivateKey);
298
302
  push('ssh_passphrase', sshPassphrase);
303
+ push('ssh_connection_id', merged.connectionId || null);
299
304
  }
300
305
 
301
306
  push('updated_at', new Date().toISOString());
@@ -26,6 +26,7 @@ export interface FileAuditLogEntry {
26
26
 
27
27
  export type FileAuditAction =
28
28
  | 'upload'
29
+ | 'download'
29
30
  | 'delete'
30
31
  | 'move'
31
32
  | 'rename'
@@ -10,6 +10,9 @@ export { engineQueries } from './engine-queries';
10
10
  export { authQueries } from './auth-queries';
11
11
  export { dbClientConnectionQueries } from './db-client-connection-queries';
12
12
  export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
13
+ export { sshConnectionQueries } from './ssh-connection-queries';
14
+ export { sshKnownHostQueries } from './ssh-known-host-queries';
15
+ export { sshPortForwardQueries } from './ssh-port-forward-queries';
13
16
  export { auditLogQueries } from './audit-log-queries';
14
17
  export { fileAuditLogQueries } from './file-audit-log-queries';
15
18
  export { mcpServerQueries } from './mcp-server-queries';