notioncode 0.1.1 → 0.1.3

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 (77) hide show
  1. package/README.md +10 -4
  2. package/agent-runtime-server/package-lock.json +4381 -0
  3. package/agent-runtime-server/package.json +36 -0
  4. package/agent-runtime-server/scripts/fix-node-pty.js +67 -0
  5. package/agent-runtime-server/server/agent-session-service.js +816 -0
  6. package/agent-runtime-server/server/claude-sdk.js +836 -0
  7. package/agent-runtime-server/server/cli.js +330 -0
  8. package/agent-runtime-server/server/constants/config.js +5 -0
  9. package/agent-runtime-server/server/cursor-cli.js +335 -0
  10. package/agent-runtime-server/server/database/db.js +653 -0
  11. package/agent-runtime-server/server/database/init.sql +99 -0
  12. package/agent-runtime-server/server/gemini-cli.js +460 -0
  13. package/agent-runtime-server/server/gemini-response-handler.js +79 -0
  14. package/agent-runtime-server/server/index.js +2569 -0
  15. package/agent-runtime-server/server/load-env.js +32 -0
  16. package/agent-runtime-server/server/middleware/auth.js +132 -0
  17. package/agent-runtime-server/server/openai-codex.js +512 -0
  18. package/agent-runtime-server/server/projects.js +2594 -0
  19. package/agent-runtime-server/server/providers/claude/adapter.js +278 -0
  20. package/agent-runtime-server/server/providers/codex/adapter.js +248 -0
  21. package/agent-runtime-server/server/providers/cursor/adapter.js +353 -0
  22. package/agent-runtime-server/server/providers/gemini/adapter.js +186 -0
  23. package/agent-runtime-server/server/providers/registry.js +44 -0
  24. package/agent-runtime-server/server/providers/types.js +119 -0
  25. package/agent-runtime-server/server/providers/utils.js +29 -0
  26. package/agent-runtime-server/server/routes/agent-sessions.js +238 -0
  27. package/agent-runtime-server/server/routes/agent.js +1244 -0
  28. package/agent-runtime-server/server/routes/auth.js +144 -0
  29. package/agent-runtime-server/server/routes/cli-auth.js +478 -0
  30. package/agent-runtime-server/server/routes/codex.js +329 -0
  31. package/agent-runtime-server/server/routes/commands.js +596 -0
  32. package/agent-runtime-server/server/routes/cursor.js +798 -0
  33. package/agent-runtime-server/server/routes/gemini.js +24 -0
  34. package/agent-runtime-server/server/routes/git.js +1508 -0
  35. package/agent-runtime-server/server/routes/mcp-utils.js +48 -0
  36. package/agent-runtime-server/server/routes/mcp.js +552 -0
  37. package/agent-runtime-server/server/routes/messages.js +61 -0
  38. package/agent-runtime-server/server/routes/plugins.js +307 -0
  39. package/agent-runtime-server/server/routes/projects.js +548 -0
  40. package/agent-runtime-server/server/routes/settings.js +276 -0
  41. package/agent-runtime-server/server/routes/taskmaster.js +1963 -0
  42. package/agent-runtime-server/server/routes/user.js +123 -0
  43. package/agent-runtime-server/server/services/notification-orchestrator.js +227 -0
  44. package/agent-runtime-server/server/services/vapid-keys.js +35 -0
  45. package/agent-runtime-server/server/sessionManager.js +226 -0
  46. package/agent-runtime-server/server/utils/commandParser.js +303 -0
  47. package/agent-runtime-server/server/utils/frontmatter.js +18 -0
  48. package/agent-runtime-server/server/utils/gitConfig.js +34 -0
  49. package/agent-runtime-server/server/utils/mcp-detector.js +198 -0
  50. package/agent-runtime-server/server/utils/plugin-loader.js +457 -0
  51. package/agent-runtime-server/server/utils/plugin-process-manager.js +184 -0
  52. package/agent-runtime-server/server/utils/taskmaster-websocket.js +129 -0
  53. package/agent-runtime-server/shared/modelConstants.js +12 -0
  54. package/agent-runtime-server/shared/modelConstants.test.js +34 -0
  55. package/agent-runtime-server/shared/networkHosts.js +22 -0
  56. package/agent-runtime-server/test_sdk.mjs +16 -0
  57. package/bin/bridges/darwin-x64/nocode-bridge +0 -0
  58. package/bin/{nocode-local.js → notioncode.js} +0 -0
  59. package/dist/assets/icon-CQtd7WEB.png +0 -0
  60. package/dist/assets/index-Ctr1ES45.js +1 -0
  61. package/dist/assets/index-DhCWie1Z.css +1 -0
  62. package/dist/assets/index-DzqxG7Z8.js +689 -0
  63. package/dist/index.html +46 -0
  64. package/dist/onboarding/step1_create.png +0 -0
  65. package/dist/onboarding/step2_capabilities.png +0 -0
  66. package/dist/onboarding/step2b_content_access.png +0 -0
  67. package/dist/onboarding/step2c_page_access.png +0 -0
  68. package/dist/onboarding/step3_token.png +0 -0
  69. package/dist/onboarding/step4_webhook.png +0 -0
  70. package/dist/onboarding/step6a_verify.png +0 -0
  71. package/dist/onboarding/step6b_copy_verify_token.png +0 -0
  72. package/dist/tinyfish-fish-only.png +0 -0
  73. package/lib/install.js +33 -2
  74. package/lib/start.js +157 -25
  75. package/package.json +7 -4
  76. package/src/shared/modelRegistry.d.ts +24 -0
  77. package/src/shared/modelRegistry.js +163 -0
