@qlairoslabs/acp-client 0.5.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 (62) hide show
  1. package/CHANGELOG-metering.md +288 -0
  2. package/CONSUMER_GUIDE.md +579 -292
  3. package/README.md +25 -0
  4. package/package.json +6 -3
  5. package/src/agent-session.ts +2589 -96
  6. package/src/cli/index.ts +33 -5
  7. package/src/cli/managed.ts +220 -0
  8. package/src/client.ts +57 -1
  9. package/src/controller.ts +43 -0
  10. package/src/index.ts +379 -3
  11. package/src/metering/catalog/build.ts +285 -0
  12. package/src/metering/catalog/index.ts +243 -0
  13. package/src/metering/catalog/live.ts +171 -0
  14. package/src/metering/catalog/models-dev.catalog.json +8797 -0
  15. package/src/metering/catalog/models-dev.meta.json +6 -0
  16. package/src/metering/categories.ts +129 -0
  17. package/src/metering/certification.ts +86 -0
  18. package/src/metering/context.ts +134 -0
  19. package/src/metering/delta.ts +108 -0
  20. package/src/metering/engine.ts +999 -0
  21. package/src/metering/money.ts +356 -0
  22. package/src/metering/opencode/channel.ts +389 -0
  23. package/src/metering/opencode/index.ts +159 -0
  24. package/src/metering/opencode/plugin.js +90 -0
  25. package/src/metering/opencode/profile.ts +159 -0
  26. package/src/metering/pricing.ts +285 -0
  27. package/src/metering/provider.ts +121 -0
  28. package/src/metering/rating.ts +349 -0
  29. package/src/metering/record.ts +275 -0
  30. package/src/metering/state.ts +421 -0
  31. package/src/metering/usage.ts +72 -0
  32. package/src/persistence/activity-projection.ts +71 -0
  33. package/src/persistence/audit-log-reader.ts +506 -0
  34. package/src/persistence/audit-runtime.ts +162 -0
  35. package/src/persistence/checkpoint.ts +304 -0
  36. package/src/persistence/config.ts +538 -0
  37. package/src/persistence/configuration-state.ts +191 -0
  38. package/src/persistence/deletion.ts +227 -0
  39. package/src/persistence/file-registry-store.ts +740 -0
  40. package/src/persistence/integrity.ts +147 -0
  41. package/src/persistence/legacy-registry-import.ts +240 -0
  42. package/src/persistence/managed-checkpoint.ts +81 -0
  43. package/src/persistence/managed-creation.ts +456 -0
  44. package/src/persistence/managed-load.ts +172 -0
  45. package/src/persistence/managed-registry.ts +57 -0
  46. package/src/persistence/migration.ts +298 -0
  47. package/src/persistence/paths.ts +172 -0
  48. package/src/persistence/projection.ts +373 -0
  49. package/src/persistence/reconfiguration.ts +453 -0
  50. package/src/persistence/records.ts +873 -0
  51. package/src/persistence/reducer.ts +498 -0
  52. package/src/persistence/registry.ts +446 -0
  53. package/src/persistence/restoration.ts +689 -0
  54. package/src/persistence/session-log-writer.ts +480 -0
  55. package/src/persistence/state-runtime.ts +176 -0
  56. package/src/persistence/transcript-reader.ts +980 -0
  57. package/src/persistence/transcript-runtime.ts +667 -0
  58. package/src/persistence/transcript-scanner.ts +385 -0
  59. package/src/persistence/truncation.ts +276 -0
  60. package/src/session-manager.ts +257 -7
  61. package/src/transcript.ts +3 -3
  62. package/src/types.ts +28 -5
@@ -16,10 +16,31 @@ 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";
23
+ import { MeteringEngine, type OpenOperation } from "./metering/engine.ts";
24
+ import {
25
+ AgentSessionHandoffError,
26
+ AgentSessionOperationError,
27
+ type AgentSessionMeteringSnapshot,
28
+ type MeteredOperationKind,
29
+ type MeteringConfig,
30
+ type MeteringReconciliation,
31
+ type OperationMeteringRecord,
32
+ } from "./metering/record.ts";
33
+ import { createModelsDevResolver } from "./metering/catalog/index.ts";
34
+ import { activeModel, resolveModelReference } from "./metering/provider.ts";
35
+ import { restoreMeteringState, type AgentSessionMeteringState } from "./metering/state.ts";
36
+ import {
37
+ contextWindowChanged,
38
+ parseContextWindow,
39
+ parseProviderCost,
40
+ providerCostChanged,
41
+ type ContextWindowStatus,
42
+ type ProviderCostSnapshot,
43
+ } from "./metering/context.ts";
23
44
  import type { SessionManager, MergedSession } from "./session-manager.ts";
