@qlairoslabs/acp-client 0.9.3 → 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;
@@ -423,11 +447,21 @@ export class AgentConversation implements AgentClient, Bridgeable {
423
447
  private readonly log: Logger;
424
448
  private transcriptWrite: Promise<void> = Promise.resolve();
425
449
  private readonly operations = new AgentConversationQueue<QueueItem>();
450
+ private stopPromise: Promise<void> | null = null;
426
451
  private phase: AgentSessionPhase = "idle";
427
452
  private notificationSeq = 0;
428
453
  private readonly listeners = new Set<AgentSessionListener>();
429
454
  private lastStateKey = "";
430
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;
431
465
  private ownerContextNonce: string | null = null;
432
466
  private metering: MeteringEngine;
433
467
  private readonly meteringConfig: MeteringConfig;
@@ -823,7 +857,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
823
857
  if (!result.resumed || !result.sessionId) {
824
858
  throw new Error("adapter did not confirm loading the recorded internal session");
825
859
  }
826
- session.setInternalSessionId(result.sessionId, false);
860
+ session.installProviderAttachment(result.sessionId, "recorded", false);
827
861
  await stageOpeningContinuation(stageContinuation, checkpoint, result.sessionId);
828
862
  const attempt: ContinuationAttempt = Object.freeze({
829
863
  strategy: "load_internal_session",
@@ -958,7 +992,18 @@ export class AgentConversation implements AgentClient, Bridgeable {
958
992
  const result = await this.controller.start();
959
993
  // A resumed thread's counters did not start at zero, so it needs restored state to
960
994
  // be attributable.
961
- 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
+ }
962
1007
  await this.persist();
963
1008
  await this.appendTranscript({
964
1009
  v: 1,
@@ -981,7 +1026,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
981
1026
  if (!result.resumed || !result.sessionId) {
982
1027
  throw new Error("adapter did not confirm loading the recorded internal session");
983
1028
  }
984
- this.setInternalSessionId(result.sessionId, false);
1029
+ this.installProviderAttachment(result.sessionId, "recorded", false);
985
1030
  return;
986
1031
  }
987
1032
  const paths = await resolveSessionLogPaths(persistence, this.agentSessionId);
@@ -1088,6 +1133,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
1088
1133
  initializeCheckpoint: async () => {
1089
1134
  const result = await this.controller.start((event) => this.reportManagedControllerProgress(event));
1090
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
+ }
1091
1143
  const now = new Date().toISOString();
1092
1144
  const sessionConfiguration = snapshotSessionConfiguration({
1093
1145
  adapterId: this.adapterId,
@@ -1113,8 +1165,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
1113
1165
  stateRevision: 1,
1114
1166
  adapterId: this.adapterId,
1115
1167
  mode: stagedContinuation.mode,
1116
- internalSessionId: stagedContinuation.internalSessionId,
1117
- 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,
1118
1176
  internalSessionHistoryRevision: 0,
1119
1177
  internalSessionHistoryDigest: EMPTY_HISTORY_DIGEST,
1120
1178
  model: stagedContinuation.model,
@@ -1190,7 +1248,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1190
1248
  throw new Error("adapter loaded a different internal session than requested");
1191
1249
  }
1192
1250
  this._mode = this.controller.currentMode;
1193
- this.setInternalSessionId(loaded.sessionId, false);
1251
+ this.installProviderAttachment(loaded.sessionId, "recorded", false);
1194
1252
  await stageOpeningContinuation(
1195
1253
  this.openBootstrap.stageContinuation,
1196
1254
  checkpoint,
@@ -1388,6 +1446,30 @@ export class AgentConversation implements AgentClient, Bridgeable {
1388
1446
  }
1389
1447
  }
1390
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
+
1391
1473
  return createContinuationReport(
1392
1474
  checkpoint,
1393
1475
  this.adapterId,
@@ -1459,6 +1541,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
1459
1541
  return this._internalSessionId;
1460
1542
  }
1461
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
+
1462
1557
  /** Active adapter route. It changes only after a durable switch activation. */
1463
1558
  get adapterId(): string {
1464
1559
  return this._adapterId;
@@ -2037,14 +2132,20 @@ export class AgentConversation implements AgentClient, Bridgeable {
2037
2132
  const action = continuation.kind === "none" && transitionKind === "handoff"
2038
2133
  ? "reset"
2039
2134
  : transitionKind;
2040
- 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;
2041
2140
  let toInternalSessionId: string | undefined;
2042
2141
  let toDescriptor: InternalSessionDescriptor | undefined;
2043
2142
  let summary: string | undefined;
2044
2143
  let targetResult: PromptResult | undefined;
2045
2144
  let targetController: AgentController | null = null;
2046
2145
  let resolvedTargetAdapter: Adapter | null = null;
2146
+ let targetMetering: MeteringEngine | null = null;
2047
2147
  let targetActivated = false;
2148
+ let targetAttachment: "runtime_only" | "recorded" = "runtime_only";
2048
2149
  let failedAfter: "start" | "target_created" | "target_activated" = "start";
2049
2150
  // Records accumulate as they complete, so a handoff that fails partway still reports
2050
2151
  // the operations it already paid for.
@@ -2109,30 +2210,29 @@ export class AgentConversation implements AgentClient, Bridgeable {
2109
2210
  summary = "";
2110
2211
  }
2111
2212
 
2112
- const replacingController = targetAdapterId !== fromAdapterId || targetMode !== this._mode;
2113
- let created: ConnectResult;
2114
- if (replacingController) {
2115
- const adapter = item.options.target?.adapter ?? (targetAdapterId === fromAdapterId
2116
- ? this.activeAdapter
2117
- : this.ownerLifecycle?.resolveAdapter?.(targetAdapterId));
2118
- if (!adapter) {
2119
- throw new Error(
2120
- `cannot resolve adapter ${targetAdapterId}; cross-adapter switch requires an Agent-owned conversation`,
2121
- );
2122
- }
2123
- resolvedTargetAdapter = adapter;
2124
- targetController = this.createController(adapter, targetAdapterId, targetMode);
2125
- created = await targetController.startFresh();
2126
- } else {
2127
- if (this.controller.isDegraded) {
2128
- throw new Error("starting a fresh provider thread requires ACP (normal) mode");
2129
- }
2130
- targetController = this.controller;
2131
- 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");
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
+ );
2132
2227
  }
2228
+ resolvedTargetAdapter = adapter;
2229
+ targetController = this.createController(adapter, targetAdapterId, targetMode);
2230
+ const created = await targetController.startFresh();
2133
2231
  if (!created.sessionId) throw new Error("harness returned no session id for handoff");
2134
2232
  toInternalSessionId = created.sessionId;
2135
- 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) {
2136
2236
  throw new Error("harness did not replace the internal session during handoff");
2137
2237
  }
2138
2238
 
@@ -2144,8 +2244,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2144
2244
  });
2145
2245
 
2146
2246
  if (this.v2Transcript) {
2147
- const transitionAt = new Date().toISOString();
2148
- toDescriptor = this.v2Descriptor(toInternalSessionId, transitionAt);
2247
+ toDescriptor = this.v2Descriptor(toInternalSessionId, new Date().toISOString());
2149
2248
  await this.v2Transcript.appendTransitionEvent({
2150
2249
  kind: "transition",
2151
2250
  transitionId: item.handoffId,
@@ -2155,40 +2254,102 @@ export class AgentConversation implements AgentClient, Bridgeable {
2155
2254
  to: toDescriptor,
2156
2255
  });
2157
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) {
2158
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);
2159
2320
  await this.v2Transcript.activateTransition({
2160
2321
  kind: "transition",
2161
2322
  transitionId: item.handoffId,
2162
2323
  transitionKind,
2163
2324
  event: "target_activated",
2164
- from: fromDescriptor,
2325
+ from: activationFrom,
2165
2326
  to: toDescriptor,
2166
- ...(fromDescriptor?.internalSessionId
2327
+ ...(activationFrom?.internalSessionId
2167
2328
  ? {
2168
2329
  historyEntry: {
2169
- internalSessionId: fromDescriptor.internalSessionId,
2170
- adapterId: fromDescriptor.adapterId,
2171
- model: fromDescriptor.model,
2172
- sessionConfiguration: fromDescriptor.sessionConfiguration,
2173
- protocol: fromDescriptor.protocol,
2174
- activatedAt: fromDescriptor.activatedAt!,
2175
- 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,
2176
2337
  transition: { kind: transitionKind, transitionId: item.handoffId },
2177
2338
  },
2178
2339
  }
2179
2340
  : {}),
2180
2341
  activationState: {
2181
2342
  resultingStateRevision: checkpoint.stateRevision + 1,
2182
- updatedAt: transitionAt,
2183
- transitionAt,
2343
+ updatedAt: activatedAt,
2344
+ transitionAt: activatedAt,
2184
2345
  boundary: checkpoint.boundary,
2185
2346
  },
2186
2347
  });
2187
2348
  failedAfter = "target_activated";
2188
2349
  }
2189
- const activatedAt = new Date().toISOString();
2350
+ const recordedByOwner = canRecord && !deferAttachment;
2190
2351
  try {
2191
- await this.ownerLifecycle?.transitionActivated?.({
2352
+ if (recordedByOwner) await this.ownerLifecycle!.transitionActivated!({
2192
2353
  transitionId: item.handoffId,
2193
2354
  agentConversationId: this.agentConversationId,
2194
2355
  internalSessionId: toInternalSessionId,
@@ -2205,58 +2366,56 @@ export class AgentConversation implements AgentClient, Bridgeable {
2205
2366
  }
2206
2367
 
2207
2368
  const previousController = this.controller;
2208
- if (targetController !== previousController) {
2209
- this.controller = targetController;
2210
- this.activeAdapter = resolvedTargetAdapter!;
2211
- this._adapterId = targetAdapterId;
2212
- this._mode = targetMode;
2213
- this.metering = new MeteringEngine({
2214
- ...this.meteringConfig,
2215
- agentSessionId: this.agentSessionId,
2216
- adapterId: targetAdapterId,
2217
- initialState: this.metering.currentState,
2218
- createdActiveThread: true,
2219
- pricing: this.meteringConfig.pricing ?? createModelsDevResolver(),
2220
- enforcement: this.meteringConfig.enforcement ?? "best_effort",
2221
- });
2222
- this.bindController(targetController);
2223
- }
2369
+ this.controller = targetController;
2370
+ this.activeAdapter = resolvedTargetAdapter;
2371
+ this._adapterId = targetAdapterId;
2372
+ this._mode = targetMode;
2373
+ this.metering = targetMetering;
2374
+ this.bindController(targetController);
2224
2375
  targetActivated = true;
2225
- 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
+ });
2226
2383
  await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2227
2384
  this.emitStateIfChanged();
2228
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
+ }
2229
2395
  await this.recordNativeAction(item.handoffId, action, "checkpoint", {
2230
- 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) });
2231
2404
  });
2232
- if (targetController !== previousController) {
2233
- await previousController.stop().catch((error) => {
2234
- this.log.warn("handoff_previous_controller_stop_failed", { error: String(error) });
2235
- });
2236
- }
2237
2405
 
2238
- if (continuation.kind !== "none") {
2239
- const seeded = await this.meteredInternalPrompt(
2240
- `${item.handoffId}:seed`,
2241
- transitionKind === "switch" ? "switch_seed" : "handoff_seed",
2242
- buildContinuationPrompt(summary),
2243
- records,
2244
- );
2245
- if (seeded.status !== "completed") {
2246
- throw new Error(`handoff continuation seeding ${seeded.status}`);
2247
- }
2248
- }
2249
- 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) {
2250
2409
  const prompted = await this.meteredInternalPrompt(
2251
2410
  `${item.handoffId}:target`,
2252
2411
  "internal_command",
2253
2412
  item.options.targetPrompt,
2254
2413
  records,
2255
2414
  );
2415
+ targetResult = copyPromptResult(prompted);
2256
2416
  if (prompted.status !== "completed") {
2257
2417
  throw new Error(`handoff target prompt ${prompted.status}`);
2258
2418
  }
2259
- targetResult = copyPromptResult(prompted);
2260
2419
  }
2261
2420
 
2262
2421
  const result: HandoffResult = Object.freeze({
@@ -2267,6 +2426,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2267
2426
  ...(transitionKind === "switch" ? { fromAdapterId, toAdapterId: targetAdapterId } : {}),
2268
2427
  summary,
2269
2428
  ...(targetResult ? { targetResult } : {}),
2429
+ providerAttachment: targetAttachment,
2270
2430
  meteringRecords: Object.freeze([...records]),
2271
2431
  });
2272
2432
  if (this.v2Transcript) {
@@ -2297,18 +2457,18 @@ export class AgentConversation implements AgentClient, Bridgeable {
2297
2457
  this.emit({ kind: "handoff_completed", result });
2298
2458
  return result;
2299
2459
  } catch (err) {
2300
- // Once session/new succeeds the controller really is on the new thread. Keep the
2301
- // public id and catalog truthful even when continuation seeding subsequently fails.
2302
- const actualSessionId = this.controller.currentSessionId;
2303
- if (!this.v2Transcript && actualSessionId && actualSessionId !== this._internalSessionId) {
2304
- this.setInternalSessionId(actualSessionId);
2305
- toInternalSessionId = actualSessionId;
2306
- this.emitStateIfChanged();
2307
- try {
2308
- await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2309
- await this.persist();
2310
- } catch (persistError) {
2311
- 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
+ }
2312
2472
  }
2313
2473
  }
2314
2474
  const error = String(err);
@@ -2339,7 +2499,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2339
2499
  error,
2340
2500
  });
2341
2501
  }
