forked from op7418/CodePilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.ts
More file actions
2152 lines (1932 loc) · 79.6 KB
/
db.ts
File metadata and controls
2152 lines (1932 loc) · 79.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Database from 'better-sqlite3';
import path from 'path';
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import type { ChatSession, Message, SettingsMap, TaskItem, TaskStatus, ApiProvider, CreateProviderRequest, UpdateProviderRequest, MediaJob, MediaJobStatus, MediaJobItem, MediaJobItemStatus, MediaContextEvent, BatchConfig } from '@/types';
import type { ChannelType, ChannelBinding } from './bridge/types';
import { getLocalDateString, localDayStartAsUTC } from './utils';
const dataDir = process.env.CLAUDE_GUI_DATA_DIR || path.join(os.homedir(), '.codepilot');
const DB_PATH = path.join(dataDir, 'codepilot.db');
let db: Database.Database | null = null;
export function getDb(): Database.Database {
if (!db) {
const dir = path.dirname(DB_PATH);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Migrate from old locations if the new DB doesn't exist yet
if (!fs.existsSync(DB_PATH)) {
const home = os.homedir();
const oldPaths = [
// Old Electron userData paths (app.getPath('userData'))
path.join(home, 'Library', 'Application Support', 'CodePilot', 'codepilot.db'),
path.join(home, 'Library', 'Application Support', 'codepilot', 'codepilot.db'),
path.join(home, 'Library', 'Application Support', 'Claude GUI', 'codepilot.db'),
// Old dev-mode fallback
path.join(process.cwd(), 'data', 'codepilot.db'),
// Legacy name
path.join(home, 'Library', 'Application Support', 'CodePilot', 'claude-gui.db'),
path.join(home, 'Library', 'Application Support', 'codepilot', 'claude-gui.db'),
];
for (const oldPath of oldPaths) {
if (fs.existsSync(oldPath)) {
try {
fs.copyFileSync(oldPath, DB_PATH);
// Also copy WAL/SHM if they exist
if (fs.existsSync(oldPath + '-wal')) fs.copyFileSync(oldPath + '-wal', DB_PATH + '-wal');
if (fs.existsSync(oldPath + '-shm')) fs.copyFileSync(oldPath + '-shm', DB_PATH + '-shm');
console.log(`[db] Migrated database from ${oldPath}`);
break;
} catch (err) {
console.warn(`[db] Failed to migrate from ${oldPath}:`, err);
}
}
}
}
db = new Database(DB_PATH);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
initDb(db);
}
return db;
}
function initDb(db: Database.Database): void {
db.exec(`
CREATE TABLE IF NOT EXISTS chat_sessions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL DEFAULT 'New Chat',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
model TEXT NOT NULL DEFAULT '',
system_prompt TEXT NOT NULL DEFAULT '',
working_directory TEXT NOT NULL DEFAULT '',
sdk_session_id TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
role TEXT NOT NULL CHECK(role IN ('user', 'assistant')),
content TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
token_usage TEXT,
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL UNIQUE,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
title TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'in_progress', 'completed', 'failed')),
description TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS api_providers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
provider_type TEXT NOT NULL DEFAULT 'anthropic',
base_url TEXT NOT NULL DEFAULT '',
api_key TEXT NOT NULL DEFAULT '',
is_active INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
extra_env TEXT NOT NULL DEFAULT '{}',
notes TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS media_generations (
id TEXT PRIMARY KEY,
type TEXT NOT NULL DEFAULT 'image',
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'processing', 'completed', 'failed')),
provider TEXT NOT NULL DEFAULT 'gemini',
model TEXT NOT NULL DEFAULT '',
prompt TEXT NOT NULL DEFAULT '',
aspect_ratio TEXT NOT NULL DEFAULT '1:1',
image_size TEXT NOT NULL DEFAULT '1K',
local_path TEXT NOT NULL DEFAULT '',
thumbnail_path TEXT NOT NULL DEFAULT '',
session_id TEXT,
message_id TEXT,
tags TEXT NOT NULL DEFAULT '[]',
metadata TEXT NOT NULL DEFAULT '{}',
favorited INTEGER NOT NULL DEFAULT 0,
error TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
completed_at TEXT
);
CREATE TABLE IF NOT EXISTS media_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
color TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS media_jobs (
id TEXT PRIMARY KEY,
session_id TEXT,
status TEXT NOT NULL DEFAULT 'draft'
CHECK(status IN ('draft','planning','planned','running','paused','completed','cancelled','failed')),
doc_paths TEXT NOT NULL DEFAULT '[]',
style_prompt TEXT NOT NULL DEFAULT '',
batch_config TEXT NOT NULL DEFAULT '{}',
total_items INTEGER NOT NULL DEFAULT 0,
completed_items INTEGER NOT NULL DEFAULT 0,
failed_items INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
completed_at TEXT,
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS media_job_items (
id TEXT PRIMARY KEY,
job_id TEXT NOT NULL,
idx INTEGER NOT NULL DEFAULT 0,
prompt TEXT NOT NULL DEFAULT '',
aspect_ratio TEXT NOT NULL DEFAULT '1:1',
image_size TEXT NOT NULL DEFAULT '1K',
model TEXT NOT NULL DEFAULT '',
tags TEXT NOT NULL DEFAULT '[]',
source_refs TEXT NOT NULL DEFAULT '[]',
status TEXT NOT NULL DEFAULT 'pending'
CHECK(status IN ('pending','processing','completed','failed','cancelled')),
retry_count INTEGER NOT NULL DEFAULT 0,
result_media_generation_id TEXT,
error TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (job_id) REFERENCES media_jobs(id) ON DELETE CASCADE,
FOREIGN KEY (result_media_generation_id) REFERENCES media_generations(id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS media_context_events (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
job_id TEXT NOT NULL,
payload TEXT NOT NULL DEFAULT '{}',
sync_mode TEXT NOT NULL DEFAULT 'manual'
CHECK(sync_mode IN ('manual','auto_batch')),
synced_at TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE,
FOREIGN KEY (job_id) REFERENCES media_jobs(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_messages_session_id ON messages(session_id);
CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at);
CREATE INDEX IF NOT EXISTS idx_sessions_updated_at ON chat_sessions(updated_at);
CREATE INDEX IF NOT EXISTS idx_tasks_session_id ON tasks(session_id);
CREATE INDEX IF NOT EXISTS idx_media_created_at ON media_generations(created_at);
CREATE INDEX IF NOT EXISTS idx_media_session_id ON media_generations(session_id);
CREATE INDEX IF NOT EXISTS idx_media_status ON media_generations(status);
CREATE INDEX IF NOT EXISTS idx_media_jobs_session_id ON media_jobs(session_id);
CREATE INDEX IF NOT EXISTS idx_media_jobs_status ON media_jobs(status);
CREATE INDEX IF NOT EXISTS idx_media_job_items_job_id ON media_job_items(job_id);
CREATE INDEX IF NOT EXISTS idx_media_job_items_status ON media_job_items(status);
CREATE INDEX IF NOT EXISTS idx_media_context_events_job_id ON media_context_events(job_id);
-- Bridge: IM channel bindings
CREATE TABLE IF NOT EXISTS channel_bindings (
id TEXT PRIMARY KEY,
channel_type TEXT NOT NULL,
chat_id TEXT NOT NULL,
codepilot_session_id TEXT NOT NULL,
sdk_session_id TEXT NOT NULL DEFAULT '',
working_directory TEXT NOT NULL DEFAULT '',
model TEXT NOT NULL DEFAULT '',
mode TEXT NOT NULL DEFAULT 'code' CHECK(mode IN ('code', 'plan', 'ask')),
active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (codepilot_session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE,
UNIQUE(channel_type, chat_id)
);
CREATE INDEX IF NOT EXISTS idx_channel_bindings_session ON channel_bindings(codepilot_session_id);
CREATE INDEX IF NOT EXISTS idx_channel_bindings_lookup ON channel_bindings(channel_type, chat_id);
-- Bridge: polling offset watermarks per adapter
CREATE TABLE IF NOT EXISTS channel_offsets (
channel_type TEXT PRIMARY KEY,
offset_value TEXT NOT NULL DEFAULT '0',
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- Bridge: idempotent message dedup
CREATE TABLE IF NOT EXISTS channel_dedupe (
dedup_key TEXT PRIMARY KEY,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_channel_dedupe_expires ON channel_dedupe(expires_at);
-- Bridge: outbound message references (for editing/deleting sent messages)
CREATE TABLE IF NOT EXISTS channel_outbound_refs (
id TEXT PRIMARY KEY,
channel_type TEXT NOT NULL,
chat_id TEXT NOT NULL,
codepilot_session_id TEXT NOT NULL,
platform_message_id TEXT NOT NULL,
purpose TEXT NOT NULL DEFAULT 'response',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_outbound_refs_session ON channel_outbound_refs(codepilot_session_id);
-- Bridge: audit log
CREATE TABLE IF NOT EXISTS channel_audit_logs (
id TEXT PRIMARY KEY,
channel_type TEXT NOT NULL,
chat_id TEXT NOT NULL,
direction TEXT NOT NULL CHECK(direction IN ('inbound', 'outbound')),
message_id TEXT NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_audit_logs_chat ON channel_audit_logs(channel_type, chat_id);
CREATE INDEX IF NOT EXISTS idx_audit_logs_created ON channel_audit_logs(created_at);
-- Bridge: permission request → IM message links
CREATE TABLE IF NOT EXISTS channel_permission_links (
id TEXT PRIMARY KEY,
permission_request_id TEXT NOT NULL,
channel_type TEXT NOT NULL,
chat_id TEXT NOT NULL,
message_id TEXT NOT NULL,
tool_name TEXT NOT NULL DEFAULT '',
suggestions TEXT NOT NULL DEFAULT '',
resolved INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_perm_links_request ON channel_permission_links(permission_request_id);
`);
// Run migrations for existing databases
migrateDb(db);
}
function migrateDb(db: Database.Database): void {
const columns = db.prepare("PRAGMA table_info(chat_sessions)").all() as { name: string }[];
const colNames = columns.map(c => c.name);
if (!colNames.includes('model')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN model TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('system_prompt')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN system_prompt TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('sdk_session_id')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN sdk_session_id TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('project_name')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN project_name TEXT NOT NULL DEFAULT ''");
// Backfill project_name from working_directory for existing rows
db.exec(`
UPDATE chat_sessions
SET project_name = CASE
WHEN working_directory != '' THEN REPLACE(REPLACE(working_directory, RTRIM(working_directory, REPLACE(working_directory, '/', '')), ''), '/', '')
ELSE ''
END
WHERE project_name = ''
`);
}
if (!colNames.includes('status')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN status TEXT NOT NULL DEFAULT 'active'");
}
if (!colNames.includes('mode')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN mode TEXT NOT NULL DEFAULT 'code'");
}
if (!colNames.includes('provider_name')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN provider_name TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('provider_id')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN provider_id TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('sdk_cwd')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN sdk_cwd TEXT NOT NULL DEFAULT ''");
// Backfill sdk_cwd from working_directory for existing sessions
db.exec("UPDATE chat_sessions SET sdk_cwd = working_directory WHERE sdk_cwd = '' AND working_directory != ''");
}
if (!colNames.includes('runtime_status')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN runtime_status TEXT NOT NULL DEFAULT 'idle'");
}
if (!colNames.includes('runtime_updated_at')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN runtime_updated_at TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('runtime_error')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN runtime_error TEXT NOT NULL DEFAULT ''");
}
if (!colNames.includes('permission_profile')) {
db.exec("ALTER TABLE chat_sessions ADD COLUMN permission_profile TEXT NOT NULL DEFAULT 'default'");
}
db.exec("CREATE INDEX IF NOT EXISTS idx_sessions_runtime_status ON chat_sessions(runtime_status)");
// Migrate is_active provider to default_provider_id setting
const defaultProviderSetting = db.prepare("SELECT value FROM settings WHERE key = 'default_provider_id'").get() as { value: string } | undefined;
if (!defaultProviderSetting) {
const activeProvider = db.prepare('SELECT id FROM api_providers WHERE is_active = 1 LIMIT 1').get() as { id: string } | undefined;
if (activeProvider) {
db.prepare(
"INSERT INTO settings (key, value) VALUES ('default_provider_id', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
).run(activeProvider.id);
}
}
const msgColumns = db.prepare("PRAGMA table_info(messages)").all() as { name: string }[];
const msgColNames = msgColumns.map(c => c.name);
if (!msgColNames.includes('token_usage')) {
db.exec("ALTER TABLE messages ADD COLUMN token_usage TEXT");
}
// Ensure tasks table exists for databases created before this migration
db.exec(`
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
title TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'in_progress', 'completed', 'failed')),
description TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_tasks_session_id ON tasks(session_id);
`);
// Add source column to tasks table (user vs sdk)
const taskColumns = db.prepare("PRAGMA table_info(tasks)").all() as { name: string }[];
const taskColNames = taskColumns.map(c => c.name);
if (!taskColNames.includes('source')) {
db.exec("ALTER TABLE tasks ADD COLUMN source TEXT NOT NULL DEFAULT 'user'");
}
if (!taskColNames.includes('sort_order')) {
db.exec("ALTER TABLE tasks ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0");
}
// Ensure api_providers table exists for databases created before this migration
db.exec(`
CREATE TABLE IF NOT EXISTS api_providers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
provider_type TEXT NOT NULL DEFAULT 'anthropic',
base_url TEXT NOT NULL DEFAULT '',
api_key TEXT NOT NULL DEFAULT '',
is_active INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
extra_env TEXT NOT NULL DEFAULT '{}',
notes TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
`);
// Add new provider fields (protocol, headers, env_overrides, role_models)
{
const providerCols = db.prepare("PRAGMA table_info(api_providers)").all() as { name: string }[];
const provColNames = providerCols.map(c => c.name);
if (!provColNames.includes('protocol')) {
db.exec("ALTER TABLE api_providers ADD COLUMN protocol TEXT NOT NULL DEFAULT ''");
}
if (!provColNames.includes('headers_json')) {
db.exec("ALTER TABLE api_providers ADD COLUMN headers_json TEXT NOT NULL DEFAULT '{}'");
}
if (!provColNames.includes('env_overrides_json')) {
db.exec("ALTER TABLE api_providers ADD COLUMN env_overrides_json TEXT NOT NULL DEFAULT ''");
}
if (!provColNames.includes('role_models_json')) {
db.exec("ALTER TABLE api_providers ADD COLUMN role_models_json TEXT NOT NULL DEFAULT '{}'");
}
if (!provColNames.includes('options_json')) {
db.exec("ALTER TABLE api_providers ADD COLUMN options_json TEXT NOT NULL DEFAULT '{}'");
}
}
// Create provider_models table
db.exec(`
CREATE TABLE IF NOT EXISTS provider_models (
id TEXT PRIMARY KEY,
provider_id TEXT NOT NULL,
model_id TEXT NOT NULL,
upstream_model_id TEXT NOT NULL DEFAULT '',
display_name TEXT NOT NULL DEFAULT '',
capabilities_json TEXT NOT NULL DEFAULT '{}',
variants_json TEXT NOT NULL DEFAULT '{}',
sort_order INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (provider_id) REFERENCES api_providers(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_provider_models_provider_id ON provider_models(provider_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_provider_models_provider_model ON provider_models(provider_id, model_id);
`);
// Ensure media_generations table exists for databases created before this migration
db.exec(`
CREATE TABLE IF NOT EXISTS media_generations (
id TEXT PRIMARY KEY,
type TEXT NOT NULL DEFAULT 'image',
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'processing', 'completed', 'failed')),
provider TEXT NOT NULL DEFAULT 'gemini',
model TEXT NOT NULL DEFAULT '',
prompt TEXT NOT NULL DEFAULT '',
aspect_ratio TEXT NOT NULL DEFAULT '1:1',
image_size TEXT NOT NULL DEFAULT '1K',
local_path TEXT NOT NULL DEFAULT '',
thumbnail_path TEXT NOT NULL DEFAULT '',
session_id TEXT,
message_id TEXT,
tags TEXT NOT NULL DEFAULT '[]',
metadata TEXT NOT NULL DEFAULT '{}',
favorited INTEGER NOT NULL DEFAULT 0,
error TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
completed_at TEXT
);
CREATE TABLE IF NOT EXISTS media_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
color TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_media_created_at ON media_generations(created_at);
CREATE INDEX IF NOT EXISTS idx_media_session_id ON media_generations(session_id);
CREATE INDEX IF NOT EXISTS idx_media_status ON media_generations(status);
`);
// Ensure media_jobs tables exist for databases created before this migration
db.exec(`
CREATE TABLE IF NOT EXISTS media_jobs (
id TEXT PRIMARY KEY,
session_id TEXT,
status TEXT NOT NULL DEFAULT 'draft'
CHECK(status IN ('draft','planning','planned','running','paused','completed','cancelled','failed')),
doc_paths TEXT NOT NULL DEFAULT '[]',
style_prompt TEXT NOT NULL DEFAULT '',
batch_config TEXT NOT NULL DEFAULT '{}',
total_items INTEGER NOT NULL DEFAULT 0,
completed_items INTEGER NOT NULL DEFAULT 0,
failed_items INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
completed_at TEXT,
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS media_job_items (
id TEXT PRIMARY KEY,
job_id TEXT NOT NULL,
idx INTEGER NOT NULL DEFAULT 0,
prompt TEXT NOT NULL DEFAULT '',
aspect_ratio TEXT NOT NULL DEFAULT '1:1',
image_size TEXT NOT NULL DEFAULT '1K',
model TEXT NOT NULL DEFAULT '',
tags TEXT NOT NULL DEFAULT '[]',
source_refs TEXT NOT NULL DEFAULT '[]',
status TEXT NOT NULL DEFAULT 'pending'
CHECK(status IN ('pending','processing','completed','failed','cancelled')),
retry_count INTEGER NOT NULL DEFAULT 0,
result_media_generation_id TEXT,
error TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (job_id) REFERENCES media_jobs(id) ON DELETE CASCADE,
FOREIGN KEY (result_media_generation_id) REFERENCES media_generations(id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS media_context_events (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
job_id TEXT NOT NULL,
payload TEXT NOT NULL DEFAULT '{}',
sync_mode TEXT NOT NULL DEFAULT 'manual'
CHECK(sync_mode IN ('manual','auto_batch')),
synced_at TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE,
FOREIGN KEY (job_id) REFERENCES media_jobs(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_media_jobs_session_id ON media_jobs(session_id);
CREATE INDEX IF NOT EXISTS idx_media_jobs_status ON media_jobs(status);
CREATE INDEX IF NOT EXISTS idx_media_job_items_job_id ON media_job_items(job_id);
CREATE INDEX IF NOT EXISTS idx_media_job_items_status ON media_job_items(status);
CREATE INDEX IF NOT EXISTS idx_media_context_events_job_id ON media_context_events(job_id);
`);
// Add favorited column to media_generations if missing
try {
db.exec("ALTER TABLE media_generations ADD COLUMN favorited INTEGER NOT NULL DEFAULT 0");
} catch {
// Column already exists
}
// Recover stale jobs: mark 'running' jobs as 'paused' after process restart
db.exec(`
UPDATE media_jobs SET status = 'paused', updated_at = datetime('now')
WHERE status = 'running'
`);
db.exec(`
UPDATE media_job_items SET status = 'pending', updated_at = datetime('now')
WHERE status = 'processing'
`);
// Create session_runtime_locks table
db.exec(`
CREATE TABLE IF NOT EXISTS session_runtime_locks (
session_id TEXT PRIMARY KEY,
lock_id TEXT NOT NULL,
owner TEXT NOT NULL,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_runtime_locks_expires_at ON session_runtime_locks(expires_at);
`);
// Create permission_requests table
db.exec(`
CREATE TABLE IF NOT EXISTS permission_requests (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
sdk_session_id TEXT NOT NULL DEFAULT '',
tool_name TEXT NOT NULL,
tool_input TEXT NOT NULL,
decision_reason TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL CHECK(status IN ('pending','allow','deny','timeout','aborted')),
updated_permissions TEXT NOT NULL DEFAULT '[]',
updated_input TEXT,
message TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL,
resolved_at TEXT,
FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_permission_session_status ON permission_requests(session_id, status);
CREATE INDEX IF NOT EXISTS idx_permission_expires_at ON permission_requests(expires_at);
`);
// Startup recovery: reset stale runtime states from previous process
db.exec(`
UPDATE chat_sessions
SET runtime_status = 'idle',
runtime_error = 'Process restarted',
runtime_updated_at = datetime('now')
WHERE runtime_status IN ('running', 'waiting_permission')
`);
db.exec("DELETE FROM session_runtime_locks");
db.exec(`
UPDATE permission_requests
SET status = 'aborted',
resolved_at = datetime('now'),
message = 'Process restarted'
WHERE status = 'pending'
`);
// Migrate existing settings to a default provider if api_providers is empty
const providerCount = db.prepare('SELECT COUNT(*) as count FROM api_providers').get() as { count: number };
if (providerCount.count === 0) {
const tokenRow = db.prepare("SELECT value FROM settings WHERE key = 'anthropic_auth_token'").get() as { value: string } | undefined;
const baseUrlRow = db.prepare("SELECT value FROM settings WHERE key = 'anthropic_base_url'").get() as { value: string } | undefined;
if (tokenRow || baseUrlRow) {
const id = crypto.randomBytes(16).toString('hex');
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
db.prepare(
'INSERT INTO api_providers (id, name, provider_type, base_url, api_key, is_active, sort_order, extra_env, notes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(id, 'Default', 'anthropic', baseUrlRow?.value || '', tokenRow?.value || '', 1, 0, '{}', 'Migrated from settings', now, now);
}
}
// Ensure bridge tables exist for databases created before bridge feature
db.exec(`
CREATE TABLE IF NOT EXISTS channel_bindings (
id TEXT PRIMARY KEY,
channel_type TEXT NOT NULL,
chat_id TEXT NOT NULL,
codepilot_session_id TEXT NOT NULL,
sdk_session_id TEXT NOT NULL DEFAULT '',
working_directory TEXT NOT NULL DEFAULT '',
model TEXT NOT NULL DEFAULT '',
mode TEXT NOT NULL DEFAULT 'code' CHECK(mode IN ('code', 'plan', 'ask')),
active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (codepilot_session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE,
UNIQUE(channel_type, chat_id)
);
CREATE INDEX IF NOT EXISTS idx_channel_bindings_session ON channel_bindings(codepilot_session_id);
CREATE INDEX IF NOT EXISTS idx_channel_bindings_lookup ON channel_bindings(channel_type, chat_id);
CREATE TABLE IF NOT EXISTS channel_offsets (
channel_type TEXT PRIMARY KEY,
offset_value TEXT NOT NULL DEFAULT '0',
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS channel_dedupe (
dedup_key TEXT PRIMARY KEY,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_channel_dedupe_expires ON channel_dedupe(expires_at);
CREATE TABLE IF NOT EXISTS channel_outbound_refs (
id TEXT PRIMARY KEY,
channel_type TEXT NOT NULL,
chat_id TEXT NOT NULL,
codepilot_session_id TEXT NOT NULL,
platform_message_id TEXT NOT NULL,
purpose TEXT NOT NULL DEFAULT 'response',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_outbound_refs_session ON channel_outbound_refs(codepilot_session_id);
CREATE TABLE IF NOT EXISTS channel_audit_logs (
id TEXT PRIMARY KEY,
channel_type TEXT NOT NULL,
chat_id TEXT NOT NULL,
direction TEXT NOT NULL CHECK(direction IN ('inbound', 'outbound')),
message_id TEXT NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_audit_logs_chat ON channel_audit_logs(channel_type, chat_id);
CREATE INDEX IF NOT EXISTS idx_audit_logs_created ON channel_audit_logs(created_at);
CREATE TABLE IF NOT EXISTS channel_permission_links (
id TEXT PRIMARY KEY,
permission_request_id TEXT NOT NULL,
channel_type TEXT NOT NULL,
chat_id TEXT NOT NULL,
message_id TEXT NOT NULL,
tool_name TEXT NOT NULL DEFAULT '',
suggestions TEXT NOT NULL DEFAULT '',
resolved INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_perm_links_request ON channel_permission_links(permission_request_id);
`);
// Migrate channel_permission_links for databases created before these columns were added
const permLinkCols = db.prepare("PRAGMA table_info(channel_permission_links)").all() as { name: string }[];
const permLinkColNames = permLinkCols.map(c => c.name);
if (permLinkColNames.length > 0 && !permLinkColNames.includes('tool_name')) {
db.exec("ALTER TABLE channel_permission_links ADD COLUMN tool_name TEXT NOT NULL DEFAULT ''");
}
if (permLinkColNames.length > 0 && !permLinkColNames.includes('suggestions')) {
db.exec("ALTER TABLE channel_permission_links ADD COLUMN suggestions TEXT NOT NULL DEFAULT ''");
}
if (permLinkColNames.length > 0 && !permLinkColNames.includes('resolved')) {
db.exec("ALTER TABLE channel_permission_links ADD COLUMN resolved INTEGER NOT NULL DEFAULT 0");
}
// Channel configs table (structured config for channel plugins)
db.exec(`
CREATE TABLE IF NOT EXISTS channel_configs (
id TEXT PRIMARY KEY,
channel_type TEXT NOT NULL,
account_id TEXT NOT NULL DEFAULT 'default',
config_json TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(channel_type, account_id)
);
`);
}
// ==========================================
// Session Operations
// ==========================================
export function getAllSessions(): ChatSession[] {
const db = getDb();
return db.prepare('SELECT * FROM chat_sessions ORDER BY updated_at DESC').all() as ChatSession[];
}
/**
* Get sessions that are currently running or waiting for permission.
*/
export function getActiveSessions(): ChatSession[] {
const db = getDb();
return db.prepare(
"SELECT * FROM chat_sessions WHERE runtime_status IN ('running', 'waiting_permission') ORDER BY runtime_updated_at DESC"
).all() as ChatSession[];
}
export function getSession(id: string): ChatSession | undefined {
const db = getDb();
return db.prepare('SELECT * FROM chat_sessions WHERE id = ?').get(id) as ChatSession | undefined;
}
export function createSession(
title?: string,
model?: string,
systemPrompt?: string,
workingDirectory?: string,
mode?: string,
providerId?: string,
permissionProfile?: string,
): ChatSession {
const db = getDb();
const id = crypto.randomBytes(16).toString('hex');
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
const wd = workingDirectory || '';
const projectName = path.basename(wd);
db.prepare(
'INSERT INTO chat_sessions (id, title, created_at, updated_at, model, system_prompt, working_directory, sdk_session_id, project_name, status, mode, sdk_cwd, provider_id, permission_profile) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(id, title || 'New Chat', now, now, model || '', systemPrompt || '', wd, '', projectName, 'active', mode || 'code', wd, providerId || '', permissionProfile || 'default');
return getSession(id)!;
}
export function getLatestSessionByWorkingDirectory(workingDirectory: string): ChatSession | undefined {
const db = getDb();
return db.prepare(
'SELECT * FROM chat_sessions WHERE working_directory = ? ORDER BY updated_at DESC LIMIT 1'
).get(workingDirectory) as ChatSession | undefined;
}
export function deleteSession(id: string): boolean {
const db = getDb();
const result = db.prepare('DELETE FROM chat_sessions WHERE id = ?').run(id);
return result.changes > 0;
}
export function updateSessionTimestamp(id: string): void {
const db = getDb();
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
db.prepare('UPDATE chat_sessions SET updated_at = ? WHERE id = ?').run(now, id);
}
export function updateSessionTitle(id: string, title: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET title = ? WHERE id = ?').run(title, id);
}
export function updateSdkSessionId(id: string, sdkSessionId: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET sdk_session_id = ? WHERE id = ?').run(sdkSessionId, id);
}
export function updateSessionModel(id: string, model: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET model = ? WHERE id = ?').run(model, id);
}
export function updateSessionProvider(id: string, providerName: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET provider_name = ? WHERE id = ?').run(providerName, id);
}
export function updateSessionProviderId(id: string, providerId: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET provider_id = ? WHERE id = ?').run(providerId, id);
}
export function getDefaultProviderId(): string | undefined {
return getSetting('default_provider_id') || undefined;
}
export function setDefaultProviderId(id: string): void {
setSetting('default_provider_id', id);
}
export function updateSessionWorkingDirectory(id: string, workingDirectory: string): void {
const db = getDb();
const projectName = path.basename(workingDirectory);
db.prepare('UPDATE chat_sessions SET working_directory = ?, project_name = ? WHERE id = ?').run(workingDirectory, projectName, id);
}
export function updateSessionMode(id: string, mode: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET mode = ? WHERE id = ?').run(mode, id);
}
export function updateSessionPermissionProfile(id: string, profile: string): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET permission_profile = ? WHERE id = ?').run(profile, id);
}
// ==========================================
// Message Operations
// ==========================================
export function getMessages(
sessionId: string,
options?: { limit?: number; beforeRowId?: number },
): { messages: Message[]; hasMore: boolean } {
const db = getDb();
const limit = options?.limit ?? 100;
const beforeRowId = options?.beforeRowId;
let rows: Message[];
if (beforeRowId) {
// Fetch `limit + 1` rows before the cursor to detect if there are more
rows = db.prepare(
'SELECT *, rowid as _rowid FROM messages WHERE session_id = ? AND rowid < ? ORDER BY rowid DESC LIMIT ?'
).all(sessionId, beforeRowId, limit + 1) as Message[];
} else {
// Fetch the most recent `limit + 1` messages
rows = db.prepare(
'SELECT *, rowid as _rowid FROM messages WHERE session_id = ? ORDER BY rowid DESC LIMIT ?'
).all(sessionId, limit + 1) as Message[];
}
const hasMore = rows.length > limit;
if (hasMore) {
rows = rows.slice(0, limit);
}
// Reverse to chronological order (ASC)
rows.reverse();
return { messages: rows, hasMore };
}
export function addMessage(
sessionId: string,
role: 'user' | 'assistant',
content: string,
tokenUsage?: string | null,
): Message {
const db = getDb();
const id = crypto.randomBytes(16).toString('hex');
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
db.prepare(
'INSERT INTO messages (id, session_id, role, content, created_at, token_usage) VALUES (?, ?, ?, ?, ?, ?)'
).run(id, sessionId, role, content, now, tokenUsage || null);
updateSessionTimestamp(sessionId);
return db.prepare('SELECT * FROM messages WHERE id = ?').get(id) as Message;
}
export function updateMessageContent(messageId: string, content: string): number {
const db = getDb();
const result = db.prepare('UPDATE messages SET content = ? WHERE id = ?').run(content, messageId);
return result.changes;
}
/**
* Find the most recent assistant message in a session that contains an image-gen-request,
* update its content, and return the real message ID. Used as fallback when the frontend
* only has a temporary message ID.
*
* Prefers exact match on rawRequestBlock (the full ```image-gen-request...``` fence).
* Falls back to prompt hint prefix match if rawRequestBlock is unavailable or doesn't match.
*/
export function updateMessageBySessionAndHint(
sessionId: string,
content: string,
rawRequestBlock?: string,
promptHint?: string,
): { changes: number; messageId?: string } {
const db = getDb();
// Strategy 1: Exact match on the raw ```image-gen-request...``` block content.
// This is unambiguous even when multiple requests share the same prompt.
if (rawRequestBlock) {
const escaped = rawRequestBlock.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_');
const row = db.prepare(
"SELECT id FROM messages WHERE session_id = ? AND role = 'assistant' AND content LIKE ? ESCAPE '\\' AND content NOT LIKE '%image-gen-result%' ORDER BY created_at DESC LIMIT 1"
).get(sessionId, `%${escaped}%`) as { id: string } | undefined;
if (row) {
const result = db.prepare('UPDATE messages SET content = ? WHERE id = ?').run(content, row.id);
return { changes: result.changes, messageId: row.id };
}
}
// Strategy 2: Fallback to prompt hint prefix match (legacy path).
if (promptHint) {
const row = db.prepare(
"SELECT id FROM messages WHERE session_id = ? AND role = 'assistant' AND content LIKE '%image-gen-request%' AND content NOT LIKE '%image-gen-result%' AND content LIKE ? ORDER BY created_at DESC LIMIT 1"
).get(sessionId, `%${promptHint.slice(0, 60)}%`) as { id: string } | undefined;
if (row) {
const result = db.prepare('UPDATE messages SET content = ? WHERE id = ?').run(content, row.id);
return { changes: result.changes, messageId: row.id };
}
}
return { changes: 0 };
}
export function clearSessionMessages(sessionId: string): void {
const db = getDb();
db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId);
// Reset SDK session ID so next message starts fresh
db.prepare('UPDATE chat_sessions SET sdk_session_id = ? WHERE id = ?').run('', sessionId);
}
// ==========================================
// Settings Operations
// ==========================================
export function getSetting(key: string): string | undefined {
const db = getDb();
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as { value: string } | undefined;
return row?.value;
}
export function setSetting(key: string, value: string): void {
const db = getDb();
db.prepare(
'INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'
).run(key, value);
}
export function getAllSettings(): SettingsMap {
const db = getDb();
const rows = db.prepare('SELECT key, value FROM settings').all() as { key: string; value: string }[];
const settings: SettingsMap = {};
for (const row of rows) {
settings[row.key] = row.value;
}
return settings;
}
// ==========================================
// Session Status Operations
// ==========================================
export function updateSessionStatus(id: string, status: 'active' | 'archived'): void {
const db = getDb();
db.prepare('UPDATE chat_sessions SET status = ? WHERE id = ?').run(status, id);
}
// ==========================================
// Task Operations
// ==========================================
export function getTasksBySession(sessionId: string): TaskItem[] {
const db = getDb();
return db.prepare('SELECT * FROM tasks WHERE session_id = ? ORDER BY sort_order ASC, created_at ASC').all(sessionId) as TaskItem[];
}
export function getTask(id: string): TaskItem | undefined {
const db = getDb();
return db.prepare('SELECT * FROM tasks WHERE id = ?').get(id) as TaskItem | undefined;
}
export function createTask(sessionId: string, title: string, description?: string): TaskItem {
const db = getDb();
const id = crypto.randomBytes(16).toString('hex');
const now = new Date().toISOString().replace('T', ' ').split('.')[0];
db.prepare(
'INSERT INTO tasks (id, session_id, title, status, description, source, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
).run(id, sessionId, title, 'pending', description || null, 'user', now, now);
return getTask(id)!;
}