@myrialabs/clopen 0.4.17 → 0.4.18

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 (89) hide show
  1. package/README.md +3 -3
  2. package/backend/auth/auth-service.ts +265 -13
  3. package/backend/auth/permissions.ts +3 -0
  4. package/backend/auth/rate-limiter.ts +1 -0
  5. package/backend/auth/session-cleanup.ts +5 -0
  6. package/backend/auth/tokens.ts +8 -1
  7. package/backend/chat/stream-manager.ts +8 -0
  8. package/backend/database/migrations/060_create_device_codes_table.ts +38 -0
  9. package/backend/database/migrations/061_add_session_device_metadata.ts +42 -0
  10. package/backend/database/migrations/062_add_session_source.ts +43 -0
  11. package/backend/database/migrations/063_add_invite_project_ids.ts +42 -0
  12. package/backend/database/migrations/064_create_messages_fts.ts +71 -0
  13. package/backend/database/migrations/index.ts +35 -0
  14. package/backend/database/queries/auth-queries.ts +100 -6
  15. package/backend/database/queries/message-queries.ts +44 -0
  16. package/backend/database/queries/session-queries.ts +117 -12
  17. package/backend/engine/README.md +21 -4
  18. package/backend/engine/adapters/claude/stream.ts +4 -2
  19. package/backend/engine/adapters/cline/agent-tool.ts +3 -2
  20. package/backend/engine/adapters/cline/ask-question-tool.ts +3 -2
  21. package/backend/engine/adapters/cline/credential.ts +2 -1
  22. package/backend/engine/adapters/cline/mcp-tools.ts +2 -1
  23. package/backend/engine/adapters/cline/models.ts +3 -1
  24. package/backend/engine/adapters/cline/presets.ts +5 -3
  25. package/backend/engine/adapters/cline/stream.ts +10 -7
  26. package/backend/engine/adapters/codex/stream.ts +3 -1
  27. package/backend/engine/adapters/copilot/stream.ts +8 -1
  28. package/backend/engine/adapters/cursor/environment.ts +4 -2
  29. package/backend/engine/adapters/cursor/models.ts +2 -1
  30. package/backend/engine/adapters/cursor/stream.ts +5 -3
  31. package/backend/engine/adapters/pi/presets.ts +3 -1
  32. package/backend/engine/adapters/pi/session-fork.ts +3 -1
  33. package/backend/engine/adapters/pi/stream.ts +11 -8
  34. package/backend/engine/bootstrap-default-engine.ts +69 -0
  35. package/backend/engine/docs/adding-an-engine.md +29 -6
  36. package/backend/engine/docs/frontend-and-chat.md +21 -5
  37. package/backend/engine/docs/lessons-learned.md +41 -0
  38. package/backend/engine/docs/quick-reference.md +3 -2
  39. package/backend/engine/docs/system-tools.md +65 -9
  40. package/backend/engine/docs/websocket-routes.md +4 -3
  41. package/backend/engine/engine-setup.ts +72 -0
  42. package/backend/engine/install-recipes.ts +82 -77
  43. package/backend/engine/install-runner.ts +27 -2
  44. package/backend/engine/sdk-loader.ts +180 -0
  45. package/backend/engine/version-check.ts +6 -6
  46. package/backend/http/files-upload.test.ts +4 -1
  47. package/backend/index.ts +32 -2
  48. package/backend/mcp/README.md +26 -8
  49. package/backend/mcp/index.ts +2 -2
  50. package/backend/mcp/internal/config.ts +54 -63
  51. package/backend/mcp/internal/remote-server.test.ts +4 -1
  52. package/backend/mcp/internal/servers/helper.ts +4 -34
  53. package/backend/mcp/internal/servers/index.ts +4 -13
  54. package/backend/tunnel/public-origin.ts +118 -0
  55. package/backend/utils/ws.ts +126 -1
  56. package/backend/ws/auth/device.ts +239 -0
  57. package/backend/ws/auth/index.ts +8 -0
  58. package/backend/ws/auth/invites.ts +16 -6
  59. package/backend/ws/auth/login.test.ts +2 -2
  60. package/backend/ws/auth/login.ts +12 -6
  61. package/backend/ws/engine/claude/status.ts +4 -4
  62. package/backend/ws/engine/cline/accounts.ts +3 -2
  63. package/backend/ws/engine/cline/status.ts +4 -12
  64. package/backend/ws/engine/codex/status.ts +4 -12
  65. package/backend/ws/engine/copilot/status.ts +5 -12
  66. package/backend/ws/engine/cursor/accounts.ts +2 -1
  67. package/backend/ws/engine/cursor/status.ts +5 -12
  68. package/backend/ws/engine/opencode/status.ts +4 -4
  69. package/backend/ws/engine/pi/status.ts +4 -12
  70. package/backend/ws/engine/qwen/status.ts +5 -12
  71. package/backend/ws/sessions/crud.ts +29 -4
  72. package/backend/ws/settings/crud.ts +10 -1
  73. package/backend/ws/system/operations.ts +34 -18
  74. package/backend/ws/system-tools/install.ts +3 -0
  75. package/backend/ws/system-tools/status.ts +7 -2
  76. package/backend/ws/tunnel/index.ts +3 -1
  77. package/backend/ws/tunnel/share.ts +27 -0
  78. package/bin/clopen.ts +1 -1
  79. package/dist/assets/{index-kME3THy5.js → index-Cz8HVhsm.js} +1 -1
  80. package/dist/assets/{index-Bu5loFQE.js → index-SI4Gcd0p.js} +1 -1
  81. package/dist/assets/main-Cry3pLcl.css +1 -0
  82. package/dist/assets/{main-HirJLquI.js → main-Dlba-fXF.js} +337 -330
  83. package/dist/index.html +2 -2
  84. package/package.json +15 -14
  85. package/shared/constants/engines.ts +39 -40
  86. package/shared/constants/tool-icons.ts +49 -0
  87. package/shared/types/stores/settings.ts +9 -0
  88. package/shared/utils/logger.ts +1 -0
  89. package/dist/assets/main-D7ATW8pp.css +0 -1
