@qlairoslabs/acp-client 0.6.0 → 0.7.0

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 (40) hide show
  1. package/CONSUMER_GUIDE.md +579 -292
  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/controller.ts +13 -0
  8. package/src/index.ts +228 -3
  9. package/src/metering/engine.ts +9 -1
  10. package/src/metering/record.ts +2 -1
  11. package/src/persistence/activity-projection.ts +71 -0
  12. package/src/persistence/audit-log-reader.ts +506 -0
  13. package/src/persistence/audit-runtime.ts +162 -0
  14. package/src/persistence/checkpoint.ts +304 -0
  15. package/src/persistence/config.ts +538 -0
  16. package/src/persistence/configuration-state.ts +191 -0
  17. package/src/persistence/deletion.ts +227 -0
  18. package/src/persistence/file-registry-store.ts +740 -0
  19. package/src/persistence/integrity.ts +147 -0
  20. package/src/persistence/legacy-registry-import.ts +240 -0
  21. package/src/persistence/managed-checkpoint.ts +81 -0
  22. package/src/persistence/managed-creation.ts +456 -0
  23. package/src/persistence/managed-load.ts +172 -0
  24. package/src/persistence/managed-registry.ts +57 -0
  25. package/src/persistence/migration.ts +298 -0
  26. package/src/persistence/paths.ts +172 -0
  27. package/src/persistence/projection.ts +373 -0
  28. package/src/persistence/reconfiguration.ts +453 -0
  29. package/src/persistence/records.ts +873 -0
  30. package/src/persistence/reducer.ts +498 -0
  31. package/src/persistence/registry.ts +446 -0
  32. package/src/persistence/restoration.ts +689 -0
  33. package/src/persistence/session-log-writer.ts +480 -0
  34. package/src/persistence/state-runtime.ts +176 -0
  35. package/src/persistence/transcript-reader.ts +980 -0
  36. package/src/persistence/transcript-runtime.ts +667 -0
  37. package/src/persistence/transcript-scanner.ts +385 -0
  38. package/src/persistence/truncation.ts +276 -0
  39. package/src/session-manager.ts +257 -7
  40. package/src/transcript.ts +3 -3
@@ -16,7 +16,7 @@ import { ActivityAggregator, type ActivitySnapshot, type AggregatedRecord } from
16
16
  import type { Adapter } from "./adapters.ts";
17
17
  import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
18
18
  import type { Capabilities } from "./capabilities.ts";
19
- import type { ConfigOptions } from "./config-options.ts";
19
+ import type { ConfigOption, ConfigOptions } from "./config-options.ts";
20
20
  import type { ConnectResult } from "./client.ts";
21
21
  import { noopLogger, type Logger } from "./logger.ts";
22
22
  import { ResponseAccumulator } from "./response.ts";
@@ -57,6 +57,45 @@ import type {
57
57
  TokenUsage,
58
58
  WireEntry,
59
59
  } from "./types.ts";
60
+ import {
61
+ resolveDirectPersistence,
62
+ type AgentSessionPersistenceOptions,
63
+ type ResolvedAgentSessionPersistence,
64
+ } from "./persistence/config.ts";
65
+ import { resolveSessionLogPaths } from "./persistence/paths.ts";
66
+ import {
67
+ createAgentSessionCheckpoint,
68
+ validateAgentSessionCheckpoint,
69
+ type AgentSessionCheckpoint,
70
+ type JsonValue,
71
+ type PersistedSessionConfigSelection,
72
+ type SessionConfigurationCheckpoint,
73
+ } from "./persistence/checkpoint.ts";
74
+ import { EMPTY_HISTORY_DIGEST } from "./persistence/reducer.ts";
75
+ import type {
76
+ InternalSessionHistoryEntry,
77
+ InternalSessionDescriptor,
78
+ TranscriptHeaderRecord,
79
+ OperationKind,
80
+ } from "./persistence/records.ts";
81
+ import { TranscriptPersistenceRuntime } from "./persistence/transcript-runtime.ts";
82
+ import { RegistryPersistenceRuntime, type PersistenceStateRuntime } from "./persistence/state-runtime.ts";
83
+ import { AuditPersistenceRuntime, AuditedPersistenceRuntime, type AuditLogIdentity } from "./persistence/audit-runtime.ts";
84
+ import { TranscriptReader } from "./persistence/transcript-reader.ts";
85
+ import {
86
+ snapshotSessionConfiguration,
87
+ snapshotSessionConfigurationAfterSelection,
88
+ snapshotAcceptedEffectiveConfiguration,
89
+ } from "./persistence/configuration-state.ts";
90
+ import { persistenceEventFromActivity } from "./persistence/activity-projection.ts";
91
+ import {
92
+ canonicalizeJson,
93
+ sha256CanonicalJson,
94
+ type PersistedMachineCode,
95
+ } from "./persistence/integrity.ts";
96
+ import type { PersistenceRepair, SessionRecoveryStatus } from "./persistence/reducer.ts";
97
+ import type { StagedContinuationState } from "./persistence/registry.ts";
98
+ import type { SessionLogWriterLock } from "./persistence/session-log-writer.ts";
60
99
 
