@qlairoslabs/acp-client 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CONSUMER_GUIDE.md +618 -291
  2. package/README.md +25 -0
  3. package/package.json +1 -1
  4. package/src/agent-session.ts +2188 -96
  5. package/src/cli/index.ts +33 -5
  6. package/src/cli/managed.ts +220 -0
  7. package/src/command-descriptors.ts +22 -0
  8. package/src/controller.ts +87 -37
  9. package/src/index.ts +229 -3
  10. package/src/metering/engine.ts +9 -1
  11. package/src/metering/record.ts +2 -1
  12. package/src/persistence/activity-projection.ts +71 -0
  13. package/src/persistence/audit-log-reader.ts +506 -0
  14. package/src/persistence/audit-runtime.ts +162 -0
  15. package/src/persistence/checkpoint.ts +304 -0
  16. package/src/persistence/config.ts +538 -0
  17. package/src/persistence/configuration-state.ts +191 -0
  18. package/src/persistence/deletion.ts +227 -0
  19. package/src/persistence/file-registry-store.ts +740 -0
  20. package/src/persistence/integrity.ts +147 -0
  21. package/src/persistence/legacy-registry-import.ts +240 -0
  22. package/src/persistence/managed-checkpoint.ts +81 -0
  23. package/src/persistence/managed-creation.ts +456 -0
  24. package/src/persistence/managed-load.ts +172 -0
  25. package/src/persistence/managed-registry.ts +57 -0
  26. package/src/persistence/migration.ts +298 -0
  27. package/src/persistence/paths.ts +172 -0
  28. package/src/persistence/projection.ts +373 -0
  29. package/src/persistence/reconfiguration.ts +453 -0
  30. package/src/persistence/records.ts +873 -0
  31. package/src/persistence/reducer.ts +498 -0
  32. package/src/persistence/registry.ts +446 -0
  33. package/src/persistence/restoration.ts +689 -0
  34. package/src/persistence/session-log-writer.ts +480 -0
  35. package/src/persistence/state-runtime.ts +176 -0
  36. package/src/persistence/transcript-reader.ts +980 -0
  37. package/src/persistence/transcript-runtime.ts +667 -0
  38. package/src/persistence/transcript-scanner.ts +385 -0
  39. package/src/persistence/truncation.ts +276 -0
  40. package/src/repl/agent-session-commands.ts +74 -1
  41. package/src/repl/commands.ts +1 -1
  42. package/src/repl/index.ts +7 -1
  43. package/src/session-manager.ts +257 -7
  44. package/src/transcript.ts +3 -3