2342
- if (!targetActivated && targetController && targetController !== this.controller) {
2502
+ if (!targetActivated && targetController) {
2343
2503
  await targetController.stop().catch(() => undefined);
2344
2504
  }
2345
2505
  await this.recordNativeAction(item.handoffId, action, "failed", { error }).catch(
@@ -2357,7 +2517,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
2357
2517
  });
2358
2518
  // A rejected handoff cannot return a HandoffResult, but the summary/seed prompts it
2359
2519
  // already ran consumed real tokens; their records travel on the error.
2360
- 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
+ });
2361
2528
  }
2362
2529
  }
2363
2530
 
@@ -2720,13 +2887,26 @@ export class AgentConversation implements AgentClient, Bridgeable {
2720
2887
  if (!this.v2Transcript) {
2721
2888
  const result = await this.controller.setMode(item.mode);
2722
2889
  this._mode = this.controller.currentMode;
2723
- 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
+ }
2724
2904
  await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2725
2905
  await this.persist();
2726
2906
  return result;
2727
2907
  }
2728
2908
 
2729
- const from = this.v2Descriptor();
2909
+ const from = descriptorFromCheckpoint(this.v2Transcript.checkpoint);
2730
2910
  let to: InternalSessionDescriptor | undefined;
2731
2911
  let failedAfter: "start" | "target_created" | "target_activated" = "start";