@@ -0,0 +1,653 @@
1
+ import Database from 'better-sqlite3';
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+ import crypto from 'crypto';
5
+ import { fileURLToPath } from 'url';
6
+ import { dirname } from 'path';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ // ANSI color codes for terminal output
12
+ const colors = {
13
+ reset: '\x1b[0m',
14
+ bright: '\x1b[1m',
15
+ cyan: '\x1b[36m',
16
+ dim: '\x1b[2m',
17
+ };
18
+
19
+ const c = {
20
+ info: (text) => `${colors.cyan}${text}${colors.reset}`,
21
+ bright: (text) => `${colors.bright}${text}${colors.reset}`,
22
+ dim: (text) => `${colors.dim}${text}${colors.reset}`,
23
+ };
24
+
25
+ // Use DATABASE_PATH environment variable if set, otherwise use default location
26
+ const DB_PATH = process.env.DATABASE_PATH || path.join(__dirname, 'auth.db');
27
+ const INIT_SQL_PATH = path.join(__dirname, 'init.sql');
28
+
29
+ // Ensure database directory exists if custom path is provided
30
+ if (process.env.DATABASE_PATH) {
31
+ const dbDir = path.dirname(DB_PATH);
32
+ try {
33
+ if (!fs.existsSync(dbDir)) {
34
+ fs.mkdirSync(dbDir, { recursive: true });
35
+ console.log(`Created database directory: ${dbDir}`);
36
+ }
37
+ } catch (error) {
38
+ console.error(`Failed to create database directory ${dbDir}:`, error.message);
39
+ throw error;
40
+ }
41
+ }
42
+
43
+ // As part of 1.19.2 we are introducing a new location for auth.db. The below handles exisitng moving legacy database from install directory to new location
44
+ const LEGACY_DB_PATH = path.join(__dirname, 'auth.db');
45
+ if (DB_PATH !== LEGACY_DB_PATH && !fs.existsSync(DB_PATH) && fs.existsSync(LEGACY_DB_PATH)) {
46
+ try {
47
+ fs.copyFileSync(LEGACY_DB_PATH, DB_PATH);
48
+ console.log(`[MIGRATION] Copied database from ${LEGACY_DB_PATH} to ${DB_PATH}`);
49
+ for (const suffix of ['-wal', '-shm']) {
50
+ if (fs.existsSync(LEGACY_DB_PATH + suffix)) {
51
+ fs.copyFileSync(LEGACY_DB_PATH + suffix, DB_PATH + suffix);
52
+ }
53
+ }
54
+ } catch (err) {
55
+ console.warn(`[MIGRATION] Could not copy legacy database: ${err.message}`);
56
+ }
57
+ }
58
+
59
+ // Create database connection
60
+ const db = new Database(DB_PATH);
61
+
62
+ // app_config must exist before any other module imports (auth.js reads the JWT secret at load time).
63
+ // runMigrations() also creates this table, but it runs too late for existing installations
64
+ // where auth.js is imported before initializeDatabase() is called.
65
+ db.exec(`CREATE TABLE IF NOT EXISTS app_config (
66
+ key TEXT PRIMARY KEY,
67
+ value TEXT NOT NULL,
68
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
69
+ )`);
70
+
71
+ // Show app installation path prominently
72
+ const appInstallPath = path.join(__dirname, '../..');
73
+ console.log('');
74
+ console.log(c.dim('═'.repeat(60)));
75
+ console.log(`${c.info('[INFO]')} App Installation: ${c.bright(appInstallPath)}`);
76
+ console.log(`${c.info('[INFO]')} Database: ${c.dim(path.relative(appInstallPath, DB_PATH))}`);
77
+ if (process.env.DATABASE_PATH) {
78
+ console.log(` ${c.dim('(Using custom DATABASE_PATH from environment)')}`);
79
+ }
80
+ console.log(c.dim('═'.repeat(60)));
81
+ console.log('');
82
+
83
+ const runMigrations = () => {
84
+ try {
85
+ const tableInfo = db.prepare("PRAGMA table_info(users)").all();
86
+ const columnNames = tableInfo.map(col => col.name);
87
+
88
+ if (!columnNames.includes('git_name')) {
89
+ console.log('Running migration: Adding git_name column');
90
+ db.exec('ALTER TABLE users ADD COLUMN git_name TEXT');
91
+ }
92
+
93
+ if (!columnNames.includes('git_email')) {
94
+ console.log('Running migration: Adding git_email column');
95
+ db.exec('ALTER TABLE users ADD COLUMN git_email TEXT');
96
+ }
97
+
98
+ if (!columnNames.includes('has_completed_onboarding')) {
99
+ console.log('Running migration: Adding has_completed_onboarding column');
100
+ db.exec('ALTER TABLE users ADD COLUMN has_completed_onboarding BOOLEAN DEFAULT 0');
101
+ }
102
+
103
+ db.exec(`
104
+ CREATE TABLE IF NOT EXISTS user_notification_preferences (
105
+ user_id INTEGER PRIMARY KEY,
106
+ preferences_json TEXT NOT NULL,
107
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
108
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
109
+ )
110
+ `);
111
+
112
+ db.exec(`
113
+ CREATE TABLE IF NOT EXISTS vapid_keys (
114
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
115
+ public_key TEXT NOT NULL,
116
+ private_key TEXT NOT NULL,
117
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
118
+ )
119
+ `);
120
+
121
+ db.exec(`
122
+ CREATE TABLE IF NOT EXISTS push_subscriptions (
123
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
124
+ user_id INTEGER NOT NULL,
125
+ endpoint TEXT NOT NULL UNIQUE,
126
+ keys_p256dh TEXT NOT NULL,
127
+ keys_auth TEXT NOT NULL,
128
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
129
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
130
+ )
131
+ `);
132
+ // Create app_config table if it doesn't exist (for existing installations)
133
+ db.exec(`CREATE TABLE IF NOT EXISTS app_config (
134
+ key TEXT PRIMARY KEY,
135
+ value TEXT NOT NULL,
136
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
137
+ )`);
138
+
139
+ // Create session_names table if it doesn't exist (for existing installations)
140
+ db.exec(`CREATE TABLE IF NOT EXISTS session_names (
141
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
142
+ session_id TEXT NOT NULL,
143
+ provider TEXT NOT NULL DEFAULT 'claude',
144
+ custom_name TEXT NOT NULL,
145
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
146
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
147
+ UNIQUE(session_id, provider)
148
+ )`);
149
+ db.exec('CREATE INDEX IF NOT EXISTS idx_session_names_lookup ON session_names(session_id, provider)');
150
+
151
+ console.log('Database migrations completed successfully');
152
+ } catch (error) {
153
+ console.error('Error running migrations:', error.message);
154
+ throw error;
155
+ }
156
+ };
157
+
158
+ // Initialize database with schema
159
+ const initializeDatabase = async () => {
160
+ try {
161
+ const initSQL = fs.readFileSync(INIT_SQL_PATH, 'utf8');
162
+ db.exec(initSQL);
163
+ console.log('Database initialized successfully');
164
+ runMigrations();
165
+ } catch (error) {
166
+ console.error('Error initializing database:', error.message);
167
+ throw error;
168
+ }
169
+ };
170
+
171
+ // User database operations
172
+ const userDb = {
173
+ // Check if any users exist
174
+ hasUsers: () => {
175
+ try {
176
+ const row = db.prepare('SELECT COUNT(*) as count FROM users').get();
177
+ return row.count > 0;
178
+ } catch (err) {
179
+ throw err;
180
+ }
181
+ },
182
+
183
+ // Create a new user
184
+ createUser: (username, passwordHash) => {
185
+ try {
186
+ const stmt = db.prepare('INSERT INTO users (username, password_hash) VALUES (?, ?)');
187
+ const result = stmt.run(username, passwordHash);
188
+ return { id: result.lastInsertRowid, username };
189
+ } catch (err) {
190
+ throw err;
191
+ }
192
+ },
193
+
194
+ ensurePlatformUser: () => {
195
+ try {
196
+ const existing = db
197
+ .prepare('SELECT id, username, created_at, last_login FROM users WHERE is_active = 1 LIMIT 1')
198
+ .get();
199
+ if (existing) {
200
+ return existing;
201
+ }
202
+
203
+ const username = 'notion-code';
204
+ const passwordHash = `platform:${crypto.randomBytes(32).toString('hex')}`;
205
+ const result = db
206
+ .prepare('INSERT INTO users (username, password_hash, has_completed_onboarding) VALUES (?, ?, 1)')
207
+ .run(username, passwordHash);
208
+
209
+ return db
210
+ .prepare('SELECT id, username, created_at, last_login FROM users WHERE id = ?')
211
+ .get(result.lastInsertRowid);
212
+ } catch (err) {
213
+ throw err;
214
+ }
215
+ },
216
+
217
+ // Get user by username
218
+ getUserByUsername: (username) => {
219
+ try {
220
+ const row = db.prepare('SELECT * FROM users WHERE username = ? AND is_active = 1').get(username);
221
+ return row;
222
+ } catch (err) {
223
+ throw err;
224
+ }
225
+ },
226
+
227
+ // Update last login time (non-fatal — logged but not thrown)
228
+ updateLastLogin: (userId) => {
229
+ try {
230
+ db.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?').run(userId);
231
+ } catch (err) {
232
+ console.warn('Failed to update last login:', err.message);
233
+ }
234
+ },
235
+
236
+ // Get user by ID
237
+ getUserById: (userId) => {
238
+ try {
239
+ const row = db.prepare('SELECT id, username, created_at, last_login FROM users WHERE id = ? AND is_active = 1').get(userId);
240
+ return row;
241
+ } catch (err) {
242
+ throw err;
243
+ }
244
+ },
245
+
246
+ getFirstUser: () => {
247
+ try {
248
+ const row = db.prepare('SELECT id, username, created_at, last_login FROM users WHERE is_active = 1 LIMIT 1').get();
249
+ return row;
250
+ } catch (err) {
251
+ throw err;
252
+ }
253
+ },
254
+
255
+ updateGitConfig: (userId, gitName, gitEmail) => {
256
+ try {
257
+ const stmt = db.prepare('UPDATE users SET git_name = ?, git_email = ? WHERE id = ?');
258
+ stmt.run(gitName, gitEmail, userId);
259
+ } catch (err) {
260
+ throw err;
261
+ }
262
+ },
263
+
264
+ getGitConfig: (userId) => {
265
+ try {
266
+ const row = db.prepare('SELECT git_name, git_email FROM users WHERE id = ?').get(userId);
267
+ return row;
268
+ } catch (err) {
269
+ throw err;
270
+ }
271
+ },
272
+
273
+ completeOnboarding: (userId) => {
274
+ try {
275
+ const stmt = db.prepare('UPDATE users SET has_completed_onboarding = 1 WHERE id = ?');
276
+ stmt.run(userId);
277
+ } catch (err) {
278
+ throw err;
279
+ }
280
+ },
281
+
282
+ hasCompletedOnboarding: (userId) => {
283
+ try {
284
+ const row = db.prepare('SELECT has_completed_onboarding FROM users WHERE id = ?').get(userId);
285
+ return row?.has_completed_onboarding === 1;
286
+ } catch (err) {
287
+ throw err;
288
+ }
289
+ }
290
+ };
291
+
292
+ // API Keys database operations
293
+ const apiKeysDb = {
294
+ // Generate a new API key
295
+ generateApiKey: () => {
296
+ return 'ck_' + crypto.randomBytes(32).toString('hex');
297
+ },
298
+
299
+ // Create a new API key
300
+ createApiKey: (userId, keyName) => {
301
+ try {
302
+ const apiKey = apiKeysDb.generateApiKey();
303
+ const stmt = db.prepare('INSERT INTO api_keys (user_id, key_name, api_key) VALUES (?, ?, ?)');
304
+ const result = stmt.run(userId, keyName, apiKey);
305
+ return { id: result.lastInsertRowid, keyName, apiKey };
306
+ } catch (err) {
307
+ throw err;
308
+ }
309
+ },
310
+
311
+ // Get all API keys for a user
312
+ getApiKeys: (userId) => {
313
+ try {
314
+ const rows = db.prepare('SELECT id, key_name, api_key, created_at, last_used, is_active FROM api_keys WHERE user_id = ? ORDER BY created_at DESC').all(userId);
315
+ return rows;
316
+ } catch (err) {
317
+ throw err;
318
+ }
319
+ },
320
+
321
+ // Validate API key and get user
322
+ validateApiKey: (apiKey) => {
323
+ try {
324
+ const row = db.prepare(`
325
+ SELECT u.id, u.username, ak.id as api_key_id
326
+ FROM api_keys ak
327
+ JOIN users u ON ak.user_id = u.id
328
+ WHERE ak.api_key = ? AND ak.is_active = 1 AND u.is_active = 1
329
+ `).get(apiKey);
330
+
331
+ if (row) {
332
+ // Update last_used timestamp
333
+ db.prepare('UPDATE api_keys SET last_used = CURRENT_TIMESTAMP WHERE id = ?').run(row.api_key_id);
334
+ }
335
+
336
+ return row;
337
+ } catch (err) {
338
+ throw err;
339
+ }
340
+ },
341
+
342
+ // Delete an API key
343
+ deleteApiKey: (userId, apiKeyId) => {
344
+ try {
345
+ const stmt = db.prepare('DELETE FROM api_keys WHERE id = ? AND user_id = ?');
346
+ const result = stmt.run(apiKeyId, userId);
347
+ return result.changes > 0;
348
+ } catch (err) {
349
+ throw err;
350
+ }
351
+ },
352
+
353
+ // Toggle API key active status
354
+ toggleApiKey: (userId, apiKeyId, isActive) => {
355
+ try {
356
+ const stmt = db.prepare('UPDATE api_keys SET is_active = ? WHERE id = ? AND user_id = ?');
357
+ const result = stmt.run(isActive ? 1 : 0, apiKeyId, userId);
358
+ return result.changes > 0;
359
+ } catch (err) {
360
+ throw err;
361
+ }
362
+ }
363
+ };
364
+
365
+ // User credentials database operations (for GitHub tokens, GitLab tokens, etc.)
366
+ const credentialsDb = {
367
+ // Create a new credential
368
+ createCredential: (userId, credentialName, credentialType, credentialValue, description = null) => {
369
+ try {
370
+ const stmt = db.prepare('INSERT INTO user_credentials (user_id, credential_name, credential_type, credential_value, description) VALUES (?, ?, ?, ?, ?)');
371
+ const result = stmt.run(userId, credentialName, credentialType, credentialValue, description);
372
+ return { id: result.lastInsertRowid, credentialName, credentialType };
373
+ } catch (err) {
374
+ throw err;
375
+ }
376
+ },
377
+
378
+ // Get all credentials for a user, optionally filtered by type
379
+ getCredentials: (userId, credentialType = null) => {
380
+ try {
381
+ let query = 'SELECT id, credential_name, credential_type, description, created_at, is_active FROM user_credentials WHERE user_id = ?';
382
+ const params = [userId];
383
+
384
+ if (credentialType) {
385
+ query += ' AND credential_type = ?';
386
+ params.push(credentialType);
387
+ }
388
+
389
+ query += ' ORDER BY created_at DESC';
390
+
391
+ const rows = db.prepare(query).all(...params);
392
+ return rows;
393
+ } catch (err) {
394
+ throw err;
395
+ }
396
+ },
397
+
398
+ // Get active credential value for a user by type (returns most recent active)
399
+ getActiveCredential: (userId, credentialType) => {
400
+ try {
401
+ const row = db.prepare('SELECT credential_value FROM user_credentials WHERE user_id = ? AND credential_type = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1').get(userId, credentialType);
402
+ return row?.credential_value || null;
403
+ } catch (err) {
404
+ throw err;
405
+ }
406
+ },
407
+
408
+ // Delete a credential
409
+ deleteCredential: (userId, credentialId) => {
410
+ try {
411
+ const stmt = db.prepare('DELETE FROM user_credentials WHERE id = ? AND user_id = ?');
412
+ const result = stmt.run(credentialId, userId);
413
+ return result.changes > 0;
414
+ } catch (err) {
415
+ throw err;
416
+ }
417
+ },
418
+
419
+ // Toggle credential active status
420
+ toggleCredential: (userId, credentialId, isActive) => {
421
+ try {
422
+ const stmt = db.prepare('UPDATE user_credentials SET is_active = ? WHERE id = ? AND user_id = ?');
423
+ const result = stmt.run(isActive ? 1 : 0, credentialId, userId);
424
+ return result.changes > 0;
425
+ } catch (err) {
426
+ throw err;
427
+ }
428
+ }
429
+ };
430
+
431
+ const DEFAULT_NOTIFICATION_PREFERENCES = {
432
+ channels: {
433
+ inApp: false,
434
+ webPush: false
435
+ },
436
+ events: {
437
+ actionRequired: true,
438
+ stop: true,
439
+ error: true
440
+ }
441
+ };
442
+
443
+ const normalizeNotificationPreferences = (value) => {
444
+ const source = value && typeof value === 'object' ? value : {};
445
+
446
+ return {
447
+ channels: {
448
+ inApp: source.channels?.inApp === true,
449
+ webPush: source.channels?.webPush === true
450
+ },
451
+ events: {
452
+ actionRequired: source.events?.actionRequired !== false,
453
+ stop: source.events?.stop !== false,
454
+ error: source.events?.error !== false
455
+ }
456
+ };
457
+ };
458
+
459
+ const notificationPreferencesDb = {
460
+ getPreferences: (userId) => {
461
+ try {
462
+ const row = db.prepare('SELECT preferences_json FROM user_notification_preferences WHERE user_id = ?').get(userId);
463
+ if (!row) {
464
+ const defaults = normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
465
+ db.prepare(
466
+ 'INSERT INTO user_notification_preferences (user_id, preferences_json, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)'
467
+ ).run(userId, JSON.stringify(defaults));
468
+ return defaults;
469
+ }
470
+
471
+ let parsed;
472
+ try {
473
+ parsed = JSON.parse(row.preferences_json);
474
+ } catch {
475
+ parsed = DEFAULT_NOTIFICATION_PREFERENCES;
476
+ }
477
+ return normalizeNotificationPreferences(parsed);
478
+ } catch (err) {
479
+ throw err;
480
+ }
481
+ },
482
+
483
+ updatePreferences: (userId, preferences) => {
484
+ try {
485
+ const normalized = normalizeNotificationPreferences(preferences);
486
+ db.prepare(
487
+ `INSERT INTO user_notification_preferences (user_id, preferences_json, updated_at)
488
+ VALUES (?, ?, CURRENT_TIMESTAMP)
489
+ ON CONFLICT(user_id) DO UPDATE SET
490
+ preferences_json = excluded.preferences_json,
491
+ updated_at = CURRENT_TIMESTAMP`
492
+ ).run(userId, JSON.stringify(normalized));
493
+ return normalized;
494
+ } catch (err) {
495
+ throw err;
496
+ }
497
+ }
498
+ };
499
+
500
+ const pushSubscriptionsDb = {
501
+ saveSubscription: (userId, endpoint, keysP256dh, keysAuth) => {
502
+ try {
503
+ db.prepare(
504
+ `INSERT INTO push_subscriptions (user_id, endpoint, keys_p256dh, keys_auth)
505
+ VALUES (?, ?, ?, ?)
506
+ ON CONFLICT(endpoint) DO UPDATE SET
507
+ user_id = excluded.user_id,
508
+ keys_p256dh = excluded.keys_p256dh,
509
+ keys_auth = excluded.keys_auth`
510
+ ).run(userId, endpoint, keysP256dh, keysAuth);
511
+ } catch (err) {
512
+ throw err;
513
+ }
514
+ },
515
+
516
+ getSubscriptions: (userId) => {
517
+ try {
518
+ return db.prepare('SELECT endpoint, keys_p256dh, keys_auth FROM push_subscriptions WHERE user_id = ?').all(userId);
519
+ } catch (err) {
520
+ throw err;
521
+ }
522
+ },
523
+
524
+ removeSubscription: (endpoint) => {
525
+ try {
526
+ db.prepare('DELETE FROM push_subscriptions WHERE endpoint = ?').run(endpoint);
527
+ } catch (err) {
528
+ throw err;
529
+ }
530
+ },
531
+
532
+ removeAllForUser: (userId) => {
533
+ try {
534
+ db.prepare('DELETE FROM push_subscriptions WHERE user_id = ?').run(userId);
535
+ } catch (err) {
536
+ throw err;
537
+ }
538
+ }
539
+ };
540
+
541
+ // Session custom names database operations
542
+ const sessionNamesDb = {
543
+ // Set (insert or update) a custom session name
544
+ setName: (sessionId, provider, customName) => {
545
+ db.prepare(`
546
+ INSERT INTO session_names (session_id, provider, custom_name)
547
+ VALUES (?, ?, ?)
548
+ ON CONFLICT(session_id, provider)
549
+ DO UPDATE SET custom_name = excluded.custom_name, updated_at = CURRENT_TIMESTAMP
550
+ `).run(sessionId, provider, customName);
551
+ },
552
+
553
+ // Get a single custom session name
554
+ getName: (sessionId, provider) => {
555
+ const row = db.prepare(
556
+ 'SELECT custom_name FROM session_names WHERE session_id = ? AND provider = ?'
557
+ ).get(sessionId, provider);
558
+ return row?.custom_name || null;
559
+ },
560
+
561
+ // Batch lookup — returns Map<sessionId, customName>
562
+ getNames: (sessionIds, provider) => {
563
+ if (!sessionIds.length) return new Map();
564
+ const placeholders = sessionIds.map(() => '?').join(',');
565
+ const rows = db.prepare(
566
+ `SELECT session_id, custom_name FROM session_names
567
+ WHERE session_id IN (${placeholders}) AND provider = ?`
568
+ ).all(...sessionIds, provider);
569
+ return new Map(rows.map(r => [r.session_id, r.custom_name]));
570
+ },
571
+
572
+ // Delete a custom session name
573
+ deleteName: (sessionId, provider) => {
574
+ return db.prepare(
575
+ 'DELETE FROM session_names WHERE session_id = ? AND provider = ?'
576
+ ).run(sessionId, provider).changes > 0;
577
+ },
578
+ };
579
+
580
+ // Apply custom session names from the database (overrides CLI-generated summaries)
581
+ function applyCustomSessionNames(sessions, provider) {
582
+ if (!sessions?.length) return;
583
+ try {
584
+ const ids = sessions.map(s => s.id);
585
+ const customNames = sessionNamesDb.getNames(ids, provider);
586
+ for (const session of sessions) {
587
+ const custom = customNames.get(session.id);
588
+ if (custom) session.summary = custom;
589
+ }
590
+ } catch (error) {
591
+ console.warn(`[DB] Failed to apply custom session names for ${provider}:`, error.message);
592
+ }
593
+ }
594
+
595
+ // App config database operations
596
+ const appConfigDb = {
597
+ get: (key) => {
598
+ try {
599
+ const row = db.prepare('SELECT value FROM app_config WHERE key = ?').get(key);
600
+ return row?.value || null;
601
+ } catch (err) {
602
+ return null;
603
+ }
604
+ },
605
+
606
+ set: (key, value) => {
607
+ db.prepare(
608
+ 'INSERT INTO app_config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'
609
+ ).run(key, value);
610
+ },
611
+
612
+ getOrCreateJwtSecret: () => {
613
+ let secret = appConfigDb.get('jwt_secret');
614
+ if (!secret) {
615
+ secret = crypto.randomBytes(64).toString('hex');
616
+ appConfigDb.set('jwt_secret', secret);
617
+ }
618
+ return secret;
619
+ }
620
+ };
621
+
622
+ // Backward compatibility - keep old names pointing to new system
623
+ const githubTokensDb = {
624
+ createGithubToken: (userId, tokenName, githubToken, description = null) => {
625
+ return credentialsDb.createCredential(userId, tokenName, 'github_token', githubToken, description);
626
+ },
627
+ getGithubTokens: (userId) => {
628
+ return credentialsDb.getCredentials(userId, 'github_token');
629
+ },
630
+ getActiveGithubToken: (userId) => {
631
+ return credentialsDb.getActiveCredential(userId, 'github_token');
632
+ },
633
+ deleteGithubToken: (userId, tokenId) => {
634
+ return credentialsDb.deleteCredential(userId, tokenId);
635
+ },
636
+ toggleGithubToken: (userId, tokenId, isActive) => {
637
+ return credentialsDb.toggleCredential(userId, tokenId, isActive);
638
+ }
639
+ };
640
+
641
+ export {
642
+ db,
643
+ initializeDatabase,
644
+ userDb,
645
+ apiKeysDb,
646
+ credentialsDb,
647
+ notificationPreferencesDb,
648
+ pushSubscriptionsDb,
649
+ sessionNamesDb,
650
+ applyCustomSessionNames,
651
+ appConfigDb,
652
+ githubTokensDb // Backward compatibility
653
+ };