@qlairoslabs/acp-client 0.9.4 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,7 +31,18 @@ import type {
31
31
  ParticipantRef,
32
32
  PersistenceJsonValue,
33
33
  } from "./persistence/backend.ts";
34
- import type { AgentConversationOwnerLifecycle } from "./agent-conversation-owner.ts";
34
+ import {
35
+ OwnedPromptPostCommitError,
36
+ type AgentConversationOwnerLifecycle,
37
+ } from "./agent-conversation-owner.ts";
38
+ import {
39
+ acknowledgeProviderAttachment,
40
+ recordedProviderAttachment,
41
+ runtimeOnlyProviderAttachment,
42
+ type ProviderAttachmentCommitAcknowledgement,
43
+ type ProviderAttachmentDescriptor,
44
+ type ProviderAttachmentState,
45
+ } from "./persistence/provider-attachment.ts";
35
46
  import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
36
47
  import type { Capabilities } from "./capabilities.ts";
37
48
  import type { ConfigOption, ConfigOptions } from "./config-options.ts";
@@ -167,7 +178,9 @@ export {
167
178
  AgentSessionPromptBlockedError,
168
179
  ContinuationUnavailableError,
169
180
  DirectAuditPersistenceUnsupportedError,
181
+ ProviderSessionError,
170
182
  } from "./agent-conversation-errors.ts";
