File size: 38,626 Bytes
fae625a
 
 
 
 
2df2e7e
fae625a
 
2df2e7e
 
 
 
 
fae625a
 
77374bd
2df2e7e
fae625a
 
 
 
 
 
 
 
2df2e7e
 
 
 
 
 
 
fae625a
 
 
 
 
 
 
 
 
2df2e7e
 
 
fae625a
2df2e7e
 
fae625a
 
 
 
2df2e7e
 
 
 
fae625a
 
 
 
 
 
 
 
 
 
 
2df2e7e
 
fae625a
2df2e7e
 
 
fae625a
 
 
 
2df2e7e
 
 
 
 
 
fae625a
 
 
 
 
 
 
2df2e7e
 
fae625a
c9a836e
 
2df2e7e
fae625a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77374bd
2df2e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fae625a
 
 
 
2df2e7e
 
fae625a
 
 
 
 
 
2df2e7e
fae625a
 
 
 
 
2df2e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fae625a
 
2df2e7e
 
fae625a
2df2e7e
 
 
fae625a
 
 
 
 
 
 
2df2e7e
 
 
 
 
 
 
 
 
 
 
 
77374bd
 
2df2e7e
77374bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df2e7e
 
 
 
 
77374bd
 
 
 
 
 
 
 
 
 
 
 
2df2e7e
 
 
77374bd
 
 
 
 
 
2df2e7e
77374bd
 
2df2e7e
 
 
 
 
 
 
 
77374bd
2df2e7e
 
77374bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df2e7e
 
 
 
 
 
 
77374bd
 
 
 
 
 
 
 
2df2e7e
 
 
fae625a
 
2df2e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fae625a
2df2e7e
fae625a
 
 
 
2df2e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fae625a
 
 
2df2e7e
fae625a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df2e7e
 
 
 
fae625a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df2e7e
fae625a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df2e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77374bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df2e7e
77374bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df2e7e
77374bd
 
 
 
 
 
 
 
2df2e7e
 
 
fae625a
 
 
 
 
 
 
2df2e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
fae625a
 
 
 
 
 
 
77374bd
fae625a
77374bd
 
 
 
 
fae625a
77374bd
 
2df2e7e
c9a836e
 
2df2e7e
 
77374bd
2df2e7e
 
77374bd
2df2e7e
 
 
 
77374bd
 
 
2df2e7e
c9a836e
fae625a
 
 
 
 
77374bd
fae625a
 
77374bd
fae625a
 
2df2e7e
77374bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fae625a
77374bd
fae625a
 
 
2df2e7e
 
 
 
 
 
 
fae625a
 
77374bd
 
 
fae625a
 
 
 
 
 
77374bd
 
 
fae625a
 
 
 
 
77374bd
 
fae625a
 
 
 
 
 
 
 
 
 
 
77374bd
 
 
 
fae625a
 
 
 
 
77374bd
fae625a
 
2df2e7e
fae625a
 
 
 
2df2e7e
 
fae625a
 
2df2e7e
fae625a
 
 
2df2e7e
77374bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df2e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
import { randomUUID } from "node:crypto";
import { ObjectId, type Filter, type UpdateFilter } from "mongodb";
import { collections } from "$lib/server/database";
import type { AgentPendingBatch, Generation, GenerationStatus } from "$lib/types/Generation";
import type { Message } from "$lib/types/Message";
import { MessageUpdateType, type MessageUpdate } from "$lib/types/MessageUpdate";
import type { Workspace } from "$lib/types/Workspace";
import { reduceAgentMessageUpdates } from "./agentMessageReducer";
import { workspaceOperationAvailableFilter } from "./WorkspaceOperation";
import {
	generationTerminalCandidates,
	markGenerationMessageInterrupted,
} from "$lib/server/generation/terminalClaim";

export const AGENT_RELAY_LEASE_MS = 8_000;
export const AGENT_TERMINALIZATION_LEASE_MS = 15_000;
export const AGENT_SANDBOX_CHANGED_MESSAGE = "Agent workspace restarted before this run completed";

export class AgentRelayLeaseLostError extends Error {
	constructor() {
		super("Agent generation relay lease was lost");
		this.name = "AgentRelayLeaseLostError";
	}
}

export class AgentGenerationIncarnationMismatchError extends Error {
	constructor() {
		super(AGENT_SANDBOX_CHANGED_MESSAGE);
		this.name = "AgentGenerationIncarnationMismatchError";
	}
}

export interface AgentBatchCommit {
	inserted: boolean;
	endSeq: number;
	sourceSequence?: number;
}

interface AcquireOptions {
	generationId: string;
	workspaceId: Workspace["_id"];
	sandboxId: string;
	sandboxGeneration: string;
	sandboxNonce?: string;
	owner?: string;
	/** Exact pre-dispatch producer lease owned by the originating request. */
	producerOwner?: string;
	leaseMs?: number;
	now?: () => Date;
}

export type AgentGenerationOwner =
	| { userId: NonNullable<Generation["userId"]> }
	| { sessionId: NonNullable<Generation["sessionId"]> };

/**
 * Fenced, crash-recoverable writer for one Agent generation.
 *
 * A batch is first reserved in `generations.agent.pending` together with its
 * exact event-log sequence range. Only then are the append-only events and the
 * materialized message written. Clearing pending advances the bridge cursor.
 * A new process therefore either skips a completed batch or finishes the same
 * reservation; there is no prompt replay and no duplicate visible update.
 */
