@myrialabs/clopen 0.3.8 → 0.3.9

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 (125) hide show
  1. package/backend/auth/permissions.ts +41 -2
  2. package/backend/chat/stream-manager.ts +71 -0
  3. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  4. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  5. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  6. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  7. package/backend/database/migrations/index.ts +29 -1
  8. package/backend/database/queries/db-client-connection-queries.ts +160 -54
  9. package/backend/database/queries/engine-queries.ts +12 -0
  10. package/backend/database/queries/project-queries.ts +10 -5
  11. package/backend/engine/README.md +1702 -0
  12. package/backend/engine/adapters/claude/models.ts +141 -0
  13. package/backend/engine/adapters/claude/stream.ts +1 -1
  14. package/backend/engine/adapters/codex/credential.ts +179 -0
  15. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  16. package/backend/engine/adapters/codex/index.ts +1 -0
  17. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  18. package/backend/engine/adapters/codex/models.ts +105 -0
  19. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  20. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  21. package/backend/engine/adapters/codex/stream.ts +310 -0
  22. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  23. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  24. package/backend/engine/adapters/copilot/index.ts +1 -0
  25. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  26. package/backend/engine/adapters/copilot/models.ts +92 -0
  27. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  28. package/backend/engine/adapters/copilot/stream.ts +573 -0
  29. package/backend/engine/adapters/opencode/config.ts +56 -104
  30. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  31. package/backend/engine/adapters/opencode/models.ts +79 -0
  32. package/backend/engine/adapters/opencode/presets.ts +91 -0
  33. package/backend/engine/adapters/opencode/stream.ts +5 -115
  34. package/backend/engine/adapters/qwen/credential.ts +78 -0
  35. package/backend/engine/adapters/qwen/environment.ts +84 -0
  36. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  37. package/backend/engine/adapters/qwen/index.ts +1 -0
  38. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  39. package/backend/engine/adapters/qwen/models.ts +81 -0
  40. package/backend/engine/adapters/qwen/presets.ts +51 -0
  41. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  42. package/backend/engine/adapters/qwen/stream.ts +380 -0
  43. package/backend/engine/index.ts +35 -0
  44. package/backend/engine/install-recipes.ts +80 -1
  45. package/backend/engine/install-runner.ts +4 -0
  46. package/backend/mcp/README.md +84 -14
  47. package/backend/mcp/config.ts +218 -17
  48. package/backend/mcp/index.ts +2 -0
  49. package/backend/mcp/project-context.ts +55 -0
  50. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  51. package/backend/mcp/servers/helper.ts +13 -0
  52. package/backend/middleware/error-handler.ts +16 -2
  53. package/backend/preview/browser/browser-preview-service.ts +4 -4
  54. package/backend/ws/README.md +128 -3
  55. package/backend/ws/access.ts +56 -0
  56. package/backend/ws/chat/stream.ts +36 -12
  57. package/backend/ws/db-client/access.ts +19 -0
  58. package/backend/ws/db-client/connections.ts +31 -17
  59. package/backend/ws/db-client/io.ts +7 -9
  60. package/backend/ws/db-client/query.ts +83 -31
  61. package/backend/ws/db-client/schema.ts +9 -4
  62. package/backend/ws/db-client/structure.ts +22 -10
  63. package/backend/ws/engine/access.ts +39 -0
  64. package/backend/ws/engine/claude/accounts.ts +15 -10
  65. package/backend/ws/engine/codex/accounts.ts +516 -0
  66. package/backend/ws/engine/codex/index.ts +14 -0
  67. package/backend/ws/engine/codex/status.ts +87 -0
  68. package/backend/ws/engine/copilot/accounts.ts +122 -0
  69. package/backend/ws/engine/copilot/index.ts +13 -0
  70. package/backend/ws/engine/copilot/status.ts +54 -0
  71. package/backend/ws/engine/index.ts +7 -1
  72. package/backend/ws/engine/opencode/providers.ts +1 -1
  73. package/backend/ws/engine/qwen/accounts.ts +137 -0
  74. package/backend/ws/engine/qwen/index.ts +15 -0
  75. package/backend/ws/engine/qwen/presets.ts +40 -0
  76. package/backend/ws/engine/qwen/status.ts +54 -0
  77. package/backend/ws/files/read.ts +3 -1
  78. package/backend/ws/files/state.ts +3 -0
  79. package/backend/ws/files/watch.ts +7 -1
  80. package/backend/ws/git/branch.ts +13 -19
  81. package/backend/ws/git/commit-message.ts +3 -4
  82. package/backend/ws/git/commit.ts +5 -7
  83. package/backend/ws/git/conflict.ts +7 -10
  84. package/backend/ws/git/diff.ts +7 -10
  85. package/backend/ws/git/log.ts +3 -4
  86. package/backend/ws/git/remote.ts +30 -43
  87. package/backend/ws/git/staging.ts +13 -19
  88. package/backend/ws/git/status.ts +7 -11
  89. package/backend/ws/messages/crud.ts +7 -13
  90. package/backend/ws/preview/access.ts +45 -0
  91. package/backend/ws/preview/browser/cleanup.ts +3 -11
  92. package/backend/ws/preview/browser/console.ts +5 -40
  93. package/backend/ws/preview/browser/interact.ts +2 -6
  94. package/backend/ws/preview/browser/native-ui.ts +5 -18
  95. package/backend/ws/preview/browser/stats.ts +2 -12
  96. package/backend/ws/preview/browser/tab-info.ts +4 -20
  97. package/backend/ws/preview/browser/tab.ts +4 -27
  98. package/backend/ws/preview/browser/webcodecs.ts +6 -47
  99. package/backend/ws/projects/crud.ts +4 -10
  100. package/backend/ws/projects/status.ts +2 -0
  101. package/backend/ws/sessions/crud.ts +22 -33
  102. package/backend/ws/settings/crud.ts +13 -13
  103. package/backend/ws/snapshot/restore.ts +5 -2
  104. package/backend/ws/snapshot/timeline.ts +3 -1
  105. package/backend/ws/system-tools/access.ts +28 -0
  106. package/backend/ws/system-tools/install.ts +13 -4
  107. package/backend/ws/system-tools/status.ts +5 -2
  108. package/backend/ws/terminal/access.ts +56 -0
  109. package/backend/ws/terminal/persistence.ts +12 -6
  110. package/backend/ws/terminal/session.ts +35 -14
  111. package/backend/ws/terminal/stream.ts +4 -1
  112. package/dist/assets/{index-DqAGCTFT.js → index-D8V2wj9B.js} +2 -2
  113. package/dist/assets/{main-DsED0rLr.js → main-C9nYVmnw.js} +206 -198
  114. package/dist/assets/main-hspyFOoK.css +1 -0
  115. package/dist/index.html +2 -2
  116. package/package.json +4 -1
  117. package/shared/constants/engines.ts +45 -140
  118. package/shared/types/database/schema.ts +1 -0
  119. package/shared/types/unified/common.ts +1 -1
  120. package/shared/types/unified/engine.ts +29 -1
  121. package/shared/types/unified/index.ts +2 -0
  122. package/shared/types/unified/message.ts +1 -1
  123. package/shared/types/unified/tool.ts +17 -2
  124. package/shared/utils/ws-server.ts +14 -0
  125. package/dist/assets/main-eWY9R8g9.css +0 -1