2732
2912
  await this.v2Transcript.appendTransitionEvent({
@@ -3025,6 +3205,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
3025
3205
  let closed: OperationMeteringRecord | null = null;
3026
3206
  let transcriptClosed = false;
3027
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();
3028
3211
  try {
3029
3212
  const res = await this.controller.prompt(providerText, wrappedHandlers, item.attachments);
3030
3213
  providerSettled = true;
@@ -3047,7 +3230,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
3047
3230
  this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
3048
3231
  }
3049
3232
  // A session may have been created lazily on first prompt (degraded has none).
3050
- 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
+ }
3051
3246
  // Metering closes BEFORE local persistence. The provider has already been paid and
3052
3247
  // has already told us what it charged; letting a transcript or catalog write failure
3053
3248
  // send us down the catch path would discard usage we are holding and, in a strict
@@ -3059,6 +3254,17 @@ export class AgentConversation implements AgentClient, Bridgeable {
3059
3254
  const record = await this.closeOperation(operation, res.status, res.usage);
3060
3255
  closed = record;
3061
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
+ }
3062
3268
  await this.persist();
3063
3269
  if (this.v2Transcript) {
3064
3270
  await this.presentation.drain();
@@ -3079,18 +3285,41 @@ export class AgentConversation implements AgentClient, Bridgeable {
3079
3285
  }
3080
3286
  const result = Object.freeze({ ...res, operationId: item.turnId, metering: record });
3081
3287
  await this.ownerRecordWrite;
3082
- await this.ownerLifecycle?.afterPrompt({
3083
- operationId: item.turnId,
3084
- agentSessionId: this.ownerAgentSessionId!,
3085
- agentConversationId: this.agentConversationId,
3086
- targetProviderContextId,
3087
- ...(owned?.identityDeliveryReceipt
3088
- ? { identityDeliveryReceipt: owned.identityDeliveryReceipt }
3089
- : {}),
3090
- ...(item.participantId ? { participantId: item.participantId } : {}),
3091
- text: item.text,
3092
- result,
3093
- });
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
+ }
3094
3323
  await this.ownerRecordWrite;
3095
3324
  return result;
3096
3325
  } catch (err) {
@@ -3173,13 +3402,27 @@ export class AgentConversation implements AgentClient, Bridgeable {
3173
3402
  });