export class AgentGenerationStore {
	readonly generationId: string;
	readonly conversationId: Generation["conversationId"];
	readonly messageId: Generation["messageId"];
	readonly workspaceId: Workspace["_id"];
	readonly sandboxId: string;
	readonly sandboxGeneration: string;
	readonly sandboxNonce?: string;
	readonly owner: string;
	readonly fence: number;

	private constructor(
		options: Required<
			Pick<AcquireOptions, "generationId" | "workspaceId" | "sandboxId" | "sandboxGeneration">
		> & {
			conversationId: Generation["conversationId"];
			messageId: Generation["messageId"];
			sandboxNonce?: string;
			owner: string;
			leaseMs: number;
			now: () => Date;
			fence: number;
		}
	) {
		this.generationId = options.generationId;
		this.conversationId = options.conversationId;
		this.messageId = options.messageId;
		this.workspaceId = options.workspaceId;
		this.sandboxId = options.sandboxId;
		this.sandboxGeneration = options.sandboxGeneration;
		this.sandboxNonce = options.sandboxNonce;
		this.owner = options.owner;
		this.fence = options.fence;
		this.leaseMs = options.leaseMs;
		this.now = options.now;
	}

	private readonly leaseMs: number;
	private readonly now: () => Date;

	static async acquire(options: AcquireOptions): Promise<AgentGenerationStore | null> {
		const owner = options.owner ?? randomUUID();
		const now = (options.now ?? (() => new Date()))();
		const leaseMs = options.leaseMs ?? AGENT_RELAY_LEASE_MS;
		const generation = await collections.generations.findOneAndUpdate(
			{
				generationId: options.generationId,
				workspaceId: options.workspaceId,
				mode: "agent",
				status: "running",
				"agent.terminalization": { $exists: false },
				$and: [
					{
						$or: [
							{ "agent.relay": { $exists: false } },
							{ "agent.relay.expiresAt": { $lte: now } },
						],
					},
					{
						$or: [
							{
								"agent.sandboxId": options.sandboxId,
								"agent.sandboxGeneration": options.sandboxGeneration,
							},
							{
								$and: [
									{ "agent.sandboxId": { $exists: false } },
									{ "agent.sandboxGeneration": { $exists: false } },
								],
							},
						],
					},
					options.producerOwner
						? {
								"agent.producer.owner": options.producerOwner,
								"agent.producer.expiresAt": { $gt: now },
							}
						: {
								$or: [
									{ "agent.producer": { $exists: false } },
									{ "agent.producer.expiresAt": { $lte: now } },
								],
							},
				],
			},
			{
				$set: {
					"agent.sandboxId": options.sandboxId,
					"agent.sandboxGeneration": options.sandboxGeneration,
					"agent.relay.owner": owner,
					"agent.relay.expiresAt": new Date(now.getTime() + leaseMs),
					lastHeartbeatAt: now,
					updatedAt: now,
				},
				$inc: { "agent.relay.fence": 1 },
				$unset: { "agent.producer": "", "agent.prompt.recovery": "" },
			},
			{ returnDocument: "after", includeResultMetadata: false }
		);

		const fence = generation?.agent?.relay?.fence;
		if (!generation || fence === undefined) {
			const current = await collections.generations.findOne(
				{
					generationId: options.generationId,
					workspaceId: options.workspaceId,
					mode: "agent",
					status: "running",
				},
				{
					projection: {
						"agent.sandboxId": 1,
						"agent.sandboxGeneration": 1,
						"agent.producer": 1,
					},
				}
			);
			const producer = current?.agent?.producer;
			if (producer && producer.expiresAt > now && producer.owner !== options.producerOwner) {
				return null;
			}
			const boundSandboxId = current?.agent?.sandboxId;
			const boundSandboxGeneration = current?.agent?.sandboxGeneration;
			if (
				current &&
				(boundSandboxId !== undefined || boundSandboxGeneration !== undefined) &&
				(boundSandboxId !== options.sandboxId ||
					boundSandboxGeneration !== options.sandboxGeneration)
			) {
				throw new AgentGenerationIncarnationMismatchError();
			}
			return null;
		}
		const generationOwner = generation.userId
			? { userId: generation.userId }
			: generation.sessionId
				? { sessionId: generation.sessionId }
				: undefined;
		if (!generationOwner) {
			await clearAcquiredRelay(options.generationId, owner, fence);
			throw new AgentGenerationIncarnationMismatchError();
		}
		const execution = await collections.workspaces.updateOne(
			{
				_id: options.workspaceId,
				conversationId: generation.conversationId,
				...generationOwner,
				retirement: { $exists: false },
				"sandbox.status": { $in: ["ready", "idle"] },
				"sandbox.id": options.sandboxId,
				"sandbox.generation": options.sandboxGeneration,
				...(options.sandboxNonce ? { "sandbox.nonce": options.sandboxNonce } : {}),
				$and: [
					workspaceOperationAvailableFilter(now),
					options.producerOwner
						? {
								"execution.generationId": options.generationId,
								"execution.phase": "producer",
								"execution.owner": options.producerOwner,
								"execution.expiresAt": { $gt: now },
							}
						: {
								$or: [
									{ "execution.generationId": options.generationId },
									{ execution: { $exists: false } },
									{ "execution.expiresAt": { $lte: now } },
								],
							},
				],
			},
			{
				$set: {
					execution: {
						generationId: options.generationId,
						phase: "relay",
						owner,
						fence,
						expiresAt: new Date(now.getTime() + leaseMs),
						sandboxId: options.sandboxId,
						sandboxGeneration: options.sandboxGeneration,
						...(options.sandboxNonce ? { sandboxNonce: options.sandboxNonce } : {}),
					},
				},
				$unset: { operation: "" },
			}
		);
		if (execution.matchedCount !== 1) {
			await clearAcquiredRelay(options.generationId, owner, fence);
			// An exact sandbox can be temporarily fenced by a workspace operation
			// (configuration, deliverables, reset) or another execution claimant.
			// That is contention, not an incarnation change, and must never cause the
			// caller to interrupt the durable generation.
			const contended = await collections.workspaces.findOne(
				{
					_id: options.workspaceId,
					conversationId: generation.conversationId,
					...generationOwner,
					retirement: { $exists: false },
					"sandbox.status": { $in: ["ready", "idle"] },
					"sandbox.id": options.sandboxId,
					"sandbox.generation": options.sandboxGeneration,
					...(options.sandboxNonce ? { "sandbox.nonce": options.sandboxNonce } : {}),
				},
				{ projection: { _id: 1 } }
			);
			if (contended) return null;
			throw new AgentGenerationIncarnationMismatchError();
		}
		return new AgentGenerationStore({
			generationId: options.generationId,
			conversationId: generation.conversationId,
			messageId: generation.messageId,
			workspaceId: options.workspaceId,
			sandboxId: options.sandboxId,
			sandboxGeneration: options.sandboxGeneration,
			...(options.sandboxNonce ? { sandboxNonce: options.sandboxNonce } : {}),
			owner,
			leaseMs,
			now: options.now ?? (() => new Date()),
			fence,
		});
	}