183
+ export type { ProviderSessionErrorDetails } from "./agent-conversation-errors.ts";
171
184
  export type {
172
185
  AgentConversationEvent,
173
186
  AgentConversationListener,
@@ -237,6 +250,19 @@ interface HandoffQueueItem {
237
250
  reject: (error: unknown) => void;
238
251
  }
239
252
 
253
+ /**
254
+ * Provider thread an internal prompt runs against.
255
+ *
256
+ * A transition seeds its target before that target has earned the right to supersede the
257
+ * source, so the seed cannot use the live controller: the live conversation is still the
258
+ * source until the seed confirms the target.
259
+ */
260
+ interface InternalPromptTarget {
261
+ readonly controller: AgentController;
262
+ readonly metering: MeteringEngine;
263
+ readonly adapterId: string;
264
+ }
265
+
240
266
  interface ConfigQueueItem {
241
267
  kind: "set_config";
242
268
  operationId: string;
@@ -429,6 +455,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
429
455
  private readonly listeners = new Set<AgentSessionListener>();
430
456
  private lastStateKey = "";
431
457
  private _internalSessionId: string | null;
458
+ private providerAttachment: ProviderAttachmentState = Object.freeze({ kind: "absent" });
459
+ /**
460
+ * The thread the local catalog currently selects for a later open.
461
+ *
462
+ * Distinct from the live id: a thread that has completed no turn is usable by this
463
+ * process but is not what a restart should return to. It survives `clearProviderAttachment`
464
+ * so a stop or a degraded stretch leaves the last confirmed thread in place.
465
+ */
466
+ private lastRecordedInternalSessionId: string | null = null;
432
467
  private ownerContextNonce: string | null = null;
433
468
  private metering: MeteringEngine;
434
469
  private readonly meteringConfig: MeteringConfig;
@@ -824,7 +859,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
824
859
  if (!result.resumed || !result.sessionId) {
825
860
  throw new Error("adapter did not confirm loading the recorded internal session");
826
861
  }
827
- session.setInternalSessionId(result.sessionId, false);
862
+ session.installProviderAttachment(result.sessionId, "recorded", false);
828
863
  await stageOpeningContinuation(stageContinuation, checkpoint, result.sessionId);
829
864
  const attempt: ContinuationAttempt = Object.freeze({
830
865
  strategy: "load_internal_session",
@@ -959,7 +994,18 @@ export class AgentConversation implements AgentClient, Bridgeable {
959
994
  const result = await this.controller.start();
960
995
  // A resumed thread's counters did not start at zero, so it needs restored state to
961
996
  // be attributable.
962
- this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
997
+ const internalSessionId = result.sessionId || this._internalSessionId;
998
+ if (internalSessionId) {
999
+ // A thread the adapter resumed was already established elsewhere; one it just
1000
+ // created has completed no turn and is not yet what a restart should return to.
1001
+ this.installProviderAttachment(
1002
+ internalSessionId,
1003
+ result.resumed ? "recorded" : "runtime_only",
1004
+ !result.resumed,
1005
+ );
1006
+ } else {
1007
+ this.setInternalSessionId(internalSessionId, !result.resumed);
1008
+ }
963
1009
  await this.persist();
964
1010
  await this.appendTranscript({
965
1011
  v: 1,
@@ -982,7 +1028,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
982
1028
  if (!result.resumed || !result.sessionId) {
983
1029
  throw new Error("adapter did not confirm loading the recorded internal session");
984
1030
  }
985
- this.setInternalSessionId(result.sessionId, false);
1031
+ this.installProviderAttachment(result.sessionId, "recorded", false);
986
1032
  return;
987
1033
  }
988
1034
  const paths = await resolveSessionLogPaths(persistence, this.agentSessionId);
@@ -1089,6 +1135,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
1089
1135
  initializeCheckpoint: async () => {
1090
1136
  const result = await this.controller.start((event) => this.reportManagedControllerProgress(event));
1091
1137
  this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
1138
+ if (this._internalSessionId) {
1139
+ this.installProviderAttachment(
1140
+ this._internalSessionId,
1141
+ result.resumed ? "recorded" : "runtime_only",
1142
+ !result.resumed,
1143
+ );
1144
+ }
1092
1145
  const now = new Date().toISOString();
1093
1146
  const sessionConfiguration = snapshotSessionConfiguration({
1094
1147
  adapterId: this.adapterId,
@@ -1114,8 +1167,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
1114
1167
  stateRevision: 1,
1115
1168
  adapterId: this.adapterId,
1116
1169
  mode: stagedContinuation.mode,
1117
- internalSessionId: stagedContinuation.internalSessionId,
1118
- internalSessionActivatedAt: stagedContinuation.internalSessionActivatedAt,
1170
+ // A thread the library just created has completed no turn, so nothing yet
1171
+ // justifies selecting it for a later resume. It stays in memory until the
1172
+ // first completed prompt's own terminal checkpoint records it. A thread the
1173
+ // adapter resumed was already established, so it is selected immediately.
1174
+ internalSessionId: result.resumed ? stagedContinuation.internalSessionId : null,
1175
+ internalSessionActivatedAt: result.resumed
1176
+ ? stagedContinuation.internalSessionActivatedAt
1177
+ : null,
1119
1178
  internalSessionHistoryRevision: 0,
1120
1179
  internalSessionHistoryDigest: EMPTY_HISTORY_DIGEST,
1121
1180
  model: stagedContinuation.model,
@@ -1191,7 +1250,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1191
1250
  throw new Error("adapter loaded a different internal session than requested");
1192
1251
  }
1193
1252
  this._mode = this.controller.currentMode;
1194
- this.setInternalSessionId(loaded.sessionId, false);
1253
+ this.installProviderAttachment(loaded.sessionId, "recorded", false);
1195
1254
  await stageOpeningContinuation(
1196
1255
  this.openBootstrap.stageContinuation,
1197
1256
  checkpoint,
@@ -1389,6 +1448,30 @@ export class AgentConversation implements AgentClient, Bridgeable {
1389
1448
  }
1390
1449
  }
1391
1450
 
1451
+ if (checkpoint.internalSessionId === null) {
1452
+ // Nothing was ever selected to continue, so there is nothing a reconstruction could
1453
+ // rebuild from. Starting fresh is the whole continuation, and the new thread stays
1454
+ // runtime-only until a completed turn earns it a place in the checkpoint.
1455
+ const created = await this.controller.startFresh(
1456
+ (event) => this.reportManagedControllerProgress(event),
1457
+ );
1458
+ if (!created.sessionId) {
1459
+ throw new Error("harness returned no session id for an unattached conversation");
1460
+ }
1461
+ this._mode = this.controller.currentMode;
1462
+ this.installProviderAttachment(created.sessionId, "runtime_only", true);
1463
+ this._configurationRestore = this.snapshotReconstructedConfiguration([]).status;
1464
+ this.continuationAcquired = true;
1465
+ return createContinuationReport(
1466
+ checkpoint,
1467
+ this.adapterId,
1468
+ this.v2Transcript,
1469
+ recordedThreadAvailability,
1470
+ attempts,
1471
+ { kind: "fresh", activeInternalSessionId: created.sessionId },
1472
+ );
1473
+ }
1474
+
1392
1475
  return createContinuationReport(
1393
1476
  checkpoint,
1394
1477
  this.adapterId,
@@ -1460,6 +1543,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
1460
1543
  return this._internalSessionId;
1461
1544
  }
1462
1545
 
1546
+ /** @internal Snapshot used by the Agent-owned persistence lifecycle. */
1547
+ get providerAttachmentState(): ProviderAttachmentState {
1548
+ return this.providerAttachment;
1549
+ }
1550
+
1551
+ /** @internal Apply an acknowledgement from the Agent-owned persistence lifecycle. */
1552
+ acknowledgeProviderAttachment(acknowledgement: ProviderAttachmentCommitAcknowledgement): void {
1553
+ this.providerAttachment = acknowledgeProviderAttachment(this.providerAttachment, acknowledgement);
1554
+ if (this.providerAttachment.kind === "recorded") {
1555
+ this.lastRecordedInternalSessionId = this.providerAttachment.descriptor.internalSessionId;
1556
+ }
1557
+ }
1558
+
1463
1559
  /** Active adapter route. It changes only after a durable switch activation. */
1464
1560
  get adapterId(): string {
1465
1561
  return this._adapterId;
@@ -2038,14 +2134,20 @@ export class AgentConversation implements AgentClient, Bridgeable {
2038
2134
  const action = continuation.kind === "none" && transitionKind === "handoff"
2039
2135
  ? "reset"
2040
2136
  : transitionKind;
2041
- const fromDescriptor = this.v2Transcript ? this.v2Descriptor() : null;
2137
+ // A transition is *from* the authoritative continuation state, which is not always
2138
+ // the live runtime: a thread that has completed no turn is live but unrecorded.
2139
+ const fromDescriptor = this.v2Transcript
2140
+ ? descriptorFromCheckpoint(this.v2Transcript.checkpoint)
2141
+ : null;
2042
2142
  let toInternalSessionId: string | undefined;
2043
2143
  let toDescriptor: InternalSessionDescriptor | undefined;
2044
2144
  let summary: string | undefined;
2045
2145
  let targetResult: PromptResult | undefined;
2046
2146
  let targetController: AgentController | null = null;
2047
2147
  let resolvedTargetAdapter: Adapter | null = null;
2148
+ let targetMetering: MeteringEngine | null = null;
2048
2149
  let targetActivated = false;
2150
+ let targetAttachment: "runtime_only" | "recorded" = "runtime_only";
2049
2151
  let failedAfter: "start" | "target_created" | "target_activated" = "start";
2050
2152
  // Records accumulate as they complete, so a handoff that fails partway still reports
2051
2153
  // the operations it already paid for.
@@ -2110,30 +2212,29 @@ export class AgentConversation implements AgentClient, Bridgeable {
2110
2212
  summary = "";
2111
2213
  }
2112
2214
 
2113
- const replacingController = targetAdapterId !== fromAdapterId || targetMode !== this._mode;
2114
- let created: ConnectResult;
2115
- if (replacingController) {
2116
- const adapter = item.options.target?.adapter ?? (targetAdapterId === fromAdapterId
2117
- ? this.activeAdapter
2118
- : this.ownerLifecycle?.resolveAdapter?.(targetAdapterId));
2119
- if (!adapter) {
2120
- throw new Error(
2121
- `cannot resolve adapter ${targetAdapterId}; cross-adapter switch requires an Agent-owned conversation`,
2122
- );
2123
- }
2124
- resolvedTargetAdapter = adapter;
2125
- targetController = this.createController(adapter, targetAdapterId, targetMode);
2126
- created = await targetController.startFresh();
2127
- } else {
2128
- if (this.controller.isDegraded) {
2129
- throw new Error("starting a fresh provider thread requires ACP (normal) mode");
2130
- }
2131
- targetController = this.controller;
2132
- created = await targetController.newSession();
2215
+ // Both same-adapter and cross-adapter transitions get their own controller. Calling
2216
+ // newSession() on the live controller replaces its thread before the target has
2217
+ // earned the right to supersede the source, so a failed seed would leave nothing to
2218
+ // roll back to.
2219
+ if (targetMode === "degraded") {
2220
+ throw new Error("starting a fresh provider thread requires ACP (normal) mode");
2133
2221
  }
2222
+ const adapter = item.options.target?.adapter ?? (targetAdapterId === fromAdapterId
2223
+ ? this.activeAdapter
2224
+ : this.ownerLifecycle?.resolveAdapter?.(targetAdapterId));
2225
+ if (!adapter) {
2226
+ throw new Error(
2227
+ `cannot resolve adapter ${targetAdapterId}; cross-adapter switch requires an Agent-owned conversation`,
2228
+ );
2229
+ }
2230
+ resolvedTargetAdapter = adapter;
2231
+ targetController = this.createController(adapter, targetAdapterId, targetMode);
2232
+ const created = await targetController.startFresh();
2134
2233
  if (!created.sessionId) throw new Error("harness returned no session id for handoff");
2135
2234
  toInternalSessionId = created.sessionId;
2136
- if (!replacingController && toInternalSessionId === fromInternalSessionId) {
2235
+ // A target naming the source's thread cannot supersede it: the provider mapping and
2236
+ // the transcript history entry would both describe one id on either side.
2237
+ if (toInternalSessionId === fromInternalSessionId) {
2137
2238
  throw new Error("harness did not replace the internal session during handoff");
2138
2239
  }
2139
2240
 
@@ -2145,8 +2246,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2145
2246
  });
2146
2247
 
2147
2248
  if (this.v2Transcript) {
2148
- const transitionAt = new Date().toISOString();
2149
- toDescriptor = this.v2Descriptor(toInternalSessionId, transitionAt);
2249
+ toDescriptor = this.v2Descriptor(toInternalSessionId, new Date().toISOString());
2150
2250
  await this.v2Transcript.appendTransitionEvent({
2151
2251
  kind: "transition",
2152
2252
  transitionId: item.handoffId,
@@ -2156,40 +2256,102 @@ export class AgentConversation implements AgentClient, Bridgeable {
2156
2256
  to: toDescriptor,
2157
2257
  });
2158
2258
  failedAfter = "target_created";
2259
+ }
2260
+
2261
+ // The target's counters start at zero, so it needs its own engine from its first
2262
+ // prompt — which happens before it is live and before it may supersede the source.
2263
+ targetMetering = new MeteringEngine({
2264
+ ...this.meteringConfig,
2265
+ agentSessionId: this.agentSessionId,
2266
+ adapterId: targetAdapterId,
2267
+ initialState: this.metering.currentState,
2268
+ createdActiveThread: true,
2269
+ pricing: this.meteringConfig.pricing ?? createModelsDevResolver(),
2270
+ enforcement: this.meteringConfig.enforcement ?? "best_effort",
2271
+ });
2272
+ const promptTarget: InternalPromptTarget = {
2273
+ controller: targetController,
2274
+ metering: targetMetering,
2275
+ adapterId: targetAdapterId,
2276
+ };
2277
+
2278
+ // A completed provider turn on the target is what entitles it to replace the source.
2279
+ // Seeding is that turn when there is continuation context; otherwise the caller's
2280
+ // first instruction is the only turn available to supply the evidence.
2281
+ const confirmedByTurn = continuation.kind !== "none"
2282
+ || item.options.targetPrompt !== undefined;
2283
+ if (continuation.kind !== "none") {
2284
+ const seeded = await this.meteredInternalPrompt(
2285
+ `${item.handoffId}:seed`,
2286
+ transitionKind === "switch" ? "switch_seed" : "handoff_seed",
2287
+ buildContinuationPrompt(summary),
2288
+ records,
2289
+ promptTarget,
2290
+ );
2291
+ if (seeded.status !== "completed") {
2292
+ throw new Error(`handoff continuation seeding ${seeded.status}`);
2293
+ }
2294
+ } else if (item.options.targetPrompt !== undefined) {
2295
+ const prompted = await this.meteredInternalPrompt(
2296
+ `${item.handoffId}:target`,
2297
+ "internal_command",
2298
+ item.options.targetPrompt,
2299
+ records,
2300
+ promptTarget,
2301
+ );
2302
+ targetResult = copyPromptResult(prompted);
2303
+ if (prompted.status !== "completed") {
2304
+ throw new Error(`handoff target prompt ${prompted.status}`);
2305
+ }
2306
+ }
2307
+
2308
+ const activatedAt = new Date().toISOString();
2309
+ // With no continuation to seed and no first instruction, nothing has run on the
2310
+ // target, so it cannot be selected for a later open. The live conversation still
2311
+ // moves to it; the previous recorded mapping stays the restart fallback until a
2312
+ // completed prompt commits this one.
2313
+ const canRecord = this.ownerLifecycle?.transitionActivated !== undefined;
2314
+ const deferAttachment = !confirmedByTurn && !this.v2Transcript;
2315
+ if (!deferAttachment && this.v2Transcript) {
2159
2316
  const checkpoint = this.v2Transcript.checkpoint;
2317
+ // Seeding the target settles an operation on the source, so the descriptor taken
2318
+ // when the transition started no longer matches the reduced state activation is
2319
+ // asserted against. It still names the same source thread; only its checkpoint
2320
+ // projection moved, so it is recomputed rather than carried.
2321
+ const activationFrom = descriptorFromCheckpoint(checkpoint);
2160
2322
  await this.v2Transcript.activateTransition({
2161
2323
  kind: "transition",
2162
2324
  transitionId: item.handoffId,
2163
2325
  transitionKind,
2164
2326
  event: "target_activated",
2165
- from: fromDescriptor,
2327
+ from: activationFrom,
2166
2328
  to: toDescriptor,
2167
- ...(fromDescriptor?.internalSessionId
2329
+ ...(activationFrom?.internalSessionId
2168
2330
  ? {
2169
2331
  historyEntry: {
2170
- internalSessionId: fromDescriptor.internalSessionId,
2171
- adapterId: fromDescriptor.adapterId,
2172
- model: fromDescriptor.model,
2173
- sessionConfiguration: fromDescriptor.sessionConfiguration,
2174
- protocol: fromDescriptor.protocol,
2175
- activatedAt: fromDescriptor.activatedAt!,
2176
- deactivatedAt: transitionAt,
2332
+ internalSessionId: activationFrom.internalSessionId,
2333
+ adapterId: activationFrom.adapterId,
2334
+ model: activationFrom.model,
2335
+ sessionConfiguration: activationFrom.sessionConfiguration,
2336
+ protocol: activationFrom.protocol,
2337
+ activatedAt: activationFrom.activatedAt!,
2338
+ deactivatedAt: activatedAt,
2177
2339
  transition: { kind: transitionKind, transitionId: item.handoffId },
2178
2340
  },
2179
2341
  }
2180
2342
  : {}),
2181
2343
  activationState: {
2182
2344
  resultingStateRevision: checkpoint.stateRevision + 1,
2183
- updatedAt: transitionAt,
2184
- transitionAt,
2345
+ updatedAt: activatedAt,
2346
+ transitionAt: activatedAt,
2185
2347
  boundary: checkpoint.boundary,
2186
2348
  },
2187
2349
  });
2188
2350
  failedAfter = "target_activated";
2189
2351
  }
2190
- const activatedAt = new Date().toISOString();
2352
+ const recordedByOwner = canRecord && !deferAttachment;
2191
2353
  try {
2192
- await this.ownerLifecycle?.transitionActivated?.({
2354
+ if (recordedByOwner) await this.ownerLifecycle!.transitionActivated!({
2193
2355
  transitionId: item.handoffId,
2194
2356
  agentConversationId: this.agentConversationId,
2195
2357
  internalSessionId: toInternalSessionId,
@@ -2206,58 +2368,56 @@ export class AgentConversation implements AgentClient, Bridgeable {
2206
2368
  }
2207
2369
 
2208
2370
  const previousController = this.controller;
2209
- if (targetController !== previousController) {
2210
- this.controller = targetController;
2211
- this.activeAdapter = resolvedTargetAdapter!;
2212
- this._adapterId = targetAdapterId;
2213
- this._mode = targetMode;
2214
- this.metering = new MeteringEngine({
2215
- ...this.meteringConfig,
2216
- agentSessionId: this.agentSessionId,
2217
- adapterId: targetAdapterId,
2218
- initialState: this.metering.currentState,
2219
- createdActiveThread: true,
2220
- pricing: this.meteringConfig.pricing ?? createModelsDevResolver(),
2221
- enforcement: this.meteringConfig.enforcement ?? "best_effort",
2222
- });
2223
- this.bindController(targetController);
2224
- }
2371
+ this.controller = targetController;
2372
+ this.activeAdapter = resolvedTargetAdapter;
2373
+ this._adapterId = targetAdapterId;
2374
+ this._mode = targetMode;
2375
+ this.metering = targetMetering;
2376
+ this.bindController(targetController);
2225
2377
  targetActivated = true;
2226
- this.setInternalSessionId(toInternalSessionId);
2378
+ targetAttachment = deferAttachment ? "runtime_only" : "recorded";
2379
+ // A handoff target is a freshly created thread, so its counters start at zero
2380
+ // whether or not it is already the selected continuation.
2381
+ this.installProviderAttachment(toInternalSessionId, targetAttachment, true, {
2382
+ acquiredAt: activatedAt,
2383
+ transitionId: item.handoffId,
2384
+ });
2227
2385
  await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2228
2386
  this.emitStateIfChanged();
2229
2387
  await this.persist();
2388
+ if (this.v2Transcript) {
2389
+ // The seed was metered on the target's engine, so the checkpoint written before
2390
+ // activation still holds the source's pre-seed totals. Publish the engine that is
2391
+ // now live, or a crash here would lose work the provider was already paid for.
2392
+ await this.v2Transcript.publishCheckpoint({ metering: this.metering.currentState })
2393
+ .catch((error) => {
2394
+ this.log.warn("handoff_metering_checkpoint_failed", { error: String(error) });
2395
+ });
2396
+ }
2230
2397
  await this.recordNativeAction(item.handoffId, action, "checkpoint", {
2231
- output: { stage: "target_activated", internalSessionId: toInternalSessionId, adapterId: targetAdapterId },
2398
+ output: {
2399
+ stage: deferAttachment ? "target_live" : "target_activated",
2400
+ internalSessionId: toInternalSessionId,
2401
+ adapterId: targetAdapterId,
2402
+ },
2403
+ });
2404
+ await previousController.stop().catch((error) => {
2405
+ this.log.warn("handoff_previous_controller_stop_failed", { error: String(error) });
2232
2406
  });
2233
- if (targetController !== previousController) {
2234
- await previousController.stop().catch((error) => {
2235
- this.log.warn("handoff_previous_controller_stop_failed", { error: String(error) });
2236
- });
2237
- }
2238
2407
 
2239
- if (continuation.kind !== "none") {
2240
- const seeded = await this.meteredInternalPrompt(
2241
- `${item.handoffId}:seed`,
2242
- transitionKind === "switch" ? "switch_seed" : "handoff_seed",
2243
- buildContinuationPrompt(summary),
2244
- records,
2245
- );
2246
- if (seeded.status !== "completed") {
2247
- throw new Error(`handoff continuation seeding ${seeded.status}`);
2248
- }
2249
- }
2250
- if (item.options.targetPrompt !== undefined) {
2408
+ // The optional first instruction runs after the target is already the recorded
2409
+ // continuation. Its failure is an operation failure, not an activation rollback.
2410
+ if (continuation.kind !== "none" && item.options.targetPrompt !== undefined) {
2251
2411
  const prompted = await this.meteredInternalPrompt(
2252
2412
  `${item.handoffId}:target`,
2253
2413
  "internal_command",
2254
2414
  item.options.targetPrompt,
2255
2415
  records,
2256
2416
  );
2417
+ targetResult = copyPromptResult(prompted);
2257
2418
  if (prompted.status !== "completed") {
2258
2419
  throw new Error(`handoff target prompt ${prompted.status}`);
2259
2420
  }
2260
- targetResult = copyPromptResult(prompted);
2261
2421
  }
2262
2422
 
2263
2423
  const result: HandoffResult = Object.freeze({
@@ -2268,6 +2428,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2268
2428
  ...(transitionKind === "switch" ? { fromAdapterId, toAdapterId: targetAdapterId } : {}),
2269
2429
  summary,
2270
2430
  ...(targetResult ? { targetResult } : {}),
2431
+ providerAttachment: targetAttachment,
2271
2432
  meteringRecords: Object.freeze([...records]),
2272
2433
  });
2273
2434
  if (this.v2Transcript) {
@@ -2298,18 +2459,18 @@ export class AgentConversation implements AgentClient, Bridgeable {
2298
2459
  this.emit({ kind: "handoff_completed", result });
2299
2460
  return result;
2300
2461
  } catch (err) {
2301
- // Once session/new succeeds the controller really is on the new thread. Keep the
2302
- // public id and catalog truthful even when continuation seeding subsequently fails.
2303
- const actualSessionId = this.controller.currentSessionId;
2304
- if (!this.v2Transcript && actualSessionId && actualSessionId !== this._internalSessionId) {
2305
- this.setInternalSessionId(actualSessionId);
2306
- toInternalSessionId = actualSessionId;
2307
- this.emitStateIfChanged();
2308
- try {
2309
- await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2310
- await this.persist();
2311
- } catch (persistError) {
2312
- this.log.warn("handoff_failure_persist_failed", { error: String(persistError) });
2462
+ if (!targetActivated && targetMetering) {
2463
+ // The target's operations were minted and reported as they settled; only the
2464
+ // running aggregate lives in the engine now being discarded. Adopting its totals
2465
+ // must not double as a correction: `reconcile` would clear a block the source is
2466
+ // legitimately under, which no accounting fold has any business doing.
2467
+ if (targetMetering.currentState.operationCount > this.metering.currentState.operationCount) {
2468
+ this.metering.adoptAccounting(targetMetering.currentState);
2469
+ try {
2470
+ await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2471
+ } catch (persistError) {
2472
+ this.log.warn("handoff_failure_persist_failed", { error: String(persistError) });
2473
+ }
2313
2474
  }
2314
2475
  }
2315
2476
  const error = String(err);
@@ -2340,7 +2501,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2340
2501
  error,
2341
2502
  });
2342
2503
  }
2343
- if (!targetActivated && targetController && targetController !== this.controller) {
2504
+ if (!targetActivated && targetController) {
2344
2505
  await targetController.stop().catch(() => undefined);
2345
2506
  }
2346
2507
  await this.recordNativeAction(item.handoffId, action, "failed", { error }).catch(
@@ -2358,7 +2519,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
2358
2519
  });
2359
2520
  // A rejected handoff cannot return a HandoffResult, but the summary/seed prompts it
2360
2521
  // already ran consumed real tokens; their records travel on the error.
2361
- throw new AgentSessionHandoffError(item.handoffId, records, err);
2522
+ throw new AgentSessionHandoffError(item.handoffId, records, err, {
2523
+ fromInternalSessionId,
2524
+ ...(toInternalSessionId ? { toInternalSessionId } : {}),
2525
+ ...(toInternalSessionId ? { providerAttachment: targetAttachment } : {}),
2526
+ activationCompleted: targetActivated,
2527
+ ...(summary !== undefined ? { summary } : {}),
2528
+ ...(targetResult ? { targetResult } : {}),
2529
+ });
2362
2530
  }
2363
2531
  }
2364
2532
 
@@ -2721,13 +2889,26 @@ export class AgentConversation implements AgentClient, Bridgeable {
2721
2889
  if (!this.v2Transcript) {
2722
2890
  const result = await this.controller.setMode(item.mode);
2723
2891
  this._mode = this.controller.currentMode;
2724
- this.setInternalSessionId(result.sessionId || null);
2892
+ const nextInternalSessionId = result.sessionId || null;
2893
+ if (nextInternalSessionId) {
2894
+ if (
2895
+ this.providerAttachment.kind === "absent"
2896
+ || this.providerAttachment.descriptor.internalSessionId !== nextInternalSessionId
2897
+ ) {
2898
+ this.installProviderAttachment(nextInternalSessionId, "runtime_only", true);
2899
+ }
2900
+ } else {
2901
+ // A mode change with no provider thread (for example ACP to degraded) leaves no
2902
+ // live attachment; the previous recorded mapping remains the restart fallback.
2903
+ this.clearProviderAttachment();
2904
+ this.setInternalSessionId(null);
2905
+ }
2725
2906
  await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2726
2907
  await this.persist();
2727
2908
  return result;
2728
2909
  }
2729
2910
 
2730
- const from = this.v2Descriptor();
2911
+ const from = descriptorFromCheckpoint(this.v2Transcript.checkpoint);
2731
2912
  let to: InternalSessionDescriptor | undefined;
2732
2913
  let failedAfter: "start" | "target_created" | "target_activated" = "start";
2733
2914
  await this.v2Transcript.appendTransitionEvent({
@@ -3026,6 +3207,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
3026
3207
  let closed: OperationMeteringRecord | null = null;
3027
3208
  let transcriptClosed = false;
3028
3209
  let providerSettled = false;
3210
+ // A lazily created thread acquires its provider session during dispatch, so this is the
3211
+ // closest observable acquisition time when `session/new` happens inside `prompt()`.
3212
+ const dispatchedAt = new Date().toISOString();
3029
3213
  try {
3030
3214
  const res = await this.controller.prompt(providerText, wrappedHandlers, item.attachments);
3031
3215
  providerSettled = true;
@@ -3048,7 +3232,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
3048
3232
  this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
3049
3233
  }
3050
3234
  // A session may have been created lazily on first prompt (degraded has none).
3051
- this.setInternalSessionId(this.controller.currentSessionId ?? this._internalSessionId);
3235
+ const observedInternalSessionId = this.controller.currentSessionId ?? this._internalSessionId;
3236
+ if (observedInternalSessionId) {
3237
+ if (
3238
+ this.providerAttachment.kind === "absent"
3239
+ || this.providerAttachment.descriptor.internalSessionId !== observedInternalSessionId
3240
+ ) {
3241
+ this.installProviderAttachment(observedInternalSessionId, "runtime_only", true, {
3242
+ acquiredAt: dispatchedAt,
3243
+ });
3244
+ }
3245
+ } else {
3246
+ this.setInternalSessionId(observedInternalSessionId);
3247
+ }
3052
3248
  // Metering closes BEFORE local persistence. The provider has already been paid and
3053
3249
  // has already told us what it charged; letting a transcript or catalog write failure
3054
3250
  // send us down the catch path would discard usage we are holding and, in a strict
@@ -3060,6 +3256,17 @@ export class AgentConversation implements AgentClient, Bridgeable {
3060
3256
  const record = await this.closeOperation(operation, res.status, res.usage);
3061
3257
  closed = record;
3062
3258
  await this.ownerLifecycle?.meteringRecorded?.(record);
3259
+ // The Agent-owned and transcript paths record the attachment inside their own
3260
+ // commit. A catalog-backed conversation has one mutable row, so the completed turn
3261
+ // is simply what makes the live thread the selected one.
3262
+ const pending = this.providerAttachment;
3263
+ if (res.status === "completed"
3264
+ && !this.ownerLifecycle
3265
+ && !this.v2Transcript
3266
+ && pending.kind === "runtime_only") {
3267
+ this.providerAttachment = recordedProviderAttachment(pending.descriptor);
3268
+ this.lastRecordedInternalSessionId = pending.descriptor.internalSessionId;
3269
+ }
3063
3270
  await this.persist();
3064
3271
  if (this.v2Transcript) {
3065
3272
  await this.presentation.drain();
@@ -3080,18 +3287,41 @@ export class AgentConversation implements AgentClient, Bridgeable {
3080
3287
  }
3081
3288
  const result = Object.freeze({ ...res, operationId: item.turnId, metering: record });
3082
3289
  await this.ownerRecordWrite;
3083
- await this.ownerLifecycle?.afterPrompt({
3084
- operationId: item.turnId,
3085
- agentSessionId: this.ownerAgentSessionId!,
3086
- agentConversationId: this.agentConversationId,
3087
- targetProviderContextId,
3088
- ...(owned?.identityDeliveryReceipt
3089
- ? { identityDeliveryReceipt: owned.identityDeliveryReceipt }
3090
- : {}),
3091
- ...(item.participantId ? { participantId: item.participantId } : {}),
3092
- text: item.text,
3093
- result,
3094
- });
3290
+ if (this.ownerLifecycle) {
3291
+ const completed = {
3292
+ operationId: item.turnId,
3293
+ agentSessionId: this.ownerAgentSessionId!,
3294
+ agentConversationId: this.agentConversationId,
3295
+ targetProviderContextId,
3296
+ ...(owned?.identityDeliveryReceipt
3297
+ ? { identityDeliveryReceipt: owned.identityDeliveryReceipt }
3298
+ : {}),
3299
+ ...(item.participantId ? { participantId: item.participantId } : {}),
3300
+ text: item.text,
3301
+ result,
3302
+ providerAttachment: this.providerAttachment,
3303
+ };
3304
+ try {
3305
+ const committed = await this.ownerLifecycle.afterPrompt(completed);
3306
+ if (committed?.providerAttachment) {
3307
+ this.providerAttachment = acknowledgeProviderAttachment(
3308
+ this.providerAttachment,
3309
+ committed.providerAttachment,
3310
+ );
3311
+ }
3312
+ } catch (error) {
3313
+ if (error instanceof OwnedPromptPostCommitError) {
3314
+ if (error.commit.providerAttachment) {
3315
+ this.providerAttachment = acknowledgeProviderAttachment(
3316
+ this.providerAttachment,
3317
+ error.commit.providerAttachment,
3318
+ );
3319
+ }
3320
+ throw error.cause ?? error;
3321
+ }
3322
+ throw error;
3323
+ }
3324
+ }
3095
3325
  await this.ownerRecordWrite;
3096
3326
  return result;
3097
3327
  } catch (err) {
@@ -3174,13 +3404,27 @@ export class AgentConversation implements AgentClient, Bridgeable {
3174
3404
  });
3175
3405
  }
3176
3406
 
3407
+ /**
3408
+ * @param liveThread Whether the settled turn ran on this conversation's own controller.
3409
+ * A transition seeds its target through a separate controller, and that turn is
3410
+ * evidence for the target, never for the thread it is trying to replace.
3411
+ */
3177
3412
  private async finishV2Prompt(
3178
3413
  status: PromptResult["status"],
3179
3414
  record: OperationMeteringRecord,
3180
3415
  errorCode?: "unknown",
3416
+ liveThread = true,
3181
3417
  ): Promise<void> {
3182
3418
  if (!this.v2Transcript || this.persistence === false) return;
3183
3419
  const observedAt = new Date().toISOString();
3420
+ // A completed turn is what entitles a newly created thread to be selected on a later
3421
+ // open, and the turn's own terminal checkpoint is what records it — so the response
3422
+ // and the thread it came from cannot disagree after a crash.
3423
+ const attachment = this.providerAttachment;
3424
+ const attaching = liveThread
3425
+ && status === "completed"
3426
+ && attachment.kind === "runtime_only"
3427
+ && this.v2Transcript.checkpoint.internalSessionId === null;
3184
3428
  await this.v2Transcript.appendEvent({
3185
3429
  kind: "metering_reference",
3186
3430
  operationId: record.operationId,
@@ -3199,9 +3443,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
3199
3443
  observedAt,
3200
3444
  }),
3201
3445
  metering: this.metering.currentState,
3446
+ ...(attaching && attachment.kind === "runtime_only" ? {
3447
+ providerAttachment: {
3448
+ internalSessionId: attachment.descriptor.internalSessionId,
3449
+ activatedAt: attachment.descriptor.acquiredAt,
3450
+ },
3451
+ } : {}),
3202
3452
  },
3203
3453
  errorCode,
3204
3454
  );
3455
+ if (attaching && this.providerAttachment === attachment) {
3456
+ this.providerAttachment = recordedProviderAttachment(attachment.descriptor);
3457
+ this.lastRecordedInternalSessionId = attachment.descriptor.internalSessionId;
3458
+ }
3205
3459
  }
3206
3460
 
3207
3461
  /**
@@ -3267,14 +3521,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
3267
3521
  operationKind: MeteredOperationKind,
3268
3522
  text: string,
3269
3523
  records: OperationMeteringRecord[],
3524
+ target?: InternalPromptTarget,
3270
3525
  ): Promise<PromptResult> {
3271
- const operation = await this.metering.open({
3526
+ const controller = target?.controller ?? this.controller;
3527
+ const metering = target?.metering ?? this.metering;
3528
+ const advertised = target ? activeModel(target.controller.configOptions) : this.advertisedModel;
3529
+ const reference = target ? resolveModelReference(target.adapterId, advertised) : null;
3530
+ const operation = await metering.open({
3272
3531
  operationId,
3273
3532
  operationKind,
3274
- internalSessionId: this._internalSessionId,
3275
- providerId: this.providerId,
3276
- model: this.model,
3277
- degraded: this.controller.isDegraded,
3533
+ internalSessionId: target ? controller.currentSessionId : this._internalSessionId,
3534
+ providerId: target ? reference?.providerId ?? null : this.providerId,
3535
+ model: target ? reference?.modelId ?? advertised : this.model,
3536
+ degraded: controller.isDegraded,
3278
3537
  });
3279
3538
  let transcriptStarted = false;
3280
3539
  if (this.v2Transcript) {
@@ -3300,8 +3559,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
3300
3559
  let closed = false;
3301
3560
  let transcriptClosed = false;
3302
3561
  try {
3303
- const result = await this.controller.prompt(text);
3304
- const record = await this.closeOperation(operation, result.status, result.usage);
3562
+ const result = await controller.prompt(text);
3563
+ const record = await this.closeOperation(
3564
+ operation,
3565
+ result.status,
3566
+ result.usage,
3567
+ undefined,
3568
+ metering,
3569
+ );
3305
3570
  records.push(record);
3306
3571
  closed = true;
3307
3572
  await this.ownerLifecycle?.meteringRecorded?.(record);
@@ -3315,13 +3580,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
3315
3580
  stopReason: result.stopReason,
3316
3581
  status: result.status,
3317
3582
  });
3318
- await this.finishV2Prompt(result.status, record);
3583
+ await this.finishV2Prompt(result.status, record, undefined, target === undefined);
3319
3584
  transcriptClosed = true;
3320
3585
  }
3321
3586
  return result;
3322
3587
  } catch (err) {
3323
3588
  if (!closed) {
3324
- const record = await this.closeOperation(operation, "error", null, String(err));
3589
+ const record = await this.closeOperation(operation, "error", null, String(err), metering);
3325
3590
  records.push(record);
3326
3591
  closed = true;
3327
3592
  await this.ownerLifecycle?.meteringRecorded?.(record);
@@ -3388,18 +3653,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
3388
3653
  outcome: "completed" | "cancelled" | "error",
3389
3654
  reportedCumulative: TokenUsage | null,
3390
3655
  usageFailureReason?: string,
3656
+ engine: MeteringEngine = this.metering,
3391
3657
  ): Promise<OperationMeteringRecord> {
3392
- const wasBlocked = this.metering.blocked;
3393
- const record = await this.metering.close(operation, {
3658
+ const wasBlocked = engine.blocked;
3659
+ const live = engine === this.metering;
3660
+ const record = await engine.close(operation, {
3394
3661
  outcome,
3395
3662
  reportedCumulative,
3396
3663
  ...(usageFailureReason ? { usageFailureReason } : {}),
3397
- contextAfter: this._contextWindow,
3398
- providerCostAfter: this._providerCost,
3664
+ // Context and provider cost describe the live thread. An unconfirmed transition
3665
+ // target has neither yet, and borrowing the source's would misreport it.
3666
+ contextAfter: live ? this._contextWindow : null,
3667
+ providerCostAfter: live ? this._providerCost : null,
3399
3668
  });
3400
3669
  this.emit({ kind: "metering_recorded", record });
3401
- if (!wasBlocked && this.metering.blocked) {
3402
- this.emit({ kind: "metering_blocked", reason: this.metering.blockedReason ?? "unknown" });
3670
+ if (!wasBlocked && engine.blocked) {
3671
+ this.emit({ kind: "metering_blocked", reason: engine.blockedReason ?? "unknown" });
3403
3672
  }
3404
3673
  return record;
3405
3674
  }
@@ -3499,6 +3768,10 @@ export class AgentConversation implements AgentClient, Bridgeable {
3499
3768
  await this.ownerRecordWrite.catch((error) => {
3500
3769
  this.log.warn("owned_runtime_persistence_failed", { error: String(error) });
3501
3770
  });
3771
+ // No live thread remains. A runtime-only attachment was never a continuation
3772
+ // candidate, and a recorded one is preserved by its provider row, so neither should
3773
+ // survive on the stopped object.
3774
+ this.clearProviderAttachment();
3502
3775
  await this.presentation.drain().catch(() => undefined);
3503
3776
  try {
3504
3777
  await this.transcriptWrite;
@@ -3674,7 +3947,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3674
3947
  if (!this.sessions) return;
3675
3948
  await this.sessions.record({
3676
3949
  agentSessionId: this.agentSessionId,
3677
- internalSessionId: this._internalSessionId,
3950
+ internalSessionId: this.lastRecordedInternalSessionId,
3678
3951
  adapter: this.adapterId,
3679
3952
  mode: this._mode,
3680
3953
  cwd: this._cwd,
@@ -3731,6 +4004,47 @@ export class AgentConversation implements AgentClient, Bridgeable {
3731
4004
  }
3732
4005
  }
3733
4006
 
4007
+ /**
4008
+ * Install the live provider attachment.
4009
+ *
4010
+ * `kind` is persistence state (may it be selected on a later open?). `created` is thread
4011
+ * provenance for metering (did its counters start at zero?). They are orthogonal: a
4012
+ * handoff target is both `recorded` and `created`, while a loaded thread is `recorded`
4013
+ * and not created.
4014
+ */
4015
+ private installProviderAttachment(
4016
+ internalSessionId: string,
4017
+ kind: "runtime_only" | "recorded",
4018
+ created: boolean,
4019
+ options: {
4020
+ readonly acquiredAt?: string;
4021
+ readonly transitionId?: string;
4022
+ } = {},
4023
+ ): void {
4024
+ const current = this.providerAttachment;
4025
+ if (current.kind === kind && current.descriptor.internalSessionId === internalSessionId) return;
4026
+ this.setInternalSessionId(internalSessionId, created);
4027
+ const descriptor: ProviderAttachmentDescriptor = {
4028
+ attachmentAttemptId: crypto.randomUUID(),
4029
+ internalSessionId,
4030
+ adapterId: this.adapterId,
4031
+ mode: this.mode,
4032
+ ...(this.model ? { model: this.model } : {}),
4033
+ acquiredAt: options.acquiredAt ?? new Date().toISOString(),
4034
+ ...(options.transitionId ? { transitionId: options.transitionId } : {}),
4035
+ };
4036
+ this.providerAttachment = kind === "runtime_only"
4037
+ ? runtimeOnlyProviderAttachment(descriptor)
4038
+ : recordedProviderAttachment(descriptor);
4039
+ if (kind === "recorded") this.lastRecordedInternalSessionId = internalSessionId;
4040
+ }
4041
+
4042
+ /** Drop the live attachment without touching persistence or the last known session id. */
4043
+ private clearProviderAttachment(): void {
4044
+ if (this.providerAttachment.kind === "absent") return;
4045
+ this.providerAttachment = Object.freeze({ kind: "absent" });
4046
+ }
4047
+
3734
4048
  /**
3735
4049
  * Apply a raw ACP `usage_update`.
3736
4050
  *