forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite-store.ts
More file actions
3951 lines (3743 loc) · 156 KB
/
Copy pathsqlite-store.ts
File metadata and controls
3951 lines (3743 loc) · 156 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 { chmodSync, lstatSync, mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { DatabaseSync, type SQLInputValue, type SQLOutputValue } from "node:sqlite";
import {
backendTombstoneCode,
backendTurnPayload,
backendTurnPayloadHash,
} from "./backend-turn-projection.js";
import { conversationTurnFromRow } from "./conversation-turns.js";
import type {
AdapterBinding,
AgentArtifact,
AgentGrant,
DesktopArtifactDelivery,
DesktopAttentionOverride,
DesktopContextAccessLog,
DesktopContextPacket,
DesktopCoordinatorDispatch,
DesktopMemoryCandidate,
DesktopTaskCandidate,
AgentEvent,
AgentIdKind,
AgentRun,
AgentSession,
AgentStore,
NewAdapterBinding,
NewAgentEvent,
NewAgentArtifact,
NewAgentGrant,
ConversationTurn,
NewAgentRun,
NewAgentSession,
NewConversationTurn,
NewSurfaceConversation,
SurfaceConversation,
NewDesktopArtifactDelivery,
NewDesktopAttentionOverride,
NewDesktopContextAccessLog,
NewDesktopContextPacket,
NewDesktopCoordinatorDispatch,
NewDesktopMemoryCandidate,
NewDesktopTaskCandidate,
NewRunAttempt,
RunAttempt,
StartupReconciliationResult,
} from "./types.js";
import { providerBoundaryForAdapter } from "./execution-policy.js";
const DATABASE_FILENAME = "omi-agentd.sqlite3";
const PHASE_1_MIGRATION_VERSION = 1;
const ARTIFACT_LIFECYCLE_MIGRATION_VERSION = 2;
const DESKTOP_CONTEXT_PACKETS_MIGRATION_VERSION = 3;
const DESKTOP_DISPATCHES_MIGRATION_VERSION = 4;
const DESKTOP_ARTIFACT_DELIVERIES_MIGRATION_VERSION = 5;
const DESKTOP_CANDIDATES_MIGRATION_VERSION = 6;
const DESKTOP_CONTEXT_ACCESS_LOG_MIGRATION_VERSION = 7;
const DESKTOP_ATTENTION_OVERRIDES_MIGRATION_VERSION = 8;
const ACTIVE_ATTEMPT_AUTHORITY_MIGRATION_VERSION = 9;
const SURFACE_CONVERSATIONS_MIGRATION_VERSION = 10;
const CONVERSATION_TURNS_MIGRATION_VERSION = 11;
const BINDING_TURN_DELIVERY_MIGRATION_VERSION = 12;
const WORKSTREAM_CONTINUITY_MIGRATION_VERSION = 13;
const SESSION_EXECUTION_POLICY_MIGRATION_VERSION = 14;
const CONVERSATION_JOURNAL_MIGRATION_VERSION = 15;
const SESSION_EXECUTION_PROFILE_MIGRATION_VERSION = 16;
const CONVERSATION_JOURNAL_SEQUENCE_MIGRATION_VERSION = 17;
const TOOL_INVOCATION_LEDGER_MIGRATION_VERSION = 18;
const KERNEL_CONTEXT_AUTHORITY_MIGRATION_VERSION = 19;
const JOURNAL_GENERATION_BASE_MIGRATION_VERSION = 20;
const OWNER_CONTEXT_SNAPSHOT_MIGRATION_VERSION = 21;
const BACKEND_CONVERSATION_DELETE_OUTBOX_MIGRATION_VERSION = 22;
const BACKEND_RECONCILE_STATE_MIGRATION_VERSION = 23;
const CLEARED_BACKEND_TURN_CLAIMS_MIGRATION_VERSION = 24;
const CONTEXT_SOURCE_SURFACE_SCOPE_MIGRATION_VERSION = 25;
const BACKEND_RECONCILE_CURSOR_MIGRATION_VERSION = 26;
const JOURNAL_PRODUCING_ATTEMPT_MIGRATION_VERSION = 27;
const CHAT_FIRST_DEFERRAL_OUTBOX_MIGRATION_VERSION = 28;
const CHAT_FIRST_MATERIALIZATION_RECEIPTS_MIGRATION_VERSION = 29;
const CHAT_FIRST_COLD_START_SEQUENCE_RECEIPTS_MIGRATION_VERSION = 30;
const LOCAL_ONLY_JOURNAL_DELIVERY_MIGRATION_VERSION = 31;
const CHAT_FIRST_COLD_START_SEQUENCE_RECEIPTS_OWNER_SCOPE_MIGRATION_VERSION = 32;
const CONVERSATION_TURN_REVISION_TURN_ID_INDEX_MIGRATION_VERSION = 33;
const ACTIVE_ATTEMPT_STATUSES = ["queued", "starting", "running", "waiting_input", "waiting_approval", "cancelling"] as const;
const TERMINAL_ATTEMPT_STATUSES = ["succeeded", "failed", "cancelled", "timed_out", "orphaned"] as const;
type DatabaseFactory = new (path: string) => Pick<DatabaseSync, "exec" | "prepare" | "close" | "isTransaction">;
type Row = Record<string, SQLOutputValue>;
export interface SqliteAgentStoreOptions {
stateDir?: string;
databasePath?: string;
reconcileOnOpen?: boolean;
nowMs?: () => number;
databaseFactory?: DatabaseFactory;
}
export interface NodeSqliteProbeOptions {
databaseFactory?: DatabaseFactory;
}
const phase1SchemaSql = `
CREATE TABLE sessions (
session_id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL,
agent_definition_id TEXT NOT NULL DEFAULT 'omi.generalist@1',
title TEXT,
status TEXT NOT NULL CHECK (status IN ('open', 'archived', 'closed')),
surface_kind TEXT NOT NULL,
external_ref_kind TEXT,
external_ref_id TEXT,
-- TODO(desktop-agent-platonic-gap-closure G6): drop legacy_client_scope + legacy_session_key two desktop releases after platonic ships.
legacy_client_scope TEXT,
legacy_session_key TEXT,
default_adapter_id TEXT NOT NULL,
default_cwd TEXT,
model_profile TEXT,
metadata_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(metadata_json)),
created_at_ms INTEGER NOT NULL,
updated_at_ms INTEGER NOT NULL,
last_activity_at_ms INTEGER NOT NULL,
CHECK ((external_ref_kind IS NULL) = (external_ref_id IS NULL)),
CHECK ((legacy_client_scope IS NULL) = (legacy_session_key IS NULL))
) STRICT;
CREATE UNIQUE INDEX sessions_external_ref_uq
ON sessions(owner_id, external_ref_kind, external_ref_id)
WHERE external_ref_kind IS NOT NULL;
CREATE UNIQUE INDEX sessions_legacy_alias_uq
ON sessions(owner_id, legacy_client_scope, legacy_session_key)
WHERE legacy_client_scope IS NOT NULL;
CREATE INDEX sessions_recent_idx
ON sessions(owner_id, last_activity_at_ms DESC);
CREATE TABLE runs (
run_id TEXT PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
parent_run_id TEXT REFERENCES runs(run_id) ON DELETE SET NULL,
client_id TEXT NOT NULL,
request_id TEXT NOT NULL,
idempotency_key TEXT,
status TEXT NOT NULL CHECK (status IN (
'queued', 'starting', 'running', 'waiting_input', 'waiting_approval',
'cancelling', 'succeeded', 'failed', 'cancelled', 'timed_out', 'orphaned'
)),
mode TEXT NOT NULL CHECK (mode IN ('ask', 'act')),
input_json TEXT NOT NULL CHECK (json_valid(input_json)),
system_prompt_hash TEXT,
model_profile TEXT,
requested_model_id TEXT,
cwd TEXT,
final_text TEXT,
result_json TEXT CHECK (result_json IS NULL OR json_valid(result_json)),
error_code TEXT,
error_message TEXT,
input_tokens INTEGER,
output_tokens INTEGER,
cache_read_tokens INTEGER,
cache_write_tokens INTEGER,
cost_usd REAL,
created_at_ms INTEGER NOT NULL,
started_at_ms INTEGER,
completed_at_ms INTEGER,
updated_at_ms INTEGER NOT NULL,
UNIQUE(client_id, request_id)
) STRICT;
CREATE UNIQUE INDEX runs_idempotency_uq
ON runs(session_id, idempotency_key)
WHERE idempotency_key IS NOT NULL;
CREATE INDEX runs_session_recent_idx
ON runs(session_id, created_at_ms DESC);
CREATE INDEX runs_status_idx
ON runs(status, created_at_ms);
CREATE TABLE adapter_bindings (
binding_id TEXT PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
adapter_id TEXT NOT NULL,
binding_generation INTEGER NOT NULL CHECK (binding_generation > 0),
adapter_native_session_id TEXT,
adapter_instance_id TEXT,
resume_fidelity TEXT NOT NULL CHECK (resume_fidelity IN ('native', 'reconstructed', 'none')),
status TEXT NOT NULL CHECK (status IN ('active', 'stale', 'invalid', 'closed')),
cwd TEXT,
model_id TEXT,
system_prompt_hash TEXT,
metadata_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(metadata_json)),
created_at_ms INTEGER NOT NULL,
updated_at_ms INTEGER NOT NULL,
last_used_at_ms INTEGER,
invalidated_at_ms INTEGER,
UNIQUE(session_id, adapter_id, binding_generation)
) STRICT;
CREATE UNIQUE INDEX adapter_bindings_one_active_uq
ON adapter_bindings(session_id, adapter_id)
WHERE status = 'active';
CREATE UNIQUE INDEX adapter_bindings_native_uq
ON adapter_bindings(adapter_id, adapter_native_session_id)
WHERE adapter_native_session_id IS NOT NULL AND status != 'closed';
CREATE INDEX adapter_bindings_session_idx
ON adapter_bindings(session_id, adapter_id, binding_generation DESC);
CREATE TABLE run_attempts (
attempt_id TEXT PRIMARY KEY,
run_id TEXT NOT NULL REFERENCES runs(run_id) ON DELETE CASCADE,
attempt_no INTEGER NOT NULL CHECK (attempt_no > 0),
status TEXT NOT NULL CHECK (status IN (
'queued', 'starting', 'running', 'waiting_input', 'waiting_approval',
'cancelling', 'succeeded', 'failed', 'cancelled', 'timed_out', 'orphaned'
)),
adapter_id TEXT NOT NULL,
adapter_instance_id TEXT NOT NULL,
runtime_node_id TEXT NOT NULL DEFAULT 'desktop-local',
binding_id TEXT REFERENCES adapter_bindings(binding_id) ON DELETE SET NULL,
adapter_native_run_id TEXT,
resume_from_attempt_id TEXT REFERENCES run_attempts(attempt_id) ON DELETE SET NULL,
checkpoint_artifact_id TEXT,
retry_reason TEXT,
retryable INTEGER NOT NULL DEFAULT 0 CHECK (retryable IN (0, 1)),
cancellation_requested_at_ms INTEGER,
cancellation_dispatched_at_ms INTEGER,
cancellation_acknowledged_at_ms INTEGER,
started_at_ms INTEGER,
completed_at_ms INTEGER,
error_code TEXT,
error_message TEXT,
metadata_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(metadata_json)),
created_at_ms INTEGER NOT NULL,
updated_at_ms INTEGER NOT NULL,
UNIQUE(run_id, attempt_no)
) STRICT;
CREATE INDEX run_attempts_run_idx
ON run_attempts(run_id, attempt_no DESC);
CREATE INDEX run_attempts_active_idx
ON run_attempts(status, created_at_ms);
CREATE UNIQUE INDEX run_attempts_one_active_per_run_uq
ON run_attempts(run_id)
WHERE status IN ('queued', 'starting', 'running', 'waiting_input', 'waiting_approval', 'cancelling');
CREATE TABLE events (
event_seq INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL UNIQUE,
session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
run_id TEXT REFERENCES runs(run_id) ON DELETE CASCADE,
attempt_id TEXT REFERENCES run_attempts(attempt_id) ON DELETE CASCADE,
type TEXT NOT NULL,
retention_class TEXT NOT NULL DEFAULT 'core' CHECK (retention_class IN ('core', 'transient')),
visibility TEXT NOT NULL DEFAULT 'ui' CHECK (visibility IN ('ui', 'internal')),
payload_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(payload_json)),
created_at_ms INTEGER NOT NULL
) STRICT;
CREATE INDEX events_session_cursor_idx
ON events(session_id, event_seq);
CREATE INDEX events_run_cursor_idx
ON events(run_id, event_seq)
WHERE run_id IS NOT NULL;
CREATE INDEX events_attempt_cursor_idx
ON events(attempt_id, event_seq)
WHERE attempt_id IS NOT NULL;
CREATE TABLE artifacts (
artifact_id TEXT PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
run_id TEXT REFERENCES runs(run_id) ON DELETE SET NULL,
attempt_id TEXT REFERENCES run_attempts(attempt_id) ON DELETE SET NULL,
kind TEXT NOT NULL,
role TEXT NOT NULL CHECK (role IN ('input', 'result', 'checkpoint', 'tool_output', 'log', 'other')),
uri TEXT NOT NULL,
display_name TEXT,
mime_type TEXT,
content_hash TEXT,
size_bytes INTEGER,
metadata_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(metadata_json)),
created_at_ms INTEGER NOT NULL
) STRICT;
CREATE INDEX artifacts_run_idx
ON artifacts(run_id, created_at_ms)
WHERE run_id IS NOT NULL;
CREATE TABLE delegations (
delegation_id TEXT PRIMARY KEY,
parent_session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
parent_run_id TEXT NOT NULL REFERENCES runs(run_id) ON DELETE CASCADE,
child_session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
child_run_id TEXT NOT NULL REFERENCES runs(run_id) ON DELETE CASCADE,
mode TEXT NOT NULL CHECK (mode IN ('call', 'spawn', 'continue')),
status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'succeeded', 'failed', 'cancelled')),
objective TEXT NOT NULL,
request_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(request_json)),
result_artifact_id TEXT REFERENCES artifacts(artifact_id) ON DELETE SET NULL,
created_at_ms INTEGER NOT NULL,
completed_at_ms INTEGER,
UNIQUE(child_run_id)
) STRICT;
CREATE INDEX delegations_parent_idx
ON delegations(parent_run_id, created_at_ms);
CREATE TABLE grants (
grant_id TEXT PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
run_id TEXT REFERENCES runs(run_id) ON DELETE CASCADE,
capability TEXT NOT NULL,
operation TEXT NOT NULL,
resource_pattern TEXT NOT NULL,
effect TEXT NOT NULL CHECK (effect IN ('allow', 'deny')),
-- TODO(desktop-agent-platonic-gap-closure G6): drop legacy_default from CHECK after ship+2 releases post-platonic.
source TEXT NOT NULL CHECK (source IN ('legacy_default', 'policy', 'user', 'system')),
constraints_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(constraints_json)),
created_at_ms INTEGER NOT NULL,
expires_at_ms INTEGER,
revoked_at_ms INTEGER
) STRICT;
CREATE INDEX grants_lookup_idx
ON grants(session_id, run_id, capability, operation, created_at_ms DESC);
`;
export function generateAgentId(kind: AgentIdKind): string {
const prefixByKind: Record<AgentIdKind, string> = {
session: "ses",
conversation: "conv",
run: "run",
attempt: "att",
event: "evt",
binding: "bind",
artifact: "art",
delegation: "del",
grant: "grant",
contextPacket: "ctx",
dispatch: "disp",
artifactDelivery: "delivery",
memoryCandidate: "memcand",
taskCandidate: "taskcand",
contextAccess: "access",
turn: "turn",
};
return `${prefixByKind[kind]}_${randomUUID().replaceAll("-", "")}`;
}
export function databasePathForStateDir(stateDir: string): string {
return join(stateDir, DATABASE_FILENAME);
}
export function probeNodeSqliteRuntime(options: NodeSqliteProbeOptions = {}): void {
const Database = options.databaseFactory ?? DatabaseSync;
let db: Pick<DatabaseSync, "exec" | "prepare" | "close" | "isTransaction"> | undefined;
try {
db = new Database(":memory:");
applyConnectionPragmas(db);
createSchemaMigrationsTable(db);
runPhase1Migration(db, Date.now());
runArtifactLifecycleMigration(db, Date.now());
runDesktopContextPacketsMigration(db, Date.now());
runDesktopDispatchesMigration(db, Date.now());
runDesktopArtifactDeliveriesMigration(db, Date.now());
runDesktopCandidatesMigration(db, Date.now());
runDesktopContextAccessLogMigration(db, Date.now());
runDesktopAttentionOverridesMigration(db, Date.now());
runActiveAttemptAuthorityMigration(db, Date.now());
runSurfaceConversationsMigration(db, Date.now());
runConversationTurnsMigration(db, Date.now());
runBindingTurnDeliveryMigration(db, Date.now());
runWorkstreamContinuityMigration(db, Date.now());
runSessionExecutionPolicyMigration(db, Date.now());
runConversationJournalMigration(db, Date.now());
runSessionExecutionProfileMigration(db, Date.now());
runConversationJournalSequenceMigration(db, Date.now());
runToolInvocationLedgerMigration(db, Date.now());
runKernelContextAuthorityMigration(db, Date.now());
runJournalGenerationBaseMigration(db, Date.now());
runOwnerContextSnapshotMigration(db, Date.now());
runBackendConversationDeleteOutboxMigration(db, Date.now());
runBackendReconcileStateMigration(db, Date.now());
runClearedBackendTurnClaimsMigration(db, Date.now());
runContextSourceSurfaceScopeMigration(db, Date.now());
runBackendReconcileCursorMigration(db, Date.now());
runJournalProducingAttemptMigration(db, Date.now());
runChatFirstDeferralOutboxMigration(db, Date.now());
runChatFirstMaterializationReceiptsMigration(db, Date.now());
runChatFirstColdStartSequenceReceiptsMigration(db, Date.now());
runLocalOnlyJournalDeliveryMigration(db, Date.now());
runTransaction(db, () => {
db?.prepare("INSERT INTO sessions (session_id, owner_id, status, surface_kind, default_adapter_id, created_at_ms, updated_at_ms, last_activity_at_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(
"ses_probe",
"owner_probe",
"open",
"probe",
"acp",
1,
1,
1,
);
db?.prepare("INSERT INTO events (event_id, session_id, type, payload_json, created_at_ms) VALUES (?, ?, ?, ?, ?)").run(
"evt_probe",
"ses_probe",
"probe.ok",
"{}",
1,
);
});
} catch (error) {
throw new Error(`Bundled Node runtime does not support required node:sqlite AgentStore features: ${messageFrom(error)}`);
} finally {
db?.close();
}
}
export class SqliteAgentStore implements AgentStore {
private readonly db: DatabaseSync;
private readonly nowMs: () => number;
private transactionDepth = 0;
constructor(options: SqliteAgentStoreOptions = {}) {
const databasePath = options.databasePath ?? databasePathForStateDir(requiredStateDir(options.stateDir));
// The Swift JIT source projection preflight requires the agent state and
// SQLite files to be owner-only because the database can contain prompt
// material. The default process umask on a developer Mac is commonly
// 022, which otherwise leaves new directories at 0755 and SQLite files at
// 0644. Set a private umask before SQLite creates its WAL/SHM sidecars,
// and repair the existing directory/file modes on every open.
process.umask(0o077);
const isInMemory = databasePath === ":memory:";
if (!isInMemory) {
const stateDirectory = dirname(databasePath);
mkdirSync(stateDirectory, { recursive: true, mode: 0o700 });
hardenOwnerOnlyDirectory(stateDirectory);
rejectSymlink(databasePath, "database");
}
const Database = options.databaseFactory ?? DatabaseSync;
this.db = new Database(databasePath) as DatabaseSync;
if (!isInMemory) {
hardenOwnerOnlyFile(databasePath, "database");
for (const suffix of ["-wal", "-shm"]) {
const sidecarPath = `${databasePath}${suffix}`;
if (pathExists(sidecarPath)) hardenOwnerOnlyFile(sidecarPath, `database ${suffix} sidecar`);
}
}
this.nowMs = options.nowMs ?? Date.now;
applyConnectionPragmas(this.db);
this.migrate();
if (options.reconcileOnOpen ?? true) {
this.reconcileStartup();
}
}
close(): void {
this.db.close();
}
migrate(): void {
createSchemaMigrationsTable(this.db);
if (!this.hasMigration(PHASE_1_MIGRATION_VERSION)) {
runPhase1Migration(this.db, this.nowMs());
}
if (!this.hasMigration(ARTIFACT_LIFECYCLE_MIGRATION_VERSION)) {
runArtifactLifecycleMigration(this.db, this.nowMs());
}
if (!this.hasMigration(DESKTOP_CONTEXT_PACKETS_MIGRATION_VERSION)) {
runDesktopContextPacketsMigration(this.db, this.nowMs());
}
if (!this.hasMigration(DESKTOP_DISPATCHES_MIGRATION_VERSION)) {
runDesktopDispatchesMigration(this.db, this.nowMs());
}
if (!this.hasMigration(DESKTOP_ARTIFACT_DELIVERIES_MIGRATION_VERSION)) {
runDesktopArtifactDeliveriesMigration(this.db, this.nowMs());
}
if (!this.hasMigration(DESKTOP_CANDIDATES_MIGRATION_VERSION)) {
runDesktopCandidatesMigration(this.db, this.nowMs());
}
if (!this.hasMigration(DESKTOP_CONTEXT_ACCESS_LOG_MIGRATION_VERSION)) {
runDesktopContextAccessLogMigration(this.db, this.nowMs());
}
if (!this.hasMigration(DESKTOP_ATTENTION_OVERRIDES_MIGRATION_VERSION)) {
runDesktopAttentionOverridesMigration(this.db, this.nowMs());
}
if (!this.hasMigration(ACTIVE_ATTEMPT_AUTHORITY_MIGRATION_VERSION)) {
runActiveAttemptAuthorityMigration(this.db, this.nowMs());
}
if (!this.hasMigration(SURFACE_CONVERSATIONS_MIGRATION_VERSION)) {
runSurfaceConversationsMigration(this.db, this.nowMs());
}
if (!this.hasMigration(CONVERSATION_TURNS_MIGRATION_VERSION)) {
runConversationTurnsMigration(this.db, this.nowMs());
}
if (!this.hasMigration(BINDING_TURN_DELIVERY_MIGRATION_VERSION)) {
runBindingTurnDeliveryMigration(this.db, this.nowMs());
}
if (!this.hasMigration(WORKSTREAM_CONTINUITY_MIGRATION_VERSION)) {
runWorkstreamContinuityMigration(this.db, this.nowMs());
}
if (!this.hasMigration(SESSION_EXECUTION_POLICY_MIGRATION_VERSION)) {
runSessionExecutionPolicyMigration(this.db, this.nowMs());
}
if (!this.hasMigration(CONVERSATION_JOURNAL_MIGRATION_VERSION)) {
runConversationJournalMigration(this.db, this.nowMs());
}
if (!this.hasMigration(SESSION_EXECUTION_PROFILE_MIGRATION_VERSION)) {
runSessionExecutionProfileMigration(this.db, this.nowMs());
}
if (!this.hasMigration(CONVERSATION_JOURNAL_SEQUENCE_MIGRATION_VERSION)) {
runConversationJournalSequenceMigration(this.db, this.nowMs());
}
if (!this.hasMigration(TOOL_INVOCATION_LEDGER_MIGRATION_VERSION)) {
runToolInvocationLedgerMigration(this.db, this.nowMs());
}
if (!this.hasMigration(KERNEL_CONTEXT_AUTHORITY_MIGRATION_VERSION)) {
runKernelContextAuthorityMigration(this.db, this.nowMs());
}
if (!this.hasMigration(JOURNAL_GENERATION_BASE_MIGRATION_VERSION)) {
runJournalGenerationBaseMigration(this.db, this.nowMs());
}
if (!this.hasMigration(OWNER_CONTEXT_SNAPSHOT_MIGRATION_VERSION)) {
runOwnerContextSnapshotMigration(this.db, this.nowMs());
}
if (!this.hasMigration(BACKEND_CONVERSATION_DELETE_OUTBOX_MIGRATION_VERSION)) {
runBackendConversationDeleteOutboxMigration(this.db, this.nowMs());
}
if (!this.hasMigration(BACKEND_RECONCILE_STATE_MIGRATION_VERSION)) {
runBackendReconcileStateMigration(this.db, this.nowMs());
}
if (!this.hasMigration(CLEARED_BACKEND_TURN_CLAIMS_MIGRATION_VERSION)) {
runClearedBackendTurnClaimsMigration(this.db, this.nowMs());
}
if (!this.hasMigration(CONTEXT_SOURCE_SURFACE_SCOPE_MIGRATION_VERSION)) {
runContextSourceSurfaceScopeMigration(this.db, this.nowMs());
}
if (!this.hasMigration(BACKEND_RECONCILE_CURSOR_MIGRATION_VERSION)) {
runBackendReconcileCursorMigration(this.db, this.nowMs());
}
if (!this.hasMigration(JOURNAL_PRODUCING_ATTEMPT_MIGRATION_VERSION)) {
runJournalProducingAttemptMigration(this.db, this.nowMs());
}
// Origin/main used migration version 28 for local-only delivery cleanup.
// A database upgraded from that build has the version row but not the
// Chat-first deferral table, so use the schema as the authoritative
// compatibility signal and let the Chat-first migration backfill it.
if (
!this.hasMigration(CHAT_FIRST_DEFERRAL_OUTBOX_MIGRATION_VERSION)
|| !this.hasTable("chat_first_deferral_outbox")
) {
runChatFirstDeferralOutboxMigration(this.db, this.nowMs());
}
if (!this.hasMigration(CHAT_FIRST_MATERIALIZATION_RECEIPTS_MIGRATION_VERSION)) {
runChatFirstMaterializationReceiptsMigration(this.db, this.nowMs());
}
if (!this.hasMigration(CHAT_FIRST_COLD_START_SEQUENCE_RECEIPTS_MIGRATION_VERSION)) {
runChatFirstColdStartSequenceReceiptsMigration(this.db, this.nowMs());
}
if (!this.hasMigration(LOCAL_ONLY_JOURNAL_DELIVERY_MIGRATION_VERSION)) {
runLocalOnlyJournalDeliveryMigration(this.db, this.nowMs());
}
if (!this.hasMigration(CHAT_FIRST_COLD_START_SEQUENCE_RECEIPTS_OWNER_SCOPE_MIGRATION_VERSION)) {
runChatFirstColdStartSequenceReceiptsOwnerScopeMigration(this.db, this.nowMs());
}
if (!this.hasMigration(CONVERSATION_TURN_REVISION_TURN_ID_INDEX_MIGRATION_VERSION)) {
runConversationTurnRevisionTurnIdIndexMigration(this.db, this.nowMs());
}
}
withTransaction<T>(work: () => T): T {
// Track nesting depth ourselves rather than trusting db.isTransaction: the
// bundled agent runtime does not reliably report an open transaction, so a
// nested call that issued its own BEGIN would fail with "cannot start a
// transaction within a transaction" and break every agent operation.
if (this.transactionDepth > 0) {
this.transactionDepth += 1;
try {
return work();
} finally {
this.transactionDepth -= 1;
}
}
this.transactionDepth += 1;
this.db.exec("BEGIN IMMEDIATE");
try {
const result = work();
this.db.exec("COMMIT");
return result;
} catch (error) {
this.db.exec("ROLLBACK");
throw error;
} finally {
this.transactionDepth -= 1;
}
}
reconcileStartup(): StartupReconciliationResult {
return this.withTransaction(() => {
const now = this.nowMs();
const repairedSessionProfileIds = repairMissingSessionExecutionProfiles(this.db, now);
const repairedProfileReferences = repairDowngradeWindowExecutionProfileReferences(this.db);
const repairedLegacyJournalTurnIds = repairDowngradeWindowJournalRows(this.db, now);
const activeAttempts = this.allRows(
`SELECT attempt_id, run_id FROM run_attempts WHERE status IN (${placeholders(ACTIVE_ATTEMPT_STATUSES.length)})`,
[...ACTIVE_ATTEMPT_STATUSES],
);
const staleBindings = this.allRows(
"SELECT binding_id, session_id FROM adapter_bindings WHERE status = ? AND resume_fidelity = ?",
["active", "none"],
);
const failedPreparedToolInvocationIds = this.allRows(
"SELECT invocation_id FROM tool_invocation_ledger WHERE status = 'prepared'",
).map((row) => text(row.invocation_id));
const outcomeUnknownToolInvocationIds = this.allRows(
"SELECT invocation_id FROM tool_invocation_ledger WHERE status = 'dispatched'",
).map((row) => text(row.invocation_id));
this.db.prepare(
`UPDATE tool_invocation_ledger
SET status = 'failed', error_code = 'daemon_restart_before_dispatch',
completed_at_ms = ?, updated_at_ms = ?
WHERE status = 'prepared'`,
).run(now, now);
this.db.prepare(
`UPDATE tool_invocation_ledger
SET status = 'outcome_unknown', error_code = 'daemon_restart_after_dispatch',
completed_at_ms = ?, updated_at_ms = ?
WHERE status = 'dispatched'`,
).run(now, now);
// The Phase 1 schema keeps run_attempts.adapter_instance_id NOT NULL;
// an empty string is the cleared process-local worker marker after restart.
this.db.prepare(`UPDATE run_attempts SET status = ?, adapter_instance_id = ?, completed_at_ms = COALESCE(completed_at_ms, ?), updated_at_ms = ? WHERE status IN (${placeholders(ACTIVE_ATTEMPT_STATUSES.length)})`).run(
"orphaned",
"",
now,
now,
...ACTIVE_ATTEMPT_STATUSES,
);
const orphanedRunIds = this.allRows(
`SELECT r.run_id
FROM runs r
WHERE r.status IN (${placeholders(ACTIVE_ATTEMPT_STATUSES.length)})
AND NOT EXISTS (
SELECT 1 FROM run_attempts a
WHERE a.run_id = r.run_id
AND a.status NOT IN (${placeholders(TERMINAL_ATTEMPT_STATUSES.length)})
)`,
[...ACTIVE_ATTEMPT_STATUSES, ...TERMINAL_ATTEMPT_STATUSES],
).map((row) => text(row.run_id));
for (const runId of orphanedRunIds) {
this.db.prepare("UPDATE runs SET status = ?, completed_at_ms = COALESCE(completed_at_ms, ?), updated_at_ms = ? WHERE run_id = ?").run(
"orphaned",
now,
now,
runId,
);
}
const clearedAttemptInstanceIds = Number(this.db.prepare("UPDATE run_attempts SET adapter_instance_id = ? WHERE adapter_instance_id != ?").run("", "").changes);
const clearedBindingInstanceIds = Number(this.db.prepare("UPDATE adapter_bindings SET adapter_instance_id = NULL WHERE adapter_instance_id IS NOT NULL").run().changes);
for (const binding of staleBindings) {
this.db.prepare("UPDATE adapter_bindings SET status = ?, adapter_instance_id = NULL, invalidated_at_ms = COALESCE(invalidated_at_ms, ?), updated_at_ms = ? WHERE binding_id = ?").run(
"stale",
now,
now,
binding.binding_id,
);
}
const eventIds: string[] = [];
for (const attempt of activeAttempts) {
eventIds.push(this.appendReconciliationEvent({
sessionId: sessionIdForRun(this.db, text(attempt.run_id)),
runId: text(attempt.run_id),
attemptId: text(attempt.attempt_id),
type: "attempt.orphaned",
payload: { attemptId: attempt.attempt_id, reason: "daemon_startup_reconciliation" },
createdAtMs: now,
}));
}
for (const runId of orphanedRunIds) {
eventIds.push(this.appendReconciliationEvent({
sessionId: sessionIdForRun(this.db, runId),
runId,
attemptId: null,
type: "run.orphaned",
payload: { runId, reason: "daemon_startup_reconciliation" },
createdAtMs: now,
}));
}
for (const binding of staleBindings) {
eventIds.push(this.appendReconciliationEvent({
sessionId: text(binding.session_id),
runId: null,
attemptId: null,
type: "binding.stale",
payload: { bindingId: binding.binding_id, reason: "non_resumable_binding_after_restart" },
createdAtMs: now,
}));
}
const reconciledJournalTurns = reconcileNonterminalJournalRows(this.db, now);
const repairedBackendTurnOutboxes = reconcileBackendTurnOutboxRows(this.db, now);
for (const repair of [...reconciledJournalTurns, ...repairedBackendTurnOutboxes]) {
const surface = this.getOptionalRow(
`SELECT agent_session_id FROM surface_conversations
WHERE conversation_id = ? ORDER BY last_active_at_ms DESC LIMIT 1`,
[repair.conversationId],
);
if (!surface) continue;
eventIds.push(this.appendReconciliationEvent({
sessionId: text(surface.agent_session_id),
runId: repair.producingRunId,
attemptId: null,
type: "journal.turn_reconciled",
payload: { turnId: repair.turnId, code: repair.code },
createdAtMs: now,
}));
}
const expiredContextPacketIds = this.allRows(
"SELECT packet_id FROM desktop_context_packets WHERE expires_at_ms IS NOT NULL AND expires_at_ms <= ?",
[now],
).map((row) => text(row.packet_id));
if (expiredContextPacketIds.length > 0) {
this.db.prepare(
"DELETE FROM desktop_context_packets WHERE expires_at_ms IS NOT NULL AND expires_at_ms <= ?",
).run(now);
}
const expiredContinuationCheckpointIds = this.allRows(
"SELECT checkpoint_id FROM workstream_continuation_checkpoints WHERE expires_at_ms <= ?",
[now],
).map((row) => text(row.checkpoint_id));
if (expiredContinuationCheckpointIds.length > 0) {
this.db.prepare("DELETE FROM workstream_continuation_checkpoints WHERE expires_at_ms <= ?").run(now);
}
this.db.prepare(
`UPDATE desktop_dispatches
SET status = ?, resolved_at_ms = COALESCE(resolved_at_ms, ?), resolved_by = COALESCE(resolved_by, ?), resolution_json = COALESCE(resolution_json, ?)
WHERE status = ?
AND expires_at_ms IS NOT NULL
AND expires_at_ms <= ?`,
).run("expired", now, "daemon_startup_reconciliation", JSON.stringify({ reason: "daemon_startup_reconciliation" }), "pending", now);
const failedArtifactDeliveryIds = this.allRows(
"SELECT delivery_id FROM desktop_artifact_deliveries WHERE delivery_status = ?",
["retrying"],
).map((row) => text(row.delivery_id));
if (failedArtifactDeliveryIds.length > 0) {
this.db.prepare(
`UPDATE desktop_artifact_deliveries
SET delivery_status = ?, updated_at_ms = ?, error_json = json_set(COALESCE(error_json, '{}'), '$.reason', ?)
WHERE delivery_status = ?`,
).run("failed", now, "daemon_startup_reconciliation", "retrying");
}
const failedTaskCandidateDeliveryIds = this.allRows(
"SELECT candidate_id FROM desktop_task_candidates WHERE delivery_status = ?",
["delivering"],
).map((row) => text(row.candidate_id));
if (failedTaskCandidateDeliveryIds.length > 0) {
this.db.prepare(
`UPDATE desktop_task_candidates
SET delivery_status = 'failed', updated_at_ms = ?,
last_delivery_error_json = json_object('reason', 'daemon_startup_reconciliation')
WHERE delivery_status = 'delivering'`,
).run(now);
}
const requeuedBackendTurnOutboxIds = this.allRows(
"SELECT turn_id FROM backend_turn_outbox WHERE status = 'delivering'",
).map((row) => text(row.turn_id));
if (requeuedBackendTurnOutboxIds.length > 0) {
this.db.prepare(
`UPDATE backend_turn_outbox
SET status = 'retrying', available_at_ms = ?, lease_expires_at_ms = NULL,
last_error_code = 'daemon_restart', updated_at_ms = ?
WHERE status = 'delivering'`,
).run(now, now);
}
const requeuedBackendConversationDeleteIds = this.allRows(
"SELECT operation_id FROM backend_conversation_delete_outbox WHERE status = 'delivering'",
).map((row) => text(row.operation_id));
if (requeuedBackendConversationDeleteIds.length > 0) {
this.db.prepare(
`UPDATE backend_conversation_delete_outbox
SET status = 'retrying', available_at_ms = ?, lease_expires_at_ms = NULL,
last_error_code = 'daemon_restart', updated_at_ms = ?
WHERE status = 'delivering'`,
).run(now, now);
}
const requeuedChatFirstDeferralIds = this.allRows(
"SELECT continuity_key FROM chat_first_deferral_outbox WHERE status = 'delivering'",
).map((row) => text(row.continuity_key));
if (requeuedChatFirstDeferralIds.length > 0) {
this.db.prepare(
`UPDATE chat_first_deferral_outbox
SET status = 'retrying', available_at_ms = 0, lease_expires_at_ms = NULL,
last_error_code = 'daemon_restart', updated_at_ms = ?
WHERE status = 'delivering'`,
).run(now);
}
this.db.prepare(
`UPDATE backend_reconcile_state
SET in_flight_id = NULL, page_cursor = NULL, page_count = 0,
candidate_frontier_remote_id = NULL, status = 'idle',
last_error_code = CASE WHEN status = 'fetching' THEN 'daemon_restart' ELSE last_error_code END,
updated_at_ms = ?
WHERE status = 'fetching'`,
).run(now);
const recoveryDispatchIds: string[] = [];
const orphanedDelegatedRuns = this.allRows(
`SELECT r.run_id, r.session_id, s.owner_id
FROM runs r
JOIN sessions s ON s.session_id = r.session_id
WHERE r.status = ?
AND r.parent_run_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM desktop_dispatches d
WHERE d.kind = 'failure_recovery'
AND d.status != 'expired'
AND d.source_run_id = r.run_id
)`,
["orphaned"],
);
for (const run of orphanedDelegatedRuns) {
const dispatch = this.insertDesktopDispatch({
ownerId: text(run.owner_id),
kind: "failure_recovery",
priority: 80,
status: "pending",
title: "Agent run needs recovery",
decisionPrompt: "A delegated local agent run was interrupted by a daemon restart. Choose whether to inspect, retry, or dismiss it.",
recommendedDefault: "inspect",
sourceSessionId: text(run.session_id),
sourceRunId: text(run.run_id),
payloadJson: JSON.stringify({ reason: "daemon_startup_reconciliation" }),
createdAtMs: now,
});
recoveryDispatchIds.push(dispatch.dispatchId);
const delegations = this.allRows(
`SELECT delegation_id, parent_session_id, parent_run_id, status
FROM delegations
WHERE child_run_id = ? AND status IN ('pending', 'running')`,
[text(run.run_id)],
);
for (const delegation of delegations) {
this.db.prepare("UPDATE delegations SET status = ?, completed_at_ms = COALESCE(completed_at_ms, ?) WHERE delegation_id = ?").run(
"failed",
now,
text(delegation.delegation_id),
);
eventIds.push(this.appendReconciliationEvent({
sessionId: text(delegation.parent_session_id),
runId: text(delegation.parent_run_id),
attemptId: null,
type: "delegation.recovery_required",
payload: {
delegationId: text(delegation.delegation_id),
childRunId: text(run.run_id),
dispatchId: dispatch.dispatchId,
reason: "child_run_orphaned_after_restart",
},
createdAtMs: now,
}));
}
}
return {
orphanedAttemptIds: activeAttempts.map((row) => text(row.attempt_id)),
orphanedRunIds,
staleBindingIds: staleBindings.map((row) => text(row.binding_id)),
expiredContextPacketIds,
expiredContinuationCheckpointIds,
failedArtifactDeliveryIds,
failedTaskCandidateDeliveryIds,
requeuedBackendTurnOutboxIds,
requeuedBackendConversationDeleteIds,
failedPreparedToolInvocationIds,
outcomeUnknownToolInvocationIds,
repairedSessionProfileIds,
repairedRunProfileReferenceIds: repairedProfileReferences.runIds,
repairedAttemptProfileReferenceIds: repairedProfileReferences.attemptIds,
repairedBindingProfileReferenceIds: repairedProfileReferences.bindingIds,
repairedLegacyJournalTurnIds,
reconciledJournalTurnIds: reconciledJournalTurns.map((repair) => repair.turnId),
repairedBackendTurnOutboxIds: repairedBackendTurnOutboxes.map((repair) => repair.turnId),
recoveryDispatchIds,
clearedAttemptInstanceIds,
clearedBindingInstanceIds,
eventIds,
};
});
}
insertSurfaceConversation(input: NewSurfaceConversation): SurfaceConversation {
this.db.prepare(
`INSERT INTO surface_conversations (
owner_id, surface_kind, external_ref_kind, external_ref_id,
conversation_id, agent_session_id, created_at_ms, last_active_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
input.ownerId,
input.surfaceKind,
input.externalRefKind,
input.externalRefId,
input.conversationId,
input.agentSessionId,
input.createdAtMs,
input.lastActiveAtMs,
);
return input;
}
insertConversationTurn(input: NewConversationTurn): ConversationTurn {
const turnId = input.turnId ?? generateAgentId("turn");
const status = input.status ?? "completed";
const turn: ConversationTurn = {
conversationId: input.conversationId,
turnId,
turnSeq: input.turnSeq ?? 0,
producerId: input.producerId ?? `legacy:${turnId}`,
payloadHash: input.payloadHash ?? "legacy",
role: input.role,
surfaceKind: input.surfaceKind,
content: input.content,
origin: input.origin ?? "legacy",
status,
contentBlocks: input.contentBlocks ?? (input.content.length > 0
? [{ type: "text", id: `${turnId}:text`, text: input.content }]
: []),
resources: input.resources ?? [],
producingRunId: input.producingRunId ?? null,
producingAttemptId: input.producingAttemptId ?? null,
remoteId: input.remoteId ?? null,
createdAtMs: input.createdAtMs,
updatedAtMs: input.updatedAtMs ?? input.createdAtMs,
completedAtMs: input.completedAtMs
?? (status === "completed" || status === "failed" ? input.createdAtMs : null),
metadataJson: input.metadataJson ?? "{}",
};
this.db.prepare(
`INSERT INTO conversation_turns (
conversation_id, turn_id, turn_seq, producer_id, payload_hash,
role, surface_kind, content, created_at_ms, metadata_json,
origin, status, content_blocks_json, resources_json, producing_run_id,
producing_attempt_id, remote_id, updated_at_ms, completed_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
turn.conversationId,
turn.turnId,
turn.turnSeq,
turn.producerId,
turn.payloadHash,
turn.role,
turn.surfaceKind,
turn.content,
turn.createdAtMs,
turn.metadataJson,
turn.origin,
turn.status,
JSON.stringify(turn.contentBlocks),
JSON.stringify(turn.resources),
turn.producingRunId,
turn.producingAttemptId,
turn.remoteId,
turn.updatedAtMs,
turn.completedAtMs,
);
return turn;
}
insertSession(input: NewAgentSession): AgentSession {
const now = this.nowMs();
const session: AgentSession = {
sessionId: input.sessionId ?? generateAgentId("session"),
ownerId: input.ownerId,
agentDefinitionId: input.agentDefinitionId ?? "omi.generalist@1",
title: input.title ?? null,
status: input.status ?? "open",
surfaceKind: input.surfaceKind,
executionRole: input.executionRole ?? "coordinator",
providerBoundary: input.providerBoundary ?? providerBoundaryForAdapter(input.defaultAdapterId),
externalRefKind: input.externalRefKind ?? null,
externalRefId: input.externalRefId ?? null,
defaultAdapterId: input.defaultAdapterId,