@@ -26,13 +26,51 @@ export const ADMIN_ONLY_ROUTES = new Set([
26
26
  'auth:revoke-invite',
27
27
  'auth:list-users',
28
28
  'auth:remove-user',
29
- 'settings:update-system',
29
+ 'settings:update',
30
+ 'settings:update-batch',
31
+ 'system:run-update',
32
+ 'system:clear-data',
30
33
  // System Tools — binary installation is an admin-only operation.
31
34
  'system-tools:status',
32
35
  'system-tools:status-all',
33
36
  'system-tools:install-start',
34
37
  'system-tools:install-cancel',
35
- 'system-tools:install-session'
38
+ 'system-tools:install-session',
39
+ // Engine — account/provider mutations are global system credentials and
40
+ // must only be changed by admins. Read-only routes (status, *-list) stay
41
+ // open so any authenticated user can see what is configured.
42
+ 'engine:claude-accounts-switch',
43
+ 'engine:claude-accounts-delete',
44
+ 'engine:claude-accounts-rename',
45
+ 'engine:claude-account-setup-start',
46
+ 'engine:claude-account-setup-submit',
47
+ 'engine:claude-account-setup-cancel',
48
+ 'engine:codex-accounts-add-api-key',
49
+ 'engine:codex-accounts-switch',
50
+ 'engine:codex-accounts-delete',
51
+ 'engine:codex-accounts-rename',
52
+ 'engine:codex-account-setup-start',
53
+ 'engine:codex-account-setup-cancel',
54
+ 'engine:codex-restart',
55
+ 'engine:copilot-accounts-add',
56
+ 'engine:copilot-accounts-switch',
57
+ 'engine:copilot-accounts-delete',
58
+ 'engine:copilot-accounts-rename',
59
+ 'engine:copilot-restart',
60
+ 'engine:qwen-accounts-add',
61
+ 'engine:qwen-accounts-switch',
62
+ 'engine:qwen-accounts-delete',
63
+ 'engine:qwen-accounts-rename',
64
+ 'engine:opencode-provider-add',
65
+ 'engine:opencode-provider-remove',
66
+ 'engine:opencode-provider-toggle',
67
+ 'engine:opencode-provider-update-options',
68
+ 'engine:opencode-account-add',
69
+ 'engine:opencode-account-switch',
70
+ 'engine:opencode-account-delete',
71
+ 'engine:opencode-account-rename',
72
+ 'engine:opencode-server-restart',
73
+ 'engine:opencode-models-dev-fetch'
36
74
  ]);