24
45
  import {
25
46
  appendTranscriptLine,
@@ -33,16 +54,58 @@ import type {
33
54
  PromptHandlers,
34
55
  PromptResult,
35
56
  SessionListEntry,
57
+ TokenUsage,
36
58
  WireEntry,
37
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";
38
99
 
39
100
  interface PromptQueueItem {
40
101
  kind: "prompt";
41
102
  turnId: string;
103
+ /** How this operation is classified in its metering record. */
104
+ operationKind: MeteredOperationKind;
42
105
  text: string;
43
106
  handlers?: PromptHandlers;
44
107
  attachments?: Attachment[];
45
- resolve: (r: PromptResult) => void;
108
+ resolve: (r: AgentSessionPromptResult) => void;
46
109
  reject: (e: unknown) => void;
47
110
  }
48
111
 
@@ -54,10 +117,48 @@ interface HandoffQueueItem {
54
117
  reject: (error: unknown) => void;
55
118
  }
56
119
 
57
- 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;
58
152
 
59
153
  /** What the stable logical session is doing right now. */
60
- 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";
61
162
 
62
163
  /** Authoritative, immutable point-in-time state for orchestration consumers. */
63
164
  export interface AgentSessionState {
@@ -70,6 +171,148 @@ export interface AgentSessionState {
70
171
  readonly internalSessionId: string | null;
71
172
  readonly adapterId: string;
72
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
+ }
73
316
  }
74
317
 
75
318
  export interface HandoffOptions {
@@ -83,6 +326,8 @@ export interface HandoffResult {
83
326
  readonly fromInternalSessionId: string | null;
84
327
  readonly toInternalSessionId: string;
85
328
  readonly summary: string;
329
+ /** One record per token-consuming operation the handoff performed, in order. */
330
+ readonly meteringRecords: readonly OperationMeteringRecord[];
86
331
  }
87
332
 
88
333
  /** Session-owned lifecycle events. Harness activity remains in PromptHandlers.onActivity. */
@@ -105,8 +350,57 @@ export type AgentSessionEvent =
105
350
  fromInternalSessionId: string | null;
106
351
  toInternalSessionId?: string;
107
352
  error: string;
353
+ /** Records produced before and during the failure. */
354
+ meteringRecords: readonly OperationMeteringRecord[];
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
+ }
373
+ /** Latest context-window observation for the ACTIVE provider thread, or null. */
374
+ | { kind: "context_window_changed"; contextWindow: ContextWindowStatus | null }
375
+ /** Latest cumulative provider-reported cost. Telemetry, never asserted to be an invoice. */
376
+ | { kind: "provider_cost_changed"; providerCost: ProviderCostSnapshot | null }
377
+ /** One immutable record per observed operation, emitted before its turn completes. */
378
+ | { kind: "metering_recorded"; record: OperationMeteringRecord }
379
+ /** A strict mode detected a metering failure; later token-consuming work will reject. */
380
+ | { kind: "metering_blocked"; reason: string }
381
+ | { kind: "metering_unblocked" }
382
+ | {
383
+ kind: "metering_reconciled";
384
+ before: AgentSessionMeteringState;
385
+ after: AgentSessionMeteringState;
386
+ reason: string;
387
+ reference?: string;
388
+ reconciledAt: number;
108
389
  };
109
390
 
391
+ /** A prompt result enriched with the operation's metering record. */
392
+ export interface AgentSessionPromptResult extends PromptResult {
393
+ readonly operationId: string;
394
+ /**
395
+ * The operation's record, or null when the operation never reached the provider.
396
+ *
397
+ * Null happens only for a queued prompt cancelled before dispatch (§16). Such an
398
+ * operation consumed nothing, and minting a record for it would put a fabricated
399
+ * entry in the consumer's ledger — so the field is honestly empty instead.
400
+ */
401
+ readonly metering: OperationMeteringRecord | null;
402
+ }
403
+
110
404
  /** Ordered envelope delivered to every AgentSession subscriber. */
111
405
  export interface AgentSessionNotification {
112
406
  readonly seq: number;
@@ -211,6 +505,10 @@ export interface AgentSessionConfig {
211
505
  wire?: (entry: WireEntry) => void;
212
506
  /** Optional catalog. When present, the session records itself here. */
213
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;
214
512
  /**
215
513
  * Absolute path to an append-only transcript file. This selects history storage only;
216
514
  * file existence never selects the provider thread. Omitted means no transcript.
@@ -236,6 +534,12 @@ export interface AgentSessionConfig {
236
534
  agentSessionId?: string;
237
535
  /** Provider-thread startup intent. Default `{ kind: "new" }`. */
238
536
  providerSession?: ProviderSession;
537
+ /**
538
+ * Token/cost metering policy. Optional: omitting it selects best-effort enforcement
539
+ * with the pinned models.dev catalog and no restored state. Metering is not something a
540
+ * consumer must turn on merely to see protocol facts.
541
+ */
542
+ metering?: MeteringConfig;
239
543
  /**
240
544
  * @deprecated Use `providerSession: { kind: "load", internalSessionId, onFailure }`.
241
545
  * Retains the historical fallback-to-new behavior for compatibility.
@@ -244,6 +548,45 @@ export interface AgentSessionConfig {
244
548
  title?: string;
245
549
  }
246
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
+
247
590
  export class AgentSession implements AgentClient, Bridgeable {
248
591
  /** Our stable AgentSession id — decoupled from the ACP/harness session id. */
249
592
  readonly agentSessionId: string;
@@ -252,6 +595,11 @@ export class AgentSession implements AgentClient, Bridgeable {
252
595
  private readonly controller: AgentController;
253
596
  private readonly sessions?: SessionManager;
254
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();
255
603
  private readonly transcriptActivity: boolean;
256
604
  private readonly activityKinds: Set<string>;
257
605
  private readonly activityRawOutput: boolean;
@@ -272,14 +620,39 @@ export class AgentSession implements AgentClient, Bridgeable {
272
620
  private readonly listeners = new Set<AgentSessionListener>();
273
621
  private lastStateKey = "";
274
622
  private _internalSessionId: string | null;
623
+ private readonly metering: MeteringEngine;
624
+ private _contextWindow: ContextWindowStatus | null = null;
625
+ private _providerCost: ProviderCostSnapshot | null = null;
626
+ /**
627
+ * A usage update that arrived before the provider thread id was known.
628
+ *
629
+ * A harness may notify immediately after session/new, before that response resolves.
630
+ * Dropping the update would lose the observation; applying it without a thread id would
631
+ * attribute it to nothing. Hold the latest one and attribute it on assignment.
632
+ */
633
+ private pendingUsageUpdate: { update: unknown; sessionId: string | null } | null = null;
275
634
  private _mode: AgentMode;
276
635
  private _cwd?: string;
277
636
  private _title?: string;
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;
278
644
 
279
- private constructor(config: AgentSessionConfig) {
645
+ private constructor(
646
+ config: AgentSessionConfig,
647
+ openBootstrap: AgentSessionOpenBootstrap | null = null,
648
+ managedCreation: ManagedAgentSessionCreationBootstrap | null = null,
649
+ ) {
280
650
  if (config.transcriptPath && config.transcriptDir) {
281
651
  throw new Error("AgentSessionConfig cannot specify both transcriptPath and transcriptDir");
282
652
  }
653
+ if (config.persistence !== undefined && (config.transcriptPath || config.transcriptDir)) {
654
+ throw new Error("AgentSessionConfig cannot combine persistence with deprecated transcript options");
655
+ }
283
656
  if (config.providerSession && config.internalSessionId !== undefined) {
284
657
  throw new Error("AgentSessionConfig cannot specify both providerSession and internalSessionId");
285
658
  }
@@ -305,6 +678,19 @@ export class AgentSession implements AgentClient, Bridgeable {
305
678
  this.agentSessionId = config.agentSessionId ?? crypto.randomUUID();
306
679
  this.adapterId = config.adapterId;
307
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;
308
694
  this._transcriptPath =
309
695
  config.transcriptPath ??
310
696
  (config.transcriptDir
@@ -323,6 +709,23 @@ export class AgentSession implements AgentClient, Bridgeable {
323
709
  this._cwd = config.cwd;
324
710
  this._title = config.title;
325
711
  this._internalSessionId = requestedInternalSessionId ?? null;
712
+ this.metering = new MeteringEngine({
713
+ agentSessionId: this.agentSessionId,
714
+ adapterId: config.adapterId,
715
+ enforcement: config.metering?.enforcement ?? "best_effort",
716
+ // Absence selects the pinned catalog; `false` is how a consumer says "no rating".
717
+ pricing: config.metering?.pricing ?? createModelsDevResolver(),
718
+ initialState: config.metering?.initialState,
719
+ ...(config.metering?.counterInterpretation
720
+ ? { counterInterpretation: config.metering.counterInterpretation }
721
+ : {}),
722
+ ...(config.metering?.inferenceSource
723
+ ? { inferenceSource: config.metering.inferenceSource }
724
+ : {}),
725
+ // A thread we are about to create has counters starting at zero; one we load does
726
+ // not, and needs restored state to be attributable.
727
+ createdActiveThread: providerSession.kind === "new",
728
+ });
326
729
  this.controller = new AgentController({
327
730
  adapter: config.adapter,
328
731
  adapterId: config.adapterId,
@@ -346,6 +749,9 @@ export class AgentSession implements AgentClient, Bridgeable {
346
749
  this.controller.subscribeAvailableCommands((commands) => {
347
750
  this.emit({ kind: "internal_session_commands_changed", commands });
348
751
  });
752
+ this.controller.subscribeUsageUpdate((update, sessionId) => {
753
+ this.applyUsageUpdate(update, sessionId);
754
+ });
349
755
  }
350
756
 
351
757
  /**
@@ -355,6 +761,10 @@ export class AgentSession implements AgentClient, Bridgeable {
355
761
  * implicitly. Consumers compose a catalog record back into this method when reopening.
356
762
  */
357
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
+ }
358
768
  const session = new AgentSession(config);
359
769
  try {
360
770
  await session.start();
@@ -365,9 +775,214 @@ export class AgentSession implements AgentClient, Bridgeable {
365
775
  }
366
776
  }
367
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
+
368
977
  private async start(): Promise<void> {
978
+ if (this.persistence !== false) {
979
+ await this.startPersistent();
980
+ return;
981
+ }
369
982
  const result = await this.controller.start();
370
- this._internalSessionId = result.sessionId || this._internalSessionId;
983
+ // A resumed thread's counters did not start at zero, so it needs restored state to
984
+ // be attributable.
985
+ this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
371
986
  await this.persist();
372
987
  await this.appendTranscript({
373
988
  v: 1,
@@ -379,10 +994,560 @@ export class AgentSession implements AgentClient, Bridgeable {
379
994
  });
380
995
  }
381
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
+
382
1481
  // --- identity ----------------------------------------------------------------
383
1482
  get internalSessionId(): string | null {
384
1483
  return this._internalSessionId;
385
1484
  }
1485
+
1486
+ /**
1487
+ * Latest context-window observation for the ACTIVE provider thread, or null.
1488
+ *
1489
+ * Context does not aggregate across threads: after a handoff or any other thread
1490
+ * replacement this is null until the new thread reports, because the old thread's
1491
+ * occupancy says nothing about the new one's.
1492
+ */
1493
+ /**
1494
+ * models.dev provider key for the active route, or null when it cannot be established.
1495
+ *
1496
+ * Comes from a tested adapter mapping, or — for a harness whose model string is
1497
+ * `<provider>/<model>` — from that string. Never guessed: see metering/provider.ts.
1498
+ */
1499
+ get providerId(): string | null {
1500
+ return resolveModelReference(this.adapterId, this.advertisedModel)?.providerId ?? null;
1501
+ }
1502
+
1503
+ /**
1504
+ * Model key for catalog lookup, or null.
1505
+ *
1506
+ * For a harness that advertises `<provider>/<model>`, this is the model half — the
1507
+ * provider prefix is routing, not part of the model's name. The raw advertised string
1508
+ * remains available through `configOptions`.
1509
+ */
1510
+ get model(): string | null {
1511
+ return resolveModelReference(this.adapterId, this.advertisedModel)?.modelId ?? this.advertisedModel;
1512
+ }
1513
+
1514
+ /** Exactly what the harness advertises, before any provider/model split. */
1515
+ get advertisedModel(): string | null {
1516
+ return activeModel(this.controller.configOptions);
1517
+ }
1518
+
1519
+ /** Bounded metering state, enforcement policy, and the last operation record. */
1520
+ get meteringSnapshot(): AgentSessionMeteringSnapshot {
1521
+ const restoration = this.metering.restoration;
1522
+ return Object.freeze({
1523
+ ...this.metering.currentState,
1524
+ enforcement: this.metering.enforcement,
1525
+ // Carry the version the restore actually reported. The `state` field is dropped
1526
+ // because the snapshot already IS the state; the version is not re-stated literally.
1527
+ restoration:
1528
+ restoration.status === "restored"
1529
+ ? { status: "restored" as const, version: restoration.version }
1530
+ : restoration,
1531
+ blocked: this.metering.blocked,
1532
+ blockedReason: this.metering.blockedReason,
1533
+ outstandingReports: this.metering.outstandingReports(this._internalSessionId),
1534
+ lastOperation: this.metering.lastOperation,
1535
+ });
1536
+ }
1537
+
1538
+ get contextWindow(): ContextWindowStatus | null {
1539
+ return this._contextWindow;
1540
+ }
1541
+
1542
+ /**
1543
+ * Latest cumulative provider-reported cost for the active thread, or null.
1544
+ *
1545
+ * Provider telemetry, kept distinct from locally rated cost and never asserted to be an
1546
+ * invoice — a subscription harness may report an API-equivalent figure.
1547
+ */
1548
+ get providerCost(): ProviderCostSnapshot | null {
1549
+ return this._providerCost;
1550
+ }
386
1551
  get mode(): AgentMode {
387
1552
  return this._mode;
388
1553
  }
@@ -394,10 +1559,65 @@ export class AgentSession implements AgentClient, Bridgeable {
394
1559
  }
395
1560
  /** Resolved history destination, configured directly or derived from transcriptDir. */
396
1561
  get transcriptPath(): string | undefined {
397
- return this._transcriptPath;
1562
+ return this.v2TranscriptPath ?? this._transcriptPath;
398
1563
  }
399
- /** Immutable current state. Late subscribers read this before listening for deltas. */
400
- get state(): AgentSessionState {
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) });
1618
+ }
1619
+ /** Immutable current state. Late subscribers read this before listening for deltas. */
1620
+ get state(): AgentSessionState {
401
1621
  return Object.freeze({
402
1622
  phase: this.phase,
403
1623
  isBusy: this.isBusy,
@@ -406,11 +1626,12 @@ export class AgentSession implements AgentClient, Bridgeable {
406
1626
  internalSessionId: this._internalSessionId,
407
1627
  adapterId: this.adapterId,
408
1628
  mode: this._mode,
1629
+ promptability: this.promptability,
409
1630
  });
410
1631
  }
411
1632
  /** True while one operation is executing. Queued work is exposed independently. */
412
1633
  get isBusy(): boolean {
413
- return this.phase === "prompting" || this.phase === "handoff";
1634
+ return this.phase !== "idle" && this.phase !== "stopped";
414
1635
  }
415
1636
  get queuedOperationCount(): number {
416
1637
  return this.queue.length;
@@ -430,15 +1651,31 @@ export class AgentSession implements AgentClient, Bridgeable {
430
1651
  text: string,
431
1652
  handlers?: PromptHandlers,
432
1653
  attachments?: Attachment[],
433
- ): Promise<PromptResult> {
434
- return new Promise<PromptResult>((resolve, reject) => {
1654
+ ): Promise<AgentSessionPromptResult> {
1655
+ return this.enqueuePrompt(text, "prompt", handlers, attachments);
1656
+ }
1657
+
1658
+ private enqueuePrompt(
1659
+ text: string,
1660
+ operationKind: MeteredOperationKind,
1661
+ handlers?: PromptHandlers,
1662
+ attachments?: Attachment[],
1663
+ ): Promise<AgentSessionPromptResult> {
1664
+ return new Promise<AgentSessionPromptResult>((resolve, reject) => {
435
1665
  if (this.phase === "stopped") {
436
1666
  reject(new Error("AgentSession is stopped"));
437
1667
  return;
438
1668
  }
1669
+ try {
1670
+ this.assertPromptable();
1671
+ } catch (error) {
1672
+ reject(error);
1673
+ return;
1674
+ }
439
1675
  this.queue.push({
440
1676
  kind: "prompt",
441
1677
  turnId: this.mintTurnId(),
1678
+ operationKind,
442
1679
  text,
443
1680
  handlers,
444
1681
  attachments,
@@ -461,7 +1698,7 @@ export class AgentSession implements AgentClient, Bridgeable {
461
1698
  name: string,
462
1699
  input?: string,
463
1700
  handlers?: PromptHandlers,
464
- ): Promise<PromptResult> {
1701
+ ): Promise<AgentSessionPromptResult> {
465
1702
  const command = name.trim();
466
1703
  if (!command || command.startsWith("/") || /\s/.test(command)) {
467
1704
  return Promise.reject(
@@ -469,7 +1706,7 @@ export class AgentSession implements AgentClient, Bridgeable {
469
1706
  );
470
1707
  }
471
1708
  const suffix = input == null || input.length === 0 ? "" : ` ${input}`;
472
- return this.prompt(`/${command}${suffix}`, handlers);
1709
+ return this.enqueuePrompt(`/${command}${suffix}`, "internal_command", handlers);
473
1710
  }
474
1711
 
475
1712
  /**
@@ -483,6 +1720,12 @@ export class AgentSession implements AgentClient, Bridgeable {
483
1720
  reject(new Error("AgentSession is stopped"));
484
1721
  return;
485
1722
  }
1723
+ try {
1724
+ this.assertPromptable();
1725
+ } catch (error) {
1726
+ reject(error);
1727
+ return;
1728
+ }
486
1729
  this.queue.push({
487
1730
  kind: "handoff",
488
1731
  handoffId: this.mintOperationId(),
@@ -503,7 +1746,15 @@ export class AgentSession implements AgentClient, Bridgeable {
503
1746
  try {
504
1747
  while (this.queue.length > 0) {
505
1748
  const item = this.queue.shift()!;
506
- 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";
507
1758
  this.emitStateIfChanged();
508
1759
  if (item.kind === "prompt") {
509
1760
  this.emit({ kind: "turn_started", turnId: item.turnId });
@@ -519,12 +1770,51 @@ export class AgentSession implements AgentClient, Bridgeable {
519
1770
  this.emit({ kind: "turn_failed", turnId: item.turnId, error: String(err) });
520
1771
  item.reject(err);
521
1772
  }
522
- } else {
1773
+ } else if (item.kind === "handoff") {
523
1774
  try {
524
1775
  item.resolve(await this.runHandoff(item));
525
1776
  } catch (err) {
526
1777
  item.reject(err);
527
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
+ }
528
1818
  }
529
1819
  }
530
1820
  } finally {
@@ -536,22 +1826,39 @@ export class AgentSession implements AgentClient, Bridgeable {
536
1826
 
537
1827
  private async runHandoff(item: HandoffQueueItem): Promise<HandoffResult> {
538
1828
  const fromInternalSessionId = this._internalSessionId;
1829
+ const fromDescriptor = this.v2Transcript ? this.v2Descriptor() : null;
539
1830
  let toInternalSessionId: string | undefined;
1831
+ let toDescriptor: InternalSessionDescriptor | undefined;
540
1832
  let summary: string | undefined;
1833
+ let failedAfter: "start" | "target_created" | "target_activated" = "start";
1834
+ // Records accumulate as they complete, so a handoff that fails partway still reports
1835
+ // the operations it already paid for.
1836
+ const records: OperationMeteringRecord[] = [];
541
1837
  this.emit({
542
1838
  kind: "handoff_started",
543
1839
  handoffId: item.handoffId,
544
1840
  fromInternalSessionId,
545
1841
  });
546
- await this.appendTranscript({
547
- v: 1,
548
- t: "handoff",
549
- event: "start",
550
- ts: Date.now(),
551
- handoffId: item.handoffId,
552
- fromInternalSessionId,
553
- ...(item.options.summary !== undefined ? { summary: item.options.summary } : {}),
554
- });
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
+ }
555
1862
 
556
1863
  try {
557
1864
  if (this.controller.isDegraded) {
@@ -560,9 +1867,16 @@ export class AgentSession implements AgentClient, Bridgeable {
560
1867
 
561
1868
  if (item.options.summary !== undefined) {
562
1869
  if (!item.options.summary.trim()) throw new Error("handoff summary cannot be blank");
1870
+ // A supplied summary removes the generation operation entirely, so no
1871
+ // `:summary` record is ever minted for it.
563
1872
  summary = item.options.summary;
564
1873
  } else {
565
- const generated = await this.controller.prompt(HANDOFF_SUMMARY_PROMPT);
1874
+ const generated = await this.meteredInternalPrompt(
1875
+ `${item.handoffId}:summary`,
1876
+ "handoff_summary",
1877
+ HANDOFF_SUMMARY_PROMPT,
1878
+ records,
1879
+ );
566
1880
  if (generated.status !== "completed" || !generated.text.trim()) {
567
1881
  throw new Error(`handoff summary generation ${generated.status}`);
568
1882
  }
@@ -572,15 +1886,63 @@ export class AgentSession implements AgentClient, Bridgeable {
572
1886
  const created = await this.controller.newSession();
573
1887
  if (!created.sessionId) throw new Error("harness returned no session id for handoff");
574
1888
  toInternalSessionId = created.sessionId;
575
- this._internalSessionId = toInternalSessionId;
576
- this.emitStateIfChanged();
577
- await this.persist();
578
-
579
1889
  if (toInternalSessionId === fromInternalSessionId) {
580
1890
  throw new Error("harness did not replace the internal session during handoff");
581
1891
  }
582
1892
 
583
- const seeded = await this.controller.prompt(continuationPrompt(summary));
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
+
1940
+ const seeded = await this.meteredInternalPrompt(
1941
+ `${item.handoffId}:seed`,
1942
+ "handoff_seed",
1943
+ continuationPrompt(summary),
1944
+ records,
1945
+ );
584
1946
  if (seeded.status !== "completed") {
585
1947
  throw new Error(`handoff continuation seeding ${seeded.status}`);
586
1948
  }
@@ -591,25 +1953,38 @@ export class AgentSession implements AgentClient, Bridgeable {
591
1953
  fromInternalSessionId,
592
1954
  toInternalSessionId,
593
1955
  summary,
1956
+ meteringRecords: Object.freeze([...records]),
594
1957
  });
595
- await this.appendTranscript({
596
- v: 1,
597
- t: "handoff",
598
- event: "complete",
599
- ts: Date.now(),
600
- handoffId: item.handoffId,
601
- fromInternalSessionId,
602
- toInternalSessionId,
603
- summary,
604
- });
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
+ }
605
1980
  this.emit({ kind: "handoff_completed", result });
606
1981
  return result;
607
1982
  } catch (err) {
608
1983
  // Once session/new succeeds the controller really is on the new thread. Keep the
609
1984
  // public id and catalog truthful even when continuation seeding subsequently fails.
610
1985
  const actualSessionId = this.controller.currentSessionId;
611
- if (actualSessionId && actualSessionId !== this._internalSessionId) {
612
- this._internalSessionId = actualSessionId;
1986
+ if (!this.v2Transcript && actualSessionId && actualSessionId !== this._internalSessionId) {
1987
+ this.setInternalSessionId(actualSessionId);
613
1988
  toInternalSessionId = actualSessionId;
614
1989
  this.emitStateIfChanged();
615
1990
  try {
@@ -619,37 +1994,542 @@ export class AgentSession implements AgentClient, Bridgeable {
619
1994
  }
620
1995
  }
621
1996
  const error = String(err);
622
- await this.appendTranscript({
623
- v: 1,
624
- t: "handoff",
625
- event: "failed",
626
- ts: Date.now(),
627
- handoffId: item.handoffId,
628
- fromInternalSessionId,
629
- ...(toInternalSessionId ? { toInternalSessionId } : {}),
630
- ...(summary !== undefined ? { summary } : {}),
631
- error,
632
- });
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
+ }
633
2024
  this.emit({
634
2025
  kind: "handoff_failed",
635
2026
  handoffId: item.handoffId,
636
2027
  fromInternalSessionId,
637
2028
  ...(toInternalSessionId ? { toInternalSessionId } : {}),
638
2029
  error,
2030
+ meteringRecords: Object.freeze([...records]),
639
2031
  });
640
- throw err;
2032
+ // A rejected handoff cannot return a HandoffResult, but the summary/seed prompts it
2033
+ // already ran consumed real tokens; their records travel on the error.
2034
+ throw new AgentSessionHandoffError(item.handoffId, records, err);
641
2035
  }
642
2036
  }
643
2037
 
644
- private async runPrompt(item: PromptQueueItem): Promise<PromptResult> {
645
- this.beginTurn(item.turnId);
646
- await this.appendTranscript({
647
- v: 1,
648
- t: "msg",
649
- role: "user",
650
- text: item.text,
651
- ts: Date.now(),
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,
652
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
+
2496
+ private async runPrompt(item: PromptQueueItem): Promise<AgentSessionPromptResult> {
2497
+ this.beginTurn(item.turnId);
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
+ }
653
2533
 
654
2534
  const chunks: string[] = [];
655
2535
  const response = new ResponseAccumulator();
@@ -668,7 +2548,7 @@ export class AgentSession implements AgentClient, Bridgeable {
668
2548
  },
669
2549
  onActivity: (event) => {
670
2550
  const result = this.aggregator.apply(event);
671
- if (this.transcriptActivity) {
2551
+ if (this.transcriptActivity || this.v2Transcript) {
672
2552
  for (const record of result.emitted) this.writeActivity(record);
673
2553
  }
674
2554
  item.handlers?.onRecord?.(result);
@@ -676,6 +2556,8 @@ export class AgentSession implements AgentClient, Bridgeable {
676
2556
  },
677
2557
  };
678
2558
 
2559
+ let closed: OperationMeteringRecord | null = null;
2560
+ let transcriptClosed = false;
679
2561
  try {
680
2562
  const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
681
2563
  // Before the assistant msg: `msg` delimits a turn, so anything still open has to
@@ -685,20 +2567,45 @@ export class AgentSession implements AgentClient, Bridgeable {
685
2567
  this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
686
2568
  }
687
2569
  // A session may have been created lazily on first prompt (degraded has none).
688
- this._internalSessionId = this.controller.currentSessionId ?? this._internalSessionId;
2570
+ this.setInternalSessionId(this.controller.currentSessionId ?? this._internalSessionId);
2571
+ // Metering closes BEFORE local persistence. The provider has already been paid and
2572
+ // has already told us what it charged; letting a transcript or catalog write failure
2573
+ // send us down the catch path would discard usage we are holding and, in a strict
2574
+ // mode, block the session over a local disk problem.
2575
+ //
2576
+ // `closed` then guards the catch path. Closing twice would accrue the operation
2577
+ // twice and emit a second record for it — double-counting tokens and cost, which is
2578
+ // a worse failure than the one closing early prevents.
2579
+ const record = await this.closeOperation(operation, res.status, res.usage);
2580
+ closed = record;
689
2581
  await this.persist();
690
- await this.appendTranscript({
691
- v: 1,
692
- t: "msg",
693
- role: "assistant",
694
- text: res.text,
695
- messages: res.messages,
696
- ts: Date.now(),
697
- usage: res.usage,
698
- stopReason: res.stopReason,
699
- status: res.status,
700
- });
701
- return res;
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
+ }
2608
+ return Object.freeze({ ...res, operationId: item.turnId, metering: record });
702
2609
  } catch (err) {
703
2610
  // Easy to miss, and the whole point of R4: a turn that died mid-tool still records
704
2611
  // what it was doing, at its real status.
@@ -710,20 +2617,283 @@ export class AgentSession implements AgentClient, Bridgeable {
710
2617
  : text
711
2618
  ? Object.freeze([{ text }])
712
2619
  : Object.freeze([]);
713
- await this.appendTranscript({
714
- v: 1,
715
- t: "msg",
716
- role: "assistant",
717
- text,
718
- messages,
719
- ts: Date.now(),
720
- stopReason: "error",
721
- status: "error",
722
- });
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
+ }
2645
+ // A failed operation may still have consumed tokens, so its record has to survive
2646
+ // the rejection rather than only reaching event subscribers.
2647
+ // Already metered: the failure happened after the operation closed (a transcript or
2648
+ // catalog write), so the record stands and must not be minted a second time.
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
+ }
2655
+ throw new AgentSessionOperationError(item.turnId, record, err);
2656
+ }
2657
+ }
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
+
2700
+ /**
2701
+ * Replace metering state after an out-of-band reconciliation, and clear any block.
2702
+ *
2703
+ * The recovery path for a strict mode that stopped on a metering failure, without the
2704
+ * unrecorded "assume zero" reset §12 rejects. Deliberately mints no operation record:
2705
+ * the adjustment is an accounting correction, not provider usage, and pretending
2706
+ * otherwise would put a fabricated operation in the consumer's ledger.
2707
+ */
2708
+ async reconcileMetering(reconciliation: MeteringReconciliation): Promise<{
2709
+ before: AgentSessionMeteringState;
2710
+ after: AgentSessionMeteringState;
2711
+ }> {
2712
+ if (this.isBusy || this.queue.length > 0) {
2713
+ throw new Error("reconcileMetering requires an idle session with no queued operations");
2714
+ }
2715
+ if (!reconciliation.reason?.trim()) {
2716
+ throw new Error("reconcileMetering requires a non-blank reason");
2717
+ }
2718
+ const restoration = restoreMeteringState(reconciliation.state, this.agentSessionId);
2719
+ if (restoration.status !== "restored") {
2720
+ throw new Error(
2721
+ `reconcileMetering state rejected: ${
2722
+ restoration.status === "ignored" ? restoration.reason : "no state supplied"
2723
+ }`,
2724
+ );
2725
+ }
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
+ }
2732
+ // Validated first: state is replaced atomically or not at all.
2733
+ const { before } = this.metering.reconcile(restoration.state);
2734
+ const after = this.metering.currentState;
2735
+ this.emit({
2736
+ kind: "metering_reconciled",
2737
+ before,
2738
+ after,
2739
+ reason: reconciliation.reason,
2740
+ ...(reconciliation.reference ? { reference: reconciliation.reference } : {}),
2741
+ reconciledAt: Date.now(),
2742
+ });
2743
+ if (wasBlocked) this.emit({ kind: "metering_unblocked" });
2744
+ return { before, after };
2745
+ }
2746
+
2747
+ /**
2748
+ * Run a library-internal prompt through the same metering primitive as a user prompt.
2749
+ *
2750
+ * Handoff summary generation and continuation seeding consume real tokens. Calling
2751
+ * `controller.prompt()` directly for them would spend a consumer's money invisibly, so
2752
+ * that path is not permitted any more (§16).
2753
+ *
2754
+ * Operation ids are deterministic children of the handoff id rather than freshly
2755
+ * minted, so a consumer can tie both halves back to the handoff that caused them.
2756
+ */
2757
+ private async meteredInternalPrompt(
2758
+ operationId: string,
2759
+ operationKind: MeteredOperationKind,
2760
+ text: string,
2761
+ records: OperationMeteringRecord[],
2762
+ ): Promise<PromptResult> {
2763
+ const operation = await this.metering.open({
2764
+ operationId,
2765
+ operationKind,
2766
+ internalSessionId: this._internalSessionId,
2767
+ providerId: this.providerId,
2768
+ model: this.model,
2769
+ degraded: this.controller.isDegraded,
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
+ }
2792
+ let closed = false;
2793
+ let transcriptClosed = false;
2794
+ try {
2795
+ const result = await this.controller.prompt(text);
2796
+ const record = await this.closeOperation(operation, result.status, result.usage);
2797
+ records.push(record);
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
+ }
2812
+ return result;
2813
+ } catch (err) {
2814
+ if (!closed) {
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
+ );
2833
+ }
723
2834
  throw err;
724
2835
  }
725
2836
  }
726
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
+
2870
+ /**
2871
+ * Close a rating unit, emit its record, and surface a strict-mode block.
2872
+ *
2873
+ * `contextAfter`/`providerCostAfter` are the latest observations seen by completion.
2874
+ * ACP gives no ordering guarantee, so neither is asserted to describe THIS operation.
2875
+ */
2876
+ private async closeOperation(
2877
+ operation: OpenOperation,
2878
+ outcome: "completed" | "cancelled" | "error",
2879
+ reportedCumulative: TokenUsage | null,
2880
+ usageFailureReason?: string,
2881
+ ): Promise<OperationMeteringRecord> {
2882
+ const wasBlocked = this.metering.blocked;
2883
+ const record = await this.metering.close(operation, {
2884
+ outcome,
2885
+ reportedCumulative,
2886
+ ...(usageFailureReason ? { usageFailureReason } : {}),
2887
+ contextAfter: this._contextWindow,
2888
+ providerCostAfter: this._providerCost,
2889
+ });
2890
+ this.emit({ kind: "metering_recorded", record });
2891
+ if (!wasBlocked && this.metering.blocked) {
2892
+ this.emit({ kind: "metering_blocked", reason: this.metering.blockedReason ?? "unknown" });
2893
+ }
2894
+ return record;
2895
+ }
2896
+
727
2897
  // --- activity ----------------------------------------------------------------
728
2898
  /**
729
2899
  * Full state of the turn IN FLIGHT, for a subscriber that joins mid-turn: send these
@@ -745,14 +2915,14 @@ export class AgentSession implements AgentClient, Bridgeable {
745
2915
  const leftover = this.aggregator.startTurn(turnId);
746
2916
  if (leftover.length > 0) {
747
2917
  this.log.warn("activity_turn_not_flushed", { records: leftover.length });
748
- 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);
749
2919
  }
750
2920
  }
751
2921
 
752
2922
  private endTurn(handlers?: PromptHandlers): void {
753
2923
  const emitted = this.aggregator.flush();
754
2924
  if (emitted.length === 0) return;
755
- 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);
756
2926
  // Live subscribers need these too: without them, a tool call on a turn that was
757
2927
  // cancelled or crashed spins forever in the UI. `wireFrames()` handles this shape.
758
2928
  handlers?.onRecord?.({ current: null, delta: null, emitted });
@@ -783,11 +2953,24 @@ export class AgentSession implements AgentClient, Bridgeable {
783
2953
  * holds without blocking the agent's update stream on disk.
784
2954
  */
785
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
+ }
786
2965
  if (!this._transcriptPath) return;
787
2966
  if (!this.activityKinds.has(record.event.kind)) return;
788
2967
  void this.appendTranscript(this.toActivityLine(record));
789
2968
  }
790
2969
 
2970
+ private async drainV2Activity(): Promise<void> {
2971
+ await this.v2ActivityWrite;
2972
+ }
2973
+
791
2974
  private toActivityLine(record: AggregatedRecord): TranscriptActivityLine {
792
2975
  let fields: Record<string, unknown> = { ...record.event };
793
2976
  if (!this.activityRawOutput) delete fields.rawOutput;
@@ -817,15 +3000,26 @@ export class AgentSession implements AgentClient, Bridgeable {
817
3000
  const dropped = this.queue.splice(0);
818
3001
  for (const item of dropped) {
819
3002
  if (item.kind === "prompt") {
3003
+ // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
3004
+ // metering record is minted (§16).
820
3005
  item.resolve({
821
3006
  text: "",
822
3007
  messages: Object.freeze([]),
823
3008
  stopReason: "cancelled",
824
3009
  status: "cancelled",
825
3010
  usage: null,
3011
+ operationId: item.turnId,
3012
+ metering: null,
826
3013
  });
827
3014
  } else {
828
- 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`));
829
3023
  }
830
3024
  }
831
3025
  this.emitStateIfChanged();
@@ -842,15 +3036,25 @@ export class AgentSession implements AgentClient, Bridgeable {
842
3036
  this.phase = "stopped";
843
3037
  this.emitStateIfChanged();
844
3038
  await this.controller.stop();
3039
+ await this.drainV2Activity().catch(() => undefined);
3040
+ await this.v2Transcript?.close();
845
3041
  }
846
3042
 
847
3043
  // --- mode swap (catalog-affecting) -------------------------------------------
848
3044
  async setMode(mode: AgentMode): Promise<ConnectResult> {
849
- const result = await this.controller.setMode(mode);
850
- this._mode = this.controller.currentMode;
851
- this._internalSessionId = result.sessionId || null; // the ACP/harness session changes on swap
852
- await this.persist();
853
- 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
+ });
854
3058
  }
855
3059
 
856
3060
  // --- thin proxies to the live connection -------------------------------------
@@ -867,7 +3071,78 @@ export class AgentSession implements AgentClient, Bridgeable {
867
3071
  * way, so it is the only route to them once the process is running.
868
3072
  */
869
3073
  setConfig(configId: string, value: unknown): Promise<void> {
870
- 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
+ });
871
3146
  }
872
3147
  /** Immutable snapshot of commands advertised by the active ACP harness. */
873
3148
  get internalSessionCommands(): readonly InternalSessionCommand[] {
@@ -942,6 +3217,76 @@ export class AgentSession implements AgentClient, Bridgeable {
942
3217
  await this.transcriptWrite;
943
3218
  }
944
3219
 
3220
+ /**
3221
+ * Replace the active provider thread id, resetting observations that belong to it.
3222
+ *
3223
+ * Every reassignment goes through here so the reset cannot be forgotten at one of the
3224
+ * several sites that swap threads (handoff, mode swap, load/resume, lazy creation).
3225
+ * Carrying a stale context window across a thread change would misreport the new
3226
+ * thread's occupancy as the old thread's.
3227
+ */
3228
+ private setInternalSessionId(next: string | null, created = true): void {
3229
+ if (next === this._internalSessionId) return;
3230
+ this._internalSessionId = next;
3231
+ // The new thread's counters restart, so the old baseline no longer describes them.
3232
+ this.metering.onThreadReplaced(next, created);
3233
+ if (this._contextWindow !== null) {
3234
+ this._contextWindow = null;
3235
+ this.emit({ kind: "context_window_changed", contextWindow: null });
3236
+ }
3237
+ if (this._providerCost !== null) {
3238
+ this._providerCost = null;
3239
+ this.emit({ kind: "provider_cost_changed", providerCost: null });
3240
+ }
3241
+ const pending = this.pendingUsageUpdate;
3242
+ this.pendingUsageUpdate = null;
3243
+ // An update buffered before the thread was named belongs to it only if it named the
3244
+ // same thread, or named none at all.
3245
+ if (pending && next && (!pending.sessionId || pending.sessionId === next)) {
3246
+ this.applyUsageUpdate(pending.update, pending.sessionId);
3247
+ }
3248
+ }
3249
+
3250
+ /**
3251
+ * Apply a raw ACP `usage_update`.
3252
+ *
3253
+ * Updates naming a different provider thread are ignored: ACP gives no ordering
3254
+ * guarantee, so a late notification from a replaced thread can arrive after the swap and
3255
+ * must not overwrite current state.
3256
+ */
3257
+ private applyUsageUpdate(update: unknown, sessionId: string | null): void {
3258
+ const active = this._internalSessionId;
3259
+ if (!active) {
3260
+ this.pendingUsageUpdate = { update, sessionId };
3261
+ return;
3262
+ }
3263
+ if (sessionId && sessionId !== active) return;
3264
+
3265
+ const observedAt = Date.now();
3266
+ const context = parseContextWindow(update, active, observedAt);
3267
+ if (context && contextWindowChanged(this._contextWindow, context)) {
3268
+ this._contextWindow = context;
3269
+ this.emit({ kind: "context_window_changed", contextWindow: context });
3270
+ }
3271
+
3272
+ const cost = parseProviderCost(update);
3273
+ if (cost.kind === "invalid") {
3274
+ // Provider cost is optional telemetry: malformed data is dropped with a diagnostic
3275
+ // and never implicitly clears a previously valid value.
3276
+ this.log.warn("provider_cost_invalid", { reason: cost.reason });
3277
+ return;
3278
+ }
3279
+ if (cost.kind === "unchanged") return;
3280
+ const next: ProviderCostSnapshot | null =
3281
+ cost.kind === "cleared"
3282
+ ? null
3283
+ : Object.freeze({ internalSessionId: active, cumulative: cost.cumulative, observedAt });
3284
+ if (providerCostChanged(this._providerCost, next)) {
3285
+ this._providerCost = next;
3286
+ this.emit({ kind: "provider_cost_changed", providerCost: next });
3287
+ }
3288
+ }
3289
+
945
3290
  /** Emit only when a field in the public snapshot changed. */
946
3291
  private emitStateIfChanged(): void {
947
3292
  const state = this.state;
@@ -951,12 +3296,20 @@ export class AgentSession implements AgentClient, Bridgeable {
951
3296
  state.internalSessionId ?? "",
952
3297
  state.adapterId,
953
3298
  state.mode,
3299
+ state.promptability.promptable ? "promptable" : state.promptability.blockers.join(","),
954
3300
  ].join("\u0000");
955
3301
  if (key === this.lastStateKey) return;
956
3302
  this.lastStateKey = key;
957
3303
  this.emit({ kind: "state_changed", state });
958
3304
  }
959
3305
 
3306
+ private assertPromptable(): void {
3307
+ const promptability = this.promptability;
3308
+ if (!promptability.promptable) {
3309
+ throw new AgentSessionPromptBlockedError(promptability.blockers);
3310
+ }
3311
+ }
3312
+
960
3313
  /** Listener failures are observation failures, never session-operation failures. */
961
3314
  private emit(event: AgentSessionEvent): void {
962
3315
  const notification: AgentSessionNotification = Object.freeze({
@@ -978,6 +3331,146 @@ export class AgentSession implements AgentClient, Bridgeable {
978
3331
  }
979
3332
  }
980
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
+
981
3474
  /** Do not let one notification observer mutate the PromptResult another observer sees. */
982
3475
  function copyPromptResult(result: PromptResult): PromptResult {
983
3476
  const messages = result.messages ?? (result.text ? [{ text: result.text }] : []);