@@ -0,0 +1,42 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add project_ids to invite_tokens for pre-assigning project access at invite time';
5
+
6
+ /**
7
+ * Lets an admin pick which projects a new member should get *when generating the
8
+ * invite*, so access is already set the moment they join — no separate trip to
9
+ * the member's project settings. Stored as a JSON array of project ids; null /
10
+ * empty means "no projects pre-assigned".
11
+ */
12
+ export const up = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Adding project_ids column to invite_tokens...');
14
+ db.exec(`ALTER TABLE invite_tokens ADD COLUMN project_ids TEXT`);
15
+ debug.log('migration', 'invite_tokens project_ids column added');
16
+ };
17
+
18
+ export const down = (db: DatabaseConnection): void => {
19
+ debug.log('migration', 'Removing project_ids column from invite_tokens...');
20
+ // SQLite pre-3.35 can't DROP COLUMN; recreate without it.
21
+ db.exec(`
22
+ CREATE TABLE invite_tokens_new (
23
+ id TEXT PRIMARY KEY,
24
+ token_hash TEXT NOT NULL UNIQUE,
25
+ role TEXT NOT NULL CHECK(role IN ('admin', 'member')),
26
+ label TEXT,
27
+ created_by TEXT NOT NULL,
28
+ max_uses INTEGER NOT NULL DEFAULT 1,
29
+ use_count INTEGER NOT NULL DEFAULT 0,
30
+ expires_at TEXT,
31
+ created_at TEXT NOT NULL,
32
+ FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE CASCADE
33
+ )
34
+ `);
35
+ db.exec(`
36
+ INSERT INTO invite_tokens_new (id, token_hash, role, label, created_by, max_uses, use_count, expires_at, created_at)
37
+ SELECT id, token_hash, role, label, created_by, max_uses, use_count, expires_at, created_at FROM invite_tokens
38
+ `);
39
+ db.exec(`DROP TABLE invite_tokens`);
40
+ db.exec(`ALTER TABLE invite_tokens_new RENAME TO invite_tokens`);
41
+ debug.log('migration', 'invite_tokens project_ids column removed');
42
+ };
@@ -0,0 +1,71 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create messages_fts (FTS5) index for fast global session content search with snippets';
5
+
6
+ /**
7
+ * Minimal inline text extraction, mirroring extractMessageText from
8
+ * backend/snapshot/helpers.ts. Duplicated (not imported) so this migration
9
+ * stays runnable standalone and isn't coupled to app code that may change
10
+ * later — the same convention 029_migrate_messages_to_unified.ts uses.
11
+ */
12
+ function extractSearchableText(msg: Record<string, unknown>): string {
13
+ if (msg.type === 'reasoning') return (msg.text as string) || '';
14
+ if (msg.type === 'compact_boundary') return '';
15
+ const content = msg.content;
16
+ if (!Array.isArray(content)) return '';
17
+ return (content as Record<string, unknown>[])
18
+ .filter(b => b.type === 'text' && b.text)
19
+ .map(b => b.text as string)
20
+ .join('\n');
21
+ }
22
+
23
+ export const up = (db: DatabaseConnection): void => {
24
+ debug.log('migration', 'Creating messages_fts virtual table...');
25
+
26
+ // project_id/session_id are UNINDEXED (used only to filter/join) — only
27
+ // `text` participates in the FTS index. Kept as our own standalone table
28
+ // (not `content=messages`) since indexed text is derived from JSON, not a
29
+ // plain column.
30
+ db.exec(`
31
+ CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
32
+ message_id UNINDEXED,
33
+ session_id UNINDEXED,
34
+ project_id UNINDEXED,
35
+ text
36
+ )
37
+ `);
38
+
39
+ debug.log('migration', 'Backfilling messages_fts from existing messages...');
40
+
41
+ const rows = db.prepare(`
42
+ SELECT m.id, m.session_id, m.data, cs.project_id
43
+ FROM messages m
44
+ INNER JOIN chat_sessions cs ON cs.id = m.session_id
45
+ `).all() as { id: string; session_id: string; data: string; project_id: string }[];
46
+
47
+ const insert = db.prepare(`
48
+ INSERT INTO messages_fts (message_id, session_id, project_id, text)
49
+ VALUES (?, ?, ?, ?)
50
+ `);
51
+
52
+ let indexed = 0;
53
+ for (const row of rows) {
54
+ try {
55
+ const msg = JSON.parse(row.data) as Record<string, unknown>;
56
+ const text = extractSearchableText(msg).trim();
57
+ if (!text) continue;
58
+ insert.run(row.id, row.session_id, row.project_id, text);
59
+ indexed++;
60
+ } catch {
61
+ // Skip unparsable rows — same tolerance as other backfills in this file set.
62
+ }
63
+ }
64
+
65
+ debug.log('migration', `messages_fts backfilled: ${indexed}/${rows.length} messages indexed`);
66
+ };
67
+
68
+ export const down = (db: DatabaseConnection): void => {
69
+ debug.log('migration', 'Dropping messages_fts virtual table...');
70
+ db.exec(`DROP TABLE IF EXISTS messages_fts`);
71
+ };
@@ -58,6 +58,11 @@ import * as migration056 from './056_support_mssql_driver';
58
58
  import * as migration057 from './057_seed_pi_provider';