	/**
	 * Atomically terminate a run that is bound to a different sandbox than the
	 * workspace's current incarnation. Missing current identity is also unsafe
	 * and terminates the run rather than permitting an unbound resume.
	 */
	static async interruptForSandboxChange(options: {
		generationId: string;
		workspaceId: Workspace["_id"];
		sandboxId?: string;
		sandboxGeneration?: string;
		sandboxNonce?: string;
	}): Promise<boolean> {
		const claimAt = new Date();
		const terminalizationId = randomUUID();
		const exactCurrentIncarnation = options.sandboxId && options.sandboxGeneration;
		const mismatchFilter: Filter<Generation> = exactCurrentIncarnation
			? {
					$and: [
						{
							$or: [
								{ "agent.sandboxId": { $exists: true } },
								{ "agent.sandboxGeneration": { $exists: true } },
							],
						},
						{
							$or: [
								{ "agent.sandboxId": { $ne: options.sandboxId } },
								{ "agent.sandboxGeneration": { $ne: options.sandboxGeneration } },
							],
						},
					],
				}
			: {};
		const generation = await collections.generations.findOneAndUpdate(
			{
				generationId: options.generationId,
				workspaceId: options.workspaceId,
				mode: "agent",
				$or: [
					{
						status: "running",
						"agent.terminalization": { $exists: false },
						...mismatchFilter,
					},
					{
						status: { $in: ["running", "interrupted"] },
						"agent.terminalization.kind": "sandbox-change",
						"agent.terminalization.expiresAt": { $lte: claimAt },
					},
				],
			},
			{
				$set: {
					"agent.terminalization": {
						id: terminalizationId,
						kind: "sandbox-change",
						claimedAt: claimAt,
						expiresAt: new Date(claimAt.getTime() + AGENT_TERMINALIZATION_LEASE_MS),
					},
					"agent.controlsOpen": false,
					lastHeartbeatAt: claimAt,
					updatedAt: claimAt,
				},
				$unset: {
					"agent.relay": "",
					"agent.producer": "",
					"agent.prompt.recovery": "",
					"agent.control": "",
				},
			},
			{ returnDocument: "after", includeResultMetadata: false }
		);
		if (!generation) return false;

		let terminalGeneration = generation;
		if (generation.status === "running") {
			const pending = generation.agent?.pending;
			if (pending) {
				await persistAgentPendingEvents(generation.generationId, pending, () => new Date());
				const renewed = await renewAgentTerminalization(
					generation.generationId,
					options.workspaceId,
					terminalizationId
				);
				if (!renewed) return false;
				const endSeq = pending.startSeq + pending.events.length - 1;
				await applyAgentPendingToMessage(renewed, pending, endSeq, () => new Date());
			}

			const terminalAt = new Date();
			const renewed = await renewAgentTerminalization(
				generation.generationId,
				options.workspaceId,
				terminalizationId,
				terminalAt
			);
			if (!renewed) return false;
			const terminalUpdate: UpdateFilter<Generation> = {
				...(pending?.kind === "system" ? { $addToSet: { "agent.systemKeys": pending.key } } : {}),
				$set: {
					status: "interrupted",
					"agent.controlsOpen": false,
					...(pending?.kind === "bridge" ? { "agent.sourceSequence": pending.sourceSequence } : {}),
					error: AGENT_SANDBOX_CHANGED_MESSAGE,
					endedAt: terminalAt,
					lastHeartbeatAt: terminalAt,
					updatedAt: terminalAt,
				},
				$unset: {
					"agent.relay": "",
					"agent.producer": "",
					"agent.prompt.recovery": "",
					"agent.control": "",
					"agent.pending": "",
					"agent.pendingApprovalIds": "",
				},
			};
			const terminalized = await collections.generations.findOneAndUpdate(
				{
					generationId: generation.generationId,
					workspaceId: options.workspaceId,
					mode: "agent",
					status: "running",
					"agent.terminalization.id": terminalizationId,
					"agent.terminalization.expiresAt": { $gt: terminalAt },
					...(pending ? { "agent.pending": pending } : { "agent.pending": { $exists: false } }),
				},
				terminalUpdate,
				{ returnDocument: "before", includeResultMetadata: false }
			);
			if (!terminalized) return false;
			terminalGeneration = terminalized;
		}

		// Keep the dedicated marker through both post-terminal side effects. If the
		// process dies here, the reaper can discover and take over the terminal row.
		const sideEffectAt = new Date();
		if (
			!(await renewAgentTerminalization(
				generation.generationId,
				options.workspaceId,
				terminalizationId,
				sideEffectAt
			))
		) {
			return false;
		}
		await markGenerationMessageInterrupted(terminalGeneration, sideEffectAt);
		await collections.workspaces.updateOne(
			{
				_id: options.workspaceId,
				"execution.generationId": options.generationId,
			},
			{ $unset: { execution: "" } }
		);
		await collections.generations.updateOne(
			{
				generationId: generation.generationId,
				workspaceId: options.workspaceId,
				"agent.terminalization.id": terminalizationId,
			},
			{ $unset: { "agent.terminalization": "" } }
		);
		return true;
	}