61
100
  interface PromptQueueItem {
62
101
  kind: "prompt";
@@ -78,10 +117,48 @@ interface HandoffQueueItem {
78
117
  reject: (error: unknown) => void;
79
118
  }
80
119
 
81
- type QueueItem = PromptQueueItem | HandoffQueueItem;
120
+ interface ConfigQueueItem {
121
+ kind: "set_config";
122
+ operationId: string;
123
+ configId: string;
124
+ value: unknown;
125
+ resolve: () => void;
126
+ reject: (error: unknown) => void;
127
+ }
128
+
129
+ interface ModeQueueItem {
130
+ kind: "set_mode";
131
+ transitionId: string;
132
+ mode: AgentMode;
133
+ resolve: (result: ConnectResult) => void;
134
+ reject: (error: unknown) => void;
135
+ }
136
+
137
+ interface ConfigResolutionQueueItem {
138
+ kind: "resolve_config";
139
+ resolution: ConfigurationMismatchResolution;
140
+ resolve: (result: ConfigurationMismatchResolutionResult) => void;
141
+ reject: (error: unknown) => void;
142
+ }
143
+
144
+ interface RecoveryResolutionQueueItem {
145
+ kind: "resolve_recovery";
146
+ resolution: AgentSessionRecoveryResolution;
147
+ resolve: (result: AgentSessionRecoveryResolutionResult) => void;
148
+ reject: (error: unknown) => void;
149
+ }
150
+
151
+ type QueueItem = PromptQueueItem | HandoffQueueItem | ConfigQueueItem | ModeQueueItem | ConfigResolutionQueueItem | RecoveryResolutionQueueItem;
82
152
 
83
153
  /** What the stable logical session is doing right now. */
84
- export type AgentSessionPhase = "idle" | "prompting" | "handoff" | "stopped";
154
+ export type AgentSessionPhase =
155
+ | "idle"
156
+ | "prompting"
157
+ | "handoff"
158
+ | "configuring"
159
+ | "recovering"
160
+ | "switching_mode"
161
+ | "stopped";
85
162
 
86
163
  /** Authoritative, immutable point-in-time state for orchestration consumers. */
87
164
  export interface AgentSessionState {
@@ -94,6 +171,148 @@ export interface AgentSessionState {
94
171
  readonly internalSessionId: string | null;
95
172
  readonly adapterId: string;
96
173
  readonly mode: AgentMode;
174
+ readonly promptability: AgentSessionPromptability;
175
+ }
176
+
177
+ export type ConfigurationRestoreStatus =
178
+ | { readonly kind: "matched" }
179
+ | { readonly kind: "partial"; readonly omittedConfigIds: readonly string[] }
180
+ | {
181
+ readonly kind: "mismatch";
182
+ readonly configIds: readonly string[];
183
+ readonly reasons: readonly string[];
184
+ };
185
+
186
+ export type PromptBlocker =
187
+ | "continuation_unavailable"
188
+ | "recovery_required"
189
+ | "configuration_mismatch"
190
+ | "persistence_unhealthy"
191
+ | "maintenance_pending"
192
+ | "session_stopped";
193
+
194
+ export type AgentSessionPromptability =
195
+ | { readonly promptable: true; readonly blockers: readonly [] }
196
+ | { readonly promptable: false; readonly blockers: readonly PromptBlocker[] };
197
+
198
+ export interface ContinuationAttempt {
199
+ readonly strategy: ContinuationStrategy["kind"];
200
+ readonly status: "succeeded" | "failed" | "skipped";
201
+ readonly errorCode?: PersistedMachineCode;
202
+ readonly reason?: string;
203
+ }
204
+
205
+ export interface ContinuationReport {
206
+ readonly recordedAdapterId: string;
207
+ readonly recordedInternalSessionId: string | null;
208
+ readonly requestedAdapterId: string;
209
+ readonly recordedConversationAvailability: "available" | "partial" | "not_captured";
210
+ readonly recordedThreadAvailability: "available" | "unavailable" | "not_checked";
211
+ readonly attempts: readonly ContinuationAttempt[];
212
+ readonly outcome:
213
+ | { readonly kind: "loaded"; readonly activeInternalSessionId: string }
214
+ | {
215
+ readonly kind: "reconstructed";
216
+ readonly source: "transcript" | "consumer";
217
+ readonly activeInternalSessionId: string;
218
+ readonly transitionId: string;
219
+ }
220
+ | { readonly kind: "unavailable" };
221
+ }
222
+
223
+ export interface TranscriptContinuationBuilderContext {
224
+ readonly agentSessionId: string;
225
+ readonly checkpoint: AgentSessionCheckpoint;
226
+ /** Snapshot-bound access to captured history; the builder decides how much to read. */
227
+ readonly transcript: TranscriptReader;
228
+ readonly targetAdapterId: string;
229
+ }
230
+
231
+ export type TranscriptContinuationBuilder = (
232
+ context: TranscriptContinuationBuilderContext,
233
+ ) => Promise<{ readonly continuation: string; readonly metadata?: Readonly<Record<string, JsonValue>> }>;
234
+
235
+ export type ContinuationStrategy =
236
+ | { readonly kind: "load_internal_session" }
237
+ | {
238
+ readonly kind: "new_from_transcript";
239
+ readonly strategyId: string;
240
+ readonly buildContinuation: TranscriptContinuationBuilder;
241
+ }
242
+ | {
243
+ readonly kind: "new_from_consumer_continuation";
244
+ readonly continuationId: string;
245
+ readonly continuation: string;
246
+ };
247
+
248
+ export interface OpenContinuationOptions {
249
+ /** Defaults to only `load_internal_session`; an empty array is invalid. */
250
+ readonly strategies?: readonly ContinuationStrategy[];
251
+ }
252
+
253
+ export interface AgentSessionOpenResult {
254
+ readonly session: AgentSession;
255
+ readonly continuation: ContinuationReport;
256
+ readonly recovery: SessionRecoveryStatus;
257
+ readonly configuration: ConfigurationRestoreStatus;
258
+ readonly promptability: AgentSessionPromptability;
259
+ readonly repairs: readonly PersistenceRepair[];
260
+ }
261
+
262
+ export type ConfigurationMismatchResolution =
263
+ | { readonly strategy: "accept_effective" }
264
+ | {
265
+ readonly strategy: "replace_restoration_targets";
266
+ readonly selections: readonly { readonly configId: string; readonly value: JsonValue }[];
267
+ };
268
+
269
+ export interface ConfigurationMismatchResolutionResult {
270
+ readonly configuration: ConfigurationRestoreStatus;
271
+ readonly appliedConfigIds: readonly string[];
272
+ }
273
+
274
+ export type AgentSessionRecoveryResolution =
275
+ | { readonly strategy: "accept_harness_state" }
276
+ | {
277
+ readonly strategy: "start_new_internal_session";
278
+ /** When omitted, the currently loaded harness thread generates portable context. */
279
+ readonly continuation?: string;
280
+ };
281
+
282
+ export interface AgentSessionRecoveryResolutionResult {
283
+ readonly previous: Extract<SessionRecoveryStatus, { readonly kind: "uncertain" }>;
284
+ readonly recovery: Extract<SessionRecoveryStatus, { readonly kind: "clean" }>;
285
+ /** Present when resolution deliberately replaced the provider thread. */
286
+ readonly handoff?: HandoffResult;
287
+ }
288
+
289
+ export class AgentSessionPromptBlockedError extends Error {
290
+ constructor(readonly blockers: readonly PromptBlocker[]) {
291
+ super(`AgentSession cannot mutate while blocked: ${blockers.join(", ")}`);
292
+ this.name = "AgentSessionPromptBlockedError";
293
+ }
294
+ }
295
+
296
+ export class ContinuationUnavailableError extends Error {
297
+ constructor(readonly continuation: ContinuationReport, options?: ErrorOptions) {
298
+ super("recorded internal session could not be loaded", options);
299
+ this.name = "ContinuationUnavailableError";
300
+ }
301
+ }
302
+
303
+ export class AdapterMismatchError extends Error {
304
+ constructor(readonly recordedAdapterId: string, readonly requestedAdapterId: string) {
305
+ super(`adapter mismatch: transcript requires ${recordedAdapterId}, received ${requestedAdapterId}`);
306
+ this.name = "AdapterMismatchError";
307
+ }
308
+ }
309
+
310
+ /** Direct V2 audit creation is deferred until it has the same crash transaction as managed creation. */
311
+ export class DirectAuditPersistenceUnsupportedError extends Error {
312
+ constructor() {
313
+ super("direct V2 audit persistence is not supported; use SessionManager.createAgentSession()");
314
+ this.name = "DirectAuditPersistenceUnsupportedError";
315
+ }
97
316
  }
98
317
 
99
318
  export interface HandoffOptions {
@@ -134,6 +353,23 @@ export type AgentSessionEvent =
134
353
  /** Records produced before and during the failure. */
135
354
  meteringRecords: readonly OperationMeteringRecord[];
136
355
  }
356
+ | { kind: "configuration_started"; operationId: string; configId: string }
357
+ | { kind: "configuration_completed"; operationId: string; configId: string }
358
+ | { kind: "configuration_failed"; operationId: string; configId: string; error: string }
359
+ | { kind: "mode_change_started"; transitionId: string; from: AgentMode; to: AgentMode }
360
+ | { kind: "mode_change_completed"; transitionId: string; from: AgentMode; to: AgentMode }
361
+ | { kind: "mode_change_failed"; transitionId: string; from: AgentMode; to: AgentMode; error: string }
362
+ | {
363
+ kind: "configuration_mismatch_resolved";
364
+ configuration: ConfigurationRestoreStatus;
365
+ appliedConfigIds: readonly string[];
366
+ }
367
+ | {
368
+ kind: "recovery_resolved";
369
+ strategy: AgentSessionRecoveryResolution["strategy"];
370
+ previous: Extract<SessionRecoveryStatus, { kind: "uncertain" }>;
371
+ recovery: Extract<SessionRecoveryStatus, { kind: "clean" }>;
372
+ }
137
373
  /** Latest context-window observation for the ACTIVE provider thread, or null. */
138
374
  | { kind: "context_window_changed"; contextWindow: ContextWindowStatus | null }
139
375
  /** Latest cumulative provider-reported cost. Telemetry, never asserted to be an invoice. */
@@ -269,6 +505,10 @@ export interface AgentSessionConfig {
269
505
  wire?: (entry: WireEntry) => void;
270
506
  /** Optional catalog. When present, the session records itself here. */
271
507
  sessions?: SessionManager;
508
+ /** New v2 persistence. Direct sessions remain persistence-free when omitted. */
509
+ persistence?: false | AgentSessionPersistenceOptions;
510
+ /** Stable creation transaction/incarnation ID; required by direct v2 persistence. */
511
+ creationId?: string;
272
512
  /**
273
513
  * Absolute path to an append-only transcript file. This selects history storage only;
274
514
  * file existence never selects the provider thread. Omitted means no transcript.
@@ -308,6 +548,45 @@ export interface AgentSessionConfig {
308
548
  title?: string;
309
549
  }
310
550
 
551
+ /** Direct restoration input. Phase 5A intentionally supports the safe recorded-thread path. */
552
+ export interface AgentSessionOpenConfig extends Omit<
553
+ AgentSessionConfig,
554
+ | "agentSessionId"
555
+ | "creationId"
556
+ | "providerSession"
557
+ | "internalSessionId"
558
+ | "mode"
559
+ | "persistence"
560
+ | "sessions"
561
+ > {
562
+ /** Required for directory/default path resolution; exact-file inference is a later slice. */
563
+ agentSessionId: string;
564
+ persistence: AgentSessionPersistenceOptions;
565
+ /** Optional consumer copy must exactly match transcript authority in this first slice. */
566
+ checkpoint?: AgentSessionCheckpoint;
567
+ continuation?: OpenContinuationOptions;
568
+ }
569
+
570
+ interface AgentSessionOpenBootstrap {
571
+ readonly transcript: PersistenceStateRuntime;
572
+ readonly transcriptPath: string;
573
+ readonly stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>;
574
+ }
575
+
576
+ /** @internal Transaction hooks supplied only by SessionManager managed creation. */
577
+ export interface ManagedAgentSessionCreationBootstrap {
578
+ readonly requestDigest: string;
579
+ readonly transcriptLock?: SessionLogWriterLock;
580
+ readonly auditLogLock?: SessionLogWriterLock;
581
+ readonly stageContinuation: (state: StagedContinuationState) => Promise<StagedContinuationState>;
582
+ }
583
+
584
+ export interface ManagedAgentSessionPersistenceSnapshot {
585
+ readonly checkpoint: AgentSessionCheckpoint;
586
+ readonly internalSessionHistory: readonly InternalSessionHistoryEntry[];
587
+ readonly auditLog: AuditLogIdentity | null;
588
+ }
589
+
311
590
  export class AgentSession implements AgentClient, Bridgeable {
312
591
  /** Our stable AgentSession id — decoupled from the ACP/harness session id. */
313
592
  readonly agentSessionId: string;
@@ -316,6 +595,11 @@ export class AgentSession implements AgentClient, Bridgeable {
316
595
  private readonly controller: AgentController;
317
596
  private readonly sessions?: SessionManager;
318
597
  private readonly _transcriptPath?: string;
598
+ private readonly persistence: false | ResolvedAgentSessionPersistence;
599
+ private readonly creationId: string;
600
+ private v2Transcript: PersistenceStateRuntime | null = null;
601
+ private v2TranscriptPath: string | null = null;
602
+ private v2ActivityWrite: Promise<void> = Promise.resolve();
319
603
  private readonly transcriptActivity: boolean;
320
604
  private readonly activityKinds: Set<string>;
321
605
  private readonly activityRawOutput: boolean;
@@ -350,11 +634,25 @@ export class AgentSession implements AgentClient, Bridgeable {
350
634
  private _mode: AgentMode;
351
635
  private _cwd?: string;
352
636
  private _title?: string;
353
-
354
- private constructor(config: AgentSessionConfig) {
637
+ private readonly openBootstrap: AgentSessionOpenBootstrap | null;
638
+ private continuationAcquired = true;
639
+ private _recovery: SessionRecoveryStatus = { kind: "clean" };
640
+ private _configurationRestore: ConfigurationRestoreStatus = { kind: "matched" };
641
+ private readonly managedCreation: ManagedAgentSessionCreationBootstrap | null;
642
+ private managedPersistenceHealthy = true;
643
+ private managedAuditLog: AuditLogIdentity | null = null;
644
+
645
+ private constructor(
646
+ config: AgentSessionConfig,
647
+ openBootstrap: AgentSessionOpenBootstrap | null = null,
648
+ managedCreation: ManagedAgentSessionCreationBootstrap | null = null,
649
+ ) {
355
650
  if (config.transcriptPath && config.transcriptDir) {
356
651
  throw new Error("AgentSessionConfig cannot specify both transcriptPath and transcriptDir");
357
652
  }
653
+ if (config.persistence !== undefined && (config.transcriptPath || config.transcriptDir)) {
654
+ throw new Error("AgentSessionConfig cannot combine persistence with deprecated transcript options");
655
+ }
358
656
  if (config.providerSession && config.internalSessionId !== undefined) {
359
657
  throw new Error("AgentSessionConfig cannot specify both providerSession and internalSessionId");
360
658
  }
@@ -380,6 +678,19 @@ export class AgentSession implements AgentClient, Bridgeable {
380
678
  this.agentSessionId = config.agentSessionId ?? crypto.randomUUID();
381
679
  this.adapterId = config.adapterId;
382
680
  this.sessions = config.sessions;
681
+ this.persistence = resolveDirectPersistence(config.persistence);
682
+ if (this.persistence !== false && config.sessions) {
683
+ throw new Error("direct persistence cannot be combined with a SessionManager; use managed creation");
684
+ }
685
+ if (this.persistence !== false && (!config.agentSessionId || !config.creationId)) {
686
+ throw new Error("direct persistence requires explicit agentSessionId and creationId");
687
+ }
688
+ if (config.creationId !== undefined && !config.creationId.trim()) {
689
+ throw new Error("AgentSessionConfig.creationId cannot be blank");
690
+ }
691
+ this.creationId = config.creationId ?? crypto.randomUUID();
692
+ this.openBootstrap = openBootstrap;
693
+ this.managedCreation = managedCreation;
383
694
  this._transcriptPath =
384
695
  config.transcriptPath ??
385
696
  (config.transcriptDir
@@ -450,6 +761,10 @@ export class AgentSession implements AgentClient, Bridgeable {
450
761
  * implicitly. Consumers compose a catalog record back into this method when reopening.
451
762
  */
452
763
  static async create(config: AgentSessionConfig): Promise<AgentSession> {
764
+ const directPersistence = resolveDirectPersistence(config.persistence);
765
+ if (directPersistence !== false && directPersistence.auditLog !== false) {
766
+ throw new DirectAuditPersistenceUnsupportedError();
767
+ }
453
768
  const session = new AgentSession(config);
454
769
  try {
455
770
  await session.start();
@@ -460,7 +775,210 @@ export class AgentSession implements AgentClient, Bridgeable {
460
775
  }
461
776
  }
462
777
 
778
+ /** @internal Create while transferring a manager-owned transcript lock and staging hook. */
779
+ static async createManaged(
780
+ config: AgentSessionConfig,
781
+ bootstrap: ManagedAgentSessionCreationBootstrap,
782
+ ): Promise<AgentSession> {
783
+ let session: AgentSession;
784
+ try {
785
+ session = new AgentSession(config, null, bootstrap);
786
+ } catch (error) {
787
+ await bootstrap.transcriptLock?.release().catch(() => undefined);
788
+ await bootstrap.auditLogLock?.release().catch(() => undefined);
789
+ throw error;
790
+ }
791
+ try {
792
+ await session.start();
793
+ return session;
794
+ } catch (error) {
795
+ await session.stop().catch(() => undefined);
796
+ await bootstrap.transcriptLock?.release().catch(() => undefined);
797
+ await bootstrap.auditLogLock?.release().catch(() => undefined);
798
+ throw error;
799
+ }
800
+ }
801
+
802
+ /** Restore one logical session by loading the exact provider thread in transcript authority. */
803
+ static async open(config: AgentSessionOpenConfig): Promise<AgentSessionOpenResult> {
804
+ return await AgentSession.openWithLock(config);
805
+ }
806
+
807
+ /** @internal Managed open after maintenance acquired the artifact lock. */
808
+ static async openManaged(
809
+ config: AgentSessionOpenConfig,
810
+ transcriptLock?: SessionLogWriterLock,
811
+ audit?: AuditPersistenceRuntime,
812
+ stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>,
813
+ ): Promise<AgentSessionOpenResult> {
814
+ return await AgentSession.openWithLock(config, transcriptLock, audit, stageContinuation);
815
+ }
816
+
817
+ /** @internal Restore a registry-authoritative session without a transcript reader. */
818
+ static async openManagedRegistry(
819
+ config: AgentSessionOpenConfig,
820
+ history: readonly InternalSessionHistoryEntry[],
821
+ audit?: AuditPersistenceRuntime,
822
+ stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>,
823
+ ): Promise<AgentSessionOpenResult> {
824
+ const checkpoint = config.checkpoint;
825
+ if (!checkpoint || checkpoint.transcript !== null) {
826
+ throw new Error("registry-managed open requires a registry-only checkpoint");
827
+ }
828
+ const strategies = normalizeContinuationStrategies(config.continuation);
829
+ if (checkpoint.adapterId !== config.adapterId && !strategies.some(isReconstructionStrategy)) {
830
+ throw new AdapterMismatchError(checkpoint.adapterId, config.adapterId);
831
+ }
832
+ if (!checkpoint.internalSessionId) {
833
+ throw new Error("registry-managed open has no recorded internal session id");
834
+ }
835
+ const { checkpoint: _checkpoint, continuation: _continuation, ...runtime } = config;
836
+ const session = new AgentSession({
837
+ ...runtime,
838
+ agentSessionId: checkpoint.agentSessionId,
839
+ creationId: checkpoint.incarnationId,
840
+ mode: "normal",
841
+ providerSession: {
842
+ kind: "load",
843
+ internalSessionId: checkpoint.internalSessionId,
844
+ onFailure: "error",
845
+ },
846
+ metering: { ...config.metering, initialState: checkpoint.metering },
847
+ });
848
+ const primary = new RegistryPersistenceRuntime(checkpoint, history);
849
+ session.v2Transcript = audit ? new AuditedPersistenceRuntime(primary, audit) : primary;
850
+ session.managedAuditLog = audit?.identity ?? null;
851
+ try {
852
+ const result = await session.controller.start();
853
+ if (!result.resumed || !result.sessionId) {
854
+ throw new Error("adapter did not confirm loading the recorded internal session");
855
+ }
856
+ session.setInternalSessionId(result.sessionId, false);
857
+ await stageOpeningContinuation(stageContinuation, checkpoint, result.sessionId);
858
+ const attempt: ContinuationAttempt = Object.freeze({
859
+ strategy: "load_internal_session",
860
+ status: "succeeded",
861
+ });
862
+ const continuation = continuationReport(
863
+ checkpoint, config.adapterId, session.v2Transcript, "available", [attempt],
864
+ { kind: "loaded", activeInternalSessionId: result.sessionId },
865
+ );
866
+ const configuration = await session.restoreOpeningConfiguration();
867
+ session._configurationRestore = configuration;
868
+ session.emitStateIfChanged();
869
+ return Object.freeze({
870
+ session,
871
+ continuation,
872
+ recovery: structuredClone(session._recovery),
873
+ configuration: structuredClone(configuration),
874
+ promptability: session.promptability,
875
+ repairs: [],
876
+ });
877
+ } catch (error) {
878
+ await session.stop().catch(() => undefined);
879
+ throw error;
880
+ }
881
+ }
882
+
883
+ private static async openWithLock(
884
+ config: AgentSessionOpenConfig,
885
+ transcriptLock?: SessionLogWriterLock,
886
+ audit?: AuditPersistenceRuntime,
887
+ stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>,
888
+ ): Promise<AgentSessionOpenResult> {
889
+ const strategies = normalizeContinuationStrategies(config.continuation);
890
+ const persistence = resolveDirectPersistence(config.persistence);
891
+ if (persistence === false || persistence.transcript === false) {
892
+ throw new Error("AgentSession.open() currently requires transcript persistence");
893
+ }
894
+ const paths = await resolveSessionLogPaths(persistence, config.agentSessionId);
895
+ if (!paths.transcriptPath) throw new Error("AgentSession.open() requires a transcript path");
896
+ if (paths.auditLogPath && !audit) {
897
+ throw new DirectAuditPersistenceUnsupportedError();
898
+ }
899
+
900
+ let primary: TranscriptPersistenceRuntime;
901
+ try {
902
+ primary = await TranscriptPersistenceRuntime.resume({
903
+ path: paths.transcriptPath,
904
+ expected: { agentSessionId: config.agentSessionId },
905
+ writerLock: transcriptLock,
906
+ });
907
+ } catch (error) {
908
+ await audit?.close().catch(() => undefined);
909
+ throw error;
910
+ }
911
+ const transcript: PersistenceStateRuntime = audit
912
+ ? new AuditedPersistenceRuntime(primary, audit)
913
+ : primary;
914
+ const checkpoint = transcript.checkpoint;
915
+ try {
916
+ validateAgentSessionCheckpoint(config.checkpoint ?? checkpoint, {
917
+ agentSessionId: config.agentSessionId,
918
+ incarnationId: checkpoint.incarnationId,
919
+ transcriptId: checkpoint.transcript?.transcriptId,
920
+ transcriptGeneration: checkpoint.transcript?.generation,
921
+ transcriptPath: paths.transcriptPath,
922
+ });
923
+ if (config.checkpoint && config.checkpoint.digest !== checkpoint.digest) {
924
+ throw new Error("consumer checkpoint does not match authoritative transcript checkpoint");
925
+ }
926
+ if (checkpoint.adapterId !== config.adapterId && !strategies.some(isReconstructionStrategy)) {
927
+ throw new AdapterMismatchError(checkpoint.adapterId, config.adapterId);
928
+ }
929
+ const { checkpoint: _suppliedCheckpoint, continuation: _continuation, ...runtimeConfig } = config;
930
+ const session = new AgentSession({
931
+ ...runtimeConfig,
932
+ agentSessionId: checkpoint.agentSessionId,
933
+ creationId: checkpoint.incarnationId,
934
+ mode: "normal",
935
+ providerSession: checkpoint.internalSessionId
936
+ ? {
937
+ kind: "load",
938
+ internalSessionId: checkpoint.internalSessionId,
939
+ onFailure: "error",
940
+ }
941
+ : { kind: "new" },
942
+ metering: {
943
+ ...config.metering,
944
+ initialState: checkpoint.metering,
945
+ },
946
+ }, { transcript, transcriptPath: paths.transcriptPath, stageContinuation });
947
+ session.managedAuditLog = audit?.identity ?? null;
948
+
949
+ try {
950
+ const continuation = await session.acquireOpeningContinuation(checkpoint, strategies);
951
+ if (continuation.outcome.kind === "unavailable") {
952
+ throw new ContinuationUnavailableError(continuation);
953
+ }
954
+ const configuration = continuation.outcome.kind === "loaded"
955
+ ? await session.restoreOpeningConfiguration()
956
+ : session._configurationRestore;
957
+ session._configurationRestore = configuration;
958
+ session.emitStateIfChanged();
959
+ return Object.freeze({
960
+ session,
961
+ continuation,
962
+ recovery: structuredClone(session._recovery),
963
+ configuration: structuredClone(configuration),
964
+ promptability: session.promptability,
965
+ repairs: transcript.openingRepairs,
966
+ });
967
+ } catch (error) {
968
+ await session.stop().catch(() => undefined);
969
+ throw error;
970
+ }
971
+ } catch (error) {
972
+ await transcript.close().catch(() => undefined);
973
+ throw error;
974
+ }
975
+ }
976
+
463
977
  private async start(): Promise<void> {
978
+ if (this.persistence !== false) {
979
+ await this.startPersistent();
980
+ return;
981
+ }
464
982
  const result = await this.controller.start();
465
983
  // A resumed thread's counters did not start at zero, so it needs restored state to
466
984
  // be attributable.
@@ -476,6 +994,490 @@ export class AgentSession implements AgentClient, Bridgeable {
476
994
  });
477
995
  }
478
996
 
997
+ private async startPersistent(): Promise<void> {
998
+ const persistence = this.persistence;
999
+ if (persistence === false) throw new Error("persistent startup requires persistence configuration");
1000
+ if (this.openBootstrap) {
1001
+ this.v2Transcript = this.openBootstrap.transcript;
1002
+ this.v2TranscriptPath = this.openBootstrap.transcriptPath;
1003
+ this._recovery = this.v2Transcript.recovery;
1004
+ const result = await this.controller.start();
1005
+ if (!result.resumed || !result.sessionId) {
1006
+ throw new Error("adapter did not confirm loading the recorded internal session");
1007
+ }
1008
+ this.setInternalSessionId(result.sessionId, false);
1009
+ return;
1010
+ }
1011
+ const paths = await resolveSessionLogPaths(persistence, this.agentSessionId);
1012
+ const createdAt = new Date().toISOString();
1013
+ const requestDigest = this.managedCreation?.requestDigest ?? sha256CanonicalJson({
1014
+ agentSessionId: this.agentSessionId,
1015
+ creationId: this.creationId,
1016
+ adapterId: this.adapterId,
1017
+ mode: this._mode,
1018
+ transcriptPath: paths.transcriptPath,
1019
+ auditLogPath: paths.auditLogPath,
1020
+ });
1021
+ let audit: AuditPersistenceRuntime | null = null;
1022
+ if (paths.auditLogPath && persistence.auditLog !== false) {
1023
+ const auditLogId = crypto.randomUUID();
1024
+ const header = {
1025
+ v: 1 as const, t: "header" as const, auditLogId, generation: 1,
1026
+ agentSessionId: this.agentSessionId, seq: 1, ts: Date.parse(createdAt),
1027
+ event: "created" as const, createdAt,
1028
+ effectivePolicy: persistence.auditLog.capture,
1029
+ effectiveLimits: persistence.limits,
1030
+ includeTruncationDigests: persistence.auditLog.includeTruncationDigests,
1031
+ installation: { kind: "creation" as const, operationId: this.creationId, requestDigest },
1032
+ };
1033
+ audit = await AuditPersistenceRuntime.create({
1034
+ path: paths.auditLogPath,
1035
+ header,
1036
+ writerLock: this.managedCreation?.auditLogLock,
1037
+ });
1038
+ this.managedAuditLog = audit.identity;
1039
+ }
1040
+ if (!paths.transcriptPath || persistence.transcript === false) {
1041
+ try {
1042
+ const result = await this.controller.start();
1043
+ this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
1044
+ if (this.managedCreation) {
1045
+ const now = new Date().toISOString();
1046
+ const observed: StagedContinuationState = {
1047
+ adapterId: this.adapterId,
1048
+ mode: this._mode,
1049
+ internalSessionId: this._internalSessionId,
1050
+ internalSessionActivatedAt: this._internalSessionId ? now : null,
1051
+ model: this.model,
1052
+ sessionConfiguration: snapshotSessionConfiguration({
1053
+ adapterId: this.adapterId,
1054
+ configOptions: this.controller.configOptions,
1055
+ policy: persistence.sessionConfiguration,
1056
+ observedAt: now,
1057
+ }),
1058
+ protocol: this.controller.isDegraded ? { name: "pty" } : { name: "acp", version: 1 },
1059
+ };
1060
+ const staged = await this.managedCreation.stageContinuation(observed);
1061
+ const primary = new RegistryPersistenceRuntime(createAgentSessionCheckpoint({
1062
+ agentSessionId: this.agentSessionId,
1063
+ incarnationId: this.creationId,
1064
+ stateRevision: 1,
1065
+ adapterId: this.adapterId,
1066
+ mode: staged.mode,
1067
+ internalSessionId: staged.internalSessionId,
1068
+ internalSessionActivatedAt: staged.internalSessionActivatedAt,
1069
+ internalSessionHistoryRevision: 0,
1070
+ internalSessionHistoryDigest: EMPTY_HISTORY_DIGEST,
1071
+ model: staged.model,
1072
+ sessionConfiguration: staged.sessionConfiguration,
1073
+ protocol: staged.protocol,
1074
+ transcript: null,
1075
+ metering: this.metering.currentState,
1076
+ boundary: { status: "settled", lastSettledOperationId: null },
1077
+ updatedAt: now,
1078
+ }));
1079
+ this.v2Transcript = audit ? new AuditedPersistenceRuntime(primary, audit) : primary;
1080
+ }
1081
+ return;
1082
+ } catch (error) {
1083
+ await audit?.close().catch(() => undefined);
1084
+ throw error;
1085
+ }
1086
+ }
1087
+
1088
+ const transcriptPath = paths.transcriptPath;
1089
+ const transcriptId = crypto.randomUUID();
1090
+ const header: TranscriptHeaderRecord = {
1091
+ v: 2,
1092
+ t: "header",
1093
+ transcriptId,
1094
+ generation: 1,
1095
+ agentSessionId: this.agentSessionId,
1096
+ seq: 1,
1097
+ ts: Date.parse(createdAt),
1098
+ event: "created",
1099
+ createdAt,
1100
+ preset: persistence.transcript.preset,
1101
+ effectivePolicy: persistence.transcript.capture,
1102
+ effectiveLimits: persistence.limits,
1103
+ includeTruncationDigests: persistence.transcript.includeTruncationDigests,
1104
+ installation: { kind: "creation", operationId: this.creationId, requestDigest },
1105
+ };
1106
+
1107
+ this.v2TranscriptPath = transcriptPath;
1108
+ const primary = await TranscriptPersistenceRuntime.create({
1109
+ path: transcriptPath,
1110
+ header,
1111
+ writerLock: this.managedCreation?.transcriptLock,
1112
+ initializeCheckpoint: async () => {
1113
+ const result = await this.controller.start();
1114
+ this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
1115
+ const now = new Date().toISOString();
1116
+ const sessionConfiguration = snapshotSessionConfiguration({
1117
+ adapterId: this.adapterId,
1118
+ configOptions: this.controller.configOptions,
1119
+ policy: persistence.sessionConfiguration,
1120
+ observedAt: now,
1121
+ });
1122
+ const observedContinuation: StagedContinuationState = {
1123
+ adapterId: this.adapterId,
1124
+ mode: this._mode,
1125
+ internalSessionId: this._internalSessionId,
1126
+ internalSessionActivatedAt: this._internalSessionId ? now : null,
1127
+ model: this.model,
1128
+ sessionConfiguration,
1129
+ protocol: this.controller.isDegraded ? { name: "pty" } : { name: "acp", version: 1 },
1130
+ };
1131
+ const stagedContinuation = this.managedCreation
1132
+ ? await this.managedCreation.stageContinuation(observedContinuation)
1133
+ : observedContinuation;
1134
+ return createAgentSessionCheckpoint({
1135
+ agentSessionId: this.agentSessionId,
1136
+ incarnationId: this.creationId,
1137
+ stateRevision: 1,
1138
+ adapterId: this.adapterId,
1139
+ mode: stagedContinuation.mode,
1140
+ internalSessionId: stagedContinuation.internalSessionId,
1141
+ internalSessionActivatedAt: stagedContinuation.internalSessionActivatedAt,
1142
+ internalSessionHistoryRevision: 0,
1143
+ internalSessionHistoryDigest: EMPTY_HISTORY_DIGEST,
1144
+ model: stagedContinuation.model,
1145
+ sessionConfiguration: stagedContinuation.sessionConfiguration,
1146
+ protocol: stagedContinuation.protocol,
1147
+ transcript: { transcriptId, generation: 1, path: transcriptPath, coveredSequence: 1 },
1148
+ metering: this.metering.currentState,
1149
+ boundary: { status: "settled", lastSettledOperationId: null },
1150
+ updatedAt: now,
1151
+ });
1152
+ },
1153
+ });
1154
+ this.v2Transcript = audit ? new AuditedPersistenceRuntime(primary, audit) : primary;
1155
+ }
1156
+
1157
+ /**
1158
+ * Acquire one live provider thread from an explicit, ordered continuation policy.
1159
+ *
1160
+ * Loading is the only implicit/default behavior. Creating and seeding a replacement
1161
+ * thread can spend tokens and changes routing identity, so it occurs only when the
1162
+ * caller supplied a reconstruction strategy.
1163
+ */
1164
+ private async acquireOpeningContinuation(
1165
+ checkpoint: AgentSessionCheckpoint,
1166
+ strategies: readonly ContinuationStrategy[],
1167
+ ): Promise<ContinuationReport> {
1168
+ if (!this.openBootstrap || this.persistence === false) {
1169
+ throw new Error("opening continuation requires transcript persistence");
1170
+ }
1171
+ this.v2Transcript = this.openBootstrap.transcript;
1172
+ this.v2TranscriptPath = this.openBootstrap.transcriptPath;
1173
+ this._recovery = this.v2Transcript.recovery;
1174
+ this.continuationAcquired = false;
1175
+
1176
+ const attempts: ContinuationAttempt[] = [];
1177
+ let recordedThreadAvailability: ContinuationReport["recordedThreadAvailability"] = "not_checked";
1178
+
1179
+ for (const strategy of strategies) {
1180
+ if (strategy.kind === "load_internal_session") {
1181
+ if (!checkpoint.internalSessionId) {
1182
+ attempts.push(Object.freeze({
1183
+ strategy: strategy.kind,
1184
+ status: "skipped",
1185
+ errorCode: "internal_session_absent",
1186
+ reason: "the continuation checkpoint has no provider thread id",
1187
+ }));
1188
+ continue;
1189
+ }
1190
+ if (checkpoint.adapterId !== this.adapterId) {
1191
+ attempts.push(Object.freeze({
1192
+ strategy: strategy.kind,
1193
+ status: "skipped",
1194
+ errorCode: "adapter_mismatch",
1195
+ reason: `recorded adapter ${checkpoint.adapterId} differs from requested adapter ${this.adapterId}`,
1196
+ }));
1197
+ continue;
1198
+ }
1199
+ if (checkpoint.mode !== "normal") {
1200
+ attempts.push(Object.freeze({
1201
+ strategy: strategy.kind,
1202
+ status: "skipped",
1203
+ errorCode: "internal_session_not_loadable",
1204
+ reason: "degraded provider threads cannot be loaded through ACP",
1205
+ }));
1206
+ continue;
1207
+ }
1208
+ try {
1209
+ const loaded = await this.controller.start();
1210
+ if (!loaded.resumed || !loaded.sessionId) {
1211
+ throw new Error("adapter did not confirm loading the recorded internal session");
1212
+ }
1213
+ if (loaded.sessionId !== checkpoint.internalSessionId) {
1214
+ throw new Error("adapter loaded a different internal session than requested");
1215
+ }
1216
+ this._mode = this.controller.currentMode;
1217
+ this.setInternalSessionId(loaded.sessionId, false);
1218
+ await stageOpeningContinuation(
1219
+ this.openBootstrap.stageContinuation,
1220
+ checkpoint,
1221
+ loaded.sessionId,
1222
+ );
1223
+ this.continuationAcquired = true;
1224
+ recordedThreadAvailability = "available";
1225
+ attempts.push(Object.freeze({ strategy: strategy.kind, status: "succeeded" }));
1226
+ return continuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1227
+ kind: "loaded",
1228
+ activeInternalSessionId: loaded.sessionId,
1229
+ });
1230
+ } catch (error) {
1231
+ recordedThreadAvailability = "unavailable";
1232
+ attempts.push(Object.freeze({
1233
+ strategy: strategy.kind,
1234
+ status: "failed",
1235
+ errorCode: "internal_session_unavailable",
1236
+ reason: String(error),
1237
+ }));
1238
+ continue;
1239
+ }
1240
+ }
1241
+
1242
+ if (this._recovery.kind !== "clean") {
1243
+ attempts.push(Object.freeze({
1244
+ strategy: strategy.kind,
1245
+ status: "skipped",
1246
+ errorCode: "recovery_required",
1247
+ reason: "transcript uncertainty must be resolved before activating a replacement thread",
1248
+ }));
1249
+ continue;
1250
+ }
1251
+
1252
+ let continuation: string;
1253
+ const source = strategy.kind === "new_from_transcript" ? "transcript" as const : "consumer" as const;
1254
+ try {
1255
+ continuation = strategy.kind === "new_from_transcript"
1256
+ ? (await strategy.buildContinuation(Object.freeze({
1257
+ agentSessionId: this.agentSessionId,
1258
+ checkpoint: structuredClone(checkpoint),
1259
+ transcript: new TranscriptReader(this.openBootstrap.transcriptPath),
1260
+ targetAdapterId: this.adapterId,
1261
+ }))).continuation
1262
+ : strategy.continuation;
1263
+ if (!continuation.trim()) throw new Error("continuation content cannot be blank");
1264
+ } catch (error) {
1265
+ attempts.push(Object.freeze({
1266
+ strategy: strategy.kind,
1267
+ status: "failed",
1268
+ errorCode: "continuation_build_failed",
1269
+ reason: String(error),
1270
+ }));
1271
+ continue;
1272
+ }
1273
+
1274
+ const transitionId = this.mintOperationId();
1275
+ const transitionKind = checkpoint.adapterId === this.adapterId ? "replacement" as const : "switch" as const;
1276
+ const from = descriptorFromCheckpoint(checkpoint);
1277
+ let to: InternalSessionDescriptor | undefined;
1278
+ let failedAfter: "start" | "target_created" | "target_activated" = "start";
1279
+ await this.v2Transcript.appendTransitionEvent({
1280
+ kind: "transition",
1281
+ transitionId,
1282
+ transitionKind,
1283
+ event: "started",
1284
+ from,
1285
+ reasonCode: "continuation_reconstruction",
1286
+ });
1287
+ try {
1288
+ const created = await this.controller.startFresh();
1289
+ if (!created.sessionId) throw new Error("harness returned no session id for reconstructed continuation");
1290
+ if (created.sessionId === checkpoint.internalSessionId && checkpoint.adapterId === this.adapterId) {
1291
+ throw new Error("harness did not create a replacement internal session");
1292
+ }
1293
+
1294
+ const restored = checkpoint.adapterId === this.adapterId
1295
+ ? await this.restoreConfigurationOnReconstructedTarget(checkpoint.sessionConfiguration)
1296
+ : this.snapshotReconstructedConfiguration([]);
1297
+ this._configurationRestore = restored.status;
1298
+ const transitionAt = new Date().toISOString();
1299
+ to = {
1300
+ internalSessionId: created.sessionId,
1301
+ adapterId: this.adapterId,
1302
+ mode: "normal",
1303
+ model: this.model,
1304
+ sessionConfiguration: restored.snapshot,
1305
+ activatedAt: transitionAt,
1306
+ protocol: { name: "acp", version: 1 },
1307
+ };
1308
+ await this.v2Transcript.appendTransitionEvent({
1309
+ kind: "transition",
1310
+ transitionId,
1311
+ transitionKind,
1312
+ event: "target_created",
1313
+ from,
1314
+ to,
1315
+ reasonCode: "continuation_reconstruction",
1316
+ });
1317
+ failedAfter = "target_created";
1318
+ const current = this.v2Transcript.checkpoint;
1319
+ await this.v2Transcript.activateTransition({
1320
+ kind: "transition",
1321
+ transitionId,
1322
+ transitionKind,
1323
+ event: "target_activated",
1324
+ from,
1325
+ to,
1326
+ ...(from.internalSessionId
1327
+ ? {
1328
+ historyEntry: {
1329
+ internalSessionId: from.internalSessionId,
1330
+ adapterId: from.adapterId,
1331
+ model: from.model,
1332
+ sessionConfiguration: from.sessionConfiguration,
1333
+ protocol: from.protocol,
1334
+ activatedAt: from.activatedAt ?? checkpoint.updatedAt,
1335
+ deactivatedAt: transitionAt,
1336
+ transition: {
1337
+ kind: transitionKind,
1338
+ transitionId,
1339
+ reasonCode: "continuation_reconstruction",
1340
+ },
1341
+ },
1342
+ }
1343
+ : {}),
1344
+ activationState: {
1345
+ resultingStateRevision: current.stateRevision + 1,
1346
+ updatedAt: transitionAt,
1347
+ transitionAt,
1348
+ boundary: current.boundary,
1349
+ },
1350
+ reasonCode: "continuation_reconstruction",
1351
+ });
1352
+ failedAfter = "target_activated";
1353
+ this._mode = "normal";
1354
+ this.setInternalSessionId(created.sessionId, true);
1355
+ await this.v2Transcript.publishCheckpoint({
1356
+ model: this.model,
1357
+ sessionConfiguration: restored.snapshot,
1358
+ metering: this.metering.currentState,
1359
+ });
1360
+
1361
+ const records: OperationMeteringRecord[] = [];
1362
+ const seeded = await this.meteredInternalPrompt(
1363
+ `${transitionId}:seed`,
1364
+ "switch_seed",
1365
+ continuationPrompt(continuation.trim()),
1366
+ records,
1367
+ );
1368
+ if (seeded.status !== "completed") {
1369
+ throw new Error(`continuation seeding ${seeded.status}`);
1370
+ }
1371
+ await this.v2Transcript.appendTransitionEvent({
1372
+ kind: "transition",
1373
+ transitionId,
1374
+ transitionKind,
1375
+ event: "completed",
1376
+ from,
1377
+ to,
1378
+ summary: continuation.trim(),
1379
+ reasonCode: "continuation_reconstruction",
1380
+ });
1381
+ this.continuationAcquired = true;
1382
+ attempts.push(Object.freeze({ strategy: strategy.kind, status: "succeeded" }));
1383
+ return continuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1384
+ kind: "reconstructed",
1385
+ source,
1386
+ activeInternalSessionId: created.sessionId,
1387
+ transitionId,
1388
+ });
1389
+ } catch (error) {
1390
+ await this.v2Transcript.appendTransitionEvent({
1391
+ kind: "transition",
1392
+ transitionId,
1393
+ transitionKind,
1394
+ event: "failed",
1395
+ from,
1396
+ ...(to ? { to } : {}),
1397
+ failedAfter,
1398
+ reasonCode: "continuation_reconstruction",
1399
+ errorCode: "unknown",
1400
+ }).catch((persistenceError) => {
1401
+ this.log.warn("continuation_failure_transcript_failed", { error: String(persistenceError) });
1402
+ });
1403
+ attempts.push(Object.freeze({
1404
+ strategy: strategy.kind,
1405
+ status: "failed",
1406
+ errorCode: "continuation_reconstruction_failed",
1407
+ reason: String(error),
1408
+ }));
1409
+ // Once activation is durable, another fallback would create a second transition
1410
+ // from a checkpoint the caller never selected. Reopen the newly active target.
1411
+ if (failedAfter === "target_activated") break;
1412
+ }
1413
+ }
1414
+
1415
+ return continuationReport(
1416
+ checkpoint,
1417
+ this.adapterId,
1418
+ this.v2Transcript,
1419
+ recordedThreadAvailability,
1420
+ attempts,
1421
+ { kind: "unavailable" },
1422
+ );
1423
+ }
1424
+
1425
+ private async restoreConfigurationOnReconstructedTarget(
1426
+ saved: SessionConfigurationCheckpoint,
1427
+ ): Promise<{ snapshot: SessionConfigurationCheckpoint; status: ConfigurationRestoreStatus }> {
1428
+ const mismatchedIds: string[] = [];
1429
+ const reasons: string[] = [];
1430
+ for (const target of [...saved.restorationTargets].sort((left, right) => left.ordinal - right.ordinal)) {
1431
+ const issue = configurationTargetIssue(this.controller.configOptions.get(target.configId), target);
1432
+ if (issue) {
1433
+ mismatchedIds.push(target.configId);
1434
+ reasons.push(issue);
1435
+ continue;
1436
+ }
1437
+ const option = this.controller.configOptions.get(target.configId)!;
1438
+ if (!sameJsonValue(option.currentValue, target.value)) {
1439
+ try {
1440
+ await this.controller.setConfig(target.configId, structuredClone(target.value));
1441
+ } catch {
1442
+ mismatchedIds.push(target.configId);
1443
+ reasons.push("reapplication_failed");
1444
+ continue;
1445
+ }
1446
+ }
1447
+ const current = this.controller.configOptions.get(target.configId);
1448
+ if (!current || !sameJsonValue(current.currentValue, target.value)) {
1449
+ mismatchedIds.push(target.configId);
1450
+ reasons.push("residual_value_mismatch");
1451
+ }
1452
+ }
1453
+ if (mismatchedIds.length > 0) {
1454
+ throw new Error(`configuration_mismatch: ${mismatchedIds.map((id, index) => `${id}:${reasons[index]}`).join(",")}`);
1455
+ }
1456
+ return this.snapshotReconstructedConfiguration(saved.restorationTargets, saved);
1457
+ }
1458
+
1459
+ private snapshotReconstructedConfiguration(
1460
+ restorationTargets: readonly PersistedSessionConfigSelection[],
1461
+ prior?: SessionConfigurationCheckpoint,
1462
+ ): { snapshot: SessionConfigurationCheckpoint; status: ConfigurationRestoreStatus } {
1463
+ if (this.persistence === false) throw new Error("configuration snapshot requires persistence");
1464
+ const snapshot = snapshotSessionConfiguration({
1465
+ adapterId: this.adapterId,
1466
+ configOptions: this.controller.configOptions,
1467
+ policy: this.persistence.sessionConfiguration,
1468
+ restorationTargets,
1469
+ });
1470
+ const omittedConfigIds = [...new Set([
1471
+ ...(prior?.restorationFidelity === "partial" ? prior.omittedConfigIds : []),
1472
+ ...snapshot.omittedConfigIds,
1473
+ ])].sort();
1474
+ const status: ConfigurationRestoreStatus = prior?.restorationFidelity === "partial"
1475
+ || snapshot.restorationFidelity === "partial"
1476
+ ? Object.freeze({ kind: "partial", omittedConfigIds: Object.freeze(omittedConfigIds) })
1477
+ : Object.freeze({ kind: "matched" });
1478
+ return { snapshot, status };
1479
+ }
1480
+
479
1481
  // --- identity ----------------------------------------------------------------
480
1482
  get internalSessionId(): string | null {
481
1483
  return this._internalSessionId;
@@ -557,7 +1559,62 @@ export class AgentSession implements AgentClient, Bridgeable {
557
1559
  }
558
1560
  /** Resolved history destination, configured directly or derived from transcriptDir. */
559
1561
  get transcriptPath(): string | undefined {
560
- return this._transcriptPath;
1562
+ return this.v2TranscriptPath ?? this._transcriptPath;
1563
+ }
1564
+ get recoveryStatus(): SessionRecoveryStatus {
1565
+ return structuredClone(this._recovery);
1566
+ }
1567
+ get configurationRestoreStatus(): ConfigurationRestoreStatus {
1568
+ return structuredClone(this._configurationRestore);
1569
+ }
1570
+
1571
+ /** @internal Current authority used by SessionManager to stage the initial registry row. */
1572
+ getManagedPersistenceSnapshot(): ManagedAgentSessionPersistenceSnapshot {
1573
+ if (!this.v2Transcript) throw new Error("managed persistence snapshot requires a v2 transcript");
1574
+ return Object.freeze({
1575
+ checkpoint: this.v2Transcript.checkpoint,
1576
+ internalSessionHistory: Object.freeze([...this.v2Transcript.internalSessionHistory]),
1577
+ auditLog: this.managedAuditLog ? structuredClone(this.managedAuditLog) : null,
1578
+ });
1579
+ }
1580
+
1581
+ /** @internal Materialize a durable post-restoration boundary before clearing a tombstone. */
1582
+ async publishManagedRestorationCheckpoint(): Promise<ManagedAgentSessionPersistenceSnapshot> {
1583
+ if (!this.v2Transcript) throw new Error("managed restoration requires a v2 transcript");
1584
+ await this.v2Transcript.publishCheckpoint({});
1585
+ return this.getManagedPersistenceSnapshot();
1586
+ }
1587
+
1588
+ /** @internal Publish every later transcript checkpoint into the managed registry. */
1589
+ attachManagedCheckpointPublisher(
1590
+ publisher: (
1591
+ checkpoint: AgentSessionCheckpoint,
1592
+ history: readonly InternalSessionHistoryEntry[],
1593
+ ) => Promise<void>,
1594
+ ): void {
1595
+ if (!this.v2Transcript) throw new Error("managed checkpoint publication requires a v2 transcript");
1596
+ this.v2Transcript.setCheckpointPublisher(async (checkpoint, history) => {
1597
+ try {
1598
+ await publisher(checkpoint, history);
1599
+ } catch (error) {
1600
+ this.managedPersistenceHealthy = false;
1601
+ this.emitStateIfChanged();
1602
+ throw error;
1603
+ }
1604
+ });
1605
+ }
1606
+ get promptability(): AgentSessionPromptability {
1607
+ const blockers: PromptBlocker[] = [];
1608
+ if (!this.continuationAcquired) blockers.push("continuation_unavailable");
1609
+ if (this._recovery.kind !== "clean") blockers.push("recovery_required");
1610
+ if (this._configurationRestore.kind === "mismatch") blockers.push("configuration_mismatch");
1611
+ if ((this.v2Transcript && !this.v2Transcript.healthy) || !this.managedPersistenceHealthy) {
1612
+ blockers.push("persistence_unhealthy");
1613
+ }
1614
+ if (this.phase === "stopped") blockers.push("session_stopped");
1615
+ return blockers.length === 0
1616
+ ? Object.freeze({ promptable: true as const, blockers: Object.freeze([] as const) })
1617
+ : Object.freeze({ promptable: false as const, blockers: Object.freeze(blockers) });
561
1618
  }
562
1619
  /** Immutable current state. Late subscribers read this before listening for deltas. */
563
1620
  get state(): AgentSessionState {
@@ -569,11 +1626,12 @@ export class AgentSession implements AgentClient, Bridgeable {
569
1626
  internalSessionId: this._internalSessionId,
570
1627
  adapterId: this.adapterId,
571
1628
  mode: this._mode,
1629
+ promptability: this.promptability,
572
1630
  });
573
1631
  }
574
1632
  /** True while one operation is executing. Queued work is exposed independently. */
575
1633
  get isBusy(): boolean {
576
- return this.phase === "prompting" || this.phase === "handoff";
1634
+ return this.phase !== "idle" && this.phase !== "stopped";
577
1635
  }
578
1636
  get queuedOperationCount(): number {
579
1637
  return this.queue.length;
@@ -608,6 +1666,12 @@ export class AgentSession implements AgentClient, Bridgeable {
608
1666
  reject(new Error("AgentSession is stopped"));
609
1667
  return;
610
1668
  }
1669
+ try {
1670
+ this.assertPromptable();
1671
+ } catch (error) {
1672
+ reject(error);
1673
+ return;
1674
+ }
611
1675
  this.queue.push({
612
1676
  kind: "prompt",
613
1677
  turnId: this.mintTurnId(),
@@ -656,6 +1720,12 @@ export class AgentSession implements AgentClient, Bridgeable {
656
1720
  reject(new Error("AgentSession is stopped"));
657
1721
  return;
658
1722
  }
1723
+ try {
1724
+ this.assertPromptable();
1725
+ } catch (error) {
1726
+ reject(error);
1727
+ return;
1728
+ }
659
1729
  this.queue.push({
660
1730
  kind: "handoff",
661
1731
  handoffId: this.mintOperationId(),
@@ -676,7 +1746,15 @@ export class AgentSession implements AgentClient, Bridgeable {
676
1746
  try {
677
1747
  while (this.queue.length > 0) {
678
1748
  const item = this.queue.shift()!;
679
- this.phase = item.kind === "prompt" ? "prompting" : "handoff";
1749
+ this.phase = item.kind === "prompt"
1750
+ ? "prompting"
1751
+ : item.kind === "handoff"
1752
+ ? "handoff"
1753
+ : item.kind === "set_config" || item.kind === "resolve_config"
1754
+ ? "configuring"
1755
+ : item.kind === "resolve_recovery"
1756
+ ? "recovering"
1757
+ : "switching_mode";
680
1758
  this.emitStateIfChanged();
681
1759
  if (item.kind === "prompt") {
682
1760
  this.emit({ kind: "turn_started", turnId: item.turnId });
@@ -692,12 +1770,51 @@ export class AgentSession implements AgentClient, Bridgeable {
692
1770
  this.emit({ kind: "turn_failed", turnId: item.turnId, error: String(err) });
693
1771
  item.reject(err);
694
1772
  }
695
- } else {
1773
+ } else if (item.kind === "handoff") {
696
1774
  try {
697
1775
  item.resolve(await this.runHandoff(item));
698
1776
  } catch (err) {
699
1777
  item.reject(err);
700
1778
  }
1779
+ } else if (item.kind === "set_config") {
1780
+ this.emit({ kind: "configuration_started", operationId: item.operationId, configId: item.configId });
1781
+ try {
1782
+ await this.runSetConfig(item);
1783
+ this.emit({ kind: "configuration_completed", operationId: item.operationId, configId: item.configId });
1784
+ item.resolve();
1785
+ } catch (err) {
1786
+ this.emit({ kind: "configuration_failed", operationId: item.operationId, configId: item.configId, error: String(err) });
1787
+ item.reject(err);
1788
+ }
1789
+ } else if (item.kind === "resolve_config") {
1790
+ try {
1791
+ const result = await this.runResolveConfigurationMismatch(item.resolution);
1792
+ this.emit({
1793
+ kind: "configuration_mismatch_resolved",
1794
+ configuration: structuredClone(result.configuration),
1795
+ appliedConfigIds: result.appliedConfigIds,
1796
+ });
1797
+ item.resolve(result);
1798
+ } catch (err) {
1799
+ item.reject(err);
1800
+ }
1801
+ } else if (item.kind === "resolve_recovery") {
1802
+ try {
1803
+ item.resolve(await this.runResolveRecovery(item.resolution));
1804
+ } catch (err) {
1805
+ item.reject(err);
1806
+ }
1807
+ } else {
1808
+ const from = this._mode;
1809
+ this.emit({ kind: "mode_change_started", transitionId: item.transitionId, from, to: item.mode });
1810
+ try {
1811
+ const result = await this.runSetMode(item);
1812
+ this.emit({ kind: "mode_change_completed", transitionId: item.transitionId, from, to: item.mode });
1813
+ item.resolve(result);
1814
+ } catch (err) {
1815
+ this.emit({ kind: "mode_change_failed", transitionId: item.transitionId, from, to: item.mode, error: String(err) });
1816
+ item.reject(err);
1817
+ }
701
1818
  }
702
1819
  }
703
1820
  } finally {
@@ -709,8 +1826,11 @@ export class AgentSession implements AgentClient, Bridgeable {
709
1826
 
710
1827
  private async runHandoff(item: HandoffQueueItem): Promise<HandoffResult> {
711
1828
  const fromInternalSessionId = this._internalSessionId;
1829
+ const fromDescriptor = this.v2Transcript ? this.v2Descriptor() : null;
712
1830
  let toInternalSessionId: string | undefined;
1831
+ let toDescriptor: InternalSessionDescriptor | undefined;
713
1832
  let summary: string | undefined;
1833
+ let failedAfter: "start" | "target_created" | "target_activated" = "start";
714
1834
  // Records accumulate as they complete, so a handoff that fails partway still reports
715
1835
  // the operations it already paid for.
716
1836
  const records: OperationMeteringRecord[] = [];
@@ -719,15 +1839,26 @@ export class AgentSession implements AgentClient, Bridgeable {
719
1839
  handoffId: item.handoffId,
720
1840
  fromInternalSessionId,
721
1841
  });
722
- await this.appendTranscript({
723
- v: 1,
724
- t: "handoff",
725
- event: "start",
726
- ts: Date.now(),
727
- handoffId: item.handoffId,
728
- fromInternalSessionId,
729
- ...(item.options.summary !== undefined ? { summary: item.options.summary } : {}),
730
- });
1842
+ if (this.v2Transcript) {
1843
+ await this.v2Transcript.appendTransitionEvent({
1844
+ kind: "transition",
1845
+ transitionId: item.handoffId,
1846
+ transitionKind: "handoff",
1847
+ event: "started",
1848
+ from: fromDescriptor,
1849
+ ...(item.options.summary !== undefined ? { summary: item.options.summary } : {}),
1850
+ });
1851
+ } else {
1852
+ await this.appendTranscript({
1853
+ v: 1,
1854
+ t: "handoff",
1855
+ event: "start",
1856
+ ts: Date.now(),
1857
+ handoffId: item.handoffId,
1858
+ fromInternalSessionId,
1859
+ ...(item.options.summary !== undefined ? { summary: item.options.summary } : {}),
1860
+ });
1861
+ }
731
1862
 
732
1863
  try {
733
1864
  if (this.controller.isDegraded) {
@@ -755,14 +1886,57 @@ export class AgentSession implements AgentClient, Bridgeable {
755
1886
  const created = await this.controller.newSession();
756
1887
  if (!created.sessionId) throw new Error("harness returned no session id for handoff");
757
1888
  toInternalSessionId = created.sessionId;
758
- this.setInternalSessionId(toInternalSessionId);
759
- this.emitStateIfChanged();
760
- await this.persist();
761
-
762
1889
  if (toInternalSessionId === fromInternalSessionId) {
763
1890
  throw new Error("harness did not replace the internal session during handoff");
764
1891
  }
765
1892
 
1893
+ if (this.v2Transcript) {
1894
+ const transitionAt = new Date().toISOString();
1895
+ toDescriptor = this.v2Descriptor(toInternalSessionId, transitionAt);
1896
+ await this.v2Transcript.appendTransitionEvent({
1897
+ kind: "transition",
1898
+ transitionId: item.handoffId,
1899
+ transitionKind: "handoff",
1900
+ event: "target_created",
1901
+ from: fromDescriptor,
1902
+ to: toDescriptor,
1903
+ });
1904
+ failedAfter = "target_created";
1905
+ const checkpoint = this.v2Transcript.checkpoint;
1906
+ await this.v2Transcript.activateTransition({
1907
+ kind: "transition",
1908
+ transitionId: item.handoffId,
1909
+ transitionKind: "handoff",
1910
+ event: "target_activated",
1911
+ from: fromDescriptor,
1912
+ to: toDescriptor,
1913
+ ...(fromDescriptor?.internalSessionId
1914
+ ? {
1915
+ historyEntry: {
1916
+ internalSessionId: fromDescriptor.internalSessionId,
1917
+ adapterId: fromDescriptor.adapterId,
1918
+ model: fromDescriptor.model,
1919
+ sessionConfiguration: fromDescriptor.sessionConfiguration,
1920
+ protocol: fromDescriptor.protocol,
1921
+ activatedAt: fromDescriptor.activatedAt!,
1922
+ deactivatedAt: transitionAt,
1923
+ transition: { kind: "handoff", transitionId: item.handoffId },
1924
+ },
1925
+ }
1926
+ : {}),
1927
+ activationState: {
1928
+ resultingStateRevision: checkpoint.stateRevision + 1,
1929
+ updatedAt: transitionAt,
1930
+ transitionAt,
1931
+ boundary: checkpoint.boundary,
1932
+ },
1933
+ });
1934
+ failedAfter = "target_activated";
1935
+ }
1936
+ this.setInternalSessionId(toInternalSessionId);
1937
+ this.emitStateIfChanged();
1938
+ await this.persist();
1939
+
766
1940
  const seeded = await this.meteredInternalPrompt(
767
1941
  `${item.handoffId}:seed`,
768
1942
  "handoff_seed",
@@ -781,23 +1955,35 @@ export class AgentSession implements AgentClient, Bridgeable {
781
1955
  summary,
782
1956
  meteringRecords: Object.freeze([...records]),
783
1957
  });
784
- await this.appendTranscript({
785
- v: 1,
786
- t: "handoff",
787
- event: "complete",
788
- ts: Date.now(),
789
- handoffId: item.handoffId,
790
- fromInternalSessionId,
791
- toInternalSessionId,
792
- summary,
793
- });
1958
+ if (this.v2Transcript) {
1959
+ await this.v2Transcript.appendTransitionEvent({
1960
+ kind: "transition",
1961
+ transitionId: item.handoffId,
1962
+ transitionKind: "handoff",
1963
+ event: "completed",
1964
+ from: fromDescriptor,
1965
+ to: toDescriptor,
1966
+ summary,
1967
+ });
1968
+ } else {
1969
+ await this.appendTranscript({
1970
+ v: 1,
1971
+ t: "handoff",
1972
+ event: "complete",
1973
+ ts: Date.now(),
1974
+ handoffId: item.handoffId,
1975
+ fromInternalSessionId,
1976
+ toInternalSessionId,
1977
+ summary,
1978
+ });
1979
+ }
794
1980
  this.emit({ kind: "handoff_completed", result });
795
1981
  return result;
796
1982
  } catch (err) {
797
1983
  // Once session/new succeeds the controller really is on the new thread. Keep the
798
1984
  // public id and catalog truthful even when continuation seeding subsequently fails.
799
1985
  const actualSessionId = this.controller.currentSessionId;
800
- if (actualSessionId && actualSessionId !== this._internalSessionId) {
1986
+ if (!this.v2Transcript && actualSessionId && actualSessionId !== this._internalSessionId) {
801
1987
  this.setInternalSessionId(actualSessionId);
802
1988
  toInternalSessionId = actualSessionId;
803
1989
  this.emitStateIfChanged();
@@ -808,17 +1994,33 @@ export class AgentSession implements AgentClient, Bridgeable {
808
1994
  }
809
1995
  }
810
1996
  const error = String(err);
811
- await this.appendTranscript({
812
- v: 1,
813
- t: "handoff",
814
- event: "failed",
815
- ts: Date.now(),
816
- handoffId: item.handoffId,
817
- fromInternalSessionId,
818
- ...(toInternalSessionId ? { toInternalSessionId } : {}),
819
- ...(summary !== undefined ? { summary } : {}),
820
- error,
821
- });
1997
+ if (this.v2Transcript) {
1998
+ await this.v2Transcript.appendTransitionEvent({
1999
+ kind: "transition",
2000
+ transitionId: item.handoffId,
2001
+ transitionKind: "handoff",
2002
+ event: "failed",
2003
+ from: fromDescriptor,
2004
+ ...(toDescriptor ? { to: toDescriptor } : {}),
2005
+ failedAfter,
2006
+ ...(summary !== undefined ? { summary } : {}),
2007
+ errorCode: "unknown",
2008
+ }).catch((persistenceError) => {
2009
+ this.log.warn("handoff_failure_transcript_failed", { error: String(persistenceError) });
2010
+ });
2011
+ } else {
2012
+ await this.appendTranscript({
2013
+ v: 1,
2014
+ t: "handoff",
2015
+ event: "failed",
2016
+ ts: Date.now(),
2017
+ handoffId: item.handoffId,
2018
+ fromInternalSessionId,
2019
+ ...(toInternalSessionId ? { toInternalSessionId } : {}),
2020
+ ...(summary !== undefined ? { summary } : {}),
2021
+ error,
2022
+ });
2023
+ }
822
2024
  this.emit({
823
2025
  kind: "handoff_failed",
824
2026
  handoffId: item.handoffId,
@@ -833,15 +2035,501 @@ export class AgentSession implements AgentClient, Bridgeable {
833
2035
  }
834
2036
  }
835
2037
 
2038
+ private async runSetConfig(item: ConfigQueueItem): Promise<void> {
2039
+ if (!this.v2Transcript || this.persistence === false) {
2040
+ await this.controller.setConfig(item.configId, item.value);
2041
+ return;
2042
+ }
2043
+
2044
+ const before = this.v2Transcript.checkpoint;
2045
+ const announced = this.controller.configOptions.get(item.configId);
2046
+ await this.v2Transcript.beginOperation(item.operationId, "set_config");
2047
+ try {
2048
+ await this.v2Transcript.syncBeforeDispatch();
2049
+ } catch (error) {
2050
+ await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(
2051
+ (abortError) => this.log.warn("transcript_predispatch_abort_failed", { error: String(abortError) }),
2052
+ );
2053
+ throw error;
2054
+ }
2055
+
2056
+ let applied = false;
2057
+ try {
2058
+ await this.controller.setConfig(item.configId, item.value);
2059
+ applied = true;
2060
+ const observedAt = new Date().toISOString();
2061
+ const sessionConfiguration = snapshotSessionConfigurationAfterSelection({
2062
+ adapterId: this.adapterId,
2063
+ configOptions: this.controller.configOptions,
2064
+ policy: this.persistence.sessionConfiguration,
2065
+ restorationTargets: before.sessionConfiguration.restorationTargets,
2066
+ selection: {
2067
+ configId: item.configId,
2068
+ type: announced?.type ?? "unknown",
2069
+ value: item.value,
2070
+ recordedAt: observedAt,
2071
+ },
2072
+ observedAt,
2073
+ });
2074
+ const persistedTarget = sessionConfiguration.restorationTargets.find(
2075
+ (target) => target.configId === item.configId,
2076
+ );
2077
+ await this.v2Transcript.appendEvent({
2078
+ kind: "configuration",
2079
+ event: "selected",
2080
+ configId: item.configId,
2081
+ ...(persistedTarget ? { value: persistedTarget.value } : {}),
2082
+ schemaDigest: sessionConfiguration.schemaDigest ?? undefined,
2083
+ });
2084
+ await this.v2Transcript.finishOperation("settled", {
2085
+ model: this.model,
2086
+ sessionConfiguration,
2087
+ metering: this.metering.currentState,
2088
+ });
2089
+ } catch (error) {
2090
+ if (applied) {
2091
+ // The harness changed even if a later local record failed. Attempt one truthful
2092
+ // checkpoint of the observed state; a poisoned runtime rejects and stays blocked.
2093
+ const observedAt = new Date().toISOString();
2094
+ const sessionConfiguration = snapshotSessionConfigurationAfterSelection({
2095
+ adapterId: this.adapterId,
2096
+ configOptions: this.controller.configOptions,
2097
+ policy: this.persistence.sessionConfiguration,
2098
+ restorationTargets: before.sessionConfiguration.restorationTargets,
2099
+ selection: {
2100
+ configId: item.configId,
2101
+ type: announced?.type ?? "unknown",
2102
+ value: item.value,
2103
+ recordedAt: observedAt,
2104
+ },
2105
+ observedAt,
2106
+ });
2107
+ await this.v2Transcript.finishOperation("failed", {
2108
+ model: this.model,
2109
+ sessionConfiguration,
2110
+ metering: this.metering.currentState,
2111
+ }, "unknown").catch((persistenceError) => {
2112
+ this.log.warn("configuration_failure_checkpoint_failed", { error: String(persistenceError) });
2113
+ });
2114
+ } else {
2115
+ await this.v2Transcript.finishOperation("failed", {}, "unknown").catch(
2116
+ (persistenceError) => this.log.warn("configuration_failure_checkpoint_failed", { error: String(persistenceError) }),
2117
+ );
2118
+ }
2119
+ throw error;
2120
+ }
2121
+ }
2122
+
2123
+ private async restoreOpeningConfiguration(): Promise<ConfigurationRestoreStatus> {
2124
+ if (!this.v2Transcript || this.persistence === false) return { kind: "matched" };
2125
+ const saved = this.v2Transcript.checkpoint.sessionConfiguration;
2126
+ const mismatchedIds: string[] = [];
2127
+ const reasons: string[] = [];
2128
+
2129
+ for (const target of [...saved.restorationTargets].sort((a, b) => a.ordinal - b.ordinal)) {
2130
+ const issue = configurationTargetIssue(this.controller.configOptions.get(target.configId), target);
2131
+ if (issue) {
2132
+ mismatchedIds.push(target.configId);
2133
+ reasons.push(issue);
2134
+ continue;
2135
+ }
2136
+ const option = this.controller.configOptions.get(target.configId)!;
2137
+ if (sameJsonValue(option.currentValue, target.value)) continue;
2138
+ if (this._recovery.kind !== "clean") {
2139
+ mismatchedIds.push(target.configId);
2140
+ reasons.push("recovery_required_before_reapplication");
2141
+ continue;
2142
+ }
2143
+ const operationId = this.mintOperationId();
2144
+ await this.v2Transcript.beginOperation(operationId, "set_config");
2145
+ try {
2146
+ await this.v2Transcript.syncBeforeDispatch();
2147
+ } catch (error) {
2148
+ await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(() => undefined);
2149
+ throw error;
2150
+ }
2151
+ try {
2152
+ await this.controller.setConfig(target.configId, structuredClone(target.value));
2153
+ const observedAt = new Date().toISOString();
2154
+ const snapshot = snapshotSessionConfiguration({
2155
+ adapterId: this.adapterId,
2156
+ configOptions: this.controller.configOptions,
2157
+ policy: this.persistence.sessionConfiguration,
2158
+ restorationTargets: saved.restorationTargets,
2159
+ observedAt,
2160
+ });
2161
+ await this.v2Transcript.appendEvent({
2162
+ kind: "configuration",
2163
+ event: "restored",
2164
+ configId: target.configId,
2165
+ value: target.value,
2166
+ schemaDigest: snapshot.schemaDigest ?? undefined,
2167
+ });
2168
+ await this.v2Transcript.finishOperation("settled", {
2169
+ model: this.model,
2170
+ sessionConfiguration: snapshot,
2171
+ metering: this.metering.currentState,
2172
+ });
2173
+ } catch (error) {
2174
+ await this.v2Transcript.finishOperation("failed", {}, "unknown").catch(() => undefined);
2175
+ mismatchedIds.push(target.configId);
2176
+ reasons.push("reapplication_failed");
2177
+ continue;
2178
+ }
2179
+ const restored = this.controller.configOptions.get(target.configId);
2180
+ if (!restored || !sameJsonValue(restored.currentValue, target.value)) {
2181
+ mismatchedIds.push(target.configId);
2182
+ reasons.push("residual_value_mismatch");
2183
+ }
2184
+ }
2185
+
2186
+ if (mismatchedIds.length > 0) {
2187
+ return Object.freeze({
2188
+ kind: "mismatch" as const,
2189
+ configIds: Object.freeze(mismatchedIds),
2190
+ reasons: Object.freeze(reasons),
2191
+ });
2192
+ }
2193
+ const current = snapshotSessionConfiguration({
2194
+ adapterId: this.adapterId,
2195
+ configOptions: this.controller.configOptions,
2196
+ policy: this.persistence.sessionConfiguration,
2197
+ restorationTargets: saved.restorationTargets,
2198
+ });
2199
+ const omittedConfigIds = [...new Set([
2200
+ ...(saved.restorationFidelity === "partial" ? saved.omittedConfigIds : []),
2201
+ ...current.omittedConfigIds,
2202
+ ])].sort();
2203
+ return saved.restorationFidelity === "partial" || current.restorationFidelity === "partial"
2204
+ ? Object.freeze({ kind: "partial" as const, omittedConfigIds: Object.freeze(omittedConfigIds) })
2205
+ : Object.freeze({ kind: "matched" as const });
2206
+ }
2207
+
2208
+ private async runResolveConfigurationMismatch(
2209
+ resolution: ConfigurationMismatchResolution,
2210
+ ): Promise<ConfigurationMismatchResolutionResult> {
2211
+ if (this._configurationRestore.kind !== "mismatch") {
2212
+ throw new Error("configuration mismatch resolution requires a mismatched session");
2213
+ }
2214
+ if (!this.v2Transcript || this.persistence === false) {
2215
+ throw new Error("configuration mismatch resolution requires v2 transcript persistence");
2216
+ }
2217
+ if (this._recovery.kind !== "clean") {
2218
+ throw new AgentSessionPromptBlockedError(["recovery_required"]);
2219
+ }
2220
+ if (!this.v2Transcript.healthy) {
2221
+ throw new AgentSessionPromptBlockedError(["persistence_unhealthy"]);
2222
+ }
2223
+
2224
+ let snapshot: SessionConfigurationCheckpoint;
2225
+ const appliedConfigIds: string[] = [];
2226
+ if (resolution.strategy === "accept_effective") {
2227
+ const recordedAt = new Date().toISOString();
2228
+ snapshot = snapshotAcceptedEffectiveConfiguration({
2229
+ adapterId: this.adapterId,
2230
+ configOptions: this.controller.configOptions,
2231
+ policy: this.persistence.sessionConfiguration,
2232
+ recordedAt,
2233
+ });
2234
+ } else {
2235
+ validateReplacementSelections(resolution.selections, this.controller.configOptions);
2236
+ let restorationTargets: readonly PersistedSessionConfigSelection[] = [];
2237
+ for (const selection of resolution.selections) {
2238
+ const option = this.controller.configOptions.get(selection.configId);
2239
+ const issue = configurationTargetIssue(option, {
2240
+ configId: selection.configId,
2241
+ type: option?.type ?? "unknown",
2242
+ value: selection.value,
2243
+ ordinal: 0,
2244
+ source: "explicit_selection",
2245
+ recordedAt: new Date(0).toISOString(),
2246
+ });
2247
+ if (issue) throw new Error(`${issue}: ${selection.configId}`);
2248
+ const recordedAt = new Date().toISOString();
2249
+ if (!sameJsonValue(option!.currentValue, selection.value)) {
2250
+ await this.applyConfigurationResolutionSelection(
2251
+ selection.configId,
2252
+ selection.value,
2253
+ this.v2Transcript.checkpoint.sessionConfiguration.restorationTargets,
2254
+ );
2255
+ appliedConfigIds.push(selection.configId);
2256
+ }
2257
+ const selected = snapshotSessionConfigurationAfterSelection({
2258
+ adapterId: this.adapterId,
2259
+ configOptions: this.controller.configOptions,
2260
+ policy: this.persistence.sessionConfiguration,
2261
+ restorationTargets,
2262
+ selection: {
2263
+ configId: selection.configId,
2264
+ type: this.controller.configOptions.get(selection.configId)?.type ?? "unknown",
2265
+ value: selection.value,
2266
+ recordedAt,
2267
+ },
2268
+ observedAt: recordedAt,
2269
+ });
2270
+ restorationTargets = selected.restorationTargets;
2271
+ }
2272
+ for (const selection of resolution.selections) {
2273
+ const current = this.controller.configOptions.get(selection.configId);
2274
+ if (!current || !sameJsonValue(current.currentValue, selection.value)) {
2275
+ throw new Error(`configuration resolution left a residual mismatch for ${selection.configId}`);
2276
+ }
2277
+ }
2278
+ snapshot = snapshotSessionConfiguration({
2279
+ adapterId: this.adapterId,
2280
+ configOptions: this.controller.configOptions,
2281
+ policy: this.persistence.sessionConfiguration,
2282
+ restorationTargets,
2283
+ });
2284
+ }
2285
+
2286
+ await this.v2Transcript.appendEvent({
2287
+ kind: "configuration",
2288
+ event: "resolved",
2289
+ schemaDigest: snapshot.schemaDigest ?? undefined,
2290
+ });
2291
+ await this.v2Transcript.publishCheckpoint({
2292
+ model: this.model,
2293
+ sessionConfiguration: snapshot,
2294
+ metering: this.metering.currentState,
2295
+ });
2296
+ const configuration: ConfigurationRestoreStatus = snapshot.restorationFidelity === "partial"
2297
+ ? Object.freeze({
2298
+ kind: "partial",
2299
+ omittedConfigIds: Object.freeze([...snapshot.omittedConfigIds]),
2300
+ })
2301
+ : Object.freeze({ kind: "matched" });
2302
+ this._configurationRestore = configuration;
2303
+ this.emitStateIfChanged();
2304
+ return Object.freeze({
2305
+ configuration: structuredClone(configuration),
2306
+ appliedConfigIds: Object.freeze(appliedConfigIds),
2307
+ });
2308
+ }
2309
+
2310
+ private async runResolveRecovery(
2311
+ resolution: AgentSessionRecoveryResolution,
2312
+ ): Promise<AgentSessionRecoveryResolutionResult> {
2313
+ if (!this.v2Transcript) throw new Error("recovery resolution requires v2 transcript persistence");
2314
+ if (this._recovery.kind !== "uncertain") {
2315
+ throw new Error("recovery resolution requires an uncertain session");
2316
+ }
2317
+ if (!this.v2Transcript.healthy) {
2318
+ throw new AgentSessionPromptBlockedError(["persistence_unhealthy"]);
2319
+ }
2320
+ const previous = structuredClone(this._recovery);
2321
+ await this.v2Transcript.acceptHarnessRecovery();
2322
+ this._recovery = { kind: "clean" };
2323
+ this.emit({
2324
+ kind: "recovery_resolved",
2325
+ strategy: resolution.strategy,
2326
+ previous,
2327
+ recovery: { kind: "clean" },
2328
+ });
2329
+ this.emitStateIfChanged();
2330
+
2331
+ let handoff: HandoffResult | undefined;
2332
+ if (resolution.strategy === "start_new_internal_session") {
2333
+ handoff = await this.runHandoff({
2334
+ kind: "handoff",
2335
+ handoffId: this.mintOperationId(),
2336
+ options: resolution.continuation === undefined
2337
+ ? Object.freeze({})
2338
+ : Object.freeze({ summary: resolution.continuation }),
2339
+ resolve: () => undefined,
2340
+ reject: () => undefined,
2341
+ });
2342
+ }
2343
+ return Object.freeze({
2344
+ previous,
2345
+ recovery: Object.freeze({ kind: "clean" as const }),
2346
+ ...(handoff ? { handoff } : {}),
2347
+ });
2348
+ }
2349
+
2350
+ private async applyConfigurationResolutionSelection(
2351
+ configId: string,
2352
+ value: JsonValue,
2353
+ restorationTargets: readonly PersistedSessionConfigSelection[],
2354
+ ): Promise<void> {
2355
+ if (!this.v2Transcript || this.persistence === false) throw new Error("v2 transcript required");
2356
+ const operationId = this.mintOperationId();
2357
+ await this.v2Transcript.beginOperation(operationId, "set_config");
2358
+ try {
2359
+ await this.v2Transcript.syncBeforeDispatch();
2360
+ } catch (error) {
2361
+ await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(() => undefined);
2362
+ throw error;
2363
+ }
2364
+ try {
2365
+ await this.controller.setConfig(configId, structuredClone(value));
2366
+ const observedAt = new Date().toISOString();
2367
+ const intermediate = snapshotSessionConfiguration({
2368
+ adapterId: this.adapterId,
2369
+ configOptions: this.controller.configOptions,
2370
+ policy: this.persistence.sessionConfiguration,
2371
+ restorationTargets,
2372
+ observedAt,
2373
+ });
2374
+ await this.v2Transcript.appendEvent({
2375
+ kind: "configuration",
2376
+ event: "selected",
2377
+ configId,
2378
+ ...(configId in intermediate.effective ? { value } : {}),
2379
+ schemaDigest: intermediate.schemaDigest ?? undefined,
2380
+ });
2381
+ await this.v2Transcript.finishOperation("settled", {
2382
+ model: this.model,
2383
+ sessionConfiguration: intermediate,
2384
+ metering: this.metering.currentState,
2385
+ });
2386
+ } catch (error) {
2387
+ await this.v2Transcript.finishOperation("failed", {}, "unknown").catch(() => undefined);
2388
+ throw error;
2389
+ }
2390
+ }
2391
+
2392
+ private async runSetMode(item: ModeQueueItem): Promise<ConnectResult> {
2393
+ if (item.mode === this._mode) return await this.controller.setMode(item.mode);
2394
+ if (!this.v2Transcript) {
2395
+ const result = await this.controller.setMode(item.mode);
2396
+ this._mode = this.controller.currentMode;
2397
+ this.setInternalSessionId(result.sessionId || null);
2398
+ await this.persist();
2399
+ return result;
2400
+ }
2401
+
2402
+ const from = this.v2Descriptor();
2403
+ let to: InternalSessionDescriptor | undefined;
2404
+ let failedAfter: "start" | "target_created" | "target_activated" = "start";
2405
+ await this.v2Transcript.appendTransitionEvent({
2406
+ kind: "transition",
2407
+ transitionId: item.transitionId,
2408
+ transitionKind: "mode_change",
2409
+ event: "started",
2410
+ from,
2411
+ reasonCode: "mode_change",
2412
+ });
2413
+ try {
2414
+ const result = await this.controller.setMode(item.mode);
2415
+ const targetMode = this.controller.currentMode;
2416
+ const targetInternalSessionId = result.sessionId || null;
2417
+ const transitionAt = new Date().toISOString();
2418
+ to = this.v2Descriptor(targetInternalSessionId, transitionAt, targetMode);
2419
+ await this.v2Transcript.appendTransitionEvent({
2420
+ kind: "transition",
2421
+ transitionId: item.transitionId,
2422
+ transitionKind: "mode_change",
2423
+ event: "target_created",
2424
+ from,
2425
+ to,
2426
+ reasonCode: "mode_change",
2427
+ });
2428
+ failedAfter = "target_created";
2429
+ const checkpoint = this.v2Transcript.checkpoint;
2430
+ await this.v2Transcript.activateTransition({
2431
+ kind: "transition",
2432
+ transitionId: item.transitionId,
2433
+ transitionKind: "mode_change",
2434
+ event: "target_activated",
2435
+ from,
2436
+ to,
2437
+ ...(from.internalSessionId
2438
+ ? {
2439
+ historyEntry: {
2440
+ internalSessionId: from.internalSessionId,
2441
+ adapterId: from.adapterId,
2442
+ model: from.model,
2443
+ sessionConfiguration: from.sessionConfiguration,
2444
+ protocol: from.protocol,
2445
+ activatedAt: from.activatedAt!,
2446
+ deactivatedAt: transitionAt,
2447
+ transition: {
2448
+ kind: "mode_change",
2449
+ transitionId: item.transitionId,
2450
+ reasonCode: "mode_change",
2451
+ },
2452
+ },
2453
+ }
2454
+ : {}),
2455
+ activationState: {
2456
+ resultingStateRevision: checkpoint.stateRevision + 1,
2457
+ updatedAt: transitionAt,
2458
+ transitionAt,
2459
+ boundary: checkpoint.boundary,
2460
+ },
2461
+ reasonCode: "mode_change",
2462
+ });
2463
+ failedAfter = "target_activated";
2464
+ this._mode = targetMode;
2465
+ this.setInternalSessionId(targetInternalSessionId);
2466
+ this.emitStateIfChanged();
2467
+ await this.v2Transcript.publishCheckpoint({ metering: this.metering.currentState });
2468
+ await this.v2Transcript.appendTransitionEvent({
2469
+ kind: "transition",
2470
+ transitionId: item.transitionId,
2471
+ transitionKind: "mode_change",
2472
+ event: "completed",
2473
+ from,
2474
+ to,
2475
+ reasonCode: "mode_change",
2476
+ });
2477
+ return result;
2478
+ } catch (error) {
2479
+ await this.v2Transcript.appendTransitionEvent({
2480
+ kind: "transition",
2481
+ transitionId: item.transitionId,
2482
+ transitionKind: "mode_change",
2483
+ event: "failed",
2484
+ from,
2485
+ ...(to ? { to } : {}),
2486
+ failedAfter,
2487
+ reasonCode: "mode_change",
2488
+ errorCode: "unknown",
2489
+ }).catch((persistenceError) => {
2490
+ this.log.warn("mode_change_failure_transcript_failed", { error: String(persistenceError) });
2491
+ });
2492
+ throw error;
2493
+ }
2494
+ }
2495
+
836
2496
  private async runPrompt(item: PromptQueueItem): Promise<AgentSessionPromptResult> {
837
2497
  this.beginTurn(item.turnId);
838
- await this.appendTranscript({
839
- v: 1,
840
- t: "msg",
841
- role: "user",
842
- text: item.text,
843
- ts: Date.now(),
844
- });
2498
+ let operation: OpenOperation;
2499
+ if (this.v2Transcript) {
2500
+ let transcriptStarted = false;
2501
+ try {
2502
+ // Metering preflight has no provider side effect. Run it before minting durable
2503
+ // operation evidence so a strict pricing/policy rejection needs no abort record.
2504
+ operation = await this.openMeteredOperation(item);
2505
+ await this.v2Transcript.beginOperation(item.turnId, persistenceOperationKind(item.operationKind));
2506
+ transcriptStarted = true;
2507
+ await this.v2Transcript.appendEvent({
2508
+ kind: "message",
2509
+ operationId: item.turnId,
2510
+ role: "user",
2511
+ text: item.text,
2512
+ });
2513
+ await this.v2Transcript.syncBeforeDispatch();
2514
+ } catch (error) {
2515
+ this.endTurn(item.handlers);
2516
+ if (transcriptStarted) {
2517
+ await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(
2518
+ (abortError) => this.log.warn("transcript_predispatch_abort_failed", { error: String(abortError) }),
2519
+ );
2520
+ }
2521
+ throw error;
2522
+ }
2523
+ } else {
2524
+ await this.appendTranscript({
2525
+ v: 1,
2526
+ t: "msg",
2527
+ role: "user",
2528
+ text: item.text,
2529
+ ts: Date.now(),
2530
+ });
2531
+ operation = await this.openMeteredOperation(item);
2532
+ }
845
2533
 
846
2534
  const chunks: string[] = [];
847
2535
  const response = new ResponseAccumulator();
@@ -860,7 +2548,7 @@ export class AgentSession implements AgentClient, Bridgeable {
860
2548
  },
861
2549
  onActivity: (event) => {
862
2550
  const result = this.aggregator.apply(event);
863
- if (this.transcriptActivity) {
2551
+ if (this.transcriptActivity || this.v2Transcript) {
864
2552
  for (const record of result.emitted) this.writeActivity(record);
865
2553
  }
866
2554
  item.handlers?.onRecord?.(result);
@@ -868,18 +2556,8 @@ export class AgentSession implements AgentClient, Bridgeable {
868
2556
  },
869
2557
  };
870
2558
 
871
- // Opened BEFORE dispatch so a strict mode fails preflight rather than after the
872
- // provider has already been paid, and so the price in force at start is what applies.
873
- const operation = await this.metering.open({
874
- operationId: item.turnId,
875
- operationKind: item.operationKind,
876
- internalSessionId: this._internalSessionId,
877
- providerId: this.providerId,
878
- model: this.model,
879
- degraded: this.controller.isDegraded,
880
- });
881
-
882
2559
  let closed: OperationMeteringRecord | null = null;
2560
+ let transcriptClosed = false;
883
2561
  try {
884
2562
  const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
885
2563
  // Before the assistant msg: `msg` delimits a turn, so anything still open has to
@@ -901,17 +2579,32 @@ export class AgentSession implements AgentClient, Bridgeable {
901
2579
  const record = await this.closeOperation(operation, res.status, res.usage);
902
2580
  closed = record;
903
2581
  await this.persist();
904
- await this.appendTranscript({
905
- v: 1,
906
- t: "msg",
907
- role: "assistant",
908
- text: res.text,
909
- messages: res.messages,
910
- ts: Date.now(),
911
- usage: res.usage,
912
- stopReason: res.stopReason,
913
- status: res.status,
914
- });
2582
+ if (this.v2Transcript) {
2583
+ await this.drainV2Activity();
2584
+ await this.v2Transcript.appendEvent({
2585
+ kind: "message",
2586
+ operationId: item.turnId,
2587
+ role: "assistant",
2588
+ text: res.text,
2589
+ structured: { version: 1, messages: res.messages },
2590
+ stopReason: res.stopReason,
2591
+ status: res.status,
2592
+ });
2593
+ await this.finishV2Prompt(res.status, record);
2594
+ transcriptClosed = true;
2595
+ } else {
2596
+ await this.appendTranscript({
2597
+ v: 1,
2598
+ t: "msg",
2599
+ role: "assistant",
2600
+ text: res.text,
2601
+ messages: res.messages,
2602
+ ts: Date.now(),
2603
+ usage: res.usage,
2604
+ stopReason: res.stopReason,
2605
+ status: res.status,
2606
+ });
2607
+ }
915
2608
  return Object.freeze({ ...res, operationId: item.turnId, metering: record });
916
2609
  } catch (err) {
917
2610
  // Easy to miss, and the whole point of R4: a turn that died mid-tool still records
@@ -924,25 +2617,86 @@ export class AgentSession implements AgentClient, Bridgeable {
924
2617
  : text
925
2618
  ? Object.freeze([{ text }])
926
2619
  : Object.freeze([]);
927
- await this.appendTranscript({
928
- v: 1,
929
- t: "msg",
930
- role: "assistant",
931
- text,
932
- messages,
933
- ts: Date.now(),
934
- stopReason: "error",
935
- status: "error",
936
- });
2620
+ if (this.v2Transcript) {
2621
+ await this.drainV2Activity().catch(() => undefined);
2622
+ if (!transcriptClosed) {
2623
+ await this.v2Transcript.appendEvent({
2624
+ kind: "message",
2625
+ operationId: item.turnId,
2626
+ role: "assistant",
2627
+ text,
2628
+ structured: { version: 1, messages },
2629
+ stopReason: "error",
2630
+ status: "error",
2631
+ }).catch(() => undefined);
2632
+ }
2633
+ } else {
2634
+ await this.appendTranscript({
2635
+ v: 1,
2636
+ t: "msg",
2637
+ role: "assistant",
2638
+ text,
2639
+ messages,
2640
+ ts: Date.now(),
2641
+ stopReason: "error",
2642
+ status: "error",
2643
+ });
2644
+ }
937
2645
  // A failed operation may still have consumed tokens, so its record has to survive
938
2646
  // the rejection rather than only reaching event subscribers.
939
2647
  // Already metered: the failure happened after the operation closed (a transcript or
940
2648
  // catalog write), so the record stands and must not be minted a second time.
941
2649
  const record = closed ?? (await this.closeOperation(operation, "error", null, String(err)));
2650
+ if (this.v2Transcript && !transcriptClosed) {
2651
+ await this.finishV2Prompt("error", record, "unknown").catch(
2652
+ (persistenceError) => this.log.warn("transcript_terminal_write_failed", { error: String(persistenceError) }),
2653
+ );
2654
+ }
942
2655
  throw new AgentSessionOperationError(item.turnId, record, err);
943
2656
  }
944
2657
  }
945
2658
 
2659
+ private openMeteredOperation(item: PromptQueueItem): Promise<OpenOperation> {
2660
+ return this.metering.open({
2661
+ operationId: item.turnId,
2662
+ operationKind: item.operationKind,
2663
+ internalSessionId: this._internalSessionId,
2664
+ providerId: this.providerId,
2665
+ model: this.model,
2666
+ degraded: this.controller.isDegraded,
2667
+ });
2668
+ }
2669
+
2670
+ private async finishV2Prompt(
2671
+ status: PromptResult["status"],
2672
+ record: OperationMeteringRecord,
2673
+ errorCode?: "unknown",
2674
+ ): Promise<void> {
2675
+ if (!this.v2Transcript || this.persistence === false) return;
2676
+ const observedAt = new Date().toISOString();
2677
+ await this.v2Transcript.appendEvent({
2678
+ kind: "metering_reference",
2679
+ operationId: record.operationId,
2680
+ meteringRecordId: record.operationId,
2681
+ status: record.usage.status === "metered" ? "available" : "unavailable",
2682
+ });
2683
+ await this.v2Transcript.finishOperation(
2684
+ status === "completed" ? "settled" : status === "cancelled" ? "cancelled" : "failed",
2685
+ {
2686
+ model: this.model,
2687
+ sessionConfiguration: snapshotSessionConfiguration({
2688
+ adapterId: this.adapterId,
2689
+ configOptions: this.controller.configOptions,
2690
+ policy: this.persistence.sessionConfiguration,
2691
+ restorationTargets: this.v2Transcript.checkpoint.sessionConfiguration.restorationTargets,
2692
+ observedAt,
2693
+ }),
2694
+ metering: this.metering.currentState,
2695
+ },
2696
+ errorCode,
2697
+ );
2698
+ }
2699
+
946
2700
  /**
947
2701
  * Replace metering state after an out-of-band reconciliation, and clear any block.
948
2702
  *
@@ -970,6 +2724,11 @@ export class AgentSession implements AgentClient, Bridgeable {
970
2724
  );
971
2725
  }
972
2726
  const wasBlocked = this.metering.blocked;
2727
+ if (this.v2Transcript) {
2728
+ // The replacement state is already fully validated above. Persist it first so a
2729
+ // successful return can never leave only the in-memory engine reconciled.
2730
+ await this.v2Transcript.publishCheckpoint({ metering: restoration.state });
2731
+ }
973
2732
  // Validated first: state is replaced atomically or not at all.
974
2733
  const { before } = this.metering.reconcile(restoration.state);
975
2734
  const after = this.metering.currentState;
@@ -1009,20 +2768,105 @@ export class AgentSession implements AgentClient, Bridgeable {
1009
2768
  model: this.model,
1010
2769
  degraded: this.controller.isDegraded,
1011
2770
  });
2771
+ let transcriptStarted = false;
2772
+ if (this.v2Transcript) {
2773
+ try {
2774
+ await this.v2Transcript.beginOperation(operationId, persistenceOperationKind(operationKind));
2775
+ transcriptStarted = true;
2776
+ await this.v2Transcript.appendEvent({
2777
+ kind: "message",
2778
+ operationId,
2779
+ role: "user",
2780
+ text,
2781
+ });
2782
+ await this.v2Transcript.syncBeforeDispatch();
2783
+ } catch (error) {
2784
+ if (transcriptStarted) {
2785
+ await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(
2786
+ (abortError) => this.log.warn("transcript_predispatch_abort_failed", { error: String(abortError) }),
2787
+ );
2788
+ }
2789
+ throw error;
2790
+ }
2791
+ }
1012
2792
  let closed = false;
2793
+ let transcriptClosed = false;
1013
2794
  try {
1014
2795
  const result = await this.controller.prompt(text);
1015
- records.push(await this.closeOperation(operation, result.status, result.usage));
2796
+ const record = await this.closeOperation(operation, result.status, result.usage);
2797
+ records.push(record);
1016
2798
  closed = true;
2799
+ if (this.v2Transcript) {
2800
+ await this.v2Transcript.appendEvent({
2801
+ kind: "message",
2802
+ operationId,
2803
+ role: "assistant",
2804
+ text: result.text,
2805
+ structured: { version: 1, messages: result.messages },
2806
+ stopReason: result.stopReason,
2807
+ status: result.status,
2808
+ });
2809
+ await this.finishV2Prompt(result.status, record);
2810
+ transcriptClosed = true;
2811
+ }
1017
2812
  return result;
1018
2813
  } catch (err) {
1019
2814
  if (!closed) {
1020
- records.push(await this.closeOperation(operation, "error", null, String(err)));
2815
+ const record = await this.closeOperation(operation, "error", null, String(err));
2816
+ records.push(record);
2817
+ closed = true;
2818
+ }
2819
+ if (this.v2Transcript && !transcriptClosed) {
2820
+ const record = records[records.length - 1]!;
2821
+ await this.v2Transcript.appendEvent({
2822
+ kind: "message",
2823
+ operationId,
2824
+ role: "assistant",
2825
+ text: "",
2826
+ structured: { version: 1, messages: [] },
2827
+ stopReason: "error",
2828
+ status: "error",
2829
+ }).catch(() => undefined);
2830
+ await this.finishV2Prompt("error", record, "unknown").catch(
2831
+ (persistenceError) => this.log.warn("transcript_terminal_write_failed", { error: String(persistenceError) }),
2832
+ );
1021
2833
  }
1022
2834
  throw err;
1023
2835
  }
1024
2836
  }
1025
2837
 
2838
+ private v2Descriptor(
2839
+ internalSessionId: string | null = this._internalSessionId,
2840
+ activatedAt?: string,
2841
+ mode: AgentMode = this._mode,
2842
+ ): InternalSessionDescriptor {
2843
+ if (!this.v2Transcript || this.persistence === false) {
2844
+ throw new Error("v2 descriptor requires transcript persistence");
2845
+ }
2846
+ const checkpoint = this.v2Transcript.checkpoint;
2847
+ const observedAt = activatedAt ?? new Date().toISOString();
2848
+ return {
2849
+ internalSessionId,
2850
+ adapterId: this.adapterId,
2851
+ mode,
2852
+ model: this.model,
2853
+ sessionConfiguration: internalSessionId === checkpoint.internalSessionId
2854
+ ? checkpoint.sessionConfiguration
2855
+ : snapshotSessionConfiguration({
2856
+ adapterId: this.adapterId,
2857
+ configOptions: this.controller.configOptions,
2858
+ policy: this.persistence.sessionConfiguration,
2859
+ observedAt,
2860
+ }),
2861
+ activatedAt: internalSessionId === checkpoint.internalSessionId
2862
+ ? checkpoint.internalSessionActivatedAt
2863
+ : internalSessionId
2864
+ ? observedAt
2865
+ : null,
2866
+ protocol: this.controller.isDegraded ? { name: "pty" } : { name: "acp", version: 1 },
2867
+ };
2868
+ }
2869
+
1026
2870
  /**
1027
2871
  * Close a rating unit, emit its record, and surface a strict-mode block.
1028
2872
  *
@@ -1071,14 +2915,14 @@ export class AgentSession implements AgentClient, Bridgeable {
1071
2915
  const leftover = this.aggregator.startTurn(turnId);
1072
2916
  if (leftover.length > 0) {
1073
2917
  this.log.warn("activity_turn_not_flushed", { records: leftover.length });
1074
- if (this.transcriptActivity) for (const record of leftover) this.writeActivity(record);
2918
+ if (this.transcriptActivity || this.v2Transcript) for (const record of leftover) this.writeActivity(record);
1075
2919
  }
1076
2920
  }
1077
2921
 
1078
2922
  private endTurn(handlers?: PromptHandlers): void {
1079
2923
  const emitted = this.aggregator.flush();
1080
2924
  if (emitted.length === 0) return;
1081
- if (this.transcriptActivity) for (const record of emitted) this.writeActivity(record);
2925
+ if (this.transcriptActivity || this.v2Transcript) for (const record of emitted) this.writeActivity(record);
1082
2926
  // Live subscribers need these too: without them, a tool call on a turn that was
1083
2927
  // cancelled or crashed spins forever in the UI. `wireFrames()` handles this shape.
1084
2928
  handlers?.onRecord?.({ current: null, delta: null, emitted });
@@ -1109,11 +2953,24 @@ export class AgentSession implements AgentClient, Bridgeable {
1109
2953
  * holds without blocking the agent's update stream on disk.
1110
2954
  */
1111
2955
  private writeActivity(record: AggregatedRecord): void {
2956
+ if (this.v2Transcript) {
2957
+ const operationId = this.v2Transcript.checkpoint.boundary.status === "in_flight"
2958
+ ? this.v2Transcript.checkpoint.boundary.interruptedOperationId
2959
+ : record.recordId.split(":", 1)[0] ?? record.recordId;
2960
+ this.v2ActivityWrite = this.v2ActivityWrite.then(async () => {
2961
+ await this.v2Transcript!.appendEvent(persistenceEventFromActivity(record, operationId));
2962
+ });
2963
+ return;
2964
+ }
1112
2965
  if (!this._transcriptPath) return;
1113
2966
  if (!this.activityKinds.has(record.event.kind)) return;
1114
2967
  void this.appendTranscript(this.toActivityLine(record));
1115
2968
  }
1116
2969
 
2970
+ private async drainV2Activity(): Promise<void> {
2971
+ await this.v2ActivityWrite;
2972
+ }
2973
+
1117
2974
  private toActivityLine(record: AggregatedRecord): TranscriptActivityLine {
1118
2975
  let fields: Record<string, unknown> = { ...record.event };
1119
2976
  if (!this.activityRawOutput) delete fields.rawOutput;
@@ -1155,7 +3012,14 @@ export class AgentSession implements AgentClient, Bridgeable {
1155
3012
  metering: null,
1156
3013
  });
1157
3014
  } else {
1158
- item.reject(new Error("handoff cancelled before it started"));
3015
+ const label = item.kind === "handoff"
3016
+ ? "handoff"
3017
+ : item.kind === "set_config" || item.kind === "resolve_config"
3018
+ ? "configuration change"
3019
+ : item.kind === "resolve_recovery"
3020
+ ? "recovery resolution"
3021
+ : "mode change";
3022
+ item.reject(new Error(`${label} cancelled before it started`));
1159
3023
  }
1160
3024
  }
1161
3025
  this.emitStateIfChanged();
@@ -1172,16 +3036,25 @@ export class AgentSession implements AgentClient, Bridgeable {
1172
3036
  this.phase = "stopped";
1173
3037
  this.emitStateIfChanged();
1174
3038
  await this.controller.stop();
3039
+ await this.drainV2Activity().catch(() => undefined);
3040
+ await this.v2Transcript?.close();
1175
3041
  }
1176
3042
 
1177
3043
  // --- mode swap (catalog-affecting) -------------------------------------------
1178
3044
  async setMode(mode: AgentMode): Promise<ConnectResult> {
1179
- const result = await this.controller.setMode(mode);
1180
- this._mode = this.controller.currentMode;
1181
- // The ACP/harness session changes on swap, so context/cost reset with it.
1182
- this.setInternalSessionId(result.sessionId || null);
1183
- await this.persist();
1184
- return result;
3045
+ if (this.phase === "stopped") throw new Error("AgentSession is stopped");
3046
+ this.assertPromptable();
3047
+ return await new Promise<ConnectResult>((resolve, reject) => {
3048
+ this.queue.push({
3049
+ kind: "set_mode",
3050
+ transitionId: this.mintOperationId(),
3051
+ mode,
3052
+ resolve,
3053
+ reject,
3054
+ });
3055
+ this.emitStateIfChanged();
3056
+ void this.pump();
3057
+ });
1185
3058
  }
1186
3059
 
1187
3060
  // --- thin proxies to the live connection -------------------------------------
@@ -1198,7 +3071,78 @@ export class AgentSession implements AgentClient, Bridgeable {
1198
3071
  * way, so it is the only route to them once the process is running.
1199
3072
  */
1200
3073
  setConfig(configId: string, value: unknown): Promise<void> {
1201
- return this.controller.setConfig(configId, value);
3074
+ if (this.phase === "stopped") return Promise.reject(new Error("AgentSession is stopped"));
3075
+ try {
3076
+ this.assertPromptable();
3077
+ } catch (error) {
3078
+ return Promise.reject(error);
3079
+ }
3080
+ let ownedValue: unknown;
3081
+ try {
3082
+ ownedValue = structuredClone(value);
3083
+ } catch (error) {
3084
+ return Promise.reject(new Error(`configuration value cannot be cloned: ${String(error)}`));
3085
+ }
3086
+ return new Promise<void>((resolve, reject) => {
3087
+ this.queue.push({
3088
+ kind: "set_config",
3089
+ operationId: this.mintOperationId(),
3090
+ configId,
3091
+ value: ownedValue,
3092
+ resolve,
3093
+ reject,
3094
+ });
3095
+ this.emitStateIfChanged();
3096
+ void this.pump();
3097
+ });
3098
+ }
3099
+ resolveConfigurationMismatch(
3100
+ resolution: ConfigurationMismatchResolution,
3101
+ ): Promise<ConfigurationMismatchResolutionResult> {
3102
+ if (this.phase === "stopped") return Promise.reject(new Error("AgentSession is stopped"));
3103
+ let owned: ConfigurationMismatchResolution;
3104
+ try {
3105
+ owned = resolution.strategy === "accept_effective"
3106
+ ? Object.freeze({ strategy: "accept_effective" })
3107
+ : Object.freeze({
3108
+ strategy: "replace_restoration_targets",
3109
+ selections: Object.freeze(resolution.selections.map((selection) => Object.freeze({
3110
+ configId: selection.configId,
3111
+ value: structuredClone(selection.value),
3112
+ }))),
3113
+ });
3114
+ } catch (error) {
3115
+ return Promise.reject(new Error(`configuration resolution cannot be cloned: ${String(error)}`));
3116
+ }
3117
+ return new Promise((resolve, reject) => {
3118
+ this.queue.push({ kind: "resolve_config", resolution: owned, resolve, reject });
3119
+ this.emitStateIfChanged();
3120
+ void this.pump();
3121
+ });
3122
+ }
3123
+ resolveRecovery(
3124
+ resolution: AgentSessionRecoveryResolution,
3125
+ ): Promise<AgentSessionRecoveryResolutionResult> {
3126
+ if (this.phase === "stopped") return Promise.reject(new Error("AgentSession is stopped"));
3127
+ if (this._recovery.kind !== "uncertain") {
3128
+ return Promise.reject(new Error("recovery resolution requires an uncertain session"));
3129
+ }
3130
+ if (resolution.strategy === "start_new_internal_session"
3131
+ && resolution.continuation !== undefined
3132
+ && !resolution.continuation.trim()) {
3133
+ return Promise.reject(new Error("recovery continuation cannot be blank"));
3134
+ }
3135
+ const owned: AgentSessionRecoveryResolution = resolution.strategy === "accept_harness_state"
3136
+ ? Object.freeze({ strategy: resolution.strategy })
3137
+ : Object.freeze({
3138
+ strategy: resolution.strategy,
3139
+ ...(resolution.continuation === undefined ? {} : { continuation: resolution.continuation }),
3140
+ });
3141
+ return new Promise((resolve, reject) => {
3142
+ this.queue.push({ kind: "resolve_recovery", resolution: owned, resolve, reject });
3143
+ this.emitStateIfChanged();
3144
+ void this.pump();
3145
+ });
1202
3146
  }
1203
3147
  /** Immutable snapshot of commands advertised by the active ACP harness. */
1204
3148
  get internalSessionCommands(): readonly InternalSessionCommand[] {
@@ -1352,12 +3296,20 @@ export class AgentSession implements AgentClient, Bridgeable {
1352
3296
  state.internalSessionId ?? "",
1353
3297
  state.adapterId,
1354
3298
  state.mode,
3299
+ state.promptability.promptable ? "promptable" : state.promptability.blockers.join(","),
1355
3300
  ].join("\u0000");
1356
3301
  if (key === this.lastStateKey) return;
1357
3302
  this.lastStateKey = key;
1358
3303
  this.emit({ kind: "state_changed", state });
1359
3304
  }
1360
3305
 
3306
+ private assertPromptable(): void {
3307
+ const promptability = this.promptability;
3308
+ if (!promptability.promptable) {
3309
+ throw new AgentSessionPromptBlockedError(promptability.blockers);
3310
+ }
3311
+ }
3312
+
1361
3313
  /** Listener failures are observation failures, never session-operation failures. */
1362
3314
  private emit(event: AgentSessionEvent): void {
1363
3315
  const notification: AgentSessionNotification = Object.freeze({
@@ -1379,6 +3331,146 @@ export class AgentSession implements AgentClient, Bridgeable {
1379
3331
  }
1380
3332
  }
1381
3333
 
3334
+ function persistenceOperationKind(kind: MeteredOperationKind): OperationKind {
3335
+ return kind === "internal_command" ? "internal_session_command" : kind;
3336
+ }
3337
+
3338
+ function continuationReport(
3339
+ checkpoint: AgentSessionCheckpoint,
3340
+ requestedAdapterId: string,
3341
+ transcript: PersistenceStateRuntime,
3342
+ recordedThreadAvailability: ContinuationReport["recordedThreadAvailability"],
3343
+ attempts: readonly ContinuationAttempt[],
3344
+ outcome: ContinuationReport["outcome"],
3345
+ ): ContinuationReport {
3346
+ return Object.freeze({
3347
+ recordedAdapterId: checkpoint.adapterId,
3348
+ recordedInternalSessionId: checkpoint.internalSessionId,
3349
+ requestedAdapterId,
3350
+ recordedConversationAvailability: transcript.conversationAvailability,
3351
+ recordedThreadAvailability,
3352
+ attempts: Object.freeze(attempts.map((attempt) => Object.freeze({ ...attempt }))),
3353
+ outcome: Object.freeze({ ...outcome }),
3354
+ });
3355
+ }
3356
+
3357
+ function descriptorFromCheckpoint(checkpoint: AgentSessionCheckpoint): InternalSessionDescriptor {
3358
+ return {
3359
+ internalSessionId: checkpoint.internalSessionId,
3360
+ adapterId: checkpoint.adapterId,
3361
+ mode: checkpoint.mode,
3362
+ model: checkpoint.model,
3363
+ sessionConfiguration: checkpoint.sessionConfiguration,
3364
+ activatedAt: checkpoint.internalSessionActivatedAt,
3365
+ protocol: checkpoint.protocol,
3366
+ };
3367
+ }
3368
+
3369
+ function isReconstructionStrategy(strategy: ContinuationStrategy): boolean {
3370
+ return strategy.kind === "new_from_transcript" || strategy.kind === "new_from_consumer_continuation";
3371
+ }
3372
+
3373
+ function normalizeContinuationStrategies(
3374
+ options: OpenContinuationOptions | undefined,
3375
+ ): readonly ContinuationStrategy[] {
3376
+ const strategies = options?.strategies ?? [{ kind: "load_internal_session" as const }];
3377
+ if (strategies.length === 0) throw new Error("continuation.strategies cannot be empty");
3378
+ return Object.freeze(strategies.map((strategy): ContinuationStrategy => {
3379
+ if (strategy.kind === "load_internal_session") {
3380
+ return Object.freeze({ kind: strategy.kind });
3381
+ }
3382
+ if (strategy.kind === "new_from_transcript") {
3383
+ if (!strategy.strategyId.trim()) throw new Error("transcript continuation strategyId cannot be blank");
3384
+ if (typeof strategy.buildContinuation !== "function") {
3385
+ throw new Error("transcript continuation strategy requires buildContinuation");
3386
+ }
3387
+ return Object.freeze({
3388
+ kind: strategy.kind,
3389
+ strategyId: strategy.strategyId,
3390
+ buildContinuation: strategy.buildContinuation,
3391
+ });
3392
+ }
3393
+ if (!strategy.continuationId.trim()) throw new Error("consumer continuationId cannot be blank");
3394
+ if (!strategy.continuation.trim()) throw new Error("consumer continuation cannot be blank");
3395
+ return Object.freeze({
3396
+ kind: strategy.kind,
3397
+ continuationId: strategy.continuationId,
3398
+ continuation: strategy.continuation,
3399
+ });
3400
+ }));
3401
+ }
3402
+
3403
+ async function stageOpeningContinuation(
3404
+ stage: ((state: StagedContinuationState) => Promise<StagedContinuationState>) | undefined,
3405
+ checkpoint: AgentSessionCheckpoint,
3406
+ internalSessionId: string,
3407
+ ): Promise<void> {
3408
+ if (!stage) return;
3409
+ const observed: StagedContinuationState = {
3410
+ adapterId: checkpoint.adapterId,
3411
+ mode: checkpoint.mode,
3412
+ internalSessionId,
3413
+ internalSessionActivatedAt: checkpoint.internalSessionActivatedAt,
3414
+ model: checkpoint.model,
3415
+ sessionConfiguration: checkpoint.sessionConfiguration,
3416
+ protocol: checkpoint.protocol,
3417
+ };
3418
+ const persisted = await stage(observed);
3419
+ if (persisted.adapterId !== observed.adapterId
3420
+ || persisted.mode !== observed.mode
3421
+ || persisted.internalSessionId !== observed.internalSessionId) {
3422
+ throw new Error("staged continuation disagrees with the loaded provider identity");
3423
+ }
3424
+ }
3425
+
3426
+ function configurationTargetIssue(
3427
+ option: ConfigOption | undefined,
3428
+ target: PersistedSessionConfigSelection,
3429
+ ): string | null {
3430
+ if (!option) return "configuration_option_missing";
3431
+ if (target.type !== "unknown" && option.type !== target.type) return "configuration_type_changed";
3432
+ if (option.type === "boolean" && typeof target.value !== "boolean") return "configuration_value_invalid";
3433
+ if (option.type === "select" && !(option.allowedValues ?? []).some(
3434
+ (choice) => sameJsonValue(choice.value, target.value),
3435
+ )) return "configuration_value_no_longer_allowed";
3436
+ return null;
3437
+ }
3438
+
3439
+ function validateReplacementSelections(
3440
+ selections: readonly { readonly configId: string; readonly value: JsonValue }[],
3441
+ options: ConfigOptions,
3442
+ ): void {
3443
+ if (selections.length === 0) throw new Error("replacement restoration targets cannot be empty");
3444
+ const ids = new Set<string>();
3445
+ for (const selection of selections) {
3446
+ if (!selection.configId.trim()) throw new Error("replacement configId cannot be blank");
3447
+ if (ids.has(selection.configId)) {
3448
+ throw new Error(`duplicate replacement configId: ${selection.configId}`);
3449
+ }
3450
+ ids.add(selection.configId);
3451
+ canonicalizeJson(selection.value);
3452
+ const option = options.get(selection.configId);
3453
+ if (!option) throw new Error(`configuration option is not announced: ${selection.configId}`);
3454
+ const issue = configurationTargetIssue(option, {
3455
+ configId: selection.configId,
3456
+ type: option.type,
3457
+ value: selection.value,
3458
+ ordinal: 0,
3459
+ source: "explicit_selection",
3460
+ recordedAt: new Date(0).toISOString(),
3461
+ });
3462
+ if (issue) throw new Error(`${issue}: ${selection.configId}`);
3463
+ }
3464
+ }
3465
+
3466
+ function sameJsonValue(left: unknown, right: JsonValue): boolean {
3467
+ try {
3468
+ return canonicalizeJson(left) === canonicalizeJson(right);
3469
+ } catch {
3470
+ return false;
3471
+ }
3472
+ }
3473
+
1382
3474
  /** Do not let one notification observer mutate the PromptResult another observer sees. */
1383
3475
  function copyPromptResult(result: PromptResult): PromptResult {
1384
3476
  const messages = result.messages ?? (result.text ? [{ text: result.text }] : []);