59
59
  import * as migration058 from './058_seed_cline_provider';
60
60
  import * as migration059 from './059_seed_cursor_provider';
61
+ import * as migration060 from './060_create_device_codes_table';
62
+ import * as migration061 from './061_add_session_device_metadata';
63
+ import * as migration062 from './062_add_session_source';
64
+ import * as migration063 from './063_add_invite_project_ids';
65
+ import * as migration064 from './064_create_messages_fts';
61
66
 
62
67
  // Export all migrations in order
63
68
  export const migrations = [
@@ -414,6 +419,36 @@ export const migrations = [
414
419
  description: migration059.description,
415
420
  up: migration059.up,
416
421
  down: migration059.down
422
+ },
423
+ {
424
+ id: '060',
425
+ description: migration060.description,
426
+ up: migration060.up,
427
+ down: migration060.down
428
+ },
429
+ {
430
+ id: '061',
431
+ description: migration061.description,
432
+ up: migration061.up,
433
+ down: migration061.down
434
+ },
435
+ {
436
+ id: '062',
437
+ description: migration062.description,
438
+ up: migration062.up,
439
+ down: migration062.down
440
+ },
441
+ {
442
+ id: '063',
443
+ description: migration063.description,
444
+ up: migration063.up,
445
+ down: migration063.down
446
+ },
447
+ {
448
+ id: '064',
449
+ description: migration064.description,
450
+ up: migration064.up,
451
+ down: migration064.down
417
452
  }
418
453
  ];
419
454
 
@@ -18,6 +18,10 @@ export interface DBAuthSession {
18
18
  expires_at: string;
19
19
  created_at: string;
20
20
  last_active_at: string;
21
+ user_agent: string | null;
22
+ ip_address: string | null;
23
+ /** How the session was created: 'setup' | 'invite' | 'device-link' | 'login' | 'pat' | 'no-auth'. */
24
+ source: string | null;
21
25
  }
22
26
 