@@ -0,0 +1,667 @@
1
+ import {
2
+ createAgentSessionCheckpoint,
3
+ type AgentSessionBoundary,
4
+ type AgentSessionCheckpoint,
5
+ type AgentSessionCheckpointInput,
6
+ type SessionConfigurationCheckpoint,
7
+ } from "./checkpoint.ts";
8
+ import { projectTranscriptEvent, type NormalizedPersistenceEvent } from "./projection.ts";
9
+ import {
10
+ reduceInternalSessionHistory,
11
+ reduceTranscriptState,
12
+ type PersistenceRepair,
13
+ type SessionRecoveryStatus,
14
+ type TranscriptHistoryReduction,
15
+ type TranscriptStructuralRecord,
16
+ } from "./reducer.ts";
17
+ import type {
18
+ InternalSessionHistoryEntry,
19
+ OperationAbortReason,
20
+ OperationKind,
21
+ TranscriptCheckpointRecord,
22
+ TranscriptOperationRecord,
23
+ } from "./records.ts";
24
+ import type { PersistedMachineCode } from "./integrity.ts";
25
+ import {
26
+ FileSessionLogWriter,
27
+ type FileSessionLogWriterOptions,
28
+ type ResumeTranscriptWriterOptions,
29
+ type SessionLogWriterLock,
30
+ } from "./session-log-writer.ts";
31
+ import type { TranscriptHeaderRecord } from "./records.ts";
32
+ import type { PersistenceStateRuntime } from "./state-runtime.ts";
33
+
34
+ export interface TranscriptTerminalCheckpointChanges {
35
+ readonly model?: string | null;
36
+ readonly sessionConfiguration?: SessionConfigurationCheckpoint;
37
+ readonly metering?: AgentSessionCheckpoint["metering"];
38
+ readonly boundary?: AgentSessionBoundary;
39
+ }
40
+
41
+ type NormalizedTransitionEvent = Extract<NormalizedPersistenceEvent, { kind: "transition" }>;
42
+ type TargetActivationEvent = Omit<NormalizedTransitionEvent, "event"> & {
43
+ readonly event: "target_activated";
44
+ };
45
+ type NonActivationTransitionEvent = Omit<NormalizedTransitionEvent, "event"> & {
46
+ readonly event: Exclude<NormalizedTransitionEvent["event"], "target_activated">;
47
+ };
48
+
49
+ export interface CreateTranscriptRuntimeOptions {
50
+ readonly path: string;
51
+ readonly header: TranscriptHeaderRecord;
52
+ /** Supplied directly by transaction coordinators that already established the target. */
53
+ readonly checkpoint?: AgentSessionCheckpoint;
54
+ /**
55
+ * Called only after the transcript header and ownership lock are durable. Live-session
56
+ * creation uses this to establish the provider thread without a dispatch-before-WAL gap.
57
+ */
58
+ readonly initializeCheckpoint?: () => Promise<AgentSessionCheckpoint>;
59
+ readonly lockTimeoutMs?: number;
60
+ readonly lockRetryMs?: number;
61
+ /** @internal Ownership transferred from managed creation. */
62
+ readonly writerLock?: SessionLogWriterLock;
63
+ }
64
+
65
+ export class TranscriptRuntimeStateError extends Error {
66
+ constructor(message: string) {
67
+ super(message);
68
+ this.name = "TranscriptRuntimeStateError";
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Live v2 transcript state machine. It is deliberately provider-agnostic: callers own
74
+ * dispatch, while this object owns the durable-before-dispatch and terminal boundaries.
75
+ */
76
+ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
77
+ private selectedCheckpointRecord: TranscriptCheckpointRecord;
78
+ private history: TranscriptHistoryReduction;
79
+ private _checkpoint: AgentSessionCheckpoint;
80
+ private _recovery: SessionRecoveryStatus;
81
+ private readonly _openingRepairs: readonly PersistenceRepair[];
82
+ private activeOperation: {
83
+ operationId: string;
84
+ kind: OperationKind;
85
+ started: TranscriptOperationRecord;
86
+ } | null = null;
87
+ private failure: Error | null = null;
88
+ private closed = false;
89
+ private checkpointPublisher: ((
90
+ checkpoint: AgentSessionCheckpoint,
91
+ history: readonly InternalSessionHistoryEntry[],
92
+ ) => Promise<void>) | null = null;
93
+
94
+ private constructor(
95
+ private readonly writer: FileSessionLogWriter<"transcript">,
96
+ private readonly header: Awaited<ReturnType<typeof FileSessionLogWriter.resumeTranscript>>["scan"]["header"],
97
+ selectedCheckpointRecord: TranscriptCheckpointRecord,
98
+ history: TranscriptHistoryReduction,
99
+ checkpoint: AgentSessionCheckpoint,
100
+ recovery: SessionRecoveryStatus,
101
+ repairs: readonly PersistenceRepair[],
102
+ private readonly conversationWasTruncated: boolean,
103
+ private openingStructuralTail: readonly TranscriptStructuralRecord[],
104
+ ) {
105
+ this.selectedCheckpointRecord = selectedCheckpointRecord;
106
+ this.history = history;
107
+ this._checkpoint = checkpoint;
108
+ this._recovery = recovery;
109
+ this._openingRepairs = Object.freeze([...repairs]);
110
+ }
111
+
112
+ /**
113
+ * Install a new transcript generation and its initial continuation checkpoint.
114
+ *
115
+ * Creation transaction ownership remains with the caller: if this method fails after
116
+ * installing the header, the caller may remove the destination only when the header's
117
+ * installation provenance proves that it belongs to that same prepared transaction.
118
+ */
119
+ static async create(options: CreateTranscriptRuntimeOptions): Promise<TranscriptPersistenceRuntime> {
120
+ if ((options.checkpoint === undefined) === (options.initializeCheckpoint === undefined)) {
121
+ throw new TranscriptRuntimeStateError("transcript creation requires exactly one checkpoint source");
122
+ }
123
+ if (options.checkpoint) assertInitialCheckpoint(options.header, options.path, options.checkpoint);
124
+ const writerOptions: FileSessionLogWriterOptions<"transcript"> = {
125
+ kind: "transcript",
126
+ path: options.path,
127
+ header: options.header,
128
+ maxRecordBytes: options.header.effectiveLimits.maxRecordBytes,
129
+ lockTimeoutMs: options.lockTimeoutMs,
130
+ lockRetryMs: options.lockRetryMs,
131
+ writerLock: options.writerLock,
132
+ };
133
+ const writer = await FileSessionLogWriter.create(writerOptions);
134
+ try {
135
+ const checkpoint = options.checkpoint ?? await options.initializeCheckpoint!();
136
+ assertInitialCheckpoint(options.header, options.path, checkpoint);
137
+ const physical = checkpointRecord(writer.nextSequence, checkpoint, options.header);
138
+ await writer.append(physical, { durable: true });
139
+ const history = reduceInternalSessionHistory([]);
140
+ const reduced = reduceTranscriptState(physical, history, []);
141
+ if (reduced.recovery.kind !== "clean") {
142
+ throw new TranscriptRuntimeStateError("initial transcript checkpoint must be settled");
143
+ }
144
+ return new TranscriptPersistenceRuntime(
145
+ writer,
146
+ options.header,
147
+ physical,
148
+ history,
149
+ reduced.checkpoint,
150
+ reduced.recovery,
151
+ [],
152
+ false,
153
+ [],
154
+ );
155
+ } catch (error) {
156
+ await writer.close().catch(() => undefined);
157
+ throw error;
158
+ }
159
+ }
160
+
161
+ static async resume(options: ResumeTranscriptWriterOptions): Promise<TranscriptPersistenceRuntime> {
162
+ const { writer, scan } = await FileSessionLogWriter.resumeTranscript(options);
163
+ try {
164
+ let selected = scan.selectedCheckpointRecord;
165
+ let history = scan.historyAtSelectedCheckpoint;
166
+ let checkpoint = scan.reduction.checkpoint;
167
+ let structuralTail = scan.structuralTailAfterSelectedCheckpoint;
168
+ if (scan.reduction.repairs.length > 0) {
169
+ const record = checkpointRecord(writer.nextSequence, checkpoint, scan.header);
170
+ await writer.append(record, { durable: true });
171
+ selected = record;
172
+ history = reduceInternalSessionHistory(scan.reduction.internalSessionHistory);
173
+ structuralTail = [];
174
+ }
175
+ return new TranscriptPersistenceRuntime(
176
+ writer,
177
+ scan.header,
178
+ selected,
179
+ history,
180
+ checkpoint,
181
+ scan.reduction.recovery,
182
+ scan.reduction.repairs,
183
+ scan.conversationTruncated,
184
+ structuralTail,
185
+ );
186
+ } catch (error) {
187
+ await writer.close().catch(() => undefined);
188
+ throw error;
189
+ }
190
+ }
191
+
192
+ get checkpoint(): AgentSessionCheckpoint {
193
+ return structuredClone(this._checkpoint);
194
+ }
195
+
196
+ get recovery(): SessionRecoveryStatus {
197
+ return structuredClone(this._recovery);
198
+ }
199
+
200
+ get openingRepairs(): readonly PersistenceRepair[] {
201
+ return this._openingRepairs.map((repair) => structuredClone(repair));
202
+ }
203
+
204
+ get conversationAvailability(): "available" | "partial" | "not_captured" {
205
+ if (this.header.effectivePolicy.messages === "none") return "not_captured";
206
+ return this.conversationWasTruncated ? "partial" : "available";
207
+ }
208
+
209
+ get healthy(): boolean {
210
+ return this.failure === null;
211
+ }
212
+
213
+ get nextSequence(): number {
214
+ return this.writer.nextSequence;
215
+ }
216
+
217
+ get internalSessionHistory(): readonly InternalSessionHistoryEntry[] {
218
+ return this.history.entries.map((entry) => structuredClone(entry));
219
+ }
220
+
221
+ /** @internal Attach the managed registry projection after creation finalizes. */
222
+ setCheckpointPublisher(
223
+ publisher: (
224
+ checkpoint: AgentSessionCheckpoint,
225
+ history: readonly InternalSessionHistoryEntry[],
226
+ ) => Promise<void>,
227
+ ): void {
228
+ if (this.checkpointPublisher) {
229
+ throw new TranscriptRuntimeStateError("managed checkpoint publisher is already attached");
230
+ }
231
+ this.checkpointPublisher = publisher;
232
+ }
233
+
234
+ async beginOperation(operationId: string, kind: OperationKind, ts = Date.now()): Promise<void> {
235
+ this.assertUsable();
236
+ if (this._recovery.kind !== "clean") throw new TranscriptRuntimeStateError("uncertain transcript recovery must be resolved before dispatch");
237
+ if (this.activeOperation) throw new TranscriptRuntimeStateError("another transcript operation is already active");
238
+ const record: TranscriptOperationRecord = {
239
+ ...this.envelope(this.writer.nextSequence, ts),
240
+ t: "operation",
241
+ operationId,
242
+ operationKind: kind,
243
+ event: "started",
244
+ stateRevision: this._checkpoint.stateRevision + 1,
245
+ };
246
+ await this.writer.append(record, { durable: true });
247
+ const reduced = reduceTranscriptState(this.selectedCheckpointRecord, this.history, [record]);
248
+ this._checkpoint = reduced.checkpoint;
249
+ this._recovery = reduced.recovery;
250
+ this.activeOperation = { operationId, kind, started: record };
251
+ try {
252
+ await this.publishManagedCheckpoint();
253
+ } catch (error) {
254
+ // Registry publication is part of the managed pre-dispatch boundary. Close the
255
+ // transcript operation truthfully before reporting failure to the caller.
256
+ await this.abortOperation("pre_dispatch_persistence_failure").catch(() => undefined);
257
+ throw error;
258
+ }
259
+ }
260
+
261
+ async appendEvent(event: NormalizedPersistenceEvent, ts = Date.now()): Promise<boolean> {
262
+ this.assertUsable();
263
+ if (event.kind === "transition") {
264
+ throw new TranscriptRuntimeStateError("transitions require the dedicated transition boundary API");
265
+ }
266
+ const record = projectTranscriptEvent(event, {
267
+ transcriptId: this.header.transcriptId,
268
+ generation: this.header.generation,
269
+ agentSessionId: this.header.agentSessionId,
270
+ seq: this.writer.nextSequence,
271
+ ts,
272
+ policy: this.header.effectivePolicy,
273
+ });
274
+ if (!record) return false;
275
+ try {
276
+ await this.writer.append(record);
277
+ return true;
278
+ } catch (error) {
279
+ this.failure = error instanceof Error ? error : new Error(String(error));
280
+ throw error;
281
+ }
282
+ }
283
+
284
+ async appendTransitionEvent(
285
+ event: NonActivationTransitionEvent,
286
+ options: { readonly durable?: boolean; readonly ts?: number } = {},
287
+ ): Promise<void> {
288
+ this.assertUsable();
289
+ if (this.activeOperation) throw new TranscriptRuntimeStateError("a transition phase cannot be recorded during an active provider operation");
290
+ const record = projectTranscriptEvent(event, {
291
+ transcriptId: this.header.transcriptId,
292
+ generation: this.header.generation,
293
+ agentSessionId: this.header.agentSessionId,
294
+ seq: this.writer.nextSequence,
295
+ ts: options.ts ?? Date.now(),
296
+ policy: this.header.effectivePolicy,
297
+ });
298
+ if (!record || record.t !== "transition") throw new TranscriptRuntimeStateError("transition projection did not produce a structural record");
299
+ try {
300
+ await this.writer.append(record, { durable: options.durable ?? true });
301
+ } catch (error) {
302
+ this.failure = error instanceof Error ? error : new Error(String(error));
303
+ throw error;
304
+ }
305
+ }
306
+
307
+ /** Publish resumable non-routing state when no provider operation is active. */
308
+ async publishCheckpoint(
309
+ changes: TranscriptTerminalCheckpointChanges,
310
+ ts = Date.now(),
311
+ ): Promise<AgentSessionCheckpoint> {
312
+ this.assertUsable();
313
+ if (this._recovery.kind !== "clean") {
314
+ throw new TranscriptRuntimeStateError("uncertain transcript recovery must be resolved before checkpoint publication");
315
+ }
316
+ if (this.activeOperation) {
317
+ throw new TranscriptRuntimeStateError("standalone checkpoint cannot publish during an active operation");
318
+ }
319
+ const next = createAgentSessionCheckpoint({
320
+ ...checkpointInput(this._checkpoint),
321
+ ...(changes.model === undefined ? {} : { model: changes.model }),
322
+ ...(changes.sessionConfiguration === undefined
323
+ ? {}
324
+ : { sessionConfiguration: structuredClone(changes.sessionConfiguration) }),
325
+ ...(changes.metering === undefined ? {} : { metering: structuredClone(changes.metering) }),
326
+ stateRevision: this._checkpoint.stateRevision + 1,
327
+ boundary: changes.boundary ?? this._checkpoint.boundary,
328
+ updatedAt: timestampToIso(ts),
329
+ });
330
+ const physical = checkpointRecord(this.writer.nextSequence, next, this.header);
331
+ try {
332
+ await this.writer.append(physical, { durable: true });
333
+ const reduced = reduceTranscriptState(this.selectedCheckpointRecord, this.history, [physical]);
334
+ this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery);
335
+ await this.publishManagedCheckpoint();
336
+ return this.checkpoint;
337
+ } catch (error) {
338
+ this.failure = error instanceof Error ? error : new Error(String(error));
339
+ throw error;
340
+ }
341
+ }
342
+
343
+ async activateTransition(
344
+ event: TargetActivationEvent,
345
+ ts = Date.now(),
346
+ ): Promise<AgentSessionCheckpoint> {
347
+ this.assertUsable();
348
+ if (this._recovery.kind !== "clean") throw new TranscriptRuntimeStateError("uncertain transcript recovery must be resolved before transition activation");
349
+ if (this.activeOperation) throw new TranscriptRuntimeStateError("a transition target cannot activate during an active provider operation");
350
+ const projected = projectTranscriptEvent(event, {
351
+ transcriptId: this.header.transcriptId,
352
+ generation: this.header.generation,
353
+ agentSessionId: this.header.agentSessionId,
354
+ seq: this.writer.nextSequence,
355
+ ts,
356
+ policy: this.header.effectivePolicy,
357
+ });
358
+ if (!projected || projected.t !== "transition") {
359
+ throw new TranscriptRuntimeStateError("target activation projection did not produce a structural record");
360
+ }
361
+ try {
362
+ await this.writer.append(projected, { durable: true });
363
+ const reduced = reduceTranscriptState(this.selectedCheckpointRecord, this.history, [projected]);
364
+ const physical = checkpointRecord(this.writer.nextSequence, reduced.checkpoint, this.header);
365
+ await this.writer.append(physical, { durable: true });
366
+ reduceTranscriptState(this.selectedCheckpointRecord, this.history, [projected, physical]);
367
+ this.installCheckpoint(
368
+ physical,
369
+ reduced.checkpoint,
370
+ reduced.recovery,
371
+ reduced.internalSessionHistory,
372
+ );
373
+ await this.publishManagedCheckpoint();
374
+ return this.checkpoint;
375
+ } catch (error) {
376
+ this.failure = error instanceof Error ? error : new Error(String(error));
377
+ throw error;
378
+ }
379
+ }
380
+
381
+ /** Flush policy-projected input appended after beginOperation before provider dispatch. */
382
+ async syncBeforeDispatch(): Promise<void> {
383
+ this.assertUsable();
384
+ this.requireActive();
385
+ await this.writer.sync();
386
+ }
387
+
388
+ async finishOperation(
389
+ event: "settled" | "failed" | "cancelled" | "interrupted",
390
+ changes: TranscriptTerminalCheckpointChanges = {},
391
+ errorCode?: PersistedMachineCode,
392
+ ts = Date.now(),
393
+ ): Promise<AgentSessionCheckpoint> {
394
+ this.assertUsable();
395
+ const active = this.requireActive();
396
+ const terminal: TranscriptOperationRecord = {
397
+ ...this.envelope(this.writer.nextSequence, ts),
398
+ t: "operation",
399
+ operationId: active.operationId,
400
+ operationKind: active.kind,
401
+ event,
402
+ ...(errorCode === undefined ? {} : { errorCode }),
403
+ };
404
+ try {
405
+ await this.writer.append(terminal);
406
+ const next = createAgentSessionCheckpoint({
407
+ ...checkpointInput(this._checkpoint),
408
+ ...(changes.model === undefined ? {} : { model: changes.model }),
409
+ ...(changes.sessionConfiguration === undefined
410
+ ? {}
411
+ : { sessionConfiguration: structuredClone(changes.sessionConfiguration) }),
412
+ ...(changes.metering === undefined ? {} : { metering: structuredClone(changes.metering) }),
413
+ stateRevision: this._checkpoint.stateRevision + 1,
414
+ transcript: { ...this._checkpoint.transcript!, coveredSequence: terminal.seq },
415
+ boundary: changes.boundary ?? { status: "settled", lastSettledOperationId: active.operationId },
416
+ updatedAt: timestampToIso(ts),
417
+ });
418
+ const physical = checkpointRecord(this.writer.nextSequence, next, this.header);
419
+ await this.writer.append(physical, { durable: true });
420
+ const reduced = reduceTranscriptState(
421
+ this.selectedCheckpointRecord,
422
+ this.history,
423
+ [active.started, terminal, physical],
424
+ );
425
+ this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery);
426
+ this.activeOperation = null;
427
+ await this.publishManagedCheckpoint();
428
+ return this.checkpoint;
429
+ } catch (error) {
430
+ this.failure = error instanceof Error ? error : new Error(String(error));
431
+ throw error;
432
+ }
433
+ }
434
+
435
+ async abortOperation(
436
+ reason: OperationAbortReason,
437
+ ts = Date.now(),
438
+ ): Promise<AgentSessionCheckpoint> {
439
+ this.assertUsable();
440
+ const active = this.requireActive();
441
+ const aborted: TranscriptOperationRecord = {
442
+ ...this.envelope(this.writer.nextSequence, ts),
443
+ t: "operation",
444
+ operationId: active.operationId,
445
+ operationKind: active.kind,
446
+ event: "aborted",
447
+ abortReason: reason,
448
+ stateRevision: this._checkpoint.stateRevision + 1,
449
+ };
450
+ try {
451
+ await this.writer.append(aborted);
452
+ const reduced = reduceTranscriptState(
453
+ this.selectedCheckpointRecord,
454
+ this.history,
455
+ [active.started, aborted],
456
+ );
457
+ const physical = checkpointRecord(this.writer.nextSequence, reduced.checkpoint, this.header);
458
+ await this.writer.append(physical, { durable: true });
459
+ reduceTranscriptState(
460
+ this.selectedCheckpointRecord,
461
+ this.history,
462
+ [active.started, aborted, physical],
463
+ );
464
+ this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery);
465
+ this.activeOperation = null;
466
+ await this.publishManagedCheckpoint();
467
+ return this.checkpoint;
468
+ } catch (error) {
469
+ this.failure = error instanceof Error ? error : new Error(String(error));
470
+ throw error;
471
+ }
472
+ }
473
+
474
+ /**
475
+ * Durably acknowledge an uncertain provider boundary without claiming its outcome.
476
+ *
477
+ * The interrupted terminal closes a boundary that had no terminal. When a terminal was
478
+ * already durable, only its missing checkpoint is materialized. The canonical reducer
479
+ * validates the complete opening tail before the runtime exposes clean state.
480
+ */
481
+ async acceptHarnessRecovery(ts = Date.now()): Promise<AgentSessionCheckpoint> {
482
+ this.assertUsable();
483
+ if (this.activeOperation) throw new TranscriptRuntimeStateError("cannot resolve recovery during an active operation");
484
+ if (this._recovery.kind !== "uncertain") {
485
+ throw new TranscriptRuntimeStateError("recovery resolution requires an uncertain transcript boundary");
486
+ }
487
+ const recovery = this._recovery;
488
+ const tail = this.openingStructuralTail.map((record) => structuredClone(record));
489
+ let coveredSequence: number;
490
+ try {
491
+ if (recovery.boundary === "terminal_without_checkpoint") {
492
+ const terminal = [...tail].reverse().find((record) =>
493
+ record.t === "operation"
494
+ && record.operationId === recovery.operationId
495
+ && record.event !== "started");
496
+ if (!terminal) {
497
+ throw new TranscriptRuntimeStateError("uncertain terminal boundary has no durable terminal record");
498
+ }
499
+ coveredSequence = terminal.seq;
500
+ } else {
501
+ const terminal: TranscriptOperationRecord = {
502
+ ...this.envelope(this.writer.nextSequence, ts),
503
+ t: "operation",
504
+ operationId: recovery.operationId,
505
+ operationKind: operationKindForRecovery(this.selectedCheckpointRecord, tail, recovery.operationId),
506
+ event: "interrupted",
507
+ errorCode: "recovery_accepted_harness_state",
508
+ };
509
+ await this.writer.append(terminal);
510
+ tail.push(terminal);
511
+ coveredSequence = terminal.seq;
512
+ }
513
+ const next = createAgentSessionCheckpoint({
514
+ ...checkpointInput(this._checkpoint),
515
+ stateRevision: this._checkpoint.stateRevision + 1,
516
+ transcript: { ...this._checkpoint.transcript!, coveredSequence },
517
+ boundary: { status: "settled", lastSettledOperationId: recovery.operationId },
518
+ updatedAt: timestampToIso(ts),
519
+ });
520
+ const physical = checkpointRecord(this.writer.nextSequence, next, this.header);
521
+ await this.writer.append(physical, { durable: true });
522
+ tail.push(physical);
523
+ const reduced = reduceTranscriptState(this.selectedCheckpointRecord, this.history, tail);
524
+ if (reduced.recovery.kind !== "clean") {
525
+ throw new TranscriptRuntimeStateError("recovery acknowledgement did not produce a clean boundary");
526
+ }
527
+ this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery, reduced.internalSessionHistory);
528
+ this.openingStructuralTail = [];
529
+ await this.publishManagedCheckpoint();
530
+ await this.appendEvent({
531
+ kind: "lifecycle",
532
+ event: "recovery_resolved",
533
+ detail: {
534
+ strategy: "accept_harness_state",
535
+ operationId: recovery.operationId,
536
+ priorBoundary: recovery.boundary,
537
+ },
538
+ });
539
+ return this.checkpoint;
540
+ } catch (error) {
541
+ this.failure = error instanceof Error ? error : new Error(String(error));
542
+ throw error;
543
+ }
544
+ }
545
+
546
+ async close(): Promise<void> {
547
+ if (this.closed) return;
548
+ this.closed = true;
549
+ await this.writer.close();
550
+ }
551
+
552
+ private installCheckpoint(
553
+ record: TranscriptCheckpointRecord,
554
+ checkpoint: AgentSessionCheckpoint,
555
+ recovery: SessionRecoveryStatus,
556
+ historyEntries: readonly InternalSessionHistoryEntry[] = this.history.entries,
557
+ ): void {
558
+ this.selectedCheckpointRecord = record;
559
+ this.history = reduceInternalSessionHistory(historyEntries);
560
+ this._checkpoint = checkpoint;
561
+ this._recovery = recovery;
562
+ }
563
+
564
+ private envelope(seq: number, ts: number) {
565
+ return {
566
+ v: 2 as const,
567
+ transcriptId: this.header.transcriptId,
568
+ generation: this.header.generation,
569
+ agentSessionId: this.header.agentSessionId,
570
+ seq,
571
+ ts,
572
+ };
573
+ }
574
+
575
+ private requireActive() {
576
+ if (!this.activeOperation) throw new TranscriptRuntimeStateError("no transcript operation is active");
577
+ return this.activeOperation;
578
+ }
579
+
580
+ private assertUsable(): void {
581
+ if (this.closed) throw new TranscriptRuntimeStateError("transcript persistence runtime is closed");
582
+ if (this.failure) throw new TranscriptRuntimeStateError(`transcript persistence runtime failed: ${this.failure.message}`);
583
+ }
584
+
585
+ private async publishManagedCheckpoint(): Promise<void> {
586
+ await this.checkpointPublisher?.(this.checkpoint, this.internalSessionHistory);
587
+ }
588
+ }
589
+
590
+ function checkpointRecord(
591
+ seq: number,
592
+ checkpoint: AgentSessionCheckpoint,
593
+ header: { transcriptId: string; generation: number; agentSessionId: string },
594
+ ): TranscriptCheckpointRecord {
595
+ return {
596
+ v: 2,
597
+ t: "checkpoint",
598
+ transcriptId: header.transcriptId,
599
+ generation: header.generation,
600
+ agentSessionId: header.agentSessionId,
601
+ seq,
602
+ ts: Date.parse(checkpoint.updatedAt),
603
+ stateRevision: checkpoint.stateRevision,
604
+ checkpoint,
605
+ };
606
+ }
607
+
608
+ function checkpointInput(checkpoint: AgentSessionCheckpoint): AgentSessionCheckpointInput {
609
+ const { version: _version, digest: _digest, ...input } = checkpoint;
610
+ return structuredClone(input);
611
+ }
612
+
613
+ function timestampToIso(ts: number): string {
614
+ try {
615
+ return new Date(ts).toISOString();
616
+ } catch (error) {
617
+ throw new TranscriptRuntimeStateError(`invalid operation timestamp: ${String(error)}`);
618
+ }
619
+ }
620
+
621
+ function operationKindForRecovery(
622
+ selected: TranscriptCheckpointRecord,
623
+ tail: readonly TranscriptStructuralRecord[],
624
+ operationId: string,
625
+ ): OperationKind {
626
+ const started = [...tail].reverse().find((record) =>
627
+ record.t === "operation" && record.operationId === operationId && record.event === "started");
628
+ if (started?.t === "operation") return started.operationKind;
629
+ // An in-flight materialized checkpoint can be selected after its started record. Its
630
+ // exact kind is presentation metadata, not continuation state; use the explicit
631
+ // catch-all rather than guessing a user prompt.
632
+ if (selected.checkpoint.boundary.status === "in_flight"
633
+ && selected.checkpoint.boundary.interruptedOperationId === operationId) return "other";
634
+ throw new TranscriptRuntimeStateError("cannot identify the uncertain operation kind");
635
+ }
636
+
637
+ function assertInitialCheckpoint(
638
+ header: TranscriptHeaderRecord,
639
+ path: string,
640
+ checkpoint: AgentSessionCheckpoint,
641
+ ): void {
642
+ if (header.event !== "created" && header.event !== "replaced") {
643
+ throw new TranscriptRuntimeStateError("new transcript generation requires a created or replaced header");
644
+ }
645
+ if (checkpoint.agentSessionId !== header.agentSessionId) {
646
+ throw new TranscriptRuntimeStateError("initial checkpoint agentSessionId disagrees with header");
647
+ }
648
+ if (!checkpoint.transcript) {
649
+ throw new TranscriptRuntimeStateError("initial transcript checkpoint has no transcript identity");
650
+ }
651
+ if (
652
+ checkpoint.transcript.transcriptId !== header.transcriptId ||
653
+ checkpoint.transcript.generation !== header.generation ||
654
+ checkpoint.transcript.path !== path
655
+ ) {
656
+ throw new TranscriptRuntimeStateError("initial checkpoint transcript identity disagrees with header");
657
+ }
658
+ if (checkpoint.transcript.coveredSequence !== header.seq) {
659
+ throw new TranscriptRuntimeStateError("initial checkpoint must cover exactly the transcript header");
660
+ }
661
+ if (checkpoint.internalSessionHistoryRevision !== 0) {
662
+ throw new TranscriptRuntimeStateError("initial checkpoint history must be empty");
663
+ }
664
+ if (checkpoint.boundary.status !== "settled" || checkpoint.boundary.lastSettledOperationId !== null) {
665
+ throw new TranscriptRuntimeStateError("initial checkpoint boundary must be settled with no operation");
666
+ }
667
+ }