forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkstream-continuity.ts
More file actions
1441 lines (1378 loc) · 57.9 KB
/
Copy pathworkstream-continuity.ts
File metadata and controls
1441 lines (1378 loc) · 57.9 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 { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import type { DesktopActionQueueItem } from "./desktop-action-queue.js";
import { buildDesktopContextPacket, type BuiltDesktopContextPacket } from "./desktop-context-packet.js";
import { generateAgentId } from "./sqlite-store.js";
import { artifactFromRow } from "./kernel-support.js";
import { migrateJournalConversation } from "./conversation-journal.js";
import { resolveSurfaceSession, type ResolveSurfaceSessionResult } from "./surface-session.js";
import type {
AgentArtifact,
AgentStore,
DesktopTaskCandidate,
DesktopTaskCandidateAction,
DesktopTaskCandidateStatus,
NewAgentArtifact,
NewDesktopContextPacket,
} from "./types.js";
const DEFAULT_CONTEXT_TTL_MS = 30 * 60 * 1_000;
const DEFAULT_OPEN_LOOP_TTL_MS = 5 * 60 * 1_000;
const MAX_SUMMARY_CHARS = 8_000;
const MAX_TASK_CHARS = 4_000;
const MAX_EVENT_COUNT = 20;
const MAX_ARTIFACT_HEAD_COUNT = 10;
const MAX_EVIDENCE_REFS = 20;
const MAX_RECEIPT_CHARS = 8_000;
const MAX_CONTINUATION_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
export interface WorkstreamSessionInput {
ownerId: string;
workstreamId: string;
defaultAdapterId?: string;
title?: string | null;
}
export interface WorkstreamEventContext {
eventId: string;
type: string;
summary: string;
occurredAtMs: number;
evidenceRefs?: EvidenceRef[];
sensitivityTier?: ContextSensitivityTier;
redactedSummary?: string;
policyDecision?: "allowed" | "dispatch_created";
dispatchId?: string;
}
export interface WorkstreamArtifactHeadContext {
logicalKey: string;
artifactId: string;
version: number;
displayName?: string | null;
contentHash?: string | null;
evidenceRefs?: EvidenceRef[];
sensitivityTier?: ContextSensitivityTier;
}
export type EvidenceKind =
| "conversation"
| "memory_item"
| "workstream_event"
| "artifact"
| "chat_message"
| "local_screen"
| "external";
export interface EvidenceRef {
kind: EvidenceKind;
id: string;
version?: string;
scope: "canonical" | "device_local";
device_id?: string;
excerpt_hash?: string;
}
export type ContextSensitivityTier = "low" | "private" | "sensitive";
export interface WorkstreamProductContext {
canonicalSummary: string;
redactedCanonicalSummary?: string;
summarySensitivityTier?: ContextSensitivityTier;
latestEventSequence: number;
selectedEvents?: WorkstreamEventContext[];
currentTask?: {
taskId: string;
title: string;
status: string;
dueAtMs?: number | null;
summary?: string | null;
sensitivityTier?: ContextSensitivityTier;
policyDecision?: "allowed" | "dispatch_created";
dispatchId?: string;
} | null;
artifactHeads?: WorkstreamArtifactHeadContext[];
provenance: {
snapshotVersion: string;
fetchedAtMs: number;
source: string;
};
}
export interface PersistWorkstreamContextInput extends WorkstreamSessionInput {
runId?: string | null;
objective: string;
context: WorkstreamProductContext;
ttlMs?: number;
nowMs?: number;
}
export interface PersistWorkstreamArtifactVersionInput extends WorkstreamSessionInput {
logicalKey: string;
evidenceRefs: EvidenceRef[];
sourceArtifactId?: string;
artifact: Omit<NewAgentArtifact, "sessionId">;
nowMs?: number;
}
export interface PersistAuthorizedPreparedArtifactInput extends PersistWorkstreamArtifactVersionInput {
grantId: string;
}
export interface WorkstreamArtifactVersion {
logicalKey: string;
version: number;
artifact: AgentArtifact;
supersedesArtifactId: string | null;
evidenceRefs: EvidenceRef[];
}
export interface WorkstreamContinuityProjection {
agentSessionId: string | null;
artifactVersions: WorkstreamArtifactVersion[];
checkpoint: WorkstreamContinuationCheckpoint | null;
}
export interface WorkstreamContinuationCheckpoint {
checkpointId: string;
ownerId: string;
workstreamId: string;
sourceRuntimeId: string;
canonicalSummary: string;
redactedCanonicalSummary: string;
summarySensitivityTier: ContextSensitivityTier;
currentTask: WorkstreamProductContext["currentTask"];
selectedEvents: WorkstreamEventContext[];
artifactHeads: WorkstreamArtifactHeadContext[];
provenance: WorkstreamProductContext["provenance"];
evidenceRefs: EvidenceRef[];
lastEventSequence: number;
createdAtMs: number;
expiresAtMs: number;
}
export interface CanonicalCandidatePayload {
idempotencyKey: string;
accountGeneration: number;
proposal: {
subject_kind: "task";
proposed_action: "create" | "update" | "complete" | "cancel" | "supersede";
task_id?: string;
task_change: Record<string, unknown>;
capture_confidence: number;
ownership_confidence: number;
goal_id?: string;
workstream_id?: string;
evidence_refs: EvidenceRef[];
source_surface: string;
};
}
export interface CanonicalCandidateReceipt {
candidateId: string;
status: "pending" | "accepted" | "rejected" | "expired";
receipt: Record<string, unknown>;
}
export interface CanonicalCandidateTransport {
createCandidate(payload: CanonicalCandidatePayload): Promise<CanonicalCandidateReceipt>;
}
export interface WorkstreamOpenLoopSnapshot {
ownerId: string;
sourceRuntimeId: string;
deviceScoped: true;
generatedAtMs: number;
expiresAtMs: number;
loops: Array<{
itemKind: DesktopActionQueueItem["kind"];
subjectKind: string;
subjectId: string;
title: string;
reason: string;
workstreamId: string | null;
sourceSessionId: string | null;
sourceRunId: string | null;
}>;
}
export interface TaskSessionMigrationReport {
migratedTaskMappings: number;
copiedTurns: number;
migratedArtifacts: number;
indexedArtifactVersions: number;
repairedArtifactHeads: number;
invalidatedBindingIds: string[];
legacySessionIds: string[];
skippedMappings: number;
compatibilityMappings: Array<{ taskId: string; workstreamId: string; agentSessionId: string }>;
}
function indexLegacyWorkstreamArtifact(
store: AgentStore,
input: {
ownerId: string;
workstreamId: string;
canonicalSessionId: string;
sourceRuntimeId: string;
sourceSessionId: string;
sourceArtifactId: string;
migratedArtifactId: string;
now: number;
},
): { indexed: boolean; repairedHead: boolean } {
const proposedLogicalKey = `legacy-task-artifact:${hash(
`${input.ownerId}:${input.workstreamId}:${input.sourceSessionId}:${input.sourceArtifactId}`,
).slice(0, 32)}`;
const proposedEvidenceRefs: EvidenceRef[] = [{
kind: "artifact",
id: input.sourceArtifactId,
version: "legacy-task-session-migration.v1",
scope: "device_local",
device_id: input.sourceRuntimeId,
}];
const artifact = store.getRow("SELECT * FROM artifacts WHERE artifact_id = ? AND session_id = ?", [
input.migratedArtifactId,
input.canonicalSessionId,
]);
let version = store.getOptionalRow(
`SELECT session_id, logical_key, version, artifact_id, supersedes_artifact_id, evidence_refs_json
FROM workstream_artifact_versions WHERE artifact_id = ?`,
[input.migratedArtifactId],
);
const indexed = !version && store.execute(
`INSERT OR IGNORE INTO workstream_artifact_versions (
session_id, logical_key, version, artifact_id, supersedes_artifact_id,
evidence_refs_json, created_at_ms
) VALUES (?, ?, 1, ?, NULL, ?, ?)`,
[
input.canonicalSessionId,
proposedLogicalKey,
input.migratedArtifactId,
JSON.stringify(proposedEvidenceRefs),
Number(artifact.created_at_ms),
],
) > 0;
version = store.getRow(
`SELECT session_id, logical_key, version, artifact_id, supersedes_artifact_id, evidence_refs_json
FROM workstream_artifact_versions WHERE artifact_id = ?`,
[input.migratedArtifactId],
);
const logicalKey = String(version.logical_key);
const logicalVersion = Number(version.version);
const supersedesArtifactId = nullableText(version.supersedes_artifact_id);
const evidenceRefs = parseEvidenceRefs(String(version.evidence_refs_json));
const metadata = {
...parseLegacyMetadata(String(artifact.metadata_json)),
sourceArtifactId: input.sourceArtifactId,
migratedFromArtifactId: input.sourceArtifactId,
migratedFromSessionId: input.sourceSessionId,
migrationVersion: "legacy-task-session-migration.v1",
workstreamId: input.workstreamId,
logicalKey,
logicalVersion,
supersedesArtifactId,
evidenceRefs,
};
store.execute("UPDATE artifacts SET metadata_json = ? WHERE artifact_id = ?", [
JSON.stringify(metadata),
input.migratedArtifactId,
]);
const currentHead = store.getOptionalRow(
`SELECT version, artifact_id FROM workstream_artifact_heads
WHERE session_id = ? AND logical_key = ?`,
[version.session_id, version.logical_key],
);
const repairedHead = !currentHead
|| Number(currentHead.version) < logicalVersion
|| (Number(currentHead.version) === logicalVersion && String(currentHead.artifact_id) !== String(version.artifact_id));
if (repairedHead) {
store.execute(
`INSERT INTO workstream_artifact_heads (session_id, logical_key, artifact_id, version, updated_at_ms)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(session_id, logical_key) DO UPDATE SET
artifact_id = excluded.artifact_id,
version = excluded.version,
updated_at_ms = excluded.updated_at_ms
WHERE excluded.version > workstream_artifact_heads.version
OR (excluded.version = workstream_artifact_heads.version
AND excluded.artifact_id != workstream_artifact_heads.artifact_id)`,
[version.session_id, version.logical_key, version.artifact_id, version.version, input.now],
);
}
if (indexed) {
store.appendEvent({
sessionId: input.canonicalSessionId,
type: "workstream.artifact_version_migrated",
visibility: "internal",
payloadJson: JSON.stringify({
artifactId: input.migratedArtifactId,
sourceArtifactId: input.sourceArtifactId,
logicalKey,
version: logicalVersion,
evidenceRefs,
}),
createdAtMs: input.now,
});
}
const deliveryId = `artifactDelivery:workstream-migration:${input.workstreamId}:${input.migratedArtifactId}`;
if (!store.getOptionalRow("SELECT delivery_id FROM desktop_artifact_deliveries WHERE delivery_id = ?", [deliveryId])) {
const storedHash = nullableText(artifact.content_hash);
const contentHash = storedHash && storedHash.length >= 16
? storedHash
: hashReadableArtifactFile(String(artifact.uri));
store.insertDesktopArtifactDelivery({
deliveryId,
artifactId: input.migratedArtifactId,
ownerId: input.ownerId,
sourceSessionId: input.canonicalSessionId,
intendedSurface: "canonical_workstream",
targetKind: "task_chat",
targetRef: input.workstreamId,
contentHash,
deliveryStatus: contentHash ? "pending" : "cancelled",
errorJson: contentHash ? null : JSON.stringify({
code: "local_only_artifact",
message: "Migrated artifact has no content hash",
}),
receiptJson: JSON.stringify({
kind: "artifact_descriptor",
sourceArtifactId: input.sourceArtifactId,
logicalKey,
artifactKind: String(artifact.kind),
uri: String(artifact.uri),
contentHash,
sourceRunId: null,
evidenceRefs,
}),
});
}
return { indexed, repairedHead };
}
function hashReadableArtifactFile(uri: string): string | null {
if (!uri.startsWith("file://")) return null;
try {
return `sha256:${createHash("sha256").update(readFileSync(fileURLToPath(uri))).digest("hex")}`;
} catch {
return null;
}
}
function parseLegacyMetadata(json: string | undefined): Record<string, unknown> {
if (!json) return {};
try {
const value = JSON.parse(json) as unknown;
if (value && !Array.isArray(value) && typeof value === "object") return value as Record<string, unknown>;
return { legacyMetadata: value };
} catch {
return {};
}
}
export function workstreamSurfaceRef(workstreamId: string) {
const id = requiredText(workstreamId, "workstreamId");
return { surfaceKind: "workstream", externalRefKind: "workstream", externalRefId: id } as const;
}
export function resolveWorkstreamSession(
store: AgentStore,
input: WorkstreamSessionInput,
nowMs: () => number = Date.now,
): ResolveSurfaceSessionResult {
return resolveSurfaceSession(
store,
{
ownerId: requiredText(input.ownerId, "ownerId"),
surfaceRef: workstreamSurfaceRef(input.workstreamId),
defaultAdapterId: input.defaultAdapterId,
title: input.title,
},
nowMs,
);
}
export function persistWorkstreamContextPacket(
store: AgentStore,
input: PersistWorkstreamContextInput,
): BuiltDesktopContextPacket {
const now = input.nowMs ?? Date.now();
const resolved = resolveWorkstreamSession(store, input, () => now);
const context = minimizeProductContext(input.context);
validateSensitiveWorkstreamContext(store, input.ownerId, context);
const built = buildDesktopContextPacket({
ownerId: input.ownerId,
sessionId: resolved.agentSessionId,
runId: input.runId ?? undefined,
surfaceKind: "workstream",
objective: input.objective,
retentionClass: "ephemeral",
ttlMs: input.ttlMs ?? DEFAULT_CONTEXT_TTL_MS,
nowMs: now,
selectedToolBundles: ["desktop.context.local_read"],
snippets: [
snippet(
"canonical-summary",
"canonical_summary",
{ workstreamId: input.workstreamId, ...context.provenance },
context.canonicalSummary,
context.redactedCanonicalSummary,
context.summarySensitivityTier,
),
...(context.currentTask
? [snippet(
"current-task",
"current_task",
{ taskId: context.currentTask.taskId, ...context.provenance },
JSON.stringify(context.currentTask),
JSON.stringify({ taskId: context.currentTask.taskId, status: context.currentTask.status, dueAtMs: context.currentTask.dueAtMs ?? null }),
context.currentTask.sensitivityTier ?? "private",
context.currentTask.policyDecision,
context.currentTask.dispatchId,
)]
: []),
...context.selectedEvents.map((event) =>
snippet(
`event-${event.eventId}`,
"selected_workstream_event",
{ eventId: event.eventId, evidenceRefs: event.evidenceRefs ?? [] },
JSON.stringify(event),
event.redactedSummary ?? (event.sensitivityTier === "low" ? event.summary : "[private workstream event]"),
event.sensitivityTier ?? "private",
event.policyDecision,
event.dispatchId,
),
),
...context.artifactHeads.map((head) =>
snippet(
`artifact-${head.artifactId}`,
"artifact_head",
{ artifactId: head.artifactId, evidenceRefs: head.evidenceRefs ?? [] },
JSON.stringify(head),
JSON.stringify({ logicalKey: head.logicalKey, artifactId: head.artifactId, version: head.version }),
head.sensitivityTier ?? "private",
),
),
],
});
store.withTransaction(() => {
store.insertDesktopContextPacket({
...(built.packet as unknown as NewDesktopContextPacket),
packetJson: JSON.stringify(built.packet.packetJson),
redactedPreviewJson: JSON.stringify(built.packet.redactedPreviewJson),
});
for (const accessLog of built.accessLogs) store.insertDesktopContextAccessLog(accessLog);
});
return built;
}
export function persistAuthorizedPreparedArtifact(
store: AgentStore,
input: PersistAuthorizedPreparedArtifactInput,
): WorkstreamArtifactVersion {
const session = resolveWorkstreamSession(store, input);
const now = input.nowMs ?? Date.now();
const grant = store.getOptionalRow(
`SELECT g.grant_id, g.session_id, g.capability, g.operation, g.resource_pattern,
g.effect, g.expires_at_ms, g.revoked_at_ms, s.owner_id
FROM grants g
JOIN sessions s ON s.session_id = g.session_id
WHERE g.grant_id = ?`,
[input.grantId],
);
if (!grant || grant.owner_id !== input.ownerId) {
throw new Error("Prepared artifact grant was not found for owner");
}
if (
grant.session_id !== session.agentSessionId
|| grant.effect !== "allow"
|| grant.capability !== "desktop.workstream.artifact.prepare"
|| grant.operation !== "prepare_artifact"
|| grant.resource_pattern !== `workstream:${input.workstreamId}`
|| grant.revoked_at_ms != null
|| typeof grant.expires_at_ms !== "number"
|| grant.expires_at_ms <= now
) {
throw new Error("Prepared artifact grant is invalid, expired, or out of scope");
}
return persistWorkstreamArtifactVersion(store, input);
}
export function persistWorkstreamArtifactVersion(
store: AgentStore,
input: PersistWorkstreamArtifactVersionInput,
): WorkstreamArtifactVersion {
const now = input.nowMs ?? Date.now();
const logicalKey = requiredText(input.logicalKey, "logicalKey");
const evidenceRefs = boundedEvidenceRefs(input.evidenceRefs, MAX_EVIDENCE_REFS);
if (evidenceRefs.length === 0) throw new Error("Workstream artifact versions require cited evidence");
return store.withTransaction(() => {
const resolved = resolveWorkstreamSession(store, input, () => now);
const sourceArtifactId = input.sourceArtifactId?.trim();
if (sourceArtifactId) {
const existing = store.getOptionalRow(
`SELECT v.version, v.supersedes_artifact_id, v.evidence_refs_json, a.*
FROM workstream_artifact_versions v
JOIN artifacts a ON a.artifact_id = v.artifact_id
WHERE v.session_id = ? AND v.logical_key = ?
AND json_extract(a.metadata_json, '$.sourceArtifactId') = ?
ORDER BY v.version DESC LIMIT 1`,
[resolved.agentSessionId, logicalKey, sourceArtifactId],
);
if (existing) {
return {
logicalKey,
version: Number(existing.version),
artifact: artifactFromRow(existing),
supersedesArtifactId: nullableText(existing.supersedes_artifact_id),
evidenceRefs: parseEvidenceRefs(String(existing.evidence_refs_json)),
};
}
}
const executionScope = resolveArtifactExecutionScope(
store,
resolved.agentSessionId,
input.artifact.runId ?? null,
input.artifact.attemptId ?? null,
);
const prior = store.getOptionalRow(
`SELECT h.artifact_id, h.version
FROM workstream_artifact_heads h
WHERE h.session_id = ? AND h.logical_key = ?`,
[resolved.agentSessionId, logicalKey],
);
const version = prior ? Number(prior.version) + 1 : 1;
const supersedesArtifactId = prior ? String(prior.artifact_id) : null;
const artifact = store.insertArtifact({
...input.artifact,
sessionId: resolved.agentSessionId,
runId: executionScope.runId,
attemptId: executionScope.attemptId,
createdAtMs: input.artifact.createdAtMs ?? now,
metadataJson: JSON.stringify({
...parseObject(input.artifact.metadataJson),
...(sourceArtifactId ? { sourceArtifactId } : {}),
workstreamId: input.workstreamId,
logicalKey,
logicalVersion: version,
supersedesArtifactId,
evidenceRefs,
}),
});
store.execute(
`INSERT INTO workstream_artifact_versions (
session_id, logical_key, version, artifact_id, supersedes_artifact_id,
evidence_refs_json, created_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?)`,
[resolved.agentSessionId, logicalKey, version, artifact.artifactId, supersedesArtifactId, JSON.stringify(evidenceRefs), now],
);
store.execute(
`INSERT INTO workstream_artifact_heads (session_id, logical_key, artifact_id, version, updated_at_ms)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(session_id, logical_key) DO UPDATE SET
artifact_id = excluded.artifact_id,
version = excluded.version,
updated_at_ms = excluded.updated_at_ms`,
[resolved.agentSessionId, logicalKey, artifact.artifactId, version, now],
);
store.appendEvent({
sessionId: resolved.agentSessionId,
runId: artifact.runId,
attemptId: artifact.attemptId,
type: "workstream.artifact_version_persisted",
payloadJson: JSON.stringify({ artifactId: artifact.artifactId, logicalKey, version, supersedesArtifactId, evidenceRefs }),
createdAtMs: now,
});
return { logicalKey, version, artifact, supersedesArtifactId, evidenceRefs };
});
}
export function projectWorkstreamContinuity(
store: AgentStore,
input: { ownerId: string; workstreamId: string; nowMs?: number },
): WorkstreamContinuityProjection {
const mapping = store.getOptionalRow(
`SELECT agent_session_id FROM surface_conversations
WHERE owner_id = ? AND surface_kind = 'workstream'
AND external_ref_kind = 'workstream' AND external_ref_id = ?`,
[input.ownerId, input.workstreamId],
);
if (!mapping) return { agentSessionId: null, artifactVersions: [], checkpoint: null };
const agentSessionId = String(mapping.agent_session_id);
const artifactVersions = store.allRows(
`SELECT v.logical_key, v.version, v.supersedes_artifact_id, v.evidence_refs_json, a.*
FROM workstream_artifact_versions v
JOIN artifacts a ON a.artifact_id = v.artifact_id
WHERE v.session_id = ? ORDER BY v.logical_key ASC, v.version ASC`,
[agentSessionId],
).map((row) => ({
logicalKey: String(row.logical_key),
version: Number(row.version),
artifact: artifactFromRow(row),
supersedesArtifactId: nullableText(row.supersedes_artifact_id),
evidenceRefs: parseEvidenceRefs(String(row.evidence_refs_json)),
}));
return {
agentSessionId,
artifactVersions,
checkpoint: readWorkstreamContinuationCheckpoint(store, {
ownerId: input.ownerId,
workstreamId: input.workstreamId,
nowMs: input.nowMs,
}),
};
}
export function exportWorkstreamContinuationCheckpoint(
store: AgentStore,
input: WorkstreamSessionInput & {
sourceRuntimeId: string;
context: WorkstreamProductContext;
ttlMs: number;
nowMs?: number;
exportDispatchId?: string;
},
): WorkstreamContinuationCheckpoint {
const now = input.nowMs ?? Date.now();
if (!Number.isFinite(input.ttlMs) || input.ttlMs <= 0 || input.ttlMs > MAX_CONTINUATION_TTL_MS) {
throw new Error("Continuation checkpoint TTL must be positive and at most seven days");
}
const resolved = resolveWorkstreamSession(store, input, () => now);
const context = minimizeProductContext(input.context);
validateSensitiveWorkstreamContext(store, input.ownerId, context);
const requiresExportApproval =
contextEvidenceRefs(context).some((ref) => ref.scope === "device_local") ||
contextHasSensitiveContent(context);
if (requiresExportApproval) {
assertApprovedContextDispatch(
store,
input.ownerId,
input.exportDispatchId,
"export_workstream_continuation",
);
}
const exportContext = targetSafeCheckpointContext(context);
const lastEventSequence = context.latestEventSequence;
const checkpoint: WorkstreamContinuationCheckpoint = {
checkpointId: `wcp_${hash(`${input.ownerId}:${input.workstreamId}:${input.sourceRuntimeId}:${lastEventSequence}:${now}`).slice(0, 24)}`,
ownerId: input.ownerId,
workstreamId: input.workstreamId,
sourceRuntimeId: requiredText(input.sourceRuntimeId, "sourceRuntimeId"),
canonicalSummary: exportContext.canonicalSummary,
redactedCanonicalSummary: exportContext.redactedCanonicalSummary,
summarySensitivityTier: exportContext.summarySensitivityTier,
currentTask: exportContext.currentTask,
selectedEvents: exportContext.selectedEvents,
artifactHeads: exportContext.artifactHeads,
provenance: exportContext.provenance,
evidenceRefs: boundedEvidenceRefs(
[...exportContext.selectedEvents.flatMap((event) => event.evidenceRefs ?? []), ...exportContext.artifactHeads.flatMap((head) => head.evidenceRefs ?? [])],
MAX_EVIDENCE_REFS,
),
lastEventSequence,
createdAtMs: now,
expiresAtMs: now + input.ttlMs,
};
upsertCheckpoint(store, checkpoint, now);
const stored = store.getRow(
`SELECT checkpoint_json FROM workstream_continuation_checkpoints
WHERE owner_id = ? AND workstream_id = ? AND source_runtime_id = ?`,
[checkpoint.ownerId, checkpoint.workstreamId, checkpoint.sourceRuntimeId],
);
return normalizeCheckpoint(JSON.parse(String(stored.checkpoint_json)) as WorkstreamContinuationCheckpoint);
}
export function importWorkstreamContinuationCheckpoint(
store: AgentStore,
checkpoint: WorkstreamContinuationCheckpoint,
input: { targetRuntimeId: string; nowMs?: number },
): ResolveSurfaceSessionResult {
const now = input.nowMs ?? Date.now();
const normalized = normalizeCheckpoint(checkpoint);
if (normalized.expiresAtMs <= now) throw new Error("Continuation checkpoint has expired");
if (normalized.expiresAtMs - normalized.createdAtMs > MAX_CONTINUATION_TTL_MS) {
throw new Error("Continuation checkpoint exceeds the maximum TTL");
}
requiredText(input.targetRuntimeId, "targetRuntimeId");
return store.withTransaction(() => {
const resolved = resolveWorkstreamSession(store, normalized, () => now);
upsertCheckpoint(store, normalized, now);
const effective = readWorkstreamContinuationCheckpoint(store, {
ownerId: normalized.ownerId,
workstreamId: normalized.workstreamId,
nowMs: now,
}) ?? normalized;
persistWorkstreamContextPacket(store, {
ownerId: effective.ownerId,
workstreamId: effective.workstreamId,
objective: "Resume imported workstream context",
context: {
canonicalSummary: effective.canonicalSummary,
redactedCanonicalSummary: effective.redactedCanonicalSummary,
summarySensitivityTier: effective.summarySensitivityTier,
latestEventSequence: effective.lastEventSequence,
currentTask: effective.currentTask,
selectedEvents: effective.selectedEvents,
artifactHeads: effective.artifactHeads,
provenance: effective.provenance,
},
ttlMs: effective.expiresAtMs - now,
nowMs: now,
});
store.appendEvent({
sessionId: resolved.agentSessionId,
type: "workstream.continuation_imported",
visibility: "internal",
payloadJson: JSON.stringify({
checkpointId: effective.checkpointId,
sourceRuntimeId: effective.sourceRuntimeId,
targetRuntimeId: input.targetRuntimeId,
lastEventSequence: effective.lastEventSequence,
}),
createdAtMs: now,
});
return resolved;
});
}
export async function deliverDesktopTaskCandidate(
store: AgentStore,
input: { ownerId: string; candidateId: string; transport: CanonicalCandidateTransport; nowMs?: () => number },
): Promise<DesktopTaskCandidate> {
const nowMs = input.nowMs ?? Date.now;
const current = readTaskCandidate(store, input.ownerId, input.candidateId);
if (current.deliveryStatus === "delivered") return current;
if (current.status !== "pending") throw new Error(`Only pending local Candidates can be delivered; got ${current.status}`);
if (!["pending", "failed"].includes(current.deliveryStatus)) {
throw new Error(`Candidate delivery is not eligible from ${current.deliveryStatus}`);
}
if (current.generationReconciled !== 1) throw new Error("Candidate account generation must be reconciled before delivery");
const payload = canonicalCandidatePayload(current);
store.execute(
`UPDATE desktop_task_candidates
SET delivery_status = 'delivering', delivery_attempt_count = delivery_attempt_count + 1,
last_delivery_error_json = NULL, updated_at_ms = ?
WHERE candidate_id = ? AND owner_id = ? AND delivery_status != 'delivered'`,
[nowMs(), current.candidateId, current.ownerId],
);
try {
const receipt = normalizeCandidateReceipt(await input.transport.createCandidate(payload));
const boundedReceipt = boundedJson(receipt.receipt, MAX_RECEIPT_CHARS);
return store.withTransaction(() => {
const deliveredAtMs = nowMs();
store.execute(
`UPDATE desktop_task_candidates
SET status = ?, delivery_status = 'delivered', backend_candidate_id = ?,
backend_receipt_json = ?, backend_resolution_status = ?,
last_delivery_error_json = NULL, delivered_at_ms = ?, updated_at_ms = ?,
resolved_at_ms = ?
WHERE candidate_id = ? AND owner_id = ?`,
[
localCandidateStatus(receipt.status),
receipt.candidateId,
JSON.stringify(boundedReceipt),
receipt.status,
deliveredAtMs,
deliveredAtMs,
receipt.status === "pending" ? null : deliveredAtMs,
current.candidateId,
current.ownerId,
],
);
if (current.sourceSessionId) {
store.appendEvent({
sessionId: current.sourceSessionId,
runId: current.sourceRunId,
type: "task_candidate.delivered",
payloadJson: JSON.stringify({
localCandidateId: current.candidateId,
backendCandidateId: receipt.candidateId,
backendStatus: receipt.status,
receiptHash: `sha256:${hash(JSON.stringify(boundedReceipt))}`,
}),
createdAtMs: deliveredAtMs,
});
}
return readTaskCandidate(store, current.ownerId, current.candidateId);
});
} catch (error) {
const failedAtMs = nowMs();
store.execute(
`UPDATE desktop_task_candidates
SET delivery_status = 'failed', last_delivery_error_json = ?, updated_at_ms = ?
WHERE candidate_id = ? AND owner_id = ? AND delivery_status != 'delivered'`,
[JSON.stringify({ message: error instanceof Error ? error.message.slice(0, 500) : "Candidate delivery failed" }), failedAtMs, current.candidateId, current.ownerId],
);
throw error;
}
}
export function projectCanonicalCandidateResolution(
store: AgentStore,
input: {
ownerId: string;
backendCandidateId: string;
status: Exclude<CanonicalCandidateReceipt["status"], "pending">;
receipt?: Record<string, unknown>;
nowMs?: number;
},
): DesktopTaskCandidate {
const now = input.nowMs ?? Date.now();
const row = store.getRow(
`SELECT candidate_id, source_session_id, source_run_id, status
FROM desktop_task_candidates WHERE owner_id = ? AND backend_candidate_id = ?`,
[input.ownerId, input.backendCandidateId],
);
const currentStatus = String(row.status) as DesktopTaskCandidateStatus;
if (currentStatus !== "forwarded" && currentStatus !== input.status) {
throw new Error(`Cannot replace terminal Candidate status ${currentStatus} with ${input.status}`);
}
return store.withTransaction(() => {
store.execute(
`UPDATE desktop_task_candidates
SET status = ?, backend_resolution_status = ?, backend_resolution_receipt_json = COALESCE(?, backend_resolution_receipt_json),
resolved_at_ms = ?, updated_at_ms = ?
WHERE owner_id = ? AND backend_candidate_id = ?`,
[input.status, input.status, input.receipt ? JSON.stringify(boundedJson(input.receipt, MAX_RECEIPT_CHARS)) : null, now, now, input.ownerId, input.backendCandidateId],
);
if (row.source_session_id) {
store.appendEvent({
sessionId: String(row.source_session_id),
runId: nullableText(row.source_run_id),
type: "task_candidate.resolution_projected",
payloadJson: JSON.stringify({ backendCandidateId: input.backendCandidateId, status: input.status }),
createdAtMs: now,
});
}
return readTaskCandidate(store, input.ownerId, String(row.candidate_id));
});
}
export function reconcileLegacyTaskCandidateOutbox(
store: AgentStore,
input: { ownerId: string; accountGeneration: number; candidateIds?: string[]; nowMs?: number },
): { eligibleCandidateIds: string[]; terminalCandidateIds: string[] } {
if (!Number.isInteger(input.accountGeneration) || input.accountGeneration < 0) {
throw new Error("accountGeneration must be a non-negative integer");
}
const rows = store.allRows(
`SELECT candidate_id, status FROM desktop_task_candidates
WHERE owner_id = ? AND generation_reconciled = 0
${input.candidateIds?.length ? `AND candidate_id IN (${input.candidateIds.map(() => "?").join(",")})` : ""}`,
[input.ownerId, ...(input.candidateIds ?? [])],
);
const eligibleCandidateIds = rows.filter((row) => row.status === "pending").map((row) => String(row.candidate_id));
const terminalCandidateIds = rows.filter((row) => row.status !== "pending").map((row) => String(row.candidate_id));
const now = input.nowMs ?? Date.now();
return store.withTransaction(() => {
for (const candidateId of eligibleCandidateIds) {
store.execute(
`UPDATE desktop_task_candidates SET account_generation = ?, generation_reconciled = 1,
delivery_status = 'pending', updated_at_ms = ?
WHERE owner_id = ? AND candidate_id = ? AND status = 'pending' AND generation_reconciled = 0`,
[input.accountGeneration, now, input.ownerId, candidateId],
);
}
for (const candidateId of terminalCandidateIds) {
store.execute(
`UPDATE desktop_task_candidates SET account_generation = ?, generation_reconciled = 1,
delivery_status = 'blocked', updated_at_ms = ?
WHERE owner_id = ? AND candidate_id = ? AND generation_reconciled = 0`,
[input.accountGeneration, now, input.ownerId, candidateId],
);
}
return { eligibleCandidateIds, terminalCandidateIds };
});
}
export function readWorkstreamContinuationCheckpoint(
store: AgentStore,
input: { ownerId: string; workstreamId: string; nowMs?: number },
): WorkstreamContinuationCheckpoint | null {
const row = store.getOptionalRow(
`SELECT checkpoint_json FROM workstream_continuation_checkpoints
WHERE owner_id = ? AND workstream_id = ? AND expires_at_ms > ?
ORDER BY last_event_sequence DESC, updated_at_ms DESC LIMIT 1`,
[input.ownerId, input.workstreamId, input.nowMs ?? Date.now()],
);
return row
? normalizeCheckpoint(JSON.parse(String(row.checkpoint_json)) as WorkstreamContinuationCheckpoint)
: null;
}
export function buildWorkstreamOpenLoopSnapshot(input: {
ownerId: string;
sourceRuntimeId: string;
actionQueue: readonly DesktopActionQueueItem[];
sessionWorkstreamIds?: ReadonlyMap<string, string>;
ttlMs?: number;
nowMs?: number;
}): WorkstreamOpenLoopSnapshot {
const now = input.nowMs ?? Date.now();
const ttl = input.ttlMs ?? DEFAULT_OPEN_LOOP_TTL_MS;
if (!Number.isFinite(ttl) || ttl <= 0) throw new Error("Open-loop snapshot TTL must be positive");
return {
ownerId: input.ownerId,
sourceRuntimeId: requiredText(input.sourceRuntimeId, "sourceRuntimeId"),
deviceScoped: true,
generatedAtMs: now,
expiresAtMs: now + ttl,
loops: input.actionQueue
.filter((item) => ["dispatch", "failed_run", "artifact_delivery", "stale_run", "candidate_review"].includes(item.kind))
.map((item) => ({
itemKind: item.kind,
subjectKind: item.subjectKind,
subjectId: item.subjectId,
title: item.title,
reason: item.reason,
workstreamId: item.sourceSessionId ? input.sessionWorkstreamIds?.get(item.sourceSessionId) ?? null : null,
sourceSessionId: item.sourceSessionId ?? null,
sourceRunId: item.sourceRunId ?? null,
})),
};
}
export function migrateTaskSessionsToWorkstreams(
store: AgentStore,
input: {
ownerId: string;
sourceRuntimeId: string;
mappings: Array<{ taskId: string; workstreamId: string }>;
nowMs?: number;
},
): TaskSessionMigrationReport {
const now = input.nowMs ?? Date.now();
return store.withTransaction(() => {
const report: TaskSessionMigrationReport = {
migratedTaskMappings: 0,
copiedTurns: 0,
migratedArtifacts: 0,
indexedArtifactVersions: 0,
repairedArtifactHeads: 0,
invalidatedBindingIds: [],
legacySessionIds: [],
skippedMappings: 0,
compatibilityMappings: [],
};
for (const mapping of input.mappings) {
const taskId = requiredText(mapping.taskId, "taskId");
const workstreamId = requiredText(mapping.workstreamId, "workstreamId");
const canonical = resolveWorkstreamSession(store, { ownerId: input.ownerId, workstreamId }, () => now);
const repairArtifacts = store.allRows(
`SELECT * FROM artifacts
WHERE session_id = ? AND json_type(metadata_json, '$.migratedFromArtifactId') = 'text'`,
[canonical.agentSessionId],
);
for (const artifact of repairArtifacts) {
const metadata = parseObject(String(artifact.metadata_json));
const sourceArtifactId = String(metadata.migratedFromArtifactId);
const sourceSessionId = String(metadata.migratedFromSessionId ?? "unknown-legacy-session");
const result = indexLegacyWorkstreamArtifact(store, {
ownerId: input.ownerId,
workstreamId,
canonicalSessionId: canonical.agentSessionId,
sourceRuntimeId: input.sourceRuntimeId,
sourceSessionId,
sourceArtifactId,
migratedArtifactId: String(artifact.artifact_id),
now,
});
report.indexedArtifactVersions += Number(result.indexed);
report.repairedArtifactHeads += Number(result.repairedHead);
}
const taskRows = store.allRows(
`SELECT conversation_id, agent_session_id, surface_kind, external_ref_kind, external_ref_id
FROM surface_conversations
WHERE owner_id = ? AND external_ref_id = ?
AND (external_ref_kind = 'task' OR surface_kind = 'task_chat')`,
[input.ownerId, taskId],
);
if (taskRows.length === 0) {
report.skippedMappings += 1;
continue;
}
for (const row of taskRows) {
const sourceConversationId = String(row.conversation_id);
const sourceSessionId = String(row.agent_session_id);
if (sourceConversationId === canonical.conversationId && sourceSessionId === canonical.agentSessionId) {