23
27
  export interface DBInviteToken {
@@ -30,6 +34,18 @@ export interface DBInviteToken {
30
34
  use_count: number;
31
35
  expires_at: string | null;
32
36
  created_at: string;
37
+ /** JSON array of project ids to grant the new member on join (null = none). */
38
+ project_ids: string | null;
39
+ }
40
+
41
+ export interface DBDeviceCode {
42
+ id: string;
43
+ code_hash: string;
44
+ user_id: string;
45
+ label: string | null;
46
+ expires_at: string;
47
+ claimed_at: string | null;
48
+ created_at: string;
33
49
  }
34
50
 
35
51
  export const authQueries = {
@@ -106,15 +122,18 @@ export const authQueries = {
106
122
  createSession(session: DBAuthSession): DBAuthSession {
107
123
  const db = getDatabase();
108
124
  db.prepare(`
109
- INSERT INTO auth_sessions (id, user_id, token_hash, expires_at, created_at, last_active_at)
110
- VALUES (?, ?, ?, ?, ?, ?)
125
+ INSERT INTO auth_sessions (id, user_id, token_hash, expires_at, created_at, last_active_at, user_agent, ip_address, source)
126
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
111
127
  `).run(
112
128
  session.id,
113
129
  session.user_id,
114
130
  session.token_hash,
115
131
  session.expires_at,
116
132
  session.created_at,
117
- session.last_active_at
133
+ session.last_active_at,
134
+ session.user_agent,
135
+ session.ip_address,
136
+ session.source
118
137
  );
119
138
  return db.prepare('SELECT * FROM auth_sessions WHERE id = ?').get(session.id) as DBAuthSession;
120
139
  },
@@ -124,6 +143,22 @@ export const authQueries = {
124
143
  return db.prepare('SELECT * FROM auth_sessions WHERE token_hash = ?').get(hash) as DBAuthSession | null;
125
144
  },
126
145
 
146
+ getSessionsByUserId(userId: string): DBAuthSession[] {
147
+ const db = getDatabase();
148
+ return db.prepare('SELECT * FROM auth_sessions WHERE user_id = ? ORDER BY last_active_at DESC').all(userId) as DBAuthSession[];
149
+ },
150
+
151
+ /** All sessions across every user (admin "Connected devices" view). */
152
+ getAllSessions(): DBAuthSession[] {
153
+ const db = getDatabase();
154
+ return db.prepare('SELECT * FROM auth_sessions ORDER BY last_active_at DESC').all() as DBAuthSession[];
155
+ },
156
+
157
+ getSessionById(id: string): DBAuthSession | null {
158
+ const db = getDatabase();
159
+ return db.prepare('SELECT * FROM auth_sessions WHERE id = ?').get(id) as DBAuthSession | null;
160
+ },
161
+
127
162
  updateLastActive(id: string): void {
128
163
  const db = getDatabase();
129
164
  const now = new Date().toISOString();
@@ -157,8 +192,8 @@ export const authQueries = {
157
192
  createInvite(invite: DBInviteToken): DBInviteToken {
158
193
  const db = getDatabase();
159
194
  db.prepare(`
160
- INSERT INTO invite_tokens (id, token_hash, role, label, created_by, max_uses, use_count, expires_at, created_at)
161
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
195
+ INSERT INTO invite_tokens (id, token_hash, role, label, created_by, max_uses, use_count, expires_at, created_at, project_ids)
196
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
162
197
  `).run(
163
198
  invite.id,
164
199
  invite.token_hash,
@@ -168,7 +203,8 @@ export const authQueries = {
168
203
  invite.max_uses,
169
204
  invite.use_count,
170
205
  invite.expires_at,
171
- invite.created_at
206
+ invite.created_at,
207
+ invite.project_ids
172
208
  );
173
209
  return db.prepare('SELECT * FROM invite_tokens WHERE id = ?').get(invite.id) as DBInviteToken;
174
210
  },
@@ -197,5 +233,63 @@ export const authQueries = {
197
233
  const db = getDatabase();
198
234
  const result = db.prepare('DELETE FROM auth_sessions').run() as { changes: number };
199
235
  return result.changes;
236
+ },
237
+
238
+ // ===================== Device Codes =====================
239
+
240
+ createDeviceCode(code: DBDeviceCode): DBDeviceCode {
241
+ const db = getDatabase();
242
+ db.prepare(`
243
+ INSERT INTO device_codes (id, code_hash, user_id, label, expires_at, claimed_at, created_at)
244
+ VALUES (?, ?, ?, ?, ?, ?, ?)
245
+ `).run(
246
+ code.id,
247
+ code.code_hash,
248
+ code.user_id,
249
+ code.label,
250
+ code.expires_at,
251
+ code.claimed_at,
252
+ code.created_at
253
+ );
254
+ return db.prepare('SELECT * FROM device_codes WHERE id = ?').get(code.id) as DBDeviceCode;
255
+ },
256
+
257
+ getDeviceCodeByHash(hash: string): DBDeviceCode | null {
258
+ const db = getDatabase();
259
+ return db.prepare('SELECT * FROM device_codes WHERE code_hash = ?').get(hash) as DBDeviceCode | null;
260
+ },
261
+
262
+ /** Mark a device code as claimed. Returns rows changed — used to guarantee single-use under races. */
263
+ markDeviceCodeClaimed(id: string, claimedAt: string): number {
264
+ const db = getDatabase();
265
+ const result = db.prepare(
266
+ 'UPDATE device_codes SET claimed_at = ? WHERE id = ? AND claimed_at IS NULL'
267
+ ).run(claimedAt, id) as { changes: number };
268
+ return result.changes;
269
+ },
270
+
271
+ deleteDeviceCode(id: string): void {
272
+ const db = getDatabase();
273
+ db.prepare('DELETE FROM device_codes WHERE id = ?').run(id);
274
+ },
275
+
276
+ /** Count a user's pending (unclaimed, unexpired) device codes. */
277
+ countPendingDeviceCodes(userId: string): number {
278
+ const db = getDatabase();
279
+ const now = new Date().toISOString();
280
+ const result = db.prepare(
281
+ 'SELECT COUNT(*) as count FROM device_codes WHERE user_id = ? AND claimed_at IS NULL AND expires_at > ?'
282
+ ).get(userId, now) as { count: number };
283
+ return result.count;
284
+ },
285
+
286
+ /** Remove expired or already-claimed device codes. */
287
+ deleteStaleDeviceCodes(): number {
288
+ const db = getDatabase();
289
+ const now = new Date().toISOString();
290
+ const result = db.prepare(
291
+ 'DELETE FROM device_codes WHERE expires_at < ? OR claimed_at IS NOT NULL'
292
+ ).run(now) as { changes: number };
293
+ return result.changes;
200
294
  }
201
295
  };
@@ -9,6 +9,37 @@ function parseMessage(row: DatabaseMessage): UnifiedMessage {
9
9
  return JSON.parse(row.data) as UnifiedMessage;
10
10
  }
11
11
 
12
+ /**
13
+ * Extract combined plain text from a message for the messages_fts index.
14
+ * Kept local (not imported from snapshot/helpers.ts) to avoid a circular
15
+ * import — helpers.ts imports messageQueries from this module's barrel.
16
+ */
17
+ function extractSearchableText(msg: UnifiedMessage): string {
18
+ if (msg.type === 'reasoning') return msg.text;
19
+ if (msg.type === 'compact_boundary') return '';
20
+ return msg.content
21
+ .filter((block): block is { type: 'text'; text: string } => block.type === 'text' && !!block.text)
22
+ .map(block => block.text)
23
+ .join('\n');
24
+ }
25
+
26
+ /** Keep the messages_fts mirror in sync with a message's current text content. */
27
+ function syncMessageFts(id: string, sessionId: string, msg: UnifiedMessage): void {
28
+ const db = getDatabase();
29
+ db.prepare('DELETE FROM messages_fts WHERE message_id = ?').run(id);
30
+
31
+ const text = extractSearchableText(msg).trim();
32
+ if (!text) return;
33
+
34
+ const session = db.prepare('SELECT project_id FROM chat_sessions WHERE id = ?').get(sessionId) as { project_id: string } | null;
35
+ if (!session) return;
36
+
37
+ db.prepare(`
38
+ INSERT INTO messages_fts (message_id, session_id, project_id, text)
39
+ VALUES (?, ?, ?, ?)
40
+ `).run(id, sessionId, session.project_id, text);
41
+ }
42
+
12
43
  export const messageQueries = {
13
44
  /**
14
45
  * Get visible messages for a session (git-like: from HEAD to root)
@@ -131,6 +162,8 @@ export const messageQueries = {
131
162
  parentMessageId
132
163
  );
133
164
 
165
+ syncMessageFts(id, messageData.session_id, msg);
166
+
134
167
  return {
135
168
  id,
136
169
  session_id: messageData.session_id,
@@ -145,19 +178,30 @@ export const messageQueries = {
145
178
  delete(id: string): void {
146
179
  const db = getDatabase();
147
180
  db.prepare('DELETE FROM messages WHERE id = ?').run(id);
181
+ db.prepare('DELETE FROM messages_fts WHERE message_id = ?').run(id);
148
182
  },
149
183
 
150
184
  deleteBySessionId(sessionId: string): void {
151
185
  const db = getDatabase();
152
186
  db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId);
187
+ db.prepare('DELETE FROM messages_fts WHERE session_id = ?').run(sessionId);
153
188
  },
154
189
 
155
190
  deleteAfterTimestamp(sessionId: string, timestamp: string): void {
156
191
  const db = getDatabase();
192
+ const ids = db.prepare(`
193
+ SELECT id FROM messages WHERE session_id = ? AND created_at >= ?
194
+ `).all(sessionId, timestamp) as { id: string }[];
195
+
157
196
  db.prepare(`
158
197
  DELETE FROM messages
159
198
  WHERE session_id = ? AND created_at >= ?
160
199
  `).run(sessionId, timestamp);
200
+
201
+ if (ids.length > 0) {
202
+ const placeholders = ids.map(() => '?').join(',');
203
+ db.prepare(`DELETE FROM messages_fts WHERE message_id IN (${placeholders})`).run(...ids.map(r => r.id));
204
+ }
161
205
  },
162
206
 
163
207
  /**
@@ -2,6 +2,13 @@ import { getDatabase } from '../index';
2
2
  import type { ChatSession, Branch, DatabaseMessage } from '$shared/types/database/schema';
3
3
  import { loadMessage } from '$shared/utils/message-formatter';
4
4
  import { extractMessageText } from '../../snapshot/helpers';
5
+ import { debug } from '$shared/utils/logger';
6
+
7
+ /** ChatSession plus an optional FTS snippet, set only for message-content matches. */
8
+ export interface SessionSearchResult extends ChatSession {
9
+ /** Snippet with char(1)/char(2) markers wrapping the matched text. */
10
+ matchSnippet?: string;
11
+ }
5
12
 
6
13
  export const sessionQueries = {
7
14
  getAll(): ChatSession[] {
@@ -233,20 +240,116 @@ export const sessionQueries = {
233
240
  },
234
241
 
235
242
  /**
236
- * Search sessions by message content.
237
- * Returns session IDs that have matching messages.
243
+ * Search sessions by message content within a single project, via the
244
+ * messages_fts index (fast index lookup, not a raw LIKE table scan).
245
+ * Returns one result per matching session with a highlighted snippet
246
+ * showing where the match occurred, ordered by relevance. Backs the
247
+ * History/Sessions modal's deep search.
248
+ */
249
+ searchByMessageContent(projectId: string, query: string, limit: number = 20): { sessionId: string; snippet: string }[] {
250
+ const db = getDatabase();
251
+ const ftsQuery = this.buildFtsQuery(query);
252
+ if (!ftsQuery) return [];
253
+
254
+ try {
255
+ const rows = db.prepare(`
256
+ SELECT fts.session_id AS session_id,
257
+ snippet(messages_fts, 3, char(1), char(2), '…', 12) AS snippet
258
+ FROM messages_fts fts
259
+ WHERE fts.project_id = ? AND fts.text MATCH ?
260
+ ORDER BY rank
261
+ LIMIT ?
262
+ `).all(projectId, ftsQuery, limit * 3) as { session_id: string; snippet: string }[];
263
+
264
+ // Keep only the best (first, since ordered by rank) match per session.
265
+ const seen = new Set<string>();
266
+ const results: { sessionId: string; snippet: string }[] = [];
267
+ for (const row of rows) {
268
+ if (seen.has(row.session_id)) continue;
269
+ seen.add(row.session_id);
270
+ results.push({ sessionId: row.session_id, snippet: row.snippet });
271
+ if (results.length >= limit) break;
272
+ }
273
+ return results;
274
+ } catch (err) {
275
+ debug.warn('database', 'FTS content search failed for project scope:', err);
276
+ return [];
277
+ }
278
+ },
279
+
280
+ /**
281
+ * Turn free-typed text into a safe FTS5 MATCH query: strip everything but
282
+ * letters/digits per word and treat each as a quoted prefix term (implicit
283
+ * AND between terms). Avoids FTS5 syntax injection from raw user input and
284
+ * gives "type as you go" prefix matching.
285
+ */
286
+ buildFtsQuery(raw: string): string | null {
287
+ const terms = raw
288
+ .split(/\s+/)
289
+ .map(t => t.replace(/[^\p{L}\p{N}]/gu, ''))
290
+ .filter(t => t.length > 0);
291
+ if (terms.length === 0) return null;
292
+ return terms.map(t => `"${t}"*`).join(' ');
293
+ },
294
+
295
+ /**
296
+ * Search sessions across every project the user has access to.
297
+ * Two passes, merged: cheap metadata match (title/head_title/head_summary)
298
+ * plus an FTS5 index lookup over message content — the latter also returns
299
+ * a highlighted snippet (wrapped in ... markers) showing where
300
+ * the match occurred. Backs the global Command Palette session search.
238
301
  */
239
- searchByMessageContent(projectId: string, query: string, limit: number = 20): string[] {
240
- const db = getDatabase();
241
- const rows = db.prepare(`
242
- SELECT DISTINCT m.session_id
243
- FROM messages m
244
- INNER JOIN chat_sessions cs ON cs.id = m.session_id
245
- WHERE cs.project_id = ?
246
- AND m.data LIKE ?
302
+ searchGlobal(userId: string, query: string, limit: number = 20): SessionSearchResult[] {
303
+ const db = getDatabase();
304
+ const trimmed = query.trim();
305
+ if (!trimmed) return [];
306
+
307
+ const results = new Map<string, SessionSearchResult>();
308
+
309
+ // Pass 1: metadata match — cheap, exact substring, no snippet needed.
310
+ const like = `%${trimmed}%`;
311
+ const metaRows = db.prepare(`
312
+ SELECT * FROM chat_sessions cs
313
+ WHERE cs.project_id IN (SELECT project_id FROM user_projects WHERE user_id = ?)
314
+ AND (cs.title LIKE ? OR cs.head_title LIKE ? OR cs.head_summary LIKE ?)
315
+ ORDER BY COALESCE(cs.last_message_at, cs.started_at) DESC
247
316
  LIMIT ?
248
- `).all(projectId, `%${query}%`, limit) as { session_id: string }[];
249
- return rows.map(r => r.session_id);
317
+ `).all(userId, like, like, like, limit) as ChatSession[];
318
+ for (const row of metaRows) {
319
+ results.set(row.id, row);
320
+ }
321
+
322
+ // Pass 2: message content match via FTS5 — fast index lookup with snippet.
323
+ const ftsQuery = this.buildFtsQuery(trimmed);
324
+ if (ftsQuery) {
325
+ try {
326
+ const contentRows = db.prepare(`
327
+ SELECT cs.*, snippet(messages_fts, 3, char(1), char(2), '…', 12) AS match_snippet
328
+ FROM messages_fts fts
329
+ INNER JOIN chat_sessions cs ON cs.id = fts.session_id
330
+ WHERE fts.project_id IN (SELECT project_id FROM user_projects WHERE user_id = ?)
331
+ AND fts.text MATCH ?
332
+ ORDER BY rank
333
+ LIMIT ?
334
+ `).all(userId, ftsQuery, limit * 2) as (ChatSession & { match_snippet: string })[];
335
+
336
+ for (const row of contentRows) {
337
+ if (results.has(row.id)) continue;
338
+ const { match_snippet, ...session } = row;
339
+ results.set(row.id, { ...session, matchSnippet: match_snippet });
340
+ }
341
+ } catch (err) {
342
+ debug.warn('database', 'FTS content search failed, falling back to metadata-only results:', err);
343
+ }
344
+ }
345
+
346
+ return Array.from(results.values())
347
+ .sort((a, b) => {
348
+ const aTime = a.last_message_at || a.started_at;
349
+ const bTime = b.last_message_at || b.started_at;
350
+ return new Date(bTime).getTime() - new Date(aTime).getTime();
351
+ })
352
+ .slice(0, limit);
250
353
  },
251
354
 
252
355
  end(id: string): void {
@@ -286,6 +389,7 @@ export const sessionQueries = {
286
389
  db.prepare('DELETE FROM message_snapshots WHERE session_id = ?').run(id);
287
390
  db.prepare('DELETE FROM session_relationships WHERE parent_session_id = ? OR child_session_id = ?').run(id, id);
288
391
  db.prepare('DELETE FROM messages WHERE session_id = ?').run(id);
392
+ db.prepare('DELETE FROM messages_fts WHERE session_id = ?').run(id);
289
393
  db.prepare('DELETE FROM user_unread_sessions WHERE session_id = ?').run(id);
290
394
  // Clear current_session_id references in user_projects
291
395
  db.prepare('UPDATE user_projects SET current_session_id = NULL WHERE current_session_id = ?').run(id);
@@ -313,6 +417,7 @@ export const sessionQueries = {
313
417
  OR child_session_id IN (SELECT id FROM chat_sessions WHERE project_id = ?)
314
418
  `).run(projectId, projectId);
315
419
  db.prepare('DELETE FROM messages WHERE session_id IN (SELECT id FROM chat_sessions WHERE project_id = ?)').run(projectId);
420
+ db.prepare('DELETE FROM messages_fts WHERE project_id = ?').run(projectId);
316
421
  db.prepare('DELETE FROM user_unread_sessions WHERE project_id = ?').run(projectId);
317
422
  // Clear current_session_id references in user_projects for this project
318
423
  db.prepare('UPDATE user_projects SET current_session_id = NULL WHERE project_id = ?').run(projectId);
@@ -11,6 +11,22 @@ adapter follows the same shape so that the rest of the system outside this
11
11
  folder — `stream-manager`, MCP, DB, WebSocket, frontend chat, settings UI —
12
12
  stays **agnostic** to the underlying SDK.
13
13
 
14
+ > **Engine SDKs are NOT bundled — they install on demand.** None of the SDK
15
+ > packages above ship in the clopen global install (they moved to
16
+ > `devDependencies` in `package.json`, which is the single source of truth for
17
+ > each engine's exact pinned version). At runtime clopen installs them on
18
+ > demand into a clopen-managed directory — `~/.clopen/stack/engines`
19
+ > (`getStackEnginesDir()`) — and every adapter **lazy-loads** its SDK via
20
+ > `loadEngineSdk(engine, pkg)` from [`sdk-loader.ts`](./sdk-loader.ts) (keep
21
+ > all type references on `import type` so they erase at runtime). The loader
22
+ > refuses to load an SDK whose installed version ≠ the pinned version, throwing
23
+ > `EngineNotReadyError` (`reason: 'not-installed' | 'needs-update'`) — the
24
+ > engine must first be installed/updated in **Settings → Stack**. This is
25
+ > what fixed `bun add -g @myrialabs/clopen` aborting mid-install (it used to
26
+ > drag 200–300 MB of native CLI binaries). Future Stack work (runtimes,
27
+ > services, per-project versioning) is specced in
28
+ > [`docs/stack-roadmap.md`](../../docs/stack-roadmap.md).
29
+
14
30
  > **In-process, session-less SDKs are their own category.** Most adapters
15
31
  > wrap a CLI subprocess or an SDK that owns a session store (on disk or via a
16
32
  > server). `cline` is different: `@cline/sdk`'s stateless `Agent` holds **no**
@@ -39,8 +55,8 @@ map, then jump to the area you need.
39
55
  2. [Adapter contract](./docs/adapter-contract.md) — the `AIEngine` interface, `EngineOutput`, `EngineQueryOptions`, the standard adapter file taxonomy, and what an adapter must NOT do.
40
56
  3. [Database](./docs/database.md) — `engine_providers` + `engine_accounts`, `engineQueries`, and how each adapter reads credentials.
41
57
  4. [WebSocket routes](./docs/websocket-routes.md) — `engine:*`, `system-tools:*`, `models:list`, `chat:stream`, and the Restart-Server pattern.
42
- 5. [Frontend & chat integration](./docs/frontend-and-chat.md) — Settings → Engines / System Tools, the model picker, the send path, reasoning/attachments/AskUserQuestion.
43
- 6. [System Tools](./docs/system-tools.md) — registering a binary in `install-recipes.ts` + the install runner.
58
+ 5. [Frontend & chat integration](./docs/frontend-and-chat.md) — Settings → Engines / Stack, the model picker, the send path, reasoning/attachments/AskUserQuestion.
59
+ 6. [Stack](./docs/system-tools.md) — registering a host tool or on-demand engine SDK in `install-recipes.ts` + the install runner.
44
60
  7. [Artifacts & Access](./docs/artifacts.md) — the extension layer (Skills, Commands, Subagents, Instructions, Permissions, Profiles, MCP), the capability matrix, and the `artifact-sync.ts` seam adapters call at stream start.
45
61
  8. [Adding a new engine](./docs/adding-an-engine.md) — the end-to-end, stage-by-stage checklist.
46
62
  9. [Lessons learned](./docs/lessons-learned.md) — §10 pitfalls (tool name/input canonicalisation, fork session, MCP reuse, auth-blob swap, sub-agent routing, OpenCode v1/v2, structured output, …).
@@ -53,7 +69,7 @@ map, then jump to the area you need.
53
69
  ```
54
70
  ┌──────────────────── FRONTEND (Svelte 5 + runes) ─────────────────────┐
55
71
  │ │
56
- │ Settings → Engines Settings → System Tools Chat Input │
72
+ │ Settings → Engines Settings → Stack Chat Input │
57
73
  │ ───────────────────── ────────────────────── ────────────── │
58
74
  │ AIEnginesSettings+panels/ SystemToolsSettings… EngineModel… │
59
75
  │ │ │ │ │
@@ -82,7 +98,8 @@ map, then jump to the area you need.
82
98
  │ │ ────────────────── │ │
83
99
  │ │ index.ts registry: getEngine / getProjectEngine│ │
84
100
  │ │ types.ts contract: AIEngine │ │
85
- │ │ install-recipes.ts per-platform install commands │ │
101
+ │ │ sdk-loader.ts on-demand loader (~/.clopen/stack/…) │ │
102
+ │ │ install-recipes.ts host-tool + engine-SDK install recipes│ │
86
103
  │ │ install-runner.ts spawns recipe, streams logs over WS │ │
87
104
  │ │ adapters/<name>/ │ │
88
105
  │ │ index.ts public surface (re-exports only) │ │
@@ -13,7 +13,7 @@
13
13
  * When v2 SDKSessionOptions gains these, migrate streamQuery() to v2.
14
14
  */
15
15
 
16
- import { query } from '@anthropic-ai/claude-agent-sdk';
16
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
17
17
  import type {
18
18
  Options,
19
19
  Query,
@@ -123,7 +123,7 @@ export class ClaudeCodeEngine implements AIEngine {
123
123
 
124
124
  // Get custom MCP servers and allowed tools
125
125
  // Pass mcpContext so tool handlers are bound to the correct project
126
- const mcpServers = getEnabledMcpServers(options.mcpContext, mcpProfileFilter);
126
+ const mcpServers = await getEnabledMcpServers(options.mcpContext, mcpProfileFilter);
127
127
  const allowedMcpTools = getAllowedMcpTools();
128
128
 
129
129
  debug.log('mcp', '📦 Loading custom MCP servers...');
@@ -199,6 +199,7 @@ export class ClaudeCodeEngine implements AIEngine {
199
199
  yield sdkPrompt;
200
200
  })();
201
201
 
202
+ const { query } = await loadEngineSdk<typeof import('@anthropic-ai/claude-agent-sdk')>('claude-code', '@anthropic-ai/claude-agent-sdk');
202
203
  const queryInstance = query({
203
204
  prompt: promptIterable,
204
205
  options: sdkOptions,
@@ -348,6 +349,7 @@ export class ClaudeCodeEngine implements AIEngine {
348
349
  };
349
350
 
350
351
  // Use plain string prompt — simpler and faster than AsyncIterable
352
+ const { query } = await loadEngineSdk<typeof import('@anthropic-ai/claude-agent-sdk')>('claude-code', '@anthropic-ai/claude-agent-sdk');
351
353
  const queryInstance = query({
352
354
  prompt,
353
355
  options: sdkOptions
@@ -10,8 +10,8 @@
10
10
  * main UI (it runs inside the tool), but the delegation actually happens.
11
11
  */
12
12
 
13
- import { createTool } from '@cline/sdk';
14
13
  import type { AgentTool, AgentToolContext } from '@cline/sdk';
14
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
15
15
 
16
16
  export interface SubagentInfo {
17
17
  slug: string;
@@ -40,7 +40,8 @@ const AGENT_INPUT_SCHEMA = {
40
40
  required: ['subagentType', 'prompt', 'description'],
41
41
  } as const;
42
42
 
43
- export function createAgentDispatchTool(bindings: AgentDispatchBindings): AgentTool {
43
+ export async function createAgentDispatchTool(bindings: AgentDispatchBindings): Promise<AgentTool> {
44
+ const { createTool } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
44
45
  const catalog = bindings.subagents.map(s => `- ${s.slug}: ${s.name} — ${s.description}`).join('\n');
45
46
  return createTool({
46
47
  name: 'Agent',