	async renew(): Promise<void> {
		const now = this.now();
		const expiresAt = new Date(now.getTime() + this.leaseMs);
		const workspace = await collections.workspaces.updateOne(
			{
				_id: this.workspaceId,
				conversationId: this.conversationId,
				retirement: { $exists: false },
				...workspaceOperationAvailableFilter(now),
				"execution.generationId": this.generationId,
				"execution.phase": "relay",
				"execution.owner": this.owner,
				"execution.fence": this.fence,
				"execution.sandboxId": this.sandboxId,
				"execution.sandboxGeneration": this.sandboxGeneration,
				...(this.sandboxNonce ? { "execution.sandboxNonce": this.sandboxNonce } : {}),
				"execution.expiresAt": { $gt: now },
				"sandbox.id": this.sandboxId,
				"sandbox.generation": this.sandboxGeneration,
				...(this.sandboxNonce ? { "sandbox.nonce": this.sandboxNonce } : {}),
			},
			{
				$set: { "execution.expiresAt": expiresAt, updatedAt: now },
				$unset: { operation: "" },
			}
		);
		if (workspace.matchedCount === 0) throw new AgentRelayLeaseLostError();
		const result = await collections.generations.updateOne(this.leaseFilter(true, now), {
			$set: {
				"agent.relay.expiresAt": expiresAt,
				lastHeartbeatAt: now,
				updatedAt: now,
			},
		});
		if (result.matchedCount === 0) {
			await this.releaseWorkspaceExecution();
			throw new AgentRelayLeaseLostError();
		}
	}

	/**
	 * Revalidate both fenced generation ownership and the exact live workspace
	 * incarnation after the bridge socket connects, immediately before prompt
	 * dispatch. A retirement claim is a hard stop even while the Job still says
	 * ready.
	 */
	async assertPromptDispatch(
		workspace: Pick<Workspace, "conversationId" | "sandbox">
	): Promise<void> {
		await this.renew();
		if (!workspace.conversationId.equals(this.conversationId)) {
			throw new AgentGenerationIncarnationMismatchError();
		}
		await this.resolveAuthoritativeOwner(workspace.sandbox.nonce);
	}

	/**
	 * Re-read ownership from the exact fenced generation, conversation, and
	 * workspace. Login moves these documents one collection at a time, so the
	 * temporary dual-owned generation/workspace may legitimately agree with the
	 * conversation through either principal. Returning only the principal shared
	 * by all three keeps this transition narrow and never treats the old session
	 * as an alias for the new account.
	 */
	async authoritativeOwner(): Promise<AgentGenerationOwner> {
		await this.renew();
		return this.resolveAuthoritativeOwner(this.sandboxNonce);
	}

