-
Notifications
You must be signed in to change notification settings - Fork 784
Expand file tree
/
Copy pathcoworkStore.ts
More file actions
1876 lines (1663 loc) · 56.2 KB
/
coworkStore.ts
File metadata and controls
1876 lines (1663 loc) · 56.2 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 { app } from 'electron';
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { Database } from 'sql.js';
import { v4 as uuidv4 } from 'uuid';
import {
extractTurnMemoryChanges,
isQuestionLikeMemoryText,
type CoworkMemoryGuardLevel,
} from './libs/coworkMemoryExtractor';
import { judgeMemoryCandidate } from './libs/coworkMemoryJudge';
// Default working directory for new users
const getDefaultWorkingDirectory = (): string => {
return path.join(os.homedir(), 'lobsterai', 'project');
};
const TASK_WORKSPACE_CONTAINER_DIR = '.lobsterai-tasks';
const normalizeRecentWorkspacePath = (cwd: string): string => {
const resolved = path.resolve(cwd);
const marker = `${path.sep}${TASK_WORKSPACE_CONTAINER_DIR}${path.sep}`;
const markerIndex = resolved.lastIndexOf(marker);
if (markerIndex > 0) {
return resolved.slice(0, markerIndex);
}
return resolved;
};
const DEFAULT_MEMORY_ENABLED = true;
const DEFAULT_MEMORY_IMPLICIT_UPDATE_ENABLED = true;
const DEFAULT_MEMORY_LLM_JUDGE_ENABLED = false;
const DEFAULT_MEMORY_GUARD_LEVEL: CoworkMemoryGuardLevel = 'strict';
const DEFAULT_MEMORY_USER_MEMORIES_MAX_ITEMS = 12;
const MIN_MEMORY_USER_MEMORIES_MAX_ITEMS = 1;
const MAX_MEMORY_USER_MEMORIES_MAX_ITEMS = 60;
const MEMORY_NEAR_DUPLICATE_MIN_SCORE = 0.82;
const MEMORY_PROCEDURAL_TEXT_RE = /(执行以下命令|run\s+(?:the\s+)?following\s+command|\b(?:cd|npm|pnpm|yarn|node|python|bash|sh|git|curl|wget)\b|\$[A-Z_][A-Z0-9_]*|&&|--[a-z0-9-]+|\/tmp\/|\.sh\b|\.bat\b|\.ps1\b)/i;
const MEMORY_ASSISTANT_STYLE_TEXT_RE = /^(?:使用|use)\s+[A-Za-z0-9._-]+\s*(?:技能|skill)/i;
function normalizeMemoryGuardLevel(value: string | undefined): CoworkMemoryGuardLevel {
if (value === 'strict' || value === 'standard' || value === 'relaxed') return value;
return DEFAULT_MEMORY_GUARD_LEVEL;
}
function parseBooleanConfig(value: string | undefined, fallback: boolean): boolean {
if (!value) return fallback;
const normalized = value.trim().toLowerCase();
if (normalized === '1' || normalized === 'true' || normalized === 'yes' || normalized === 'on') return true;
if (normalized === '0' || normalized === 'false' || normalized === 'no' || normalized === 'off') return false;
return fallback;
}
function clampMemoryUserMemoriesMaxItems(value: number): number {
if (!Number.isFinite(value)) return DEFAULT_MEMORY_USER_MEMORIES_MAX_ITEMS;
return Math.max(
MIN_MEMORY_USER_MEMORIES_MAX_ITEMS,
Math.min(MAX_MEMORY_USER_MEMORIES_MAX_ITEMS, Math.floor(value))
);
}
function normalizeMemoryText(value: string): string {
return value.replace(/\s+/g, ' ').trim();
}
function extractConversationSearchTerms(value: string): string[] {
const normalized = normalizeMemoryText(value).toLowerCase();
if (!normalized) return [];
const terms: string[] = [];
const seen = new Set<string>();
const addTerm = (term: string): void => {
const normalizedTerm = normalizeMemoryText(term).toLowerCase();
if (!normalizedTerm) return;
if (/^[a-z0-9]$/i.test(normalizedTerm)) return;
if (seen.has(normalizedTerm)) return;
seen.add(normalizedTerm);
terms.push(normalizedTerm);
};
// Keep the full phrase and additionally match by per-token terms.
addTerm(normalized);
const tokens = normalized
.split(/[\s,,、|/\\;;]+/g)
.map((token) => token.replace(/^['"`]+|['"`]+$/g, '').trim())
.filter(Boolean);
for (const token of tokens) {
addTerm(token);
if (terms.length >= 8) break;
}
return terms.slice(0, 8);
}
function normalizeMemoryMatchKey(value: string): string {
return normalizeMemoryText(value)
.toLowerCase()
.replace(/[\u0000-\u001f]/g, ' ')
.replace(/[^\p{L}\p{N}\s]/gu, ' ')
.replace(/\s+/g, ' ')
.trim();
}
function normalizeMemorySemanticKey(value: string): string {
const key = normalizeMemoryMatchKey(value);
if (!key) return '';
return key
.replace(/^(?:the user|user|i am|i m|i|my|me)\s+/i, '')
.replace(/^(?:该用户|这个用户|用户|本人|我的|我们|咱们|咱|我|你的|你)\s*/u, '')
.replace(/\s+/g, ' ')
.trim();
}
function buildTokenFrequencyMap(value: string): Map<string, number> {
const tokens = value
.split(/\s+/g)
.map((token) => token.trim())
.filter(Boolean);
const map = new Map<string, number>();
for (const token of tokens) {
map.set(token, (map.get(token) || 0) + 1);
}
return map;
}
function scoreTokenOverlap(left: string, right: string): number {
const leftMap = buildTokenFrequencyMap(left);
const rightMap = buildTokenFrequencyMap(right);
if (leftMap.size === 0 || rightMap.size === 0) return 0;
let leftCount = 0;
let rightCount = 0;
let intersection = 0;
for (const count of leftMap.values()) leftCount += count;
for (const count of rightMap.values()) rightCount += count;
for (const [token, leftValue] of leftMap.entries()) {
intersection += Math.min(leftValue, rightMap.get(token) || 0);
}
const denominator = Math.min(leftCount, rightCount);
if (denominator <= 0) return 0;
return intersection / denominator;
}
function buildCharacterBigramMap(value: string): Map<string, number> {
const compact = value.replace(/\s+/g, '').trim();
if (!compact) return new Map<string, number>();
if (compact.length <= 1) return new Map<string, number>([[compact, 1]]);
const map = new Map<string, number>();
for (let index = 0; index < compact.length - 1; index += 1) {
const gram = compact.slice(index, index + 2);
map.set(gram, (map.get(gram) || 0) + 1);
}
return map;
}
function scoreCharacterBigramDice(left: string, right: string): number {
const leftMap = buildCharacterBigramMap(left);
const rightMap = buildCharacterBigramMap(right);
if (leftMap.size === 0 || rightMap.size === 0) return 0;
let leftCount = 0;
let rightCount = 0;
let intersection = 0;
for (const count of leftMap.values()) leftCount += count;
for (const count of rightMap.values()) rightCount += count;
for (const [gram, leftValue] of leftMap.entries()) {
intersection += Math.min(leftValue, rightMap.get(gram) || 0);
}
const denominator = leftCount + rightCount;
if (denominator <= 0) return 0;
return (2 * intersection) / denominator;
}
function scoreMemorySimilarity(left: string, right: string): number {
if (!left || !right) return 0;
if (left === right) return 1;
const compactLeft = left.replace(/\s+/g, '');
const compactRight = right.replace(/\s+/g, '');
if (compactLeft && compactLeft === compactRight) {
return 1;
}
let phraseScore = 0;
if (compactLeft && compactRight && (compactLeft.includes(compactRight) || compactRight.includes(compactLeft))) {
phraseScore = Math.min(compactLeft.length, compactRight.length) / Math.max(compactLeft.length, compactRight.length);
}
return Math.max(
phraseScore,
scoreTokenOverlap(left, right),
scoreCharacterBigramDice(left, right)
);
}
function scoreMemoryTextQuality(value: string): number {
const normalized = normalizeMemoryText(value);
if (!normalized) return 0;
let score = normalized.length;
if (/^(?:该用户|这个用户|用户)\s*/u.test(normalized)) {
score -= 12;
}
if (/^(?:the user|user)\b/i.test(normalized)) {
score -= 12;
}
if (/^(?:我|我的|我是|我有|我会|我喜欢|我偏好)/u.test(normalized)) {
score += 4;
}
if (/^(?:i|i am|i'm|my)\b/i.test(normalized)) {
score += 4;
}
return score;
}
function choosePreferredMemoryText(currentText: string, incomingText: string): string {
const normalizedCurrent = truncate(normalizeMemoryText(currentText), 360);
const normalizedIncoming = truncate(normalizeMemoryText(incomingText), 360);
if (!normalizedCurrent) return normalizedIncoming;
if (!normalizedIncoming) return normalizedCurrent;
const currentScore = scoreMemoryTextQuality(normalizedCurrent);
const incomingScore = scoreMemoryTextQuality(normalizedIncoming);
if (incomingScore > currentScore + 1) return normalizedIncoming;
if (currentScore > incomingScore + 1) return normalizedCurrent;
return normalizedIncoming.length >= normalizedCurrent.length ? normalizedIncoming : normalizedCurrent;
}
function isMeaningfulDeleteFragment(value: string): boolean {
if (!value) return false;
const tokens = value.split(/\s+/g).filter(Boolean);
if (tokens.length >= 2) return true;
if (/[\u3400-\u9fff]/u.test(value)) return value.length >= 4;
return value.length >= 6;
}
function includesAsBoundedPhrase(target: string, fragment: string): boolean {
if (!target || !fragment) return false;
const paddedTarget = ` ${target} `;
const paddedFragment = ` ${fragment} `;
if (paddedTarget.includes(paddedFragment)) {
return true;
}
// CJK phrases are often unsegmented, so token boundaries are unreliable.
if (/[\u3400-\u9fff]/u.test(fragment) && !fragment.includes(' ')) {
return target.includes(fragment);
}
return false;
}
function scoreDeleteMatch(targetKey: string, queryKey: string): number {
if (!targetKey || !queryKey) return 0;
if (targetKey === queryKey) {
return 1000 + queryKey.length;
}
if (!isMeaningfulDeleteFragment(queryKey)) {
return 0;
}
if (!includesAsBoundedPhrase(targetKey, queryKey)) {
return 0;
}
return 100 + Math.min(targetKey.length, queryKey.length);
}
function buildMemoryFingerprint(text: string): string {
const key = normalizeMemoryMatchKey(text);
return crypto.createHash('sha1').update(key).digest('hex');
}
function truncate(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
return `${value.slice(0, maxChars - 1)}…`;
}
function parseTimeToMs(input?: string | null): number | null {
if (!input) return null;
const timestamp = Date.parse(input);
if (!Number.isFinite(timestamp)) return null;
return timestamp;
}
function shouldAutoDeleteMemoryText(text: string): boolean {
const normalized = normalizeMemoryText(text);
if (!normalized) return false;
return MEMORY_ASSISTANT_STYLE_TEXT_RE.test(normalized)
|| MEMORY_PROCEDURAL_TEXT_RE.test(normalized)
|| isQuestionLikeMemoryText(normalized);
}
// Types mirroring src/types/cowork.ts for main process use
export type CoworkSessionStatus = 'idle' | 'running' | 'completed' | 'error';
export type CoworkMessageType = 'user' | 'assistant' | 'tool_use' | 'tool_result' | 'system';
export type CoworkExecutionMode = 'auto' | 'local' | 'sandbox';
export type CoworkAgentEngine = 'openclaw' | 'yd_cowork';
export type AgentSource = 'custom' | 'preset';
export interface Agent {
id: string;
name: string;
description: string;
systemPrompt: string;
identity: string;
model: string;
icon: string;
skillIds: string[];
enabled: boolean;
isDefault: boolean;
source: AgentSource;
presetId: string;
createdAt: number;
updatedAt: number;
}
export interface CreateAgentRequest {
id?: string;
name: string;
description?: string;
systemPrompt?: string;
identity?: string;
model?: string;
icon?: string;
skillIds?: string[];
source?: AgentSource;
presetId?: string;
}
export interface UpdateAgentRequest {
name?: string;
description?: string;
systemPrompt?: string;
identity?: string;
model?: string;
icon?: string;
skillIds?: string[];
enabled?: boolean;
}
const COWORK_AGENT_ENGINE = 'openclaw';
function normalizeCoworkAgentEngineValue(value?: string | null): CoworkAgentEngine {
if (value === COWORK_AGENT_ENGINE || value === 'openclaw') {
return value;
}
return COWORK_AGENT_ENGINE;
}
export interface CoworkMessageMetadata {
toolName?: string;
toolInput?: Record<string, unknown>;
toolResult?: string;
toolUseId?: string | null;
error?: string;
isError?: boolean;
isStreaming?: boolean;
isFinal?: boolean;
skillIds?: string[];
[key: string]: unknown;
}
export interface CoworkMessage {
id: string;
type: CoworkMessageType;
content: string;
timestamp: number;
metadata?: CoworkMessageMetadata;
}
export interface CoworkSession {
id: string;
title: string;
claudeSessionId: string | null;
status: CoworkSessionStatus;
pinned: boolean;
cwd: string;
systemPrompt: string;
executionMode: CoworkExecutionMode;
activeSkillIds: string[];
agentId: string;
messages: CoworkMessage[];
createdAt: number;
updatedAt: number;
}
export interface CoworkSessionSummary {
id: string;
title: string;
status: CoworkSessionStatus;
pinned: boolean;
agentId: string;
createdAt: number;
updatedAt: number;
}
export type CoworkUserMemoryStatus = 'created' | 'stale' | 'deleted';
export interface CoworkUserMemory {
id: string;
text: string;
confidence: number;
isExplicit: boolean;
status: CoworkUserMemoryStatus;
createdAt: number;
updatedAt: number;
lastUsedAt: number | null;
}
export interface CoworkUserMemorySource {
id: string;
memoryId: string;
sessionId: string | null;
messageId: string | null;
role: 'user' | 'assistant' | 'tool' | 'system';
isActive: boolean;
createdAt: number;
}
export interface CoworkUserMemorySourceInput {
sessionId?: string;
messageId?: string;
role?: 'user' | 'assistant' | 'tool' | 'system';
}
export interface CoworkUserMemoryStats {
total: number;
created: number;
stale: number;
deleted: number;
explicit: number;
implicit: number;
}
export interface CoworkConversationSearchRecord {
sessionId: string;
title: string;
updatedAt: number;
url: string;
human: string;
assistant: string;
}
export interface CoworkConfig {
workingDirectory: string;
systemPrompt: string;
executionMode: CoworkExecutionMode;
agentEngine: CoworkAgentEngine;
memoryEnabled: boolean;
memoryImplicitUpdateEnabled: boolean;
memoryLlmJudgeEnabled: boolean;
memoryGuardLevel: CoworkMemoryGuardLevel;
memoryUserMemoriesMaxItems: number;
}
export type CoworkConfigUpdate = Partial<Pick<
CoworkConfig,
| 'workingDirectory'
| 'executionMode'
| 'agentEngine'
| 'memoryEnabled'
| 'memoryImplicitUpdateEnabled'
| 'memoryLlmJudgeEnabled'
| 'memoryGuardLevel'
| 'memoryUserMemoriesMaxItems'
>>;
export interface ApplyTurnMemoryUpdatesOptions {
sessionId: string;
userText: string;
assistantText: string;
implicitEnabled: boolean;
memoryLlmJudgeEnabled: boolean;
guardLevel: CoworkMemoryGuardLevel;
userMessageId?: string;
assistantMessageId?: string;
}
export interface ApplyTurnMemoryUpdatesResult {
totalChanges: number;
created: number;
updated: number;
deleted: number;
judgeRejected: number;
llmReviewed: number;
skipped: number;
}
let cachedDefaultSystemPrompt: string | null = null;
const getDefaultSystemPrompt = (): string => {
if (cachedDefaultSystemPrompt !== null) {
return cachedDefaultSystemPrompt;
}
try {
const promptPath = path.join(app.getAppPath(), 'resources', 'SYSTEM_PROMPT.md');
cachedDefaultSystemPrompt = fs.readFileSync(promptPath, 'utf-8');
} catch {
cachedDefaultSystemPrompt = '';
}
return cachedDefaultSystemPrompt;
};
interface CoworkMessageRow {
id: string;
type: string;
content: string;
metadata: string | null;
created_at: number;
sequence: number | null;
}
interface CoworkUserMemoryRow {
id: string;
text: string;
fingerprint: string;
confidence: number;
is_explicit: number;
status: string;
created_at: number;
updated_at: number;
last_used_at: number | null;
}
export class CoworkStore {
private db: Database;
private saveDb: () => void;
constructor(db: Database, saveDb: () => void) {
this.db = db;
this.saveDb = saveDb;
}
private getOne<T>(sql: string, params: (string | number | null)[] = []): T | undefined {
const result = this.db.exec(sql, params);
if (!result[0]?.values[0]) return undefined;
const columns = result[0].columns;
const values = result[0].values[0];
const row: Record<string, unknown> = {};
columns.forEach((col, i) => {
row[col] = values[i];
});
return row as T;
}
private getAll<T>(sql: string, params: (string | number | null)[] = []): T[] {
const result = this.db.exec(sql, params);
if (!result[0]?.values) return [];
const columns = result[0].columns;
return result[0].values.map((values) => {
const row: Record<string, unknown> = {};
columns.forEach((col, i) => {
row[col] = values[i];
});
return row as T;
});
}
createSession(
title: string,
cwd: string,
systemPrompt: string = '',
executionMode: CoworkExecutionMode = 'local',
activeSkillIds: string[] = [],
agentId: string = 'main',
options?: { hidden?: boolean }
): CoworkSession {
const id = uuidv4();
const now = Date.now();
const hidden = options?.hidden ? 1 : 0;
this.db.run(`
INSERT INTO cowork_sessions (id, title, claude_session_id, status, cwd, system_prompt, execution_mode, active_skill_ids, agent_id, pinned, hidden, created_at, updated_at)
VALUES (?, ?, NULL, 'idle', ?, ?, ?, ?, ?, 0, ?, ?, ?)
`, [id, title, cwd, systemPrompt, executionMode, JSON.stringify(activeSkillIds), agentId, hidden, now, now]);
this.saveDb();
return {
id,
title,
claudeSessionId: null,
status: 'idle',
pinned: false,
cwd,
systemPrompt,
executionMode,
activeSkillIds,
agentId,
messages: [],
createdAt: now,
updatedAt: now,
};
}
getSession(id: string): CoworkSession | null {
interface SessionRow {
id: string;
title: string;
claude_session_id: string | null;
status: string;
pinned?: number | null;
cwd: string;
system_prompt: string;
execution_mode?: string | null;
active_skill_ids?: string | null;
agent_id?: string | null;
created_at: number;
updated_at: number;
}
const row = this.getOne<SessionRow>(`
SELECT id, title, claude_session_id, status, pinned, cwd, system_prompt, execution_mode, active_skill_ids, agent_id, created_at, updated_at
FROM cowork_sessions
WHERE id = ?
`, [id]);
if (!row) return null;
const messages = this.getSessionMessages(id);
let activeSkillIds: string[] = [];
if (row.active_skill_ids) {
try {
activeSkillIds = JSON.parse(row.active_skill_ids);
} catch {
activeSkillIds = [];
}
}
return {
id: row.id,
title: row.title,
claudeSessionId: row.claude_session_id,
status: row.status as CoworkSessionStatus,
pinned: Boolean(row.pinned),
cwd: row.cwd,
systemPrompt: row.system_prompt,
executionMode: (row.execution_mode as CoworkExecutionMode) || 'local',
activeSkillIds,
agentId: row.agent_id || 'main',
messages,
createdAt: row.created_at,
updatedAt: row.updated_at,
};
}
updateSession(
id: string,
updates: Partial<Pick<CoworkSession, 'title' | 'claudeSessionId' | 'status' | 'cwd' | 'systemPrompt' | 'executionMode'>>
): void {
const now = Date.now();
const setClauses: string[] = ['updated_at = ?'];
const values: (string | number | null)[] = [now];
if (updates.title !== undefined) {
setClauses.push('title = ?');
values.push(updates.title);
}
if (updates.claudeSessionId !== undefined) {
setClauses.push('claude_session_id = ?');
values.push(updates.claudeSessionId);
}
if (updates.status !== undefined) {
setClauses.push('status = ?');
values.push(updates.status);
}
if (updates.cwd !== undefined) {
setClauses.push('cwd = ?');
values.push(updates.cwd);
}
if (updates.systemPrompt !== undefined) {
setClauses.push('system_prompt = ?');
values.push(updates.systemPrompt);
}
if (updates.executionMode !== undefined) {
setClauses.push('execution_mode = ?');
values.push(updates.executionMode);
}
values.push(id);
this.db.run(`
UPDATE cowork_sessions
SET ${setClauses.join(', ')}
WHERE id = ?
`, values);
this.saveDb();
}
deleteSession(id: string): void {
this.markMemorySourcesInactiveBySession(id);
this.db.run('DELETE FROM cowork_sessions WHERE id = ?', [id]);
this.markOrphanImplicitMemoriesStale();
this.saveDb();
}
deleteSessions(ids: string[]): void {
if (ids.length === 0) return;
for (const id of ids) {
this.markMemorySourcesInactiveBySession(id);
}
const placeholders = ids.map(() => '?').join(',');
this.db.run(`DELETE FROM cowork_sessions WHERE id IN (${placeholders})`, ids);
this.markOrphanImplicitMemoriesStale();
this.saveDb();
}
setSessionPinned(id: string, pinned: boolean): void {
this.db.run('UPDATE cowork_sessions SET pinned = ? WHERE id = ?', [pinned ? 1 : 0, id]);
this.saveDb();
}
listSessions(agentId?: string): CoworkSessionSummary[] {
interface SessionSummaryRow {
id: string;
title: string;
status: string;
pinned: number | null;
agent_id: string | null;
created_at: number;
updated_at: number;
}
let rows: SessionSummaryRow[];
if (agentId) {
rows = this.getAll<SessionSummaryRow>(`
SELECT id, title, status, pinned, agent_id, created_at, updated_at
FROM cowork_sessions
WHERE agent_id = ? AND COALESCE(hidden, 0) = 0
ORDER BY pinned DESC, updated_at DESC
`, [agentId]);
} else {
rows = this.getAll<SessionSummaryRow>(`
SELECT id, title, status, pinned, agent_id, created_at, updated_at
FROM cowork_sessions
WHERE COALESCE(hidden, 0) = 0
ORDER BY pinned DESC, updated_at DESC
`);
}
return rows.map(row => ({
id: row.id,
title: row.title,
status: row.status as CoworkSessionStatus,
pinned: Boolean(row.pinned),
agentId: row.agent_id || 'main',
createdAt: row.created_at,
updatedAt: row.updated_at,
}));
}
resetRunningSessions(): number {
const now = Date.now();
this.db.run(`
UPDATE cowork_sessions
SET status = 'idle', updated_at = ?
WHERE status = 'running'
`, [now]);
this.saveDb();
const changes = this.db.getRowsModified?.();
return typeof changes === 'number' ? changes : 0;
}
listRecentCwds(limit: number = 8): string[] {
interface CwdRow {
cwd: string;
updated_at: number;
}
const rows = this.getAll<CwdRow>(`
SELECT cwd, updated_at
FROM cowork_sessions
WHERE cwd IS NOT NULL AND TRIM(cwd) != ''
ORDER BY updated_at DESC
LIMIT ?
`, [Math.max(limit * 8, limit)]);
const deduped: string[] = [];
const seen = new Set<string>();
for (const row of rows) {
const normalized = normalizeRecentWorkspacePath(row.cwd);
if (!normalized || seen.has(normalized)) {
continue;
}
seen.add(normalized);
deduped.push(normalized);
if (deduped.length >= limit) {
break;
}
}
return deduped;
}
private getSessionMessages(sessionId: string): CoworkMessage[] {
const rows = this.getAll<CoworkMessageRow>(`
SELECT id, type, content, metadata, created_at, sequence
FROM cowork_messages
WHERE session_id = ?
ORDER BY
COALESCE(sequence, created_at) ASC,
created_at ASC,
ROWID ASC
`, [sessionId]);
return rows.map(row => ({
id: row.id,
type: row.type as CoworkMessageType,
content: row.content,
timestamp: row.created_at,
metadata: row.metadata ? JSON.parse(row.metadata) : undefined,
}));
}
addMessage(sessionId: string, message: Omit<CoworkMessage, 'id' | 'timestamp'>): CoworkMessage {
const id = uuidv4();
const now = Date.now();
const sequenceRow = this.db.exec(`
SELECT COALESCE(MAX(sequence), 0) + 1 as next_seq
FROM cowork_messages
WHERE session_id = ?
`, [sessionId]);
const sequence = sequenceRow[0]?.values[0]?.[0] as number || 1;
this.db.run(`
INSERT INTO cowork_messages (id, session_id, type, content, metadata, created_at, sequence)
VALUES (?, ?, ?, ?, ?, ?, ?)
`, [
id,
sessionId,
message.type,
message.content,
message.metadata ? JSON.stringify(message.metadata) : null,
now,
sequence,
]);
this.db.run('UPDATE cowork_sessions SET updated_at = ? WHERE id = ?', [now, sessionId]);
this.saveDb();
return {
id,
type: message.type,
content: message.content,
timestamp: now,
metadata: message.metadata,
};
}
/**
* Insert a message before an existing message (by shifting sequences).
* Used for channel-originated sessions where user messages need to appear
* before assistant messages that were created during streaming.
*/
insertMessageBeforeId(sessionId: string, beforeMessageId: string, message: Omit<CoworkMessage, 'id' | 'timestamp'>): CoworkMessage {
const id = uuidv4();
const now = Date.now();
// Get the target message's sequence
const targetRow = this.db.exec(
'SELECT sequence FROM cowork_messages WHERE id = ? AND session_id = ?',
[beforeMessageId, sessionId],
);
const targetSequence = targetRow[0]?.values[0]?.[0] as number | undefined;
if (targetSequence === undefined) {
// Fallback to normal append if the target message is not found
return this.addMessage(sessionId, message);
}
// Shift all messages with sequence >= target up by 1
this.db.run(
'UPDATE cowork_messages SET sequence = sequence + 1 WHERE session_id = ? AND sequence >= ?',
[sessionId, targetSequence],
);
// Insert at the target's original sequence
this.db.run(`
INSERT INTO cowork_messages (id, session_id, type, content, metadata, created_at, sequence)
VALUES (?, ?, ?, ?, ?, ?, ?)
`, [
id,
sessionId,
message.type,
message.content,
message.metadata ? JSON.stringify(message.metadata) : null,
now,
targetSequence,
]);
this.db.run('UPDATE cowork_sessions SET updated_at = ? WHERE id = ?', [now, sessionId]);
this.saveDb();
return {
id,
type: message.type,
content: message.content,
timestamp: now,
metadata: message.metadata,
};
}
/**
* Delete a message from a session.
* Used by reconciliation to remove duplicate or spurious messages.
*/
deleteMessage(sessionId: string, messageId: string): boolean {
this.db.run(
'DELETE FROM cowork_messages WHERE id = ? AND session_id = ?',
[messageId, sessionId],
);
const deleted = (this.db.getRowsModified?.() || 0) > 0;
if (deleted) {
this.saveDb();
}
return deleted;
}
/**
* Replace all user/assistant messages in a session with the given list.
* Tool messages (tool_use, tool_result, system) are preserved in their existing positions.
* Used by history reconciliation to align local state with the authoritative gateway history.
*/
replaceConversationMessages(
sessionId: string,
authoritative: Array<{ role: 'user' | 'assistant'; text: string }>,
): void {
const now = Date.now();
// Delete all existing user/assistant messages for this session
this.db.run(
"DELETE FROM cowork_messages WHERE session_id = ? AND type IN ('user', 'assistant')",
[sessionId],
);
// Re-insert authoritative messages with correct sequence numbers
// First, get the current max sequence from remaining messages (tool_use, tool_result, system)
const seqRow = this.db.exec(
'SELECT COALESCE(MAX(sequence), 0) as max_seq FROM cowork_messages WHERE session_id = ?',
[sessionId],
);
let nextSeq = ((seqRow[0]?.values[0]?.[0] as number) || 0) + 1;
for (const entry of authoritative) {
const id = uuidv4();
this.db.run(`
INSERT INTO cowork_messages (id, session_id, type, content, metadata, created_at, sequence)
VALUES (?, ?, ?, ?, ?, ?, ?)
`, [
id,
sessionId,
entry.role,
entry.text,
JSON.stringify({ isStreaming: false, isFinal: true }),
now,
nextSeq++,
]);
}
this.db.run('UPDATE cowork_sessions SET updated_at = ? WHERE id = ?', [now, sessionId]);
this.saveDb();
}
updateMessage(sessionId: string, messageId: string, updates: { content?: string; metadata?: CoworkMessageMetadata }): void {
const setClauses: string[] = [];
const values: (string | null)[] = [];
if (updates.content !== undefined) {
setClauses.push('content = ?');
values.push(updates.content);
}
if (updates.metadata !== undefined) {
setClauses.push('metadata = ?');
values.push(updates.metadata ? JSON.stringify(updates.metadata) : null);
}
if (setClauses.length === 0) return;
values.push(messageId);
values.push(sessionId);
this.db.run(`
UPDATE cowork_messages
SET ${setClauses.join(', ')}
WHERE id = ? AND session_id = ?
`, values);
this.saveDb();
}
// Config operations
getConfig(): CoworkConfig {
interface ConfigRow {
value: string;