37
75
 
38
76
  /**
@@ -67,3 +105,4 @@ export function checkRouteAccess(
67
105
  // All other routes — any authenticated user
68
106
  return { allowed: true };
69
107
  }
108
+
@@ -277,6 +277,13 @@ class StreamManager extends EventEmitter {
277
277
  projectContextService.registerSession(request.chatSessionId, request.projectId);
278
278
  projectContextService.registerStream(streamId, request.projectId, request.chatSessionId);
279
279
  }
280
+ // Hand the AbortSignal to MCP so tool handlers can fast-fail on
281
+ // cancellation. Without this, the engine subprocess dies on cancel
282
+ // but the in-flight HTTP-MCP tool keeps issuing puppeteer ops —
283
+ // surfacing as "preview keeps moving by itself" after interrupt.
284
+ if (streamState.abortController) {
285
+ projectContextService.registerStreamSignal(streamId, streamState.abortController.signal);
286
+ }
280
287
 
281
288
  // Emit connection event immediately
282
289
  this.emitStreamEvent(streamState, 'connection', {
@@ -686,6 +693,13 @@ class StreamManager extends EventEmitter {
686
693
  });
687
694
  }
688
695
  }
696
+ // Codex emits usage only once per turn (after all items
697
+ // streamed live), so saved assistant rows have usage:null.
698
+ // Backfill the turn's aggregate to every saved assistant
699
+ // without usage so it survives a refresh.
700
+ if (successResult.usage && streamState.engine === 'codex') {
701
+ this.backfillUsageForStream(streamState, successResult.usage, requestSender);
702
+ }
689
703
  } else {
690
704
  const errResult = output as ErrorResultEvent;
691
705
  if (errResult.errors?.length) {
@@ -1337,6 +1351,63 @@ class StreamManager extends EventEmitter {
1337
1351
  }
1338
1352
  }
1339
1353
 
1354
+ /**
1355
+ * Backfill `usage` onto every saved assistant row for a stream.
1356
+ *
1357
+ * Codex SDK emits its `Usage` aggregate exactly once per turn (in
1358
+ * `turn.completed`), well after the individual assistant items have
1359
+ * streamed and been persisted live with `usage: null`. Without this
1360
+ * backfill the persisted tool_use rows would carry no usage data, and
1361
+ * after a browser refresh the frontend would lose the per-message usage
1362
+ * that the live stream had attached in memory.
1363
+ *
1364
+ * Engine-gated to Codex by the caller: Claude Code and Copilot already
1365
+ * attach per-call usage on each assistant message, so applying a
1366
+ * stream-wide aggregate to them would overwrite that finer-grained data.
1367
+ */
1368
+ private backfillUsageForStream(
1369
+ streamState: StreamState,
1370
+ usage: TokenUsage,
1371
+ requestSender: StreamRequest['sender'],
1372
+ ): void {
1373
+ try {
1374
+ const { getDatabase } = require('../database');
1375
+ const db = getDatabase();
1376
+ const updateStmt = db.prepare('UPDATE messages SET data = ? WHERE id = ?');
1377
+
1378
+ for (const entry of streamState.messages as any[]) {
1379
+ const msg = entry?.message as UnifiedMessage | undefined;
1380
+ if (!msg || msg.type !== 'assistant') continue;
1381
+ if (msg.usage) continue;
1382
+ if (!entry.message_id) continue;
1383
+
1384
+ const patched: AssistantMessage = { ...(msg as AssistantMessage), usage };
1385
+ try {
1386
+ updateStmt.run(JSON.stringify(patched), entry.message_id);
1387
+ } catch (err) {
1388
+ debug.error('chat', 'Failed to UPDATE usage row:', err);
1389
+ continue;
1390
+ }
1391
+
1392
+ entry.message = patched;
1393
+ entry.usage = usage;
1394
+
1395
+ this.emitStreamEvent(streamState, 'message', {
1396
+ processId: streamState.processId,
1397
+ message: patched,
1398
+ usage,
1399
+ timestamp: patched.createdAt,
1400
+ message_id: entry.message_id,
1401
+ parent_message_id: entry.parent_message_id ?? null,
1402
+ sender_id: requestSender.id,
1403
+ sender_name: requestSender.name,
1404
+ });
1405
+ }
1406
+ } catch (err) {
1407
+ debug.error('chat', 'Failed to backfill usage for stream:', err);
1408
+ }
1409
+ }
1410
+
1340
1411
  /**
1341
1412
  * Extract detailed error info from an error object.
1342
1413
  * Handles engine-specific error shapes (Anthropic APIError, OpenCode SDK errors).
@@ -0,0 +1,19 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Seed GitHub Copilot provider into engine_providers';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Seeding GitHub Copilot provider...');
8
+ db.exec(`
9
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
10
+ VALUES ('copilot', 'github', 'GitHub', NULL, NULL, '{}', 1)
11
+ `);
12
+ debug.log('migration', 'GitHub Copilot provider seeded');
13
+ };
14
+
15
+ export const down = (db: DatabaseConnection): void => {
16
+ debug.log('migration', 'Removing GitHub Copilot provider...');
17
+ db.exec(`DELETE FROM engine_providers WHERE engine_type = 'copilot' AND slug = 'github'`);
18
+ debug.log('migration', 'GitHub Copilot provider removed');
19
+ };
@@ -0,0 +1,19 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Seed OpenAI Codex provider into engine_providers';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Seeding OpenAI Codex provider...');
8
+ db.exec(`
9
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
10
+ VALUES ('codex', 'openai', 'OpenAI', NULL, NULL, '{}', 1)
11
+ `);
12
+ debug.log('migration', 'OpenAI Codex provider seeded');
13
+ };
14
+
15
+ export const down = (db: DatabaseConnection): void => {
16
+ debug.log('migration', 'Removing OpenAI Codex provider...');
17
+ db.exec(`DELETE FROM engine_providers WHERE engine_type = 'codex' AND slug = 'openai'`);
18
+ debug.log('migration', 'OpenAI Codex provider removed');
19
+ };
@@ -0,0 +1,119 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description =
5
+ 'Seed Qwen Code provider and store credentials as JSON with per-account preset/baseUrl';
6
+
7
+ interface ProviderRow {
8
+ id: number;
9
+ options: string | null;
10
+ }
11
+
12
+ interface AccountRow {
13
+ id: number;
14
+ credential: string | null;
15
+ }
16
+
17
+ const DEFAULT_PRESET = 'dashscope-intl';
18
+ const DASHSCOPE_INTL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1';
19
+ const DASHSCOPE_CN = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
20
+ const OPENROUTER = 'https://openrouter.ai/api/v1';
21
+ const FIREWORKS = 'https://api.fireworks.ai/inference/v1';
22
+
23
+ function presetFromBaseUrl(baseUrl: string | null | undefined): string {
24
+ if (!baseUrl) return DEFAULT_PRESET;
25
+ const lower = baseUrl.toLowerCase();
26
+ if (lower.startsWith(DASHSCOPE_INTL.toLowerCase())) return 'dashscope-intl';
27
+ if (lower.startsWith(DASHSCOPE_CN.toLowerCase())) return 'dashscope-cn';
28
+ if (lower.startsWith(OPENROUTER.toLowerCase())) return 'openrouter';
29
+ if (lower.startsWith(FIREWORKS.toLowerCase())) return 'fireworks';
30
+ return 'custom';
31
+ }
32
+
33
+ export const up = (db: DatabaseConnection): void => {
34
+ debug.log('migration', 'Seeding Qwen Code provider...');
35
+ db.exec(`
36
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
37
+ VALUES ('qwen', 'qwen', 'Qwen', NULL, NULL, '{}', 1)
38
+ `);
39
+ debug.log('migration', 'Qwen Code provider seeded');
40
+
41
+ debug.log('migration', 'Migrating Qwen credentials to JSON form...');
42
+
43
+ const providers = db.prepare(
44
+ `SELECT id, options FROM engine_providers WHERE engine_type = 'qwen'`
45
+ ).all() as ProviderRow[];
46
+
47
+ for (const provider of providers) {
48
+ // Pull the previous provider-level baseUrl (if any) so we can fold it
49
+ // into each account's credential JSON.
50
+ let providerBaseUrl: string | undefined;
51
+ try {
52
+ const opts = JSON.parse(provider.options || '{}') as { baseUrl?: unknown };
53
+ if (typeof opts.baseUrl === 'string' && opts.baseUrl.trim().length > 0) {
54
+ providerBaseUrl = opts.baseUrl.trim();
55
+ }
56
+ } catch {
57
+ /* malformed options — treat as no baseUrl */
58
+ }
59
+
60
+ const preset = presetFromBaseUrl(providerBaseUrl);
61
+
62
+ const accounts = db.prepare(
63
+ `SELECT id, credential FROM engine_accounts WHERE provider_id = ?`
64
+ ).all(provider.id) as AccountRow[];
65
+
66
+ for (const account of accounts) {
67
+ const raw = (account.credential ?? '').trim();
68
+ // Skip accounts that already store JSON (idempotent re-run safety).
69
+ if (raw.startsWith('{')) continue;
70
+
71
+ const json: Record<string, unknown> = { apiKey: raw, preset };
72
+ if (providerBaseUrl) json.baseUrl = providerBaseUrl;
73
+
74
+ db.prepare(`UPDATE engine_accounts SET credential = ? WHERE id = ?`).run(
75
+ JSON.stringify(json),
76
+ account.id,
77
+ );
78
+ }
79
+
80
+ // Clear the provider-level baseUrl now that it's per-account.
81
+ if (providerBaseUrl !== undefined) {
82
+ db.prepare(`UPDATE engine_providers SET options = ? WHERE id = ?`).run('{}', provider.id);
83
+ }
84
+ }
85
+
86
+ debug.log('migration', 'Qwen credentials migrated to JSON form');
87
+ };
88
+
89
+ export const down = (db: DatabaseConnection): void => {
90
+ // Best-effort reverse: extract `apiKey` from the JSON blob and write it
91
+ // back as a raw string before removing the provider.
92
+ debug.log('migration', 'Reverting Qwen credentials to raw API key strings...');
93
+
94
+ const providers = db.prepare(
95
+ `SELECT id, options FROM engine_providers WHERE engine_type = 'qwen'`
96
+ ).all() as ProviderRow[];
97
+
98
+ for (const provider of providers) {
99
+ const accounts = db.prepare(
100
+ `SELECT id, credential FROM engine_accounts WHERE provider_id = ?`
101
+ ).all(provider.id) as AccountRow[];
102
+
103
+ for (const account of accounts) {
104
+ const raw = (account.credential ?? '').trim();
105
+ if (!raw.startsWith('{')) continue;
106
+ try {
107
+ const parsed = JSON.parse(raw) as { apiKey?: unknown };
108
+ const apiKey = typeof parsed.apiKey === 'string' ? parsed.apiKey : '';
109
+ db.prepare(`UPDATE engine_accounts SET credential = ? WHERE id = ?`).run(apiKey, account.id);
110
+ } catch {
111
+ /* leave malformed entries alone */
112
+ }
113
+ }
114
+ }
115
+
116
+ debug.log('migration', 'Removing Qwen Code provider...');
117
+ db.exec(`DELETE FROM engine_providers WHERE engine_type = 'qwen' AND slug = 'qwen'`);
118
+ debug.log('migration', 'Qwen Code provider removed');
119
+ };
@@ -0,0 +1,34 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add owner_user_id to db_client_connections table';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding owner_user_id to db_client_connections...');
8
+
9
+ // SQLite does not support IF NOT EXISTS for ADD COLUMN, so we ignore duplicate-column errors.
10
+ try {
11
+ db.exec(`
12
+ ALTER TABLE db_client_connections
13
+ ADD COLUMN owner_user_id TEXT
14
+ `);
15
+ } catch (error) {
16
+ const message = error instanceof Error ? error.message : String(error);
17
+ if (!message.toLowerCase().includes('duplicate column name')) {
18
+ throw error;
19
+ }
20
+ }
21
+
22
+ db.exec(`
23
+ CREATE INDEX IF NOT EXISTS idx_db_client_conn_owner
24
+ ON db_client_connections(owner_user_id)
25
+ `);
26
+
27
+ debug.log('migration', 'owner_user_id migration completed');
28
+ };
29
+
30
+ export const down = (db: DatabaseConnection): void => {
31
+ // SQLite cannot drop columns without table rebuild; keep rollback non-destructive.
32
+ debug.log('migration', 'Dropping idx_db_client_conn_owner index...');
33
+ db.exec('DROP INDEX IF EXISTS idx_db_client_conn_owner');
34
+ };
@@ -30,6 +30,10 @@ import * as migration028 from './028_create_opencode_accounts_table';
30
30
  import * as migration029 from './029_migrate_messages_to_unified';