	private async resolveAuthoritativeOwner(
		expectedSandboxNonce?: string
	): Promise<AgentGenerationOwner> {
		for (let attempt = 0; attempt < 4; attempt++) {
			const now = this.now();
			const [generation, conversation, workspace] = await Promise.all([
				collections.generations.findOne(this.leaseFilter(true, now), {
					projection: { userId: 1, sessionId: 1 },
				}),
				collections.conversations.findOne(
					{
						_id: this.conversationId,
						mode: "agent",
						workspaceId: this.workspaceId,
						messages: {
							$elemMatch: { id: this.messageId, generationId: this.generationId },
						},
					},
					{ projection: { userId: 1, sessionId: 1 } }
				),
				collections.workspaces.findOne(
					{
						_id: this.workspaceId,
						conversationId: this.conversationId,
						retirement: { $exists: false },
						"execution.generationId": this.generationId,
						"execution.phase": "relay",
						"execution.owner": this.owner,
						"execution.fence": this.fence,
						"execution.sandboxId": this.sandboxId,
						"execution.sandboxGeneration": this.sandboxGeneration,
						...(this.sandboxNonce ? { "execution.sandboxNonce": this.sandboxNonce } : {}),
						"execution.expiresAt": { $gt: now },
						"sandbox.status": { $in: ["ready", "idle"] },
						"sandbox.id": this.sandboxId,
						"sandbox.generation": this.sandboxGeneration,
						...(expectedSandboxNonce ? { "sandbox.nonce": expectedSandboxNonce } : {}),
					},
					{ projection: { userId: 1, sessionId: 1 } }
				),
			]);
			if (!generation) throw new AgentRelayLeaseLostError();
			if (!conversation || !workspace) {
				throw new AgentGenerationIncarnationMismatchError();
			}

			if (
				generation.userId &&
				conversation.userId?.equals(generation.userId) &&
				workspace.userId?.equals(generation.userId)
			) {
				return { userId: generation.userId };
			}
			if (
				generation.sessionId &&
				conversation.sessionId === generation.sessionId &&
				workspace.sessionId === generation.sessionId
			) {
				return { sessionId: generation.sessionId };
			}

			// The three primary reads can straddle one of the short login handoff
			// writes. Yield and re-read the exact fenced chain before declaring it
			// inconsistent.
			await Promise.resolve();
		}
		throw new AgentGenerationIncarnationMismatchError();
	}

	async resumePending(): Promise<AgentBatchCommit | undefined> {
		await this.renew();
		let generation = await collections.generations.findOne(this.leaseFilter());
		if (!generation) throw new AgentRelayLeaseLostError();
		const pending = generation.agent?.pending;
		if (pending) return this.flushPending(generation, pending);
		await this.synchronizeEventCursor(generation);
		generation = await collections.generations.findOne(this.leaseFilter());
		if (!generation) throw new AgentRelayLeaseLostError();
		return undefined;
	}

	private async synchronizeEventCursor(generation: Generation): Promise<void> {
		const latest = await collections.generationEvents.findOne(
			{ generationId: this.generationId },
			{ sort: { seq: -1 }, projection: { seq: 1 } }
		);
		if (!latest) return;
		await this.materializeEventBacklog(generation, latest.seq);
		const result = await collections.generations.updateOne(this.leaseFilter(), {
			$max: { seq: latest.seq },
		});
		if (result.matchedCount === 0) throw new AgentRelayLeaseLostError();
	}

	private async materializeEventBacklog(generation: Generation, latestSeq: number): Promise<void> {
		for (let attempt = 0; attempt < 8; attempt++) {
			const conversation = await collections.conversations.findOne(
				{ _id: generation.conversationId },
				{ projection: { messages: 1 } }
			);
			const current = conversation?.messages.find(
				(message) =>
					message.id === generation.messageId && message.generationId === generation.generationId
			);
			if (!current) throw new Error("Agent generation message no longer exists");
			const cursor = current.materializedSeq ?? 0;
			if (cursor >= latestSeq) return;
			const backlog = await collections.generationEvents
				.find({ generationId: this.generationId, seq: { $gt: cursor, $lte: latestSeq } })
				.sort({ seq: 1 })
				.toArray();
			if (!backlog.length) return;
			let contiguousEnd = cursor;
			const updates: MessageUpdate[] = [];
			for (const record of backlog) {
				if (record.seq !== contiguousEnd + 1) break;
				updates.push(record.event);
				contiguousEnd = record.seq;
			}
			if (!updates.length) return;
			const reduced = reduceAgentMessageUpdates(current, updates);
			const result = await collections.conversations.updateOne(
				{
					_id: generation.conversationId,
					messages: {
						$elemMatch: {
							id: generation.messageId,
							generationId: generation.generationId,
							...(cursor === 0
								? {
										$or: [{ materializedSeq: { $exists: false } }, { materializedSeq: 0 }],
									}
								: { materializedSeq: cursor }),
						},
					},
				},
				{
					$set: {
						"messages.$": { ...reduced.message, materializedSeq: contiguousEnd },
						...(reduced.title ? { title: reduced.title } : {}),
						updatedAt: this.now(),
					},
				}
			);
			if (result.matchedCount === 1 && contiguousEnd >= latestSeq) return;
		}
		throw new Error("Agent event backlog changed too frequently to materialize");
	}

	async commitBridgeBatch(
		sourceSequence: number,
		events: readonly MessageUpdate[]
	): Promise<AgentBatchCommit> {
		if (!Number.isSafeInteger(sourceSequence) || sourceSequence < 1) {
			throw new Error("Agent bridge sequence must be a positive safe integer");
		}
		await this.resumePending();

		for (;;) {
			const generation = await collections.generations.findOne(this.leaseFilter());
			if (!generation) throw new AgentRelayLeaseLostError();
			if ((generation.agent?.sourceSequence ?? 0) >= sourceSequence) {
				return {
					inserted: false,
					endSeq: generation.seq,
					sourceSequence,
				};
			}
			if (generation.agent?.pending) {
				await this.flushPending(generation, generation.agent.pending);
				continue;
			}

			const pending: AgentPendingBatch = {
				kind: "bridge",
				sourceSequence,
				startSeq: generation.seq + 1,
				events: [...events],
			};
			const now = this.now();
			const reservation = await collections.generations.updateOne(
				{
					...this.leaseFilter(),
					seq: generation.seq,
					"agent.pending": { $exists: false },
					"agent.sourceSequence": { $lt: sourceSequence },
				},
				{
					$set: {
						"agent.pending": pending,
						seq: generation.seq + events.length,
						"agent.relay.expiresAt": new Date(now.getTime() + this.leaseMs),
						lastHeartbeatAt: now,
						updatedAt: now,
					},
				}
			);
			if (reservation.matchedCount === 0) continue;
			return this.flushPending(
				{
					...generation,
					seq: generation.seq + events.length,
					agent: {
						sourceSequence: generation.agent?.sourceSequence ?? 0,
						...generation.agent,
						pending,
					},
				},
				pending
			);
		}
	}

