@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,689 @@
1
+ import {
2
+ AgentSession,
3
+ type AgentSessionOpenResult,
4
+ } from "../agent-session.ts";
5
+ import type { ManagedAgentSessionLoadConfig } from "./managed-load.ts";
6
+ import { loadManagedAgentSession, persistenceFromManagedRecord } from "./managed-load.ts";
7
+ import { attachManagedRegistryPublisher, projectManagedAgentSessionRecord } from "./managed-registry.ts";
8
+ import {
9
+ AgentSessionStoreConflictError,
10
+ MaintenanceAlreadyCompletedError,
11
+ type AgentSessionRecord,
12
+ type AgentSessionStore,
13
+ type RestorationMaintenance,
14
+ type StagedContinuationState,
15
+ } from "./registry.ts";
16
+ import { sha256CanonicalJson } from "./integrity.ts";
17
+ import { acquireSessionLogWriterLock } from "./session-log-writer.ts";
18
+ import type { SessionLogWriterLock } from "./session-log-writer.ts";
19
+ import { AuditPersistenceRuntime } from "./audit-runtime.ts";
20
+ import { createAgentSessionCheckpoint } from "./checkpoint.ts";
21
+ import type {
22
+ AuditLogConfig,
23
+ ResolvedAuditLogConfig,
24
+ ResolvedTranscriptConfig,
25
+ TranscriptConfig,
26
+ } from "./config.ts";
27
+ import { resolveDirectPersistence } from "./config.ts";
28
+ import { resolveSessionLogPaths } from "./paths.ts";
29
+ import { FileSessionLogWriter } from "./session-log-writer.ts";
30
+ import { chmod, lstat, mkdir, open, rename, unlink } from "node:fs/promises";
31
+ import { dirname, isAbsolute, resolve as resolvePath } from "node:path";
32
+ import { scanTranscriptContinuation } from "./transcript-scanner.ts";
33
+ import { AuditLogReader } from "./audit-log-reader.ts";
34
+ import type { AuditLogHeaderRecord } from "./records.ts";
35
+
36
+ export interface RestoreAgentSessionOptions extends ManagedAgentSessionLoadConfig {
37
+ readonly restorationId: string;
38
+ readonly expectedIncarnationId: string;
39
+ readonly expectedRecordRevision: number;
40
+ readonly replacementTranscript?: false | (TranscriptConfig & { readonly path: string });
41
+ readonly replacementAuditLog?: false | (AuditLogConfig & { readonly path: string });
42
+ }
43
+
44
+ export class AgentSessionRestorationError extends Error {
45
+ constructor(message: string, options?: ErrorOptions) {
46
+ super(message, options);
47
+ this.name = "AgentSessionRestorationError";
48
+ }
49
+ }
50
+
51
+ /** Reactivate a tombstone whose authoritative transcript was retained. */
52
+ export async function restoreManagedAgentSession(
53
+ store: AgentSessionStore,
54
+ agentSessionId: string,
55
+ options: RestoreAgentSessionOptions,
56
+ ): Promise<AgentSessionOpenResult> {
57
+ validateOptions(agentSessionId, options);
58
+ const record = await store.getAgentSessionRecord(agentSessionId);
59
+ if (!record) throw new AgentSessionStoreConflictError("agent-session record does not exist");
60
+ options = await normalizeRestorationOptions(record, options);
61
+ if (record.incarnationId !== options.expectedIncarnationId
62
+ || record.recordRevision !== options.expectedRecordRevision) {
63
+ return await completedOrConflict(store, agentSessionId, record, options);
64
+ }
65
+ if (!record.deletion) throw new AgentSessionRestorationError("only a deleted managed session can be restored");
66
+ const retainedTranscript = record.transcript && !record.deletion.transcriptDeletedAt
67
+ ? record.transcript : null;
68
+ const retainedAudit = record.auditLog && !record.deletion.auditLogDeletedAt
69
+ ? record.auditLog : null;
70
+ if (!retainedTranscript && options.replacementTranscript === undefined) {
71
+ throw new AgentSessionRestorationError(
72
+ "a deleted transcript requires explicit replacementTranscript:false or a replacement",
73
+ );
74
+ }
75
+ if (retainedTranscript && options.replacementTranscript !== undefined) {
76
+ throw new AgentSessionRestorationError("a retained transcript cannot be replaced during this restoration slice");
77
+ }
78
+ if (!retainedAudit && record.auditLog && options.replacementAuditLog === undefined) {
79
+ throw new AgentSessionRestorationError("deleted audit-log state must be explicitly disabled or replaced");
80
+ }
81
+ if (retainedAudit && options.replacementAuditLog !== undefined) {
82
+ throw new AgentSessionRestorationError(
83
+ "a retained audit log cannot be replaced during this restoration slice",
84
+ );
85
+ }
86
+ await validateRestorationRequest(record, options, retainedTranscript, retainedAudit);
87
+ const requestDigest = restorationDigest(agentSessionId, options);
88
+ const transcriptPath = retainedTranscript?.path
89
+ ?? (options.replacementTranscript
90
+ ? options.replacementTranscript.path : null);
91
+ const auditPath = retainedAudit?.path
92
+ ?? (options.replacementAuditLog
93
+ ? options.replacementAuditLog.path : null);
94
+ const locks = await acquireOrderedLocks([
95
+ transcriptPath,
96
+ auditPath,
97
+ ]);
98
+ const transcriptLock = transcriptPath ? locks.get(transcriptPath) : undefined;
99
+ const auditLock = auditPath ? locks.get(auditPath) : undefined;
100
+ let transferred = false;
101
+ let opened: AgentSessionOpenResult | null = null;
102
+ try {
103
+ await validateRestorationArtifacts(
104
+ record, options, requestDigest, retainedTranscript, retainedAudit,
105
+ );
106
+ const proposed = restorationMaintenance(record, options, requestDigest);
107
+ const prepared = await store.prepareMaintenance(agentSessionId, proposed, {
108
+ expectedRecordRevision: options.expectedRecordRevision,
109
+ });
110
+ if (prepared.status === "already_completed") {
111
+ throw new MaintenanceAlreadyCompletedError(prepared.receipt);
112
+ }
113
+ if (prepared.maintenance.kind !== "restoration") {
114
+ throw new AgentSessionRestorationError("prepared maintenance is not restoration");
115
+ }
116
+ if (prepared.maintenance.details.stagedRecord) {
117
+ await store.finalizeMaintenance(
118
+ agentSessionId, record.incarnationId, options.restorationId, requestDigest,
119
+ { save: prepared.maintenance.details.stagedRecord },
120
+ );
121
+ await Promise.all([...locks.values()].map((lock) => lock.release().catch(() => undefined)));
122
+ transferred = true;
123
+ return await loadManagedAgentSession(store, agentSessionId, runtimeOptions(options));
124
+ }
125
+ const runtime = runtimeOptions(options);
126
+ const authorityRecord = await prepareRestorationAuthority(
127
+ record, options, requestDigest, prepared.maintenance.startedAt,
128
+ );
129
+ let currentMaintenance = prepared.maintenance;
130
+ const stageContinuation = async (
131
+ observed: StagedContinuationState,
132
+ ): Promise<StagedContinuationState> => {
133
+ const existing = currentMaintenance.details.stagedContinuation;
134
+ if (existing) {
135
+ assertSameContinuation(existing, observed);
136
+ return existing;
137
+ }
138
+ const staged: RestorationMaintenance = {
139
+ ...currentMaintenance,
140
+ details: { ...currentMaintenance.details, stagedContinuation: observed },
141
+ };
142
+ await store.updateMaintenance(
143
+ agentSessionId, record.incarnationId, options.restorationId, staged,
144
+ );
145
+ currentMaintenance = staged;
146
+ return observed;
147
+ };
148
+ const activeAudit = authorityRecord.auditLog;
149
+ const audit = activeAudit
150
+ ? await AuditPersistenceRuntime.resume({
151
+ path: activeAudit.path,
152
+ agentSessionId,
153
+ auditLogId: activeAudit.auditLogId,
154
+ generation: activeAudit.generation,
155
+ writerLock: auditLock,
156
+ })
157
+ : undefined;
158
+ transferred = true;
159
+ opened = authorityRecord.transcript
160
+ ? await AgentSession.openManaged({
161
+ ...runtime,
162
+ agentSessionId,
163
+ persistence: persistenceFromManagedRecord(authorityRecord),
164
+ }, transcriptLock, audit, stageContinuation)
165
+ : await AgentSession.openManagedRegistry({
166
+ ...runtime,
167
+ agentSessionId,
168
+ checkpoint: authorityRecord.checkpoint,
169
+ persistence: {
170
+ transcript: false,
171
+ auditLog: authorityRecord.auditLog ? {
172
+ path: authorityRecord.auditLog.path,
173
+ capture: authorityRecord.auditLog.effectivePolicy,
174
+ includeTruncationDigests: authorityRecord.auditLog.includeTruncationDigests,
175
+ } : false,
176
+ sessionConfiguration: authorityRecord.sessionConfigurationPersistence ?? { values: "typed" },
177
+ },
178
+ }, authorityRecord.internalSessionHistory, audit, stageContinuation);
179
+ const snapshot = await opened.session.publishManagedRestorationCheckpoint();
180
+ const stagedContinuation: StagedContinuationState = {
181
+ adapterId: snapshot.checkpoint.adapterId,
182
+ mode: snapshot.checkpoint.mode,
183
+ internalSessionId: snapshot.checkpoint.internalSessionId,
184
+ internalSessionActivatedAt: snapshot.checkpoint.internalSessionActivatedAt,
185
+ model: snapshot.checkpoint.model,
186
+ sessionConfiguration: snapshot.checkpoint.sessionConfiguration,
187
+ protocol: snapshot.checkpoint.protocol,
188
+ };
189
+ const { deletion: _deletion, ...activeRecord } = authorityRecord;
190
+ const projected = projectManagedAgentSessionRecord(
191
+ { ...activeRecord, recordRevision: record.recordRevision },
192
+ snapshot.checkpoint,
193
+ snapshot.internalSessionHistory,
194
+ { lastOpenedAt: snapshot.checkpoint.updatedAt },
195
+ );
196
+ const existingContinuation = currentMaintenance.details.stagedContinuation;
197
+ if (existingContinuation) assertSameContinuation(existingContinuation, stagedContinuation);
198
+ const continuationStaged: RestorationMaintenance = existingContinuation
199
+ ? currentMaintenance
200
+ : { ...currentMaintenance, details: { ...currentMaintenance.details, stagedContinuation } };
201
+ if (!existingContinuation) {
202
+ await store.updateMaintenance(
203
+ agentSessionId, record.incarnationId, options.restorationId, continuationStaged,
204
+ );
205
+ }
206
+ const staged: RestorationMaintenance = {
207
+ ...continuationStaged,
208
+ details: { ...continuationStaged.details, stagedRecord: projected },
209
+ };
210
+ await store.updateMaintenance(
211
+ agentSessionId, record.incarnationId, options.restorationId, staged,
212
+ );
213
+ await store.finalizeMaintenance(
214
+ agentSessionId,
215
+ record.incarnationId,
216
+ options.restorationId,
217
+ requestDigest,
218
+ { save: projected },
219
+ );
220
+ attachManagedRegistryPublisher(opened.session, store);
221
+ return opened;
222
+ } catch (error) {
223
+ await opened?.session.stop().catch(() => undefined);
224
+ throw error;
225
+ } finally {
226
+ if (!transferred) {
227
+ await Promise.all([...locks.values()].map((lock) => lock.release().catch(() => undefined)));
228
+ }
229
+ }
230
+ }
231
+
232
+ async function prepareRestorationAuthority(
233
+ record: AgentSessionRecord,
234
+ options: RestoreAgentSessionOptions,
235
+ requestDigest: string,
236
+ createdAt: string,
237
+ ): Promise<AgentSessionRecord> {
238
+ const keepTranscript = record.transcript !== null && record.deletion?.transcriptDeletedAt === undefined;
239
+ const keepAudit = record.auditLog !== null && record.deletion?.auditLogDeletedAt === undefined;
240
+ let checkpoint = record.checkpoint;
241
+ let transcript = keepTranscript ? record.transcript : null;
242
+ if (!keepTranscript && options.replacementTranscript) {
243
+ const config = options.replacementTranscript;
244
+ const resolved = resolveDirectPersistence({
245
+ transcript: config, auditLog: false,
246
+ sessionConfiguration: record.sessionConfigurationPersistence,
247
+ limits: record.transcript?.effectiveLimits,
248
+ });
249
+ if (resolved === false || resolved.transcript === false) throw new AgentSessionRestorationError("replacement transcript is disabled");
250
+ const transcriptId = stableReplacementId(requestDigest, "transcript");
251
+ const { version: _version, digest: _digest, ...input } = checkpoint;
252
+ checkpoint = createAgentSessionCheckpoint({
253
+ ...input,
254
+ stateRevision: checkpoint.stateRevision + 1,
255
+ transcript: { transcriptId, generation: 1, path: config.path, coveredSequence: 1 },
256
+ updatedAt: createdAt,
257
+ });
258
+ checkpoint = await installRestorationTranscript(record, config.path, resolved.transcript, resolved.limits, checkpoint, transcriptId, options.restorationId, requestDigest, createdAt);
259
+ transcript = {
260
+ path: config.path, transcriptId, generation: 1,
261
+ preset: resolved.transcript.preset,
262
+ effectivePolicy: resolved.transcript.capture,
263
+ effectiveLimits: resolved.limits,
264
+ includeTruncationDigests: resolved.transcript.includeTruncationDigests,
265
+ };
266
+ } else if (!keepTranscript && checkpoint.transcript) {
267
+ const { version: _version, digest: _digest, ...input } = checkpoint;
268
+ checkpoint = createAgentSessionCheckpoint({
269
+ ...input,
270
+ stateRevision: checkpoint.stateRevision + 1,
271
+ transcript: null,
272
+ updatedAt: createdAt,
273
+ });
274
+ }
275
+ let auditLog = keepAudit ? record.auditLog : null;
276
+ if (!keepAudit && options.replacementAuditLog) {
277
+ const config = options.replacementAuditLog;
278
+ const resolved = resolveDirectPersistence({ transcript: false, auditLog: config, limits: record.auditLog?.effectiveLimits });
279
+ if (resolved === false || resolved.auditLog === false) throw new AgentSessionRestorationError("replacement audit log is disabled");
280
+ const auditLogId = stableReplacementId(requestDigest, "audit");
281
+ await installRestorationAudit(record, config.path, resolved.auditLog, resolved.limits, auditLogId, options.restorationId, requestDigest, createdAt);
282
+ auditLog = {
283
+ path: config.path, auditLogId, generation: 1,
284
+ effectivePolicy: resolved.auditLog.capture,
285
+ effectiveLimits: resolved.limits,
286
+ includeTruncationDigests: resolved.auditLog.includeTruncationDigests,
287
+ };
288
+ }
289
+ return { ...record, checkpoint, transcript, auditLog };
290
+ }
291
+
292
+ async function acquireOrderedLocks(paths: readonly (string | null)[]): Promise<Map<string, SessionLogWriterLock>> {
293
+ const locks = new Map<string, SessionLogWriterLock>();
294
+ try {
295
+ for (const path of [...new Set(paths.filter((value): value is string => value !== null))]
296
+ .sort((left, right) => left.localeCompare(right))) {
297
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
298
+ await chmod(dirname(path), 0o700).catch(() => undefined);
299
+ locks.set(path, await acquireSessionLogWriterLock(path));
300
+ }
301
+ return locks;
302
+ } catch (error) {
303
+ await Promise.all([...locks.values()].map((lock) => lock.release().catch(() => undefined)));
304
+ throw error;
305
+ }
306
+ }
307
+
308
+ function stableReplacementId(requestDigest: string, kind: "transcript" | "audit"): string {
309
+ return `${kind}-${sha256CanonicalJson({ requestDigest, kind }).slice(0, 32)}`;
310
+ }
311
+
312
+ async function installRestorationTranscript(
313
+ record: AgentSessionRecord,
314
+ path: string,
315
+ config: ResolvedTranscriptConfig,
316
+ limits: NonNullable<AgentSessionRecord["transcript"]>["effectiveLimits"],
317
+ checkpoint: AgentSessionRecord["checkpoint"],
318
+ transcriptId: string,
319
+ operationId: string,
320
+ requestDigest: string,
321
+ createdAt: string,
322
+ ): Promise<AgentSessionRecord["checkpoint"]> {
323
+ if (await exists(path)) {
324
+ const scan = await scanTranscriptContinuation(path, {
325
+ agentSessionId: record.agentSessionId, transcriptId, generation: 1,
326
+ });
327
+ if (scan.reduction.checkpoint.incarnationId !== checkpoint.incarnationId
328
+ || scan.reduction.checkpoint.stateRevision < checkpoint.stateRevision) {
329
+ throw new AgentSessionRestorationError("existing restoration transcript has incompatible authority");
330
+ }
331
+ return scan.reduction.checkpoint;
332
+ }
333
+ const temp = `${path}.restoration-${requestDigest.slice(0, 24)}`;
334
+ await unlink(temp).catch(() => undefined);
335
+ const writer = await FileSessionLogWriter.create({
336
+ kind: "transcript", path: temp, logicalPath: path,
337
+ header: {
338
+ v: 2, t: "header", transcriptId, generation: 1,
339
+ agentSessionId: record.agentSessionId, seq: 1, ts: Date.parse(createdAt),
340
+ event: "replaced", createdAt,
341
+ preset: config.preset,
342
+ effectivePolicy: config.capture,
343
+ effectiveLimits: limits,
344
+ includeTruncationDigests: config.includeTruncationDigests,
345
+ installation: { kind: "restoration", operationId, requestDigest },
346
+ },
347
+ maxRecordBytes: limits.maxRecordBytes,
348
+ });
349
+ try {
350
+ await writer.append({
351
+ v: 2, t: "checkpoint", transcriptId, generation: 1,
352
+ agentSessionId: record.agentSessionId, seq: 2, ts: Date.parse(createdAt),
353
+ stateRevision: checkpoint.stateRevision, checkpoint,
354
+ }, { durable: true });
355
+ } finally {
356
+ await writer.close();
357
+ }
358
+ await rename(temp, path);
359
+ await syncDirectory(dirname(path));
360
+ return checkpoint;
361
+ }
362
+
363
+ async function installRestorationAudit(
364
+ record: AgentSessionRecord,
365
+ path: string,
366
+ config: ResolvedAuditLogConfig,
367
+ limits: NonNullable<AgentSessionRecord["auditLog"]>["effectiveLimits"],
368
+ auditLogId: string,
369
+ operationId: string,
370
+ requestDigest: string,
371
+ createdAt: string,
372
+ ): Promise<void> {
373
+ if (await exists(path)) return;
374
+ const temp = `${path}.restoration-${requestDigest.slice(0, 24)}`;
375
+ await unlink(temp).catch(() => undefined);
376
+ const writer = await FileSessionLogWriter.create({
377
+ kind: "audit", path: temp,
378
+ header: {
379
+ v: 1, t: "header", auditLogId, generation: 1,
380
+ agentSessionId: record.agentSessionId, seq: 1, ts: Date.parse(createdAt),
381
+ event: "replaced", createdAt,
382
+ effectivePolicy: config.capture,
383
+ effectiveLimits: limits,
384
+ includeTruncationDigests: config.includeTruncationDigests,
385
+ installation: { kind: "restoration", operationId, requestDigest },
386
+ },
387
+ maxRecordBytes: limits.maxRecordBytes,
388
+ });
389
+ await writer.close();
390
+ await rename(temp, path);
391
+ await syncDirectory(dirname(path));
392
+ }
393
+
394
+ async function exists(path: string): Promise<boolean> {
395
+ try {
396
+ const info = await lstat(path);
397
+ if (!info.isFile() || info.isSymbolicLink()) {
398
+ throw new AgentSessionRestorationError(`replacement destination is not a regular file: ${path}`);
399
+ }
400
+ return true;
401
+ } catch (error) {
402
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
403
+ throw error;
404
+ }
405
+ }
406
+
407
+ async function syncDirectory(path: string): Promise<void> {
408
+ const handle = await open(path, "r");
409
+ try { await handle.sync(); } finally { await handle.close(); }
410
+ }
411
+
412
+ function runtimeOptions(options: RestoreAgentSessionOptions): ManagedAgentSessionLoadConfig {
413
+ const {
414
+ restorationId: _restorationId,
415
+ expectedIncarnationId: _expectedIncarnationId,
416
+ expectedRecordRevision: _expectedRecordRevision,
417
+ replacementTranscript: _replacementTranscript,
418
+ replacementAuditLog: _replacementAuditLog,
419
+ ...runtime
420
+ } = options;
421
+ return runtime;
422
+ }
423
+
424
+ async function completedOrConflict(
425
+ store: AgentSessionStore,
426
+ id: string,
427
+ record: AgentSessionRecord,
428
+ options: RestoreAgentSessionOptions,
429
+ ): Promise<never> {
430
+ const result = await store.prepareMaintenance(
431
+ id,
432
+ restorationMaintenance(record, options, restorationDigest(id, options)),
433
+ { expectedRecordRevision: options.expectedRecordRevision },
434
+ );
435
+ if (result.status === "already_completed") {
436
+ throw new MaintenanceAlreadyCompletedError(result.receipt);
437
+ }
438
+ throw new AgentSessionStoreConflictError("agent-session record compare-and-swap failed");
439
+ }
440
+
441
+ function restorationMaintenance(
442
+ record: AgentSessionRecord,
443
+ options: RestoreAgentSessionOptions,
444
+ requestDigest: string,
445
+ ): RestorationMaintenance {
446
+ return {
447
+ kind: "restoration",
448
+ incarnationId: options.expectedIncarnationId,
449
+ baseRecordRevision: options.expectedRecordRevision,
450
+ operationId: options.restorationId,
451
+ requestDigest,
452
+ status: "prepared",
453
+ startedAt: new Date().toISOString(),
454
+ details: {
455
+ transcript: record.transcript && !record.deletion?.transcriptDeletedAt
456
+ ? { action: "retain", path: record.transcript.path }
457
+ : options.replacementTranscript
458
+ ? { action: "replace", path: options.replacementTranscript.path }
459
+ : { action: "disable" },
460
+ auditLog: record.auditLog && !record.deletion?.auditLogDeletedAt
461
+ ? { action: "retain", path: record.auditLog.path }
462
+ : options.replacementAuditLog
463
+ ? { action: "replace", path: options.replacementAuditLog.path }
464
+ : { action: "disable" },
465
+ },
466
+ };
467
+ }
468
+
469
+ function restorationDigest(id: string, options: RestoreAgentSessionOptions): string {
470
+ return sha256CanonicalJson({
471
+ agentSessionId: id,
472
+ restorationId: options.restorationId,
473
+ expectedIncarnationId: options.expectedIncarnationId,
474
+ expectedRecordRevision: options.expectedRecordRevision,
475
+ adapterId: options.adapterId,
476
+ strategies: options.continuation?.strategies?.map((strategy) =>
477
+ strategy.kind === "new_from_transcript"
478
+ ? { kind: strategy.kind, strategyId: strategy.strategyId }
479
+ : strategy.kind === "new_from_consumer_continuation"
480
+ ? { kind: strategy.kind, continuationId: strategy.continuationId }
481
+ : { kind: strategy.kind }) ?? [{ kind: "load_internal_session" }],
482
+ replacementTranscript: options.replacementTranscript === undefined ? "retain" : options.replacementTranscript,
483
+ replacementAuditLog: options.replacementAuditLog === undefined ? "retain" : options.replacementAuditLog,
484
+ });
485
+ }
486
+
487
+ function validateOptions(id: string, options: RestoreAgentSessionOptions): void {
488
+ if (!id.trim() || !options?.restorationId?.trim() || !options?.expectedIncarnationId?.trim()) {
489
+ throw new AgentSessionRestorationError("session, restoration, and incarnation IDs must be nonblank");
490
+ }
491
+ if (!Number.isSafeInteger(options.expectedRecordRevision) || options.expectedRecordRevision < 1) {
492
+ throw new AgentSessionRestorationError("expectedRecordRevision must be a positive safe integer");
493
+ }
494
+ if (options.continuation?.strategies?.some(
495
+ (strategy) => strategy.kind !== "load_internal_session",
496
+ )) {
497
+ throw new AgentSessionRestorationError(
498
+ "v0 tombstone restoration only supports loading the recorded provider thread",
499
+ );
500
+ }
501
+ }
502
+
503
+ async function validateRestorationRequest(
504
+ record: AgentSessionRecord,
505
+ options: RestoreAgentSessionOptions,
506
+ retainedTranscript: NonNullable<AgentSessionRecord["transcript"]> | null,
507
+ retainedAudit: NonNullable<AgentSessionRecord["auditLog"]> | null,
508
+ ): Promise<void> {
509
+ if (options.adapterId !== record.adapterId) {
510
+ throw new AgentSessionRestorationError(
511
+ `v0 tombstone restoration requires recorded adapter ${record.adapterId}`,
512
+ );
513
+ }
514
+ const strategies = options.continuation?.strategies;
515
+ if (strategies && (strategies.length !== 1 || strategies[0]?.kind !== "load_internal_session")) {
516
+ throw new AgentSessionRestorationError(
517
+ "v0 tombstone restoration requires exactly one load_internal_session strategy",
518
+ );
519
+ }
520
+
521
+ const transcriptPath = retainedTranscript?.path
522
+ ?? (options.replacementTranscript ? options.replacementTranscript.path : null);
523
+ const auditPath = retainedAudit?.path
524
+ ?? (options.replacementAuditLog ? options.replacementAuditLog.path : null);
525
+ const combined = resolveDirectPersistence({
526
+ transcript: transcriptPath ? { path: transcriptPath } : false,
527
+ auditLog: auditPath ? { path: auditPath } : false,
528
+ });
529
+ if (combined === false) throw new AgentSessionRestorationError("restoration path validation failed");
530
+ await resolveSessionLogPaths(combined, record.agentSessionId);
531
+ }
532
+
533
+ async function normalizeRestorationOptions(
534
+ record: AgentSessionRecord,
535
+ options: RestoreAgentSessionOptions,
536
+ ): Promise<RestoreAgentSessionOptions> {
537
+ let replacementTranscript = options.replacementTranscript;
538
+ if (replacementTranscript) {
539
+ const path = await exactReplacementFilePath(
540
+ replacementTranscript.path,
541
+ "replacement transcript",
542
+ );
543
+ const resolved = resolveDirectPersistence({
544
+ transcript: { ...replacementTranscript, path },
545
+ auditLog: false,
546
+ sessionConfiguration: record.sessionConfigurationPersistence,
547
+ limits: record.transcript?.effectiveLimits,
548
+ });
549
+ if (resolved === false || resolved.transcript === false) {
550
+ throw new AgentSessionRestorationError("replacement transcript is disabled");
551
+ }
552
+ const paths = await resolveSessionLogPaths(resolved, record.agentSessionId);
553
+ if (!paths.transcriptPath || paths.transcriptPath !== path) {
554
+ throw new AgentSessionRestorationError("replacement transcript must name its final file");
555
+ }
556
+ replacementTranscript = {
557
+ path: paths.transcriptPath,
558
+ preset: resolved.transcript.preset,
559
+ capture: resolved.transcript.capture,
560
+ includeTruncationDigests: resolved.transcript.includeTruncationDigests,
561
+ };
562
+ }
563
+
564
+ let replacementAuditLog = options.replacementAuditLog;
565
+ if (replacementAuditLog) {
566
+ const path = await exactReplacementFilePath(
567
+ replacementAuditLog.path,
568
+ "replacement audit log",
569
+ );
570
+ const resolved = resolveDirectPersistence({
571
+ transcript: false,
572
+ auditLog: { ...replacementAuditLog, path },
573
+ limits: record.auditLog?.effectiveLimits,
574
+ });
575
+ if (resolved === false || resolved.auditLog === false) {
576
+ throw new AgentSessionRestorationError("replacement audit log is disabled");
577
+ }
578
+ const paths = await resolveSessionLogPaths(resolved, record.agentSessionId);
579
+ if (!paths.auditLogPath || paths.auditLogPath !== path) {
580
+ throw new AgentSessionRestorationError("replacement audit log must name its final file");
581
+ }
582
+ replacementAuditLog = {
583
+ path: paths.auditLogPath,
584
+ capture: resolved.auditLog.capture,
585
+ includeTruncationDigests: resolved.auditLog.includeTruncationDigests,
586
+ };
587
+ }
588
+
589
+ return {
590
+ ...options,
591
+ ...(replacementTranscript !== undefined ? { replacementTranscript } : {}),
592
+ ...(replacementAuditLog !== undefined ? { replacementAuditLog } : {}),
593
+ };
594
+ }
595
+
596
+ async function exactReplacementFilePath(path: string, label: string): Promise<string> {
597
+ if (!isAbsolute(path) || resolvePath(path) !== path) {
598
+ throw new AgentSessionRestorationError(
599
+ `${label} path must be an absolute normalized final filename`,
600
+ );
601
+ }
602
+ try {
603
+ const info = await lstat(path);
604
+ if (info.isDirectory()) {
605
+ throw new AgentSessionRestorationError(
606
+ `${label} path must name its final file, not a directory`,
607
+ );
608
+ }
609
+ } catch (error) {
610
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
611
+ }
612
+ return path;
613
+ }
614
+
615
+ async function validateRestorationArtifacts(
616
+ record: AgentSessionRecord,
617
+ options: RestoreAgentSessionOptions,
618
+ requestDigest: string,
619
+ retainedTranscript: NonNullable<AgentSessionRecord["transcript"]> | null,
620
+ retainedAudit: NonNullable<AgentSessionRecord["auditLog"]> | null,
621
+ ): Promise<void> {
622
+ if (retainedTranscript) {
623
+ await scanTranscriptContinuation(retainedTranscript.path, {
624
+ agentSessionId: record.agentSessionId,
625
+ transcriptId: retainedTranscript.transcriptId,
626
+ generation: retainedTranscript.generation,
627
+ });
628
+ } else if (options.replacementTranscript && await exists(options.replacementTranscript.path)) {
629
+ const transcriptId = stableReplacementId(requestDigest, "transcript");
630
+ const scan = await scanTranscriptContinuation(options.replacementTranscript.path, {
631
+ agentSessionId: record.agentSessionId,
632
+ transcriptId,
633
+ generation: 1,
634
+ });
635
+ if (scan.header.installation?.kind !== "restoration"
636
+ || scan.header.installation.operationId !== options.restorationId
637
+ || scan.header.installation.requestDigest !== requestDigest
638
+ || scan.reduction.checkpoint.incarnationId !== record.incarnationId
639
+ || scan.reduction.checkpoint.stateRevision < record.checkpoint.stateRevision + 1) {
640
+ throw new AgentSessionRestorationError(
641
+ "existing replacement transcript does not belong to this restoration",
642
+ );
643
+ }
644
+ }
645
+
646
+ if (retainedAudit) {
647
+ const header = await readAuditHeader(retainedAudit.path);
648
+ if (header.agentSessionId !== record.agentSessionId
649
+ || header.auditLogId !== retainedAudit.auditLogId
650
+ || header.generation !== retainedAudit.generation) {
651
+ throw new AgentSessionRestorationError("retained audit log identity disagrees with registry");
652
+ }
653
+ } else if (options.replacementAuditLog && await exists(options.replacementAuditLog.path)) {
654
+ const auditLogId = stableReplacementId(requestDigest, "audit");
655
+ const header = await readAuditHeader(options.replacementAuditLog.path);
656
+ if (header.agentSessionId !== record.agentSessionId
657
+ || header.auditLogId !== auditLogId
658
+ || header.generation !== 1
659
+ || header.installation?.kind !== "restoration"
660
+ || header.installation.operationId !== options.restorationId
661
+ || header.installation.requestDigest !== requestDigest) {
662
+ throw new AgentSessionRestorationError(
663
+ "existing replacement audit log does not belong to this restoration",
664
+ );
665
+ }
666
+ }
667
+ }
668
+
669
+ async function readAuditHeader(path: string): Promise<AuditLogHeaderRecord> {
670
+ const page = await new AuditLogReader(path).readPage({ limit: 1, types: ["header"] });
671
+ const header = page.items[0];
672
+ if (!header || header.t !== "header") {
673
+ throw new AgentSessionRestorationError("audit log does not contain a valid header");
674
+ }
675
+ return header as AuditLogHeaderRecord;
676
+ }
677
+
678
+ function assertSameContinuation(
679
+ expected: StagedContinuationState,
680
+ observed: StagedContinuationState,
681
+ ): void {
682
+ if (expected.adapterId !== observed.adapterId
683
+ || expected.mode !== observed.mode
684
+ || expected.internalSessionId !== observed.internalSessionId) {
685
+ throw new AgentSessionRestorationError(
686
+ "restored continuation disagrees with staged provider identity",
687
+ );
688
+ }
689
+ }