31
31
  import * as migration030 from './030_add_files_panel_state_to_user_projects';
32
32
  import * as migration031 from './031_create_db_client_tables';
33
+ import * as migration032 from './032_seed_copilot_provider';
34
+ import * as migration033 from './033_seed_codex_provider';
35
+ import * as migration034 from './034_seed_qwen_provider';
36
+ import * as migration035 from './035_add_owner_to_db_client_connections';
33
37
 
34
38
  // Export all migrations in order
35
39
  export const migrations = [
@@ -218,7 +222,31 @@ export const migrations = [
218
222
  description: migration031.description,
219
223
  up: migration031.up,
220
224
  down: migration031.down
225
+ },
226
+ {
227
+ id: '032',
228
+ description: migration032.description,
229
+ up: migration032.up,
230
+ down: migration032.down
231
+ },
232
+ {
233
+ id: '033',
234
+ description: migration033.description,
235
+ up: migration033.up,
236
+ down: migration033.down
237
+ },
238
+ {
239
+ id: '034',
240
+ description: migration034.description,
241
+ up: migration034.up,
242
+ down: migration034.down
243
+ },
244
+ {
245
+ id: '035',
246
+ description: migration035.description,
247
+ up: migration035.up,
248
+ down: migration035.down
221
249
  }
222
250
  ];