	async commitSystemBatch(
		key: string,
		events: readonly MessageUpdate[]
	): Promise<AgentBatchCommit> {
		if (!key || key.length > 128) throw new Error("Invalid Agent system batch key");
		await this.resumePending();

		for (;;) {
			const generation = await collections.generations.findOne(this.leaseFilter());
			if (!generation) throw new AgentRelayLeaseLostError();
			if (generation.agent?.systemKeys?.includes(key)) {
				return { inserted: false, endSeq: generation.seq };
			}
			if (generation.agent?.pending) {
				await this.flushPending(generation, generation.agent.pending);
				continue;
			}

			const pending: AgentPendingBatch = {
				kind: "system",
				key,
				startSeq: generation.seq + 1,
				events: [...events],
			};
			const now = this.now();
			const reservation = await collections.generations.updateOne(
				{
					...this.leaseFilter(),
					seq: generation.seq,
					"agent.pending": { $exists: false },
					"agent.systemKeys": { $ne: key },
				},
				{
					$set: {
						"agent.pending": pending,
						seq: generation.seq + events.length,
						"agent.relay.expiresAt": new Date(now.getTime() + this.leaseMs),
						lastHeartbeatAt: now,
						updatedAt: now,
					},
				}
			);
			if (reservation.matchedCount === 0) continue;
			return this.flushPending(
				{
					...generation,
					seq: generation.seq + events.length,
					agent: {
						sourceSequence: generation.agent?.sourceSequence ?? 0,
						...generation.agent,
						pending,
					},
				},
				pending
			);
		}
	}

	async finish(status: GenerationStatus, error?: string): Promise<boolean> {
		await this.resumePending();
		const now = this.now();
		for (const candidate of generationTerminalCandidates(status)) {
			const stoppedFallback = candidate.status === "interrupted" && status !== "interrupted";
			const generation = await collections.generations.findOneAndUpdate(
				{
					...this.leaseFilter(),
					...candidate.filter,
					// Enqueue and terminalization contend on this same document. A control
					// which wins must be drained before finish may be retried.
					"agent.control": { $exists: false },
				},
				{
					$set: {
						status: candidate.status,
						"agent.controlsOpen": false,
						endedAt: now,
						lastHeartbeatAt: now,
						updatedAt: now,
						...(!stoppedFallback && error ? { error } : {}),
					},
					$unset: { "agent.relay": "", "agent.pendingApprovalIds": "" },
				},
				{ returnDocument: "before", includeResultMetadata: false }
			);
			if (!generation) continue;
			if (candidate.status === "interrupted") {
				await markGenerationMessageInterrupted(generation, now);
			}
			await this.releaseWorkspaceExecution();
			return true;
		}
		return false;
	}

	/**
	 * Fail an exact relay after recovery has become impossible.
	 *
	 * Normal completion must drain and seal the control mailbox through
	 * `finish()`. Fatal recovery paths are different: the workspace or bridge
	 * needed to drain that mailbox may no longer exist, and `resumePending()` can
	 * no longer renew the reciprocal workspace lease. Keeping the generation in
	 * `running` in that case only strands it for every later reaper sweep.
	 *
	 * This transition is deliberately fenced by the still-live generation relay
	 * owner/fence/incarnation. It closes and discards an undeliverable control in
	 * the same Mongo write, then releases only this relay's exact workspace
	 * execution claim. A replacement relay which has already taken ownership wins
	 * the fence and this method becomes a no-op.
	 */
	async finishUnrecoverable(status: "interrupted" | "error", error: string): Promise<boolean> {
		for (const candidate of generationTerminalCandidates(status)) {
			for (let attempt = 0; attempt < 8; attempt++) {
				const observedAt = this.now();
				const filter = { ...this.leaseFilter(true, observedAt), ...candidate.filter };
				const observed = await collections.generations.findOne(filter);
				if (!observed) break;
				const pending = observed.agent?.pending;
				if (pending) {
					// Keep the WAL reservation durable until its idempotent conversation
					// materialization succeeds. A crash after the apply therefore leaves a
					// retryable pending record instead of exposing event rows which the
					// durable conversation never incorporated.
					await this.persistPendingEvents(pending);
					const renewalAt = this.now();
					const renewed = await collections.generations.updateOne(
						{
							...this.leaseFilter(true, renewalAt),
							...candidate.filter,
							"agent.pending": pending,
						},
						{
							$set: {
								"agent.relay.expiresAt": new Date(renewalAt.getTime() + this.leaseMs),
								lastHeartbeatAt: renewalAt,
								updatedAt: renewalAt,
							},
						}
					);
					if (renewed.matchedCount === 0) continue;
					const endSeq = pending.startSeq + pending.events.length - 1;
					await this.applyPendingToMessage(observed, pending, endSeq);
				}

				const terminalAt = this.now();
				const stoppedFallback = candidate.status === "interrupted" && status !== "interrupted";
				const generation = await collections.generations.findOneAndUpdate(
					{
						...this.leaseFilter(true, terminalAt),
						...candidate.filter,
						...(pending ? { "agent.pending": pending } : { "agent.pending": { $exists: false } }),
					},
					{
						...(pending?.kind === "system"
							? { $addToSet: { "agent.systemKeys": pending.key } }
							: {}),
						$set: {
							status: candidate.status,
							"agent.controlsOpen": false,
							...(pending?.kind === "bridge"
								? { "agent.sourceSequence": pending.sourceSequence }
								: {}),
							...(!stoppedFallback ? { error } : {}),
							endedAt: terminalAt,
							lastHeartbeatAt: terminalAt,
							updatedAt: terminalAt,
						},
						$unset: {
							"agent.relay": "",
							"agent.control": "",
							"agent.pending": "",
							"agent.pendingApprovalIds": "",
						},
					},
					{ returnDocument: "before", includeResultMetadata: false }
				);
				if (!generation) continue;
				if (candidate.status === "interrupted") {
					await markGenerationMessageInterrupted(generation, terminalAt);
				}
				await this.releaseWorkspaceExecution();
				return true;
			}
		}
		return false;
	}

