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