223
251
 
224
- export default migrations;
252
+ export default migrations;
@@ -64,6 +64,36 @@ function rowToConnection(row: DBDbClientConnectionRow): DbClientConnection {
64
64
  };
65
65
  }
66
66
 
67
+ function redactConnectionSecrets(connection: DbClientConnection): DbClientConnection {
68
+ return {
69
+ ...connection,
70
+ password: null,
71
+ ssh: {
72
+ ...connection.ssh,
73
+ password: undefined,
74
+ privateKey: undefined,
75
+ passphrase: undefined
76
+ }
77
+ };
78
+ }
79
+
80
+ function hasConnectionAccess(
81
+ row: DBDbClientConnectionRow,
82
+ userId: string,
83
+ isAdmin: boolean
84
+ ): boolean {
85
+ if (isAdmin) return true;
86
+ return row.owner_user_id === userId;
87
+ }
88
+
89
+ function preserveExistingSecret(
90
+ patchValue: string | undefined,
91
+ existingValue: string | null
92
+ ): string | null {
93
+ if (patchValue === undefined || patchValue === '') return existingValue;
94
+ return patchValue;
95
+ }
96
+
67
97
  interface InsertParams {
68
98
  name: string;
69
99
  driver: DbDriver;
@@ -77,9 +107,10 @@ interface InsertParams {
77
107
  ssh: DbClientSshConfig;
78
108
  options: Record<string, unknown>;
79
109
  color: string | null;
110
+ ownerUserId: string | null;
80
111
  }
81
112
 
82
- function normalizeInput(input: DbClientConnectionInput): InsertParams {
113
+ function normalizeInput(input: DbClientConnectionInput, ownerUserId: string | null): InsertParams {
83
114
  const ssh: DbClientSshConfig = {
84
115
  ...DEFAULT_SSH,
85
116
  ...(input.ssh ?? {})
@@ -96,11 +127,102 @@ function normalizeInput(input: DbClientConnectionInput): InsertParams {
96
127
  sslCa: input.sslCa ?? null,
97
128
  ssh,
98
129
  options: input.options ?? {},
99
- color: input.color ?? null
130
+ color: input.color ?? null,
131
+ ownerUserId
100
132
  };
101
133
  }
102
134
 
135
+ function getRowById(id: string): DBDbClientConnectionRow | null {
136
+ const db = getDatabase();
137
+ return db.prepare(`
138
+ SELECT * FROM db_client_connections WHERE id = ?
139
+ `).get(id) as DBDbClientConnectionRow | null;
140
+ }
141
+
142
+ function insertConnection(input: DbClientConnectionInput, ownerUserId: string | null): DbClientConnection {
143
+ const db = getDatabase();
144
+ const id = crypto.randomUUID();
145
+ const now = new Date().toISOString();
146
+ const params = normalizeInput(input, ownerUserId);
147
+
148
+ db.prepare(`
149
+ INSERT INTO db_client_connections (
150
+ id, name, driver,
151
+ host, port, username, password, database,
152
+ ssl_mode, ssl_ca,
153
+ ssh_enabled, ssh_host, ssh_port, ssh_username, ssh_auth_method,
154
+ ssh_password, ssh_private_key, ssh_passphrase,
155
+ options_json, color,
156
+ owner_user_id,
157
+ created_at, updated_at, last_used_at
158
+ ) VALUES (
159
+ ?, ?, ?,
160
+ ?, ?, ?, ?, ?,
161
+ ?, ?,
162
+ ?, ?, ?, ?, ?,
163
+ ?, ?, ?,
164
+ ?, ?,
165
+ ?,
166
+ ?, ?, ?
167
+ )
168
+ `).run(
169
+ id, params.name, params.driver,
170
+ params.host, params.port, params.username, params.password, params.database,
171
+ params.sslMode, params.sslCa,
172
+ params.ssh.enabled ? 1 : 0,
173
+ params.ssh.host || null,
174
+ params.ssh.port,
175
+ params.ssh.username || null,
176
+ params.ssh.authMethod,
177
+ params.ssh.password || null,
178
+ params.ssh.privateKey || null,
179
+ params.ssh.passphrase || null,
180
+ JSON.stringify(params.options),
181
+ params.color,
182
+ params.ownerUserId,
183
+ now, now, null
184
+ );
185
+
186
+ const row = getRowById(id);
187
+ if (!row) {
188
+ throw new Error('db-client connection not found');
189
+ }
190
+ return rowToConnection(row);
191
+ }
192
+
103
193
  export const dbClientConnectionQueries = {
194
+ listForUser(userId: string, isAdmin: boolean): DbClientConnection[] {
195
+ const db = getDatabase();
196
+ const rows = (isAdmin
197
+ ? db.prepare(`
198
+ SELECT * FROM db_client_connections
199
+ ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
200
+ `).all()
201
+ : db.prepare(`
202
+ SELECT * FROM db_client_connections
203
+ WHERE owner_user_id = ?
204
+ ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
205
+ `).all(userId)) as DBDbClientConnectionRow[];
206
+
207
+ return rows.map((row) => redactConnectionSecrets(rowToConnection(row)));
208
+ },
209
+
210
+ getForUser(id: string, userId: string, isAdmin: boolean): DbClientConnection | null {
211
+ const row = getRowById(id);
212
+ if (!row || !hasConnectionAccess(row, userId, isAdmin)) {
213
+ return null;
214
+ }
215
+ return redactConnectionSecrets(rowToConnection(row));
216
+ },
217
+
218
+ ensureAccess(id: string, userId: string, isAdmin: boolean): DbClientConnection {
219
+ const row = getRowById(id);
220
+ if (!row || !hasConnectionAccess(row, userId, isAdmin)) {
221
+ throw new Error('db-client connection not found');
222
+ }
223
+ return rowToConnection(row);
224
+ },
225
+
104
226
  list(): DbClientConnection[] {
105
227
  const db = getDatabase();
106
228
  const rows = db.prepare(`
@@ -111,61 +233,22 @@ export const dbClientConnectionQueries = {
111
233
  },
112
234
 
113
235
  get(id: string): DbClientConnection | null {
114
- const db = getDatabase();
115
- const row = db.prepare(`
116
- SELECT * FROM db_client_connections WHERE id = ?
117
- `).get(id) as DBDbClientConnectionRow | null;
236
+ const row = getRowById(id);
118
237
  return row ? rowToConnection(row) : null;
119
238
  },
120
239
 
121
240
  create(input: DbClientConnectionInput): DbClientConnection {
122
- const db = getDatabase();
123
- const id = crypto.randomUUID();
124
- const now = new Date().toISOString();
125
- const params = normalizeInput(input);
126
-
127
- db.prepare(`
128
- INSERT INTO db_client_connections (
129
- id, name, driver,
130
- host, port, username, password, database,
131
- ssl_mode, ssl_ca,
132
- ssh_enabled, ssh_host, ssh_port, ssh_username, ssh_auth_method,
133
- ssh_password, ssh_private_key, ssh_passphrase,
134
- options_json, color,
135
- created_at, updated_at, last_used_at
136
- ) VALUES (
137
- ?, ?, ?,
138
- ?, ?, ?, ?, ?,
139
- ?, ?,
140
- ?, ?, ?, ?, ?,
141
- ?, ?, ?,
142
- ?, ?,
143
- ?, ?, ?
144
- )
145
- `).run(
146
- id, params.name, params.driver,
147
- params.host, params.port, params.username, params.password, params.database,
148
- params.sslMode, params.sslCa,
149
- params.ssh.enabled ? 1 : 0,
150
- params.ssh.host || null,
151
- params.ssh.port,
152
- params.ssh.username || null,
153
- params.ssh.authMethod,
154
- params.ssh.password || null,
155
- params.ssh.privateKey || null,
156
- params.ssh.passphrase || null,
157
- JSON.stringify(params.options),
158
- params.color,
159
- now, now, null
160
- );
161
-
162
- const row = db.prepare('SELECT * FROM db_client_connections WHERE id = ?').get(id) as DBDbClientConnectionRow;
163
- return rowToConnection(row);
241
+ return insertConnection(input, null);
242
+ },
243
+
244
+ createForUser(input: DbClientConnectionInput, ownerUserId: string): DbClientConnection {
245
+ const connection = insertConnection(input, ownerUserId);
246
+ return redactConnectionSecrets(connection);
164
247
  },
165
248
 
166
249
  update(id: string, patch: Partial<DbClientConnectionInput>): DbClientConnection {
167
250
  const db = getDatabase();
168
- const existing = db.prepare('SELECT * FROM db_client_connections WHERE id = ?').get(id) as DBDbClientConnectionRow | null;
251
+ const existing = getRowById(id);
169
252
  if (!existing) {
170
253
  throw new Error('db-client connection not found');
171
254
  }
@@ -182,7 +265,7 @@ export const dbClientConnectionQueries = {
182
265
  if (patch.host !== undefined) push('host', patch.host || null);
183
266
  if (patch.port !== undefined) push('port', patch.port ?? null);
184
267
  if (patch.username !== undefined) push('username', patch.username || null);
185
- if (patch.password !== undefined) push('password', patch.password || null);
268
+ if (patch.password !== undefined && patch.password !== '') push('password', patch.password);
186
269
  if (patch.database !== undefined) push('database', patch.database || null);
187
270
  if (patch.sslMode !== undefined) push('ssl_mode', patch.sslMode);
188
271
  if (patch.sslCa !== undefined) push('ssl_ca', patch.sslCa || null);
@@ -201,14 +284,18 @@ export const dbClientConnectionQueries = {
201
284
  passphrase: existing.ssh_passphrase ?? '',
202
285
  ...patch.ssh
203
286
  };
287
+ const sshPassword = preserveExistingSecret(patch.ssh.password, existing.ssh_password);
288
+ const sshPrivateKey = preserveExistingSecret(patch.ssh.privateKey, existing.ssh_private_key);
289
+ const sshPassphrase = preserveExistingSecret(patch.ssh.passphrase, existing.ssh_passphrase);
290
+
204
291
  push('ssh_enabled', merged.enabled ? 1 : 0);
205
292
  push('ssh_host', merged.host || null);
206
293
  push('ssh_port', merged.port);
207
294
  push('ssh_username', merged.username || null);
208
295
  push('ssh_auth_method', merged.authMethod);
209
- push('ssh_password', merged.password || null);
210
- push('ssh_private_key', merged.privateKey || null);
211
- push('ssh_passphrase', merged.passphrase || null);
296
+ push('ssh_password', sshPassword);
297
+ push('ssh_private_key', sshPrivateKey);
298
+ push('ssh_passphrase', sshPassphrase);
212
299
  }
213
300
 
214
301
  push('updated_at', new Date().toISOString());
@@ -220,15 +307,34 @@ export const dbClientConnectionQueries = {
220
307
  values.push(id);
221
308
  db.prepare(`UPDATE db_client_connections SET ${sets.join(', ')} WHERE id = ?`).run(...values);
222
309
 
223
- const row = db.prepare('SELECT * FROM db_client_connections WHERE id = ?').get(id) as DBDbClientConnectionRow;
310
+ const row = getRowById(id);
311
+ if (!row) {
312
+ throw new Error('db-client connection not found');
313
+ }
224
314
  return rowToConnection(row);
225
315
  },
226
316
 
317
+ updateForUser(
318
+ id: string,
319
+ patch: Partial<DbClientConnectionInput>,
320
+ userId: string,
321
+ isAdmin: boolean
322
+ ): DbClientConnection {
323
+ this.ensureAccess(id, userId, isAdmin);
324
+ const updated = this.update(id, patch);
325
+ return redactConnectionSecrets(updated);
326
+ },
327
+
227
328
  delete(id: string): void {
228
329
  const db = getDatabase();
229
330
  db.prepare('DELETE FROM db_client_connections WHERE id = ?').run(id);
230
331
  },
231
332
 
333
+ deleteForUser(id: string, userId: string, isAdmin: boolean): void {
334
+ this.ensureAccess(id, userId, isAdmin);
335
+ this.delete(id);
336
+ },
337
+
232
338
  markUsed(id: string): void {
233
339
  const db = getDatabase();
234
340
  const now = new Date().toISOString();