3174
3403
  }
3175
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
+ */
3176
3410
  private async finishV2Prompt(
3177
3411
  status: PromptResult["status"],
3178
3412
  record: OperationMeteringRecord,
3179
3413
  errorCode?: "unknown",
3414
+ liveThread = true,
3180
3415
  ): Promise<void> {
3181
3416
  if (!this.v2Transcript || this.persistence === false) return;
3182
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;
3183
3426
  await this.v2Transcript.appendEvent({
3184
3427
  kind: "metering_reference",
3185
3428
  operationId: record.operationId,
@@ -3198,9 +3441,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
3198
3441
  observedAt,
3199
3442
  }),
3200
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
+ } : {}),
3201
3450
  },
3202
3451
  errorCode,
3203
3452
  );
3453
+ if (attaching && this.providerAttachment === attachment) {
3454
+ this.providerAttachment = recordedProviderAttachment(attachment.descriptor);
3455
+ this.lastRecordedInternalSessionId = attachment.descriptor.internalSessionId;
3456
+ }
3204
3457
  }
3205
3458
 
3206
3459
  /**
@@ -3266,14 +3519,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
3266
3519
  operationKind: MeteredOperationKind,
3267
3520
  text: string,
3268
3521
  records: OperationMeteringRecord[],
3522
+ target?: InternalPromptTarget,
3269
3523
  ): Promise<PromptResult> {
3270
- 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({
3271
3529
  operationId,
3272
3530
  operationKind,
3273
- internalSessionId: this._internalSessionId,
3274
- providerId: this.providerId,
3275
- model: this.model,
3276
- 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,
3277
3535
  });
3278
3536
  let transcriptStarted = false;
3279
3537
  if (this.v2Transcript) {
@@ -3299,8 +3557,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
3299
3557
  let closed = false;
3300
3558
  let transcriptClosed = false;
3301
3559
  try {
3302
- const result = await this.controller.prompt(text);
3303
- 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
+ );
3304
3568
  records.push(record);
3305
3569
  closed = true;
3306
3570
  await this.ownerLifecycle?.meteringRecorded?.(record);
@@ -3314,13 +3578,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
3314
3578
  stopReason: result.stopReason,
3315
3579
  status: result.status,
3316
3580
  });
3317
- await this.finishV2Prompt(result.status, record);
3581
+ await this.finishV2Prompt(result.status, record, undefined, target === undefined);
3318
3582
  transcriptClosed = true;
3319
3583
  }
3320
3584
  return result;
3321
3585
  } catch (err) {
3322
3586
  if (!closed) {
3323
- const record = await this.closeOperation(operation, "error", null, String(err));
3587
+ const record = await this.closeOperation(operation, "error", null, String(err), metering);
3324
3588
  records.push(record);
3325
3589
  closed = true;
3326
3590
  await this.ownerLifecycle?.meteringRecorded?.(record);
@@ -3387,18 +3651,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
3387
3651
  outcome: "completed" | "cancelled" | "error",
3388
3652
  reportedCumulative: TokenUsage | null,
3389
3653
  usageFailureReason?: string,
3654
+ engine: MeteringEngine = this.metering,
3390
3655
  ): Promise<OperationMeteringRecord> {
3391
- const wasBlocked = this.metering.blocked;
3392
- 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, {
3393
3659
  outcome,
3394
3660
  reportedCumulative,
3395
3661
  ...(usageFailureReason ? { usageFailureReason } : {}),
3396
- contextAfter: this._contextWindow,
3397
- 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,
3398
3666
  });
3399
3667
  this.emit({ kind: "metering_recorded", record });
3400
- if (!wasBlocked && this.metering.blocked) {
3401
- 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" });
3402
3670
  }
3403
3671
  return record;
3404
3672
  }
@@ -3475,20 +3743,55 @@ export class AgentConversation implements AgentClient, Bridgeable {
3475
3743
  this.controller.interrupt(options);
3476
3744
  }
3477
3745
 
3478
- async stop(): Promise<void> {
3479
- if (this.phase === "stopped") return;
3480
- // Stop is terminal for this stable object. Drop work that never started, interrupt the
3481
- // active turn, and publish stopped before awaiting process teardown so a concurrent
3482
- // prompt cannot slip into a controller that is going away.
3483
- this.interrupt({ clearQueue: true });
3746
+ stop(): Promise<void> {
3747
+ if (this.stopPromise) return this.stopPromise;
3748
+ // Publish the terminal state synchronously. All callers then share the same
3749
+ // completion promise, including callers arriving while teardown is in progress.
3484
3750
  this.phase = "stopped";
3485
- this.emitStateIfChanged();
3486
- await this.controller.stop();
3487
- await this.ownerRecordWrite.catch((error) => {
3488
- this.log.warn("owned_runtime_persistence_failed", { error: String(error) });
3751
+ const failures: unknown[] = [];
3752
+ const completion = Promise.resolve().then(async () => {
3753
+ try {
3754
+ await this.controller.stop();
3755
+ } catch (error) {
3756
+ failures.push(error);
3757
+ }
3758
+ // Closing the provider can reject an active prompt. Its catch/finally path may
3759
+ // enqueue final message and metering writes, so the pre-stop write tail is not
3760
+ // sufficient evidence that persistence is quiescent.
3761
+ try {
3762
+ await this.operations.waitForIdle();
3763
+ } catch (error) {
3764
+ failures.push(error);
3765
+ }
3766
+ await this.ownerRecordWrite.catch((error) => {
3767
+ this.log.warn("owned_runtime_persistence_failed", { error: String(error) });
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();
3773
+ await this.presentation.drain().catch(() => undefined);
3774
+ try {
3775
+ await this.transcriptWrite;
3776
+ } catch (error) {
3777
+ failures.push(error);
3778
+ }
3779
+ try {
3780
+ await this.v2Transcript?.close();
3781
+ } catch (error) {
3782
+ failures.push(error);
3783
+ }
3784
+ if (failures.length === 1) throw failures[0];
3785
+ if (failures.length > 1) throw new AggregateError(failures, "AgentSession shutdown failed");
3489
3786
  });
3490
- await this.presentation.drain().catch(() => undefined);
3491
- await this.v2Transcript?.close();
3787
+ this.stopPromise = completion;
3788
+ try {
3789
+ this.interrupt({ clearQueue: true });
3790
+ } catch (error) {
3791
+ failures.push(error);
3792
+ }
3793
+ this.emitStateIfChanged();
3794
+ return completion;
3492
3795
  }
3493
3796
 
3494
3797
  // --- mode swap (catalog-affecting) -------------------------------------------
@@ -3642,7 +3945,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3642
3945
  if (!this.sessions) return;
3643
3946
  await this.sessions.record({
3644
3947
  agentSessionId: this.agentSessionId,
3645
- internalSessionId: this._internalSessionId,
3948
+ internalSessionId: this.lastRecordedInternalSessionId,
3646
3949
  adapter: this.adapterId,
3647
3950
  mode: this._mode,
3648
3951
  cwd: this._cwd,
@@ -3699,6 +4002,47 @@ export class AgentConversation implements AgentClient, Bridgeable {
3699
4002
  }
3700
4003
  }
3701
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
+
3702
4046
  /**
3703
4047
  * Apply a raw ACP `usage_update`.
3704
4048
  *