	async release(): Promise<void> {
		await collections.generations.updateOne(this.leaseFilter(false), {
			$unset: { "agent.relay": "" },
			$set: { updatedAt: this.now() },
		});
		await this.releaseWorkspaceExecution();
	}

	private async releaseWorkspaceExecution(): Promise<void> {
		await collections.workspaces.updateOne(
			{
				_id: this.workspaceId,
				"execution.generationId": this.generationId,
				"execution.phase": "relay",
				"execution.owner": this.owner,
				"execution.fence": this.fence,
			},
			{ $unset: { execution: "" } }
		);
	}

	private async flushPending(
		generation: Generation,
		pending: AgentPendingBatch
	): Promise<AgentBatchCommit> {
		const endSeq = pending.startSeq + pending.events.length - 1;
		await this.persistPendingEvents(pending);

		// Do not materialize the captured batch until both reciprocal workspace
		// ownership and the exact generation relay fence have accepted it. A stale
		// relay may remain inside this method after its lease expires; durable event
		// upserts are idempotent, but mutating the conversation before the fence
		// checks would let that zombie publish output after replacement/terminality.
		const now = this.now();
		const expiresAt = new Date(now.getTime() + this.leaseMs);
		const approvalRequestIds = pendingApprovalRequestIds(pending);
		const workspace = await collections.workspaces.updateOne(
			{
				_id: this.workspaceId,
				conversationId: this.conversationId,
				retirement: { $exists: false },
				...workspaceOperationAvailableFilter(now),
				"sandbox.id": this.sandboxId,
				"sandbox.generation": this.sandboxGeneration,
				...(this.sandboxNonce ? { "sandbox.nonce": this.sandboxNonce } : {}),
				"execution.generationId": this.generationId,
				"execution.phase": "relay",
				"execution.owner": this.owner,
				"execution.fence": this.fence,
				"execution.sandboxId": this.sandboxId,
				"execution.sandboxGeneration": this.sandboxGeneration,
				...(this.sandboxNonce ? { "execution.sandboxNonce": this.sandboxNonce } : {}),
				"execution.expiresAt": { $gt: now },
			},
			{
				...(pending.kind === "bridge"
					? { $max: { "piSession.lastSequence": pending.sourceSequence } }
					: {}),
				$set: {
					"execution.expiresAt": expiresAt,
					updatedAt: now,
				},
				$unset: { operation: "" },
			}
		);
		if (workspace.matchedCount === 0) throw new AgentRelayLeaseLostError();
		const renewed = await collections.generations.updateOne(
			{
				...this.leaseFilter(true, now),
				"agent.pending": pending,
			},
			{
				$set: {
					"agent.relay.expiresAt": expiresAt,
					lastHeartbeatAt: now,
					updatedAt: now,
				},
			}
		);
		if (renewed.matchedCount === 0) throw new AgentRelayLeaseLostError();

		await this.applyPendingToMessage(generation, pending, endSeq);

		const completionAt = this.now();
		const completion: UpdateFilter<Generation> =
			pending.kind === "bridge"
				? {
						...(approvalRequestIds.length
							? {
									$addToSet: {
										"agent.pendingApprovalIds": { $each: approvalRequestIds },
									},
								}
							: {}),
						$set: {
							"agent.sourceSequence": pending.sourceSequence,
							"agent.relay.expiresAt": new Date(completionAt.getTime() + this.leaseMs),
							lastHeartbeatAt: completionAt,
							updatedAt: completionAt,
						},
						$unset: { "agent.pending": "" as const },
					}
				: {
						$addToSet: { "agent.systemKeys": pending.key },
						$set: {
							"agent.relay.expiresAt": new Date(completionAt.getTime() + this.leaseMs),
							lastHeartbeatAt: completionAt,
							updatedAt: completionAt,
						},
						$unset: { "agent.pending": "" as const },
					};
		const result = await collections.generations.updateOne(
			{
				...this.leaseFilter(true, completionAt),
				"agent.pending": pending,
			},
			completion
		);
		if (result.matchedCount === 0) throw new AgentRelayLeaseLostError();
		return {
			inserted: true,
			endSeq: Math.max(generation.seq, endSeq),
			...(pending.kind === "bridge" ? { sourceSequence: pending.sourceSequence } : {}),
		};
	}

	private async persistPendingEvents(pending: AgentPendingBatch): Promise<void> {
		await persistAgentPendingEvents(this.generationId, pending, this.now);
	}

	private async applyPendingToMessage(
		generation: Generation,
		pending: AgentPendingBatch,
		endSeq: number
	): Promise<void> {
		await applyAgentPendingToMessage(generation, pending, endSeq, this.now);
	}

	private leaseFilter(requireRunning = true, at = this.now()): Filter<Generation> {
		return {
			generationId: this.generationId,
			workspaceId: this.workspaceId,
			...(requireRunning ? { status: "running" as const } : {}),
			"agent.sandboxId": this.sandboxId,
			"agent.sandboxGeneration": this.sandboxGeneration,
			"agent.relay.owner": this.owner,
			"agent.relay.fence": this.fence,
			...(requireRunning ? { "agent.relay.expiresAt": { $gt: at } } : {}),
		};
	}
}

async function renewAgentTerminalization(
	generationId: string,
	workspaceId: Workspace["_id"],
	id: string,
	now = new Date()
): Promise<Generation | null> {
	return collections.generations.findOneAndUpdate(
		{
			generationId,
			workspaceId,
			"agent.terminalization.id": id,
		},
		{
			$set: {
				"agent.terminalization.expiresAt": new Date(now.getTime() + AGENT_TERMINALIZATION_LEASE_MS),
				lastHeartbeatAt: now,
				updatedAt: now,
			},
		},
		{ returnDocument: "after", includeResultMetadata: false }
	);
}

async function persistAgentPendingEvents(
	generationId: string,
	pending: AgentPendingBatch,
	now: () => Date
): Promise<void> {
	if (!pending.events.length) return;
	await collections.generationEvents.bulkWrite(
		pending.events.map((event, index) => ({
			updateOne: {
				filter: { generationId, seq: pending.startSeq + index },
				update: {
					$setOnInsert: {
						_id: new ObjectId(),
						generationId,
						seq: pending.startSeq + index,
						event,
						...(pending.kind === "bridge"
							? { sourceSequence: pending.sourceSequence, sourceIndex: index }
							: { systemKey: pending.key, systemIndex: index }),
						createdAt: now(),
					},
				},
				upsert: true,
			},
		})),
		{ ordered: true }
	);
}

async function applyAgentPendingToMessage(
	generation: Generation,
	pending: AgentPendingBatch,
	endSeq: number,
	now: () => Date
): Promise<void> {
	for (let attempt = 0; attempt < 8; attempt++) {
		const conversation = await collections.conversations.findOne(
			{ _id: generation.conversationId },
			{ projection: { messages: 1, title: 1 } }
		);
		const current = conversation?.messages.find(
			(message) =>
				message.id === generation.messageId && message.generationId === generation.generationId
		);
		if (!conversation || !current) throw new Error("Agent generation message no longer exists");

		if (pending.kind === "bridge" && (current.agentSequence ?? 0) >= pending.sourceSequence) {
			return;
		}
		if (pending.kind === "system" && current.agentSystemKeys?.includes(pending.key)) {
			return;
		}

		const reduced = reduceAgentMessageUpdates(current, pending.events);
		const next: Message = {
			...reduced.message,
			materializedSeq: Math.max(current.materializedSeq ?? 0, endSeq),
			...(pending.kind === "bridge"
				? { agentSequence: pending.sourceSequence }
				: { agentSystemKeys: [...(current.agentSystemKeys ?? []), pending.key] }),
		};
		const markerFilter: Record<string, unknown> =
			pending.kind === "bridge"
				? {
						$or: [
							{ agentSequence: { $exists: false } },
							{ agentSequence: { $lt: pending.sourceSequence } },
						],
					}
				: { agentSystemKeys: { $ne: pending.key } };
		const result = await collections.conversations.updateOne(
			{
				_id: generation.conversationId,
				messages: {
					$elemMatch: {
						id: generation.messageId,
						generationId: generation.generationId,
						...markerFilter,
					},
				},
			},
			{
				$set: {
					"messages.$": next,
					...(reduced.title ? { title: reduced.title } : {}),
					updatedAt: now(),
				},
			}
		);
		if (result.matchedCount === 1) return;
	}
	throw new Error("Agent message changed too frequently to materialize relay output");
}

function pendingApprovalRequestIds(pending: AgentPendingBatch): string[] {
	return [
		...new Set(
			pending.events.flatMap((event) =>
				event.type === MessageUpdateType.AgentApproval ? [event.requestId] : []
			)
		),
	];
}

async function clearAcquiredRelay(
	generationId: string,
	owner: string,
	fence: number
): Promise<void> {
	await collections.generations.updateOne(
		{
			generationId,
			status: "running",
			"agent.relay.owner": owner,
			"agent.relay.fence": fence,
		},
		{ $unset: { "agent.relay": "" } }
	);
}