@qlairoslabs/acp-client 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG-consumer-fixes.md +55 -0
  2. package/CHANGELOG-operation-lifecycle.md +64 -0
  3. package/CONSUMER_GUIDE.md +287 -12
  4. package/MIGRATION-0.10-to-0.12.md +189 -0
  5. package/README.md +6 -3
  6. package/package.json +5 -2
  7. package/src/adapters.ts +3 -1
  8. package/src/agent/adoption/replay.ts +1 -0
  9. package/src/agent/config.ts +4 -0
  10. package/src/agent/conversation-manager.ts +178 -150
  11. package/src/agent/error-record-writer.ts +77 -0
  12. package/src/agent/persisted-lifecycle.ts +152 -35
  13. package/src/agent/record-capture.ts +18 -18
  14. package/src/agent-adapter-registry.ts +2 -0
  15. package/src/agent-client.ts +9 -3
  16. package/src/agent-conversation-contracts.ts +6 -0
  17. package/src/agent-conversation-owner.ts +31 -6
  18. package/src/agent-conversation-presentation.ts +12 -1
  19. package/src/agent-conversation-queue.ts +3 -2
  20. package/src/agent-session.ts +535 -94
  21. package/src/agent.ts +46 -23
  22. package/src/audit/config.ts +4 -0
  23. package/src/audit/projection.ts +3 -0
  24. package/src/checkpointing/recovery.ts +5 -0
  25. package/src/checkpointing/strategy.ts +2 -0
  26. package/src/client.ts +120 -30
  27. package/src/controller.ts +116 -7
  28. package/src/degraded/pty-client.ts +25 -1
  29. package/src/index.ts +17 -0
  30. package/src/internal-inference/config.ts +7 -0
  31. package/src/internal-inference/contracts.ts +3 -0
  32. package/src/internal-inference/coordination/handles.ts +11 -2
  33. package/src/internal-inference/coordination/manager.ts +20 -3
  34. package/src/internal-inference/index.ts +2 -0
  35. package/src/internal-inference/persistence/records.ts +3 -1
  36. package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
  37. package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
  38. package/src/internal-inference/runtime/harness-runtime.ts +19 -2
  39. package/src/media/acp.ts +118 -0
  40. package/src/media/capture.ts +15 -0
  41. package/src/media/content.ts +142 -0
  42. package/src/media/files.ts +28 -0
  43. package/src/media/parts.ts +145 -0
  44. package/src/media/pending.ts +51 -0
  45. package/src/media/redact.ts +14 -0
  46. package/src/media/store.ts +127 -0
  47. package/src/metering/provider.ts +8 -1
  48. package/src/operations/activity-tracker.ts +31 -0
  49. package/src/operations/contracts.ts +63 -0
  50. package/src/operations/errors.ts +31 -0
  51. package/src/operations/index.ts +6 -0
  52. package/src/operations/stale-policy.ts +51 -0
  53. package/src/operations/supervisor.ts +209 -0
  54. package/src/operations/timers.ts +12 -0
  55. package/src/out-of-band-messages.ts +49 -32
  56. package/src/persistence/audit-runtime.ts +14 -2
  57. package/src/persistence/backend.ts +108 -12
  58. package/src/persistence/error-records.ts +27 -0
  59. package/src/persistence/index.ts +8 -0
  60. package/src/persistence/presentation.ts +9 -1
  61. package/src/persistence/projection.ts +20 -0
  62. package/src/persistence/records.ts +45 -6
  63. package/src/persistence/sqlite-backend.ts +207 -16
  64. package/src/persistence/sqlite-conversation-records.ts +31 -4
  65. package/src/persistence/sqlite-files.ts +95 -0
  66. package/src/persistence/sqlite-media-store.ts +67 -0
  67. package/src/persistence/sqlite-schema.ts +86 -10
  68. package/src/persistence/state-runtime.ts +2 -0
  69. package/src/persistence/timeline-reconcile.ts +21 -4
  70. package/src/persistence/transcript-reader.ts +11 -4
  71. package/src/persistence/transcript-runtime.ts +105 -12
  72. package/src/repl/repl.ts +1 -1
  73. package/src/response.ts +40 -8
  74. package/src/steering/combine.ts +11 -4
  75. package/src/steering/contracts.ts +14 -4
  76. package/src/steering/controller.ts +96 -21
  77. package/src/steering/index.ts +1 -0
  78. package/src/transport/acp-transport.ts +18 -7
  79. package/src/types.ts +7 -0
  80. package/src/updates.ts +4 -4
@@ -9,6 +9,10 @@
9
9
  // Adapter ownership remains here during the compatibility tranche. The later Agent owner
10
10
  // supplies the adapter registry used by cross-adapter conversation transitions.
11
11
 
12
+ import { isMissingProviderSessionError } from "./checkpointing/recovery.ts";
13
+ import type { CancelOutcome, CancelReason, OperationLifecycleConfig } from "./operations/contracts.ts";
14
+ import { OperationStalledError } from "./operations/errors.ts";
15
+ import { OperationSupervisor } from "./operations/supervisor.ts";
12
16
  import {
13
17
  AgentController,
14
18
  type AgentControllerConfig,
@@ -135,6 +139,7 @@ import {
135
139
  AgentSessionPromptBlockedError,
136
140
  ContinuationUnavailableError,
137
141
  DirectAuditPersistenceUnsupportedError,
142
+ ProviderSessionError,
138
143
  } from "./agent-conversation-errors.ts";
139
144
  import type {
140
145
  AgentSessionEvent,
@@ -181,6 +186,43 @@ import {
181
186
  normalizeContinuationStrategies,
182
187
  stageOpeningContinuation,
183
188
  } from "./agent-conversation-continuation.ts";
189
+ import { attachmentParts } from "./media/acp.ts";
190
+ import {
191
+ partsText,
192
+ promptParts,
193
+ transcriptParts,
194
+ unresolvedParts,
195
+ type MessagePart,
196
+ type ResolvedPart,
197
+ } from "./media/parts.ts";
198
+ import { redactMedia } from "./media/redact.ts";
199
+
200
+ /** The text of an object-form prompt: its leading text plus its text parts. */
201
+ function promptInputText(input: { readonly text?: string; readonly parts?: readonly MessagePart[] }): string {
202
+ return partsText(promptParts(input) ?? [{ kind: "text", text: input.text ?? "" }]);
203
+ }
204
+
205
+ /** The older JSONL transcript has no media store: a message with parts keeps a line per part. */
206
+ function legacyTranscriptText(
207
+ text: string,
208
+ parts?: readonly MessagePart[],
209
+ attachments?: readonly Attachment[],
210
+ ): string {
211
+ if (!parts && !attachments?.length) return text;
212
+ return transcriptParts([...(parts ?? [{ kind: "text", text }]), ...attachmentParts(attachments)]);
213
+ }
214
+
215
+ /** The older JSONL transcript's view of response messages, with a line per media part. */
216
+ function legacyTranscriptMessages(messages: readonly ResponseMessage[], text: string) {
217
+ const messageText = (message: ResponseMessage) => (message.parts ? transcriptParts(message.parts) : message.text);
218
+ return {
219
+ text: messages.some((message) => message.parts) ? messages.map(messageText).join("\n\n") : text,
220
+ messages: messages.map((message) => ({
221
+ ...(message.messageId ? { messageId: message.messageId } : {}),
222
+ text: messageText(message),
223
+ })),
224
+ };
225
+ }
184
226
 
185
227
  export {
186
228
  AdapterMismatchError,
@@ -234,7 +276,8 @@ interface PromptQueueItem extends SteeringPrompt {
234
276
 
235
277
  /** Object-form prompt input for per-message consumer metadata on Agent-owned conversations. */
236
278
  export interface AgentConversationPromptInput {
237
- readonly text: string;
279
+ readonly text?: string;
280
+ readonly parts?: readonly MessagePart[];
238
281
  readonly consumerMetadata?: PersistenceJsonValue;
239
282
  readonly handlers?: PromptHandlers;
240
283
  readonly attachments?: Attachment[];
@@ -323,6 +366,8 @@ export interface AgentSessionConfig {
323
366
  /** @deprecated Use launcher and its exact spawnEnv. */
324
367
  env?: Record<string, string>;
325
368
  cwd?: string;
369
+ /** Additional absolute directories declared to the provider. */
370
+ additionalDirectories?: string[];
326
371
  /** Default MCP servers bound at session creation/switch, unless a call overrides them. */
327
372
  mcpServers?: schema.McpServer[];
328
373
  defaultPermission?: "approve" | "cancel";
@@ -370,6 +415,8 @@ export interface AgentSessionConfig {
370
415
  agentSessionId?: string;
371
416
  /** Provider-thread startup intent. Default `{ kind: "new" }`. */
372
417
  providerSession?: ProviderSession;
418
+ /** Stale limits per operation kind (turns, internal inference, recap). */
419
+ operationLifecycle?: OperationLifecycleConfig;
373
420
  /**
374
421
  * Token/cost metering policy. Optional: omitting it selects best-effort enforcement
375
422
  * with the pinned models.dev catalog and no restored state. Metering is not something a
@@ -492,6 +539,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
492
539
  private _title?: string;
493
540
  private readonly openBootstrap: AgentSessionOpenBootstrap | null;
494
541
  private continuationAcquired = true;
542
+ /** The continuation strategies the conversation was opened with; reconnect applies the same list. */
543
+ private continuationStrategies: readonly ContinuationStrategy[] = [{ kind: "load_internal_session" }];
544
+ /**
545
+ * What the conversation does when its provider session cannot be loaded and it has no transcript
546
+ * persistence (`providerSession.onFailure`).
547
+ */
548
+ private sessionLoadFailure: "error" | "new" = "new";
495
549
  private _recovery: SessionRecoveryStatus = { kind: "clean" };
496
550
  private _configurationRestore: ConfigurationRestoreStatus = { kind: "matched" };
497
551
  private readonly managedCreation: ManagedAgentSessionCreationBootstrap | null;
@@ -499,6 +553,21 @@ export class AgentConversation implements AgentClient, Bridgeable {
499
553
  private managedAuditLog: AuditLogIdentity | null = null;
500
554
  private readonly managedOpenProgress?: ManagedOpenProgressReporter;
501
555
  private managedInitializationReported = false;
556
+ private readonly operationLifecycle: OperationLifecycleConfig;
557
+ private reconnecting = false;
558
+ private detachControllerConnection: (() => void) | null = null;
559
+ private activeSupervisor: OperationSupervisor | null = null;
560
+ /**
561
+ * The operation now running, so records written during it (protocol lines) carry its id: the
562
+ * queued item, or an internal prompt while it runs. Internal prompts run inside a queued item or
563
+ * while the conversation opens, never beside a queued item, so one field is enough.
564
+ */
565
+ private runningOperationId: string | null = null;
566
+ /**
567
+ * The last consumer turn whose provider request itself failed (stalled, crashed, errored). Only
568
+ * such a turn holds the queue.
569
+ */
570
+ private providerFailedTurnId: string | null = null;
502
571
  private readonly ownerLifecycle?: AgentConversationOwnerLifecycle;
503
572
  private _participants: ParticipantRef[];
504
573
  private ownerRecordWrite: Promise<void> = Promise.resolve();
@@ -551,13 +620,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
551
620
  this.agentConversationId = config.agentConversationId ?? createAgentConversationId();
552
621
  this.ownerAgentSessionId = config.ownerAgentSessionId
553
622
  ?? (isAgentSessionId(this.agentSessionId) ? this.agentSessionId : null);
623
+ this.operationLifecycle = config.operationLifecycle ?? {};
554
624
  this.ownerLifecycle = config.ownerLifecycle;
555
625
  this.defaultPermission = config.defaultPermission ?? "cancel";
556
626
  this.steering = new SteeringController<QueueItem>(
557
627
  {
558
628
  queue: this.operations,
559
629
  emit: (event) => this.emit(event),
560
- cancelProviderTurn: () => this.controller.interrupt(),
630
+ cancelProviderTurn: () => this.cancelOperation("steer"),
561
631
  emitState: () => this.emitStateIfChanged(),
562
632
  },
563
633
  config.busyDelivery ?? "steer",
@@ -620,10 +690,12 @@ export class AgentConversation implements AgentClient, Bridgeable {
620
690
  createdActiveThread: providerSession.kind === "new",
621
691
  });
622
692
  this.controllerDefaults = {
693
+ operationLifecycle: this.operationLifecycle,
623
694
  launcher: config.launcher,
624
695
  execPrefix: config.execPrefix,
625
696
  env: config.env,
626
697
  cwd: config.cwd,
698
+ additionalDirectories: config.additionalDirectories,
627
699
  mcpServers: config.mcpServers,
628
700
  defaultPermission: config.defaultPermission,
629
701
  clientInfo: config.clientInfo,
@@ -639,6 +711,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
639
711
  }
640
712
  : {}),
641
713
  };
714
+ if (providerSession.kind === "load") this.sessionLoadFailure = providerSession.onFailure ?? "error";
642
715
  this.controller = this.createController(config.adapter, config.adapterId, this._mode, {
643
716
  sessionId: requestedInternalSessionId,
644
717
  sessionLoadFailure: providerSession.kind === "load"
@@ -667,6 +740,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
667
740
  }
668
741
 
669
742
  private bindController(controller: AgentController): void {
743
+ this.detachControllerConnection?.();
744
+ this.detachControllerConnection = controller.subscribeConnection(() => this.emitStateIfChanged());
670
745
  this.detachControllerCommands?.();
671
746
  this.detachControllerUsage?.();
672
747
  this.detachControllerCommands = controller.subscribeAvailableCommands((commands) => {
@@ -679,10 +754,10 @@ export class AgentConversation implements AgentClient, Bridgeable {
679
754
  });
680
755
  }
681
756
 
682
- private queueOwnedRecord(record: NewConversationRecord): void {
757
+ private queueOwnedRecord(record: NewConversationRecord, parts?: readonly ResolvedPart[]): void {
683
758
  if (!this.ownerLifecycle?.record) return;
684
759
  this.ownerRecordWrite = this.ownerRecordWrite
685
- .then(() => this.ownerLifecycle!.record!(record))
760
+ .then(() => this.ownerLifecycle!.record!(record, parts))
686
761
  .catch((error) => {
687
762
  this.markManagedPersistenceUnhealthy();
688
763
  throw error;
@@ -711,7 +786,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
711
786
  if (!this.ownerAgentSessionId || !this.ownerLifecycle?.record) return;
712
787
  let message: PersistenceJsonValue;
713
788
  try {
714
- message = JSON.parse(entry.line) as PersistenceJsonValue;
789
+ message = redactMedia(JSON.parse(entry.line)) as PersistenceJsonValue;
715
790
  } catch {
716
791
  message = entry.line;
717
792
  }
@@ -721,6 +796,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
721
796
  agentConversationId: this.agentConversationId,
722
797
  kind: "protocol",
723
798
  timestamp: new Date(entry.ts).toISOString(),
799
+ ...(this.runningOperationId ? { operationId: this.runningOperationId } : {}),
724
800
  direction: entry.dir === "err" ? "error" : entry.dir,
725
801
  ...(protocolMethod(message) ? { method: protocolMethod(message)! } : {}),
726
802
  message,
@@ -736,7 +812,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
736
812
  turnId,
737
813
  record,
738
814
  );
739
- if (runtimeRecord) this.queueOwnedRecord(runtimeRecord);
815
+ if (runtimeRecord) this.queueOwnedRecord({ ...runtimeRecord, operationId: turnId });
740
816
  }
741
817
  }
742
818
 
@@ -753,6 +829,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
753
829
  agentConversationId: this.agentConversationId,
754
830
  kind: "native_action",
755
831
  timestamp: new Date().toISOString(),
832
+ operationId: transitionId,
756
833
  action,
757
834
  transitionId,
758
835
  state,
@@ -1229,13 +1306,35 @@ export class AgentConversation implements AgentClient, Bridgeable {
1229
1306
  this.v2Transcript = this.openBootstrap.transcript;
1230
1307
  this.v2TranscriptPath = this.openBootstrap.transcriptPath;
1231
1308
  this._recovery = this.v2Transcript.recovery;
1309
+ this.continuationStrategies = strategies;
1310
+ return await this.acquireContinuation(checkpoint, strategies);
1311
+ }
1312
+
1313
+ /**
1314
+ * Walk the continuation strategies in order: at open, and again after a crash when the provider no
1315
+ * longer has the session (`failedLoad`, then only the reconstruction strategies are passed).
1316
+ */
1317
+ private async acquireContinuation(
1318
+ checkpoint: AgentSessionCheckpoint,
1319
+ strategies: readonly ContinuationStrategy[],
1320
+ failedLoad?: unknown,
1321
+ ): Promise<ContinuationReport> {
1322
+ if (!this.v2Transcript) throw new Error("continuation requires transcript persistence");
1232
1323
  this.continuationAcquired = false;
1233
1324
 
1234
- const attempts: ContinuationAttempt[] = [];
1235
- let recordedThreadAvailability: ContinuationReport["recordedThreadAvailability"] = "not_checked";
1325
+ const attempts: ContinuationAttempt[] = failedLoad === undefined ? [] : [Object.freeze({
1326
+ strategy: "load_internal_session" as const,
1327
+ status: "failed" as const,
1328
+ errorCode: "internal_session_unavailable" as const,
1329
+ reason: String(failedLoad),
1330
+ })];
1331
+ let recordedThreadAvailability: ContinuationReport["recordedThreadAvailability"] = failedLoad === undefined
1332
+ ? "not_checked"
1333
+ : "unavailable";
1236
1334
 
1237
1335
  for (const strategy of strategies) {
1238
1336
  if (strategy.kind === "load_internal_session") {
1337
+ if (!this.openBootstrap) throw new Error("loading the recorded session is an opening strategy");
1239
1338
  if (!checkpoint.internalSessionId) {
1240
1339
  attempts.push(Object.freeze({
1241
1340
  strategy: strategy.kind,
@@ -1310,11 +1409,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
1310
1409
  let continuation: string;
1311
1410
  const source = strategy.kind === "new_from_transcript" ? "transcript" as const : "consumer" as const;
1312
1411
  try {
1412
+ if (strategy.kind === "new_from_transcript" && !this.v2TranscriptPath) {
1413
+ throw new Error("no transcript to build from");
1414
+ }
1313
1415
  continuation = strategy.kind === "new_from_transcript"
1314
1416
  ? (await strategy.buildContinuation(Object.freeze({
1315
1417
  agentSessionId: this.agentSessionId,
1316
1418
  checkpoint: structuredClone(checkpoint),
1317
- transcript: new TranscriptReader(this.openBootstrap.transcriptPath),
1419
+ transcript: new TranscriptReader(this.v2TranscriptPath!),
1318
1420
  targetAdapterId: this.adapterId,
1319
1421
  }))).continuation
1320
1422
  : strategy.continuation;
@@ -1764,6 +1866,11 @@ export class AgentConversation implements AgentClient, Bridgeable {
1764
1866
  /** Immutable current state. Late subscribers read this before listening for deltas. */
1765
1867
  get state(): AgentSessionState {
1766
1868
  return Object.freeze({
1869
+ pendingHold: this.steering.hold,
1870
+ operation: this.activeSupervisor?.activity ?? null,
1871
+ providerConnection: this.reconnecting
1872
+ ? "reconnecting"
1873
+ : this.controller.isConnected ? "connected" : "disconnected",
1767
1874
  phase: this.phase,
1768
1875
  isBusy: this.isBusy,
1769
1876
  queuedOperationCount: this.queuedOperationCount,
@@ -1806,8 +1913,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
1806
1913
  return typeof input === "string"
1807
1914
  ? this.enqueuePrompt(input, "prompt", handlers, attachments)
1808
1915
  : this.enqueuePrompt(
1809
- input.text, "prompt", input.handlers, input.attachments,
1810
- undefined, input.consumerMetadata, input.delivery,
1916
+ promptInputText(input), "prompt", input.handlers, input.attachments,
1917
+ undefined, input.consumerMetadata, input.delivery, promptParts(input),
1811
1918
  );
1812
1919
  }
1813
1920
 
@@ -1838,8 +1945,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
1838
1945
  if (typeof input !== "string") {
1839
1946
  if (!input.participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
1840
1947
  return this.enqueuePrompt(
1841
- input.text, "prompt", input.handlers, input.attachments,
1842
- input.participantId.trim(), input.consumerMetadata, input.delivery,
1948
+ promptInputText(input), "prompt", input.handlers, input.attachments,
1949
+ input.participantId.trim(), input.consumerMetadata, input.delivery, promptParts(input),
1843
1950
  );
1844
1951
  }
1845
1952
  const participantId = input;
@@ -1861,6 +1968,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1861
1968
  participantId?: string,
1862
1969
  consumerMetadata?: PersistenceJsonValue,
1863
1970
  delivery?: PromptDelivery,
1971
+ messageParts?: readonly MessagePart[],
1864
1972
  ): PromptHandle {
1865
1973
  const id = this.mintTurnId();
1866
1974
  const promise = new Promise<AgentSessionPromptResult>((resolve, reject) => {
@@ -1896,6 +2004,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1896
2004
  ...(stableConsumerMetadata !== undefined ? { consumerMetadata: stableConsumerMetadata } : {}),
1897
2005
  handlers,
1898
2006
  attachments,
2007
+ messageParts,
1899
2008
  resolve,
1900
2009
  reject,
1901
2010
  };
@@ -2016,6 +2125,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2016
2125
  agentConversationId: this.agentConversationId,
2017
2126
  kind: "message",
2018
2127
  timestamp: new Date().toISOString(),
2128
+ operationId: turnId,
2019
2129
  role: "user",
2020
2130
  ...(user ? { participantId: user.id } : {}),
2021
2131
  content: item.text,
@@ -2030,6 +2140,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2030
2140
  agentConversationId: this.agentConversationId,
2031
2141
  kind: "message",
2032
2142
  timestamp: new Date().toISOString(),
2143
+ operationId: turnId,
2033
2144
  role: "assistant",
2034
2145
  logicalMessageId: `message:${turnId}:assistant:${assistants}`,
2035
2146
  content: item.text,
@@ -2080,6 +2191,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2080
2191
  agentConversationId: this.agentConversationId,
2081
2192
  kind: "message",
2082
2193
  timestamp: new Date().toISOString(),
2194
+ operationId: recapId,
2083
2195
  role: "assistant",
2084
2196
  logicalMessageId: `message:${recapId}:assistant:1`,
2085
2197
  content: summary,
@@ -2152,13 +2264,24 @@ export class AgentConversation implements AgentClient, Bridgeable {
2152
2264
  ? "recovering"
2153
2265
  : "switching_mode";
2154
2266
  this.emitStateIfChanged();
2267
+ this.runningOperationId = item.kind === "prompt" ? item.turnId
2268
+ : item.kind === "handoff" ? item.handoffId
2269
+ : item.kind === "set_config" ? item.operationId
2270
+ : item.kind === "set_mode" ? item.transitionId
2271
+ : null;
2155
2272
  if (item.kind === "prompt") {
2156
2273
  // A run of steer messages at the head of the queue goes out as one prompt.
2157
- const prompt = this.steering.prepareRun(item) as PromptQueueItem;
2274
+ let reportDelivery: (() => void) | undefined;
2275
+ const prompt = this.steering.prepareRun(item, (event) => {
2276
+ reportDelivery = () => this.emit(event);
2277
+ }) as PromptQueueItem;
2278
+ this.runningOperationId = prompt.turnId;
2158
2279
  this.steering.turnStarted(prompt);
2159
2280
  this.emit({ kind: "turn_started", turnId: prompt.turnId });
2160
2281
  let stopReason: string | undefined;
2161
2282
  try {
2283
+ await this.ensureProvider();
2284
+ reportDelivery?.();
2162
2285
  const result = await this.runPrompt(prompt);
2163
2286
  stopReason = result.stopReason;
2164
2287
  this.emit({
@@ -2168,10 +2291,20 @@ export class AgentConversation implements AgentClient, Bridgeable {
2168
2291
  });
2169
2292
  prompt.resolve(result);
2170
2293
  } catch (err) {
2294
+ // A prompt that never reached the provider (blocked, rejected, no provider) holds nothing.
2295
+ const failure = err instanceof OperationStalledError ? "stalled" : "error";
2296
+ const providerFailed = this.providerFailedTurnId === prompt.turnId;
2297
+ stopReason = providerFailed ? failure : undefined;
2298
+ if (providerFailed) this.steering.failed(prompt.turnId, failure);
2299
+ if (err instanceof OperationStalledError) {
2300
+ const following = this.steering.followingSteers();
2301
+ if (following.length) err.followedBy = following;
2302
+ }
2171
2303
  this.emit({ kind: "turn_failed", turnId: prompt.turnId, error: String(err) });
2172
2304
  prompt.reject(err);
2173
2305
  } finally {
2174
2306
  this.steering.turnEnded(stopReason);
2307
+ this.providerFailedTurnId = null;
2175
2308
  }
2176
2309
  } else if (item.kind === "handoff") {
2177
2310
  try {
@@ -2180,56 +2313,69 @@ export class AgentConversation implements AgentClient, Bridgeable {
2180
2313
  item.reject(err);
2181
2314
  }
2182
2315
  } else if (item.kind === "set_config") {
2183
- this.emit({ kind: "configuration_started", operationId: item.operationId, configId: item.configId });
2184
- try {
2185
- if (this.ownerAgentSessionId) {
2186
- await this.recordOwned({
2187
- recordId: `${item.operationId}:configuration:started`,
2188
- agentSessionId: this.ownerAgentSessionId,
2189
- agentConversationId: this.agentConversationId,
2190
- kind: "configuration",
2191
- timestamp: new Date().toISOString(),
2192
- operation: "set",
2193
- configId: item.configId,
2194
- value: toPersistenceJsonValue(item.value),
2195
- status: "started",
2196
- });
2197
- }
2198
- await this.runSetConfig(item);
2199
- if (this.ownerAgentSessionId) {
2200
- await this.recordOwned({
2201
- recordId: `${item.operationId}:configuration:completed`,
2202
- agentSessionId: this.ownerAgentSessionId,
2203
- agentConversationId: this.agentConversationId,
2204
- kind: "configuration",
2205
- timestamp: new Date().toISOString(),
2206
- operation: "set",
2207
- configId: item.configId,
2208
- value: toPersistenceJsonValue(item.value),
2209
- status: "completed",
2210
- });
2211
- }
2212
- this.emit({ kind: "configuration_completed", operationId: item.operationId, configId: item.configId });
2316
+ // One connection attempt: a failure is reported by the normal path below, not retried by it.
2317
+ const connectError = await this.ensureProvider().then(
2318
+ () => null,
2319
+ (error: unknown) => error ?? new Error("provider connection failed"),
2320
+ );
2321
+ if (connectError === null && this.isUnchangedSelection(item)) {
2213
2322
  item.resolve();
2214
- } catch (err) {
2215
- if (this.ownerAgentSessionId) {
2216
- await this.recordOwned({
2217
- recordId: `${item.operationId}:configuration:failed`,
2218
- agentSessionId: this.ownerAgentSessionId,
2219
- agentConversationId: this.agentConversationId,
2220
- kind: "configuration",
2221
- timestamp: new Date().toISOString(),
2222
- operation: "set",
2223
- configId: item.configId,
2224
- value: toPersistenceJsonValue(item.value),
2225
- status: "failed",
2226
- error: String(err),
2227
- }).catch((persistenceError) => this.log.warn("configuration_failure_persistence_failed", {
2228
- error: String(persistenceError),
2229
- }));
2323
+ } else {
2324
+ this.emit({ kind: "configuration_started", operationId: item.operationId, configId: item.configId });
2325
+ try {
2326
+ if (this.ownerAgentSessionId) {
2327
+ await this.recordOwned({
2328
+ recordId: `${item.operationId}:configuration:started`,
2329
+ agentSessionId: this.ownerAgentSessionId,
2330
+ agentConversationId: this.agentConversationId,
2331
+ kind: "configuration",
2332
+ timestamp: new Date().toISOString(),
2333
+ operationId: item.operationId,
2334
+ operation: "set",
2335
+ configId: item.configId,
2336
+ value: toPersistenceJsonValue(item.value),
2337
+ status: "started",
2338
+ });
2339
+ }
2340
+ if (connectError !== null) throw connectError;
2341
+ await this.runSetConfig(item);
2342
+ if (this.ownerAgentSessionId) {
2343
+ await this.recordOwned({
2344
+ recordId: `${item.operationId}:configuration:completed`,
2345
+ agentSessionId: this.ownerAgentSessionId,
2346
+ agentConversationId: this.agentConversationId,
2347
+ kind: "configuration",
2348
+ timestamp: new Date().toISOString(),
2349
+ operationId: item.operationId,
2350
+ operation: "set",
2351
+ configId: item.configId,
2352
+ value: toPersistenceJsonValue(item.value),
2353
+ status: "completed",
2354
+ });
2355
+ }
2356
+ this.emit({ kind: "configuration_completed", operationId: item.operationId, configId: item.configId });
2357
+ item.resolve();
2358
+ } catch (err) {
2359
+ if (this.ownerAgentSessionId) {
2360
+ await this.recordOwned({
2361
+ recordId: `${item.operationId}:configuration:failed`,
2362
+ agentSessionId: this.ownerAgentSessionId,
2363
+ agentConversationId: this.agentConversationId,
2364
+ kind: "configuration",
2365
+ timestamp: new Date().toISOString(),
2366
+ operationId: item.operationId,
2367
+ operation: "set",
2368
+ configId: item.configId,
2369
+ value: toPersistenceJsonValue(item.value),
2370
+ status: "failed",
2371
+ error: String(err),
2372
+ }).catch((persistenceError) => this.log.warn("configuration_failure_persistence_failed", {
2373
+ error: String(persistenceError),
2374
+ }));
2375
+ }
2376
+ this.emit({ kind: "configuration_failed", operationId: item.operationId, configId: item.configId, error: String(err) });
2377
+ item.reject(err);
2230
2378
  }
2231
- this.emit({ kind: "configuration_failed", operationId: item.operationId, configId: item.configId, error: String(err) });
2232
- item.reject(err);
2233
2379
  }
2234
2380
  } else if (item.kind === "resolve_config") {
2235
2381
  try {
@@ -2270,26 +2416,29 @@ export class AgentConversation implements AgentClient, Bridgeable {
2270
2416
  item.reject(err);
2271
2417
  }
2272
2418
  }
2419
+ this.runningOperationId = null;
2273
2420
  // Promise consumers must observe the settled public state. The old in-class
2274
2421
  // loop reached its `finally` synchronously after resolving the last item;
2275
2422
  // crossing the extracted queue's async callback adds a microtask boundary.
2276
2423
  // Settle here only when no next item exists, preserving both that ordering and
2277
2424
  // the no-idle-gap guarantee between queued operations.
2278
2425
  this.settleIdleIfDrained();
2279
- });
2426
+ }, () => this.steering.takeNext());
2280
2427
  } finally {
2428
+ this.runningOperationId = null;
2281
2429
  if (this.phase !== "stopped") this.phase = "idle";
2282
2430
  this.emitStateIfChanged();
2283
2431
  }
2284
2432
  }
2285
2433
 
2286
2434
  private settleIdleIfDrained(): void {
2287
- if (this.operations.queuedCount !== 0 || this.phase === "stopped") return;
2435
+ if (this.steering.hasRunnable || this.phase === "stopped") return;
2288
2436
  this.phase = "idle";
2289
2437
  this.emitStateIfChanged();
2290
2438
  }
2291
2439
 
2292
2440
  private async runHandoff(item: HandoffQueueItem): Promise<HandoffResult> {
2441
+ await this.ensureProvider();
2293
2442
  const fromInternalSessionId = this._internalSessionId;
2294
2443
  const fromAdapterId = this.adapterId;
2295
2444
  const targetAdapterId = item.options.target?.adapterId ?? fromAdapterId;
@@ -2695,7 +2844,24 @@ export class AgentConversation implements AgentClient, Bridgeable {
2695
2844
  }
2696
2845
  }
2697
2846
 
2847
+ /**
2848
+ * A selection that changes nothing is not applied or recorded: the harness already reports the
2849
+ * value, and (with a transcript) it is already the explicit restoration target. Consumers that
2850
+ * re-apply settings on every start would otherwise record a change each time. Any doubt returns
2851
+ * false so the normal path runs and reports it. The caller connects first.
2852
+ */
2853
+ private isUnchangedSelection(item: ConfigQueueItem): boolean {
2854
+ const option = this.controller.configOptions.get(item.configId);
2855
+ if (!option || !sameJsonValue(item.value, option.currentValue as JsonValue)) return false;
2856
+ if (!this.v2Transcript || this.persistence === false) return true;
2857
+ return this.v2Transcript.checkpoint.sessionConfiguration.restorationTargets.some((target) =>
2858
+ target.configId === item.configId
2859
+ && target.source === "explicit_selection"
2860
+ && sameJsonValue(item.value, target.value));
2861
+ }
2862
+
2698
2863
  private async runSetConfig(item: ConfigQueueItem): Promise<void> {
2864
+ await this.ensureProvider();
2699
2865
  if (!this.v2Transcript || this.persistence === false) {
2700
2866
  await this.controller.setConfig(item.configId, item.value);
2701
2867
  return;
@@ -3050,6 +3216,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3050
3216
  }
3051
3217
 
3052
3218
  private async runSetMode(item: ModeQueueItem): Promise<ConnectResult> {
3219
+ await this.ensureProvider();
3053
3220
  if (item.mode === this._mode) return await this.controller.setMode(item.mode);
3054
3221
  if (!this.v2Transcript) {
3055
3222
  const result = await this.controller.setMode(item.mode);
@@ -3181,6 +3348,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
3181
3348
  ...(item.consumerMetadata !== undefined ? { consumerMetadata: item.consumerMetadata } : {}),
3182
3349
  ...(item.parts ? { parts: item.parts } : {}),
3183
3350
  text: item.text,
3351
+ messageParts: item.messageParts,
3352
+ attachments: item.attachments,
3353
+ mediaContext: {
3354
+ cwd: this.controllerDefaults.cwd ?? process.cwd(),
3355
+ ...(this.controller.isDegraded
3356
+ ? { degraded: true }
3357
+ : { capabilities: this.controller.capabilities.agent.promptCapabilities }),
3358
+ },
3184
3359
  })
3185
3360
  : undefined;
3186
3361
  for (const participant of owned?.participants ?? (owned?.participant ? [owned.participant] : [])) {
@@ -3188,7 +3363,6 @@ export class AgentConversation implements AgentClient, Bridgeable {
3188
3363
  this._participants = [...this._participants, Object.freeze({ ...participant })];
3189
3364
  }
3190
3365
  }
3191
- const providerText = owned?.providerText ?? item.text;
3192
3366
  this.beginTurn(item.turnId);
3193
3367
  let operation: OpenOperation;
3194
3368
  if (this.v2Transcript) {
@@ -3200,7 +3374,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
3200
3374
  await this.v2Transcript.beginOperation(item.turnId, persistenceOperationKind(item.operationKind));
3201
3375
  transcriptStarted = true;
3202
3376
  // A combined prompt shows each original message, as it was sent.
3203
- const userTexts = item.parts ? item.parts.map((part) => part.text) : [item.text];
3377
+ const userTexts = item.parts
3378
+ ? item.parts.map((part) => legacyTranscriptText(part.text, part.messageParts, part.attachments))
3379
+ : [legacyTranscriptText(item.text, item.messageParts, item.attachments)];
3204
3380
  const userRecords = [];
3205
3381
  for (const [index, text] of userTexts.entries()) {
3206
3382
  userRecords.push(await this.v2Transcript.appendPresentationEvent({
@@ -3228,7 +3404,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3228
3404
  v: 1,
3229
3405
  t: "msg",
3230
3406
  role: "user",
3231
- text: item.text,
3407
+ text: legacyTranscriptText(item.text, item.messageParts, item.attachments),
3232
3408
  ts: Date.now(),
3233
3409
  });
3234
3410
  operation = await this.openMeteredOperation(item);
@@ -3241,6 +3417,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3241
3417
  readonly id: string;
3242
3418
  providerMessageId?: string;
3243
3419
  text: string;
3420
+ parts?: readonly ResolvedPart[];
3244
3421
  revision: number;
3245
3422
  dirty: boolean;
3246
3423
  } | null = null;
@@ -3255,36 +3432,44 @@ export class AgentConversation implements AgentClient, Bridgeable {
3255
3432
  };
3256
3433
  return assistantMessage;
3257
3434
  };
3435
+ // When each message that ended before the turn did received its last text, in order. The
3436
+ // turn's commit records those messages as completed at these times; only the last message
3437
+ // takes the turn's own outcome.
3438
+ const messageEnds: string[] = [];
3258
3439
  const flushAssistantMessage = (
3259
3440
  status: "in_progress" | "completed" | "cancelled" | "error",
3260
3441
  stopReason?: string,
3261
3442
  force = false,
3443
+ ended = false,
3262
3444
  ) => {
3263
3445
  if ((!this.v2Transcript && !this.ownerLifecycle) || !assistantMessage
3264
3446
  || (!assistantMessage.dirty && !force)) return;
3265
3447
  assistantMessage.revision++;
3266
3448
  assistantMessage.dirty = false;
3267
3449
  const message = assistantMessage;
3268
- if (this.ownerAgentSessionId && status === "in_progress") {
3450
+ const timestamp = new Date().toISOString();
3451
+ if (ended) messageEnds.push(timestamp);
3452
+ if (this.ownerAgentSessionId && (status === "in_progress" || ended)) {
3269
3453
  this.queueOwnedRecord({
3270
3454
  recordId: `${message.id}:snapshot:${message.revision}`,
3271
3455
  agentSessionId: this.ownerAgentSessionId,
3272
3456
  agentConversationId: this.agentConversationId,
3273
3457
  kind: "message",
3274
- timestamp: new Date().toISOString(),
3458
+ timestamp,
3459
+ operationId: item.turnId,
3275
3460
  role: "assistant",
3276
3461
  logicalMessageId: message.id,
3277
3462
  content: message.text,
3278
- status,
3463
+ status: ended ? "completed" : "in_progress",
3279
3464
  metadata: JSON.stringify({ operationId: item.turnId,
3280
3465
  ...(message.providerMessageId ? { providerMessageId: message.providerMessageId } : {}) }),
3281
- });
3466
+ }, message.parts);
3282
3467
  }
3283
3468
  if (this.v2Transcript) this.presentation.queuePresentation({
3284
3469
  kind: "message",
3285
3470
  operationId: item.turnId,
3286
3471
  role: "assistant",
3287
- text: message.text,
3472
+ text: message.parts ? transcriptParts(message.parts) : message.text,
3288
3473
  ...(message.providerMessageId === undefined ? {} : { providerMessageId: message.providerMessageId }),
3289
3474
  structured: {
3290
3475
  version: 1,
@@ -3297,6 +3482,12 @@ export class AgentConversation implements AgentClient, Bridgeable {
3297
3482
  presentation: { id: message.id, revision: message.revision },
3298
3483
  });
3299
3484
  };
3485
+ // A message receives no more text once the next message or a tool call begins. Record it
3486
+ // completed then, rather than leaving it open until the turn ends.
3487
+ const endAssistantMessage = () => {
3488
+ flushAssistantMessage("completed", undefined, true, true);
3489
+ assistantMessage = null;
3490
+ };
3300
3491
  const wrappedHandlers: PromptHandlers = {
3301
3492
  ...item.handlers,
3302
3493
  // Fired from here, from the one aggregator this session owns — nothing below needs
@@ -3315,7 +3506,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3315
3506
  response.append(chunk);
3316
3507
  if (this.v2Transcript || this.ownerLifecycle) {
3317
3508
  if (chunk.startsMessage) {
3318
- flushAssistantMessage("completed", undefined, assistantMessage !== null);
3509
+ endAssistantMessage();
3319
3510
  beginAssistantMessage(chunk.messageId);
3320
3511
  }
3321
3512
  const current = assistantMessage ?? beginAssistantMessage(chunk.messageId);
@@ -3323,6 +3514,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3323
3514
  current.providerMessageId = chunk.messageId;
3324
3515
  }
3325
3516
  current.text += chunk.text;
3517
+ current.parts = response.currentParts();
3326
3518
  current.dirty = true;
3327
3519
  // Persist the first usable snapshot. Later token chunks remain in memory until
3328
3520
  // an interleaving item, a new message, or the operation boundary.
@@ -3333,14 +3525,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
3333
3525
  onActivity: (event) => {
3334
3526
  // The message snapshot must enter the shared queue before an activity first seen
3335
3527
  // after it. Later activity revisions keep their original presentation position.
3336
- flushAssistantMessage("in_progress");
3337
- this.steering.observeActivity(item.turnId, event);
3528
+ if (event.kind === "tool") endAssistantMessage();
3529
+ else flushAssistantMessage("in_progress");
3530
+ if (!this.activeSupervisor) this.steering.observeActivity(item.turnId, event);
3338
3531
  const result = this.presentation.applyActivity(event);
3339
3532
  this.queueActivityRecords(item.turnId, result.emitted);
3340
3533
  item.handlers?.onRecord?.(result);
3341
3534
  item.handlers?.onActivity?.(event);
3342
3535
  },
3343
- onPermissionRequest: async (request) => {
3536
+ onPermissionRequest: async (request, signal) => {
3344
3537
  const permissionBase = `${item.turnId}:permission:${request.toolCallId}`;
3345
3538
  if (this.ownerAgentSessionId) {
3346
3539
  await this.recordOwned({
@@ -3349,6 +3542,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3349
3542
  agentConversationId: this.agentConversationId,
3350
3543
  kind: "permission",
3351
3544
  timestamp: new Date().toISOString(),
3545
+ operationId: item.turnId,
3352
3546
  permissionId: request.toolCallId,
3353
3547
  state: "requested",
3354
3548
  request: toPersistenceJsonValue({
@@ -3360,7 +3554,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3360
3554
  });
3361
3555
  }
3362
3556
  const outcome = item.handlers?.onPermissionRequest
3363
- ? await item.handlers.onPermissionRequest(request)
3557
+ ? await permissionWithAbort(() => item.handlers!.onPermissionRequest!(request, signal), signal)
3364
3558
  : defaultPermissionOutcome(request, this.defaultPermission);
3365
3559
  if (this.ownerAgentSessionId) {
3366
3560
  await this.recordOwned({
@@ -3369,6 +3563,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3369
3563
  agentConversationId: this.agentConversationId,
3370
3564
  kind: "permission",
3371
3565
  timestamp: new Date().toISOString(),
3566
+ operationId: item.turnId,
3372
3567
  permissionId: request.toolCallId,
3373
3568
  state: "resolved",
3374
3569
  outcome: permissionRecordOutcome(request, outcome),
@@ -3385,7 +3580,18 @@ export class AgentConversation implements AgentClient, Bridgeable {
3385
3580
  // closest observable acquisition time when `session/new` happens inside `prompt()`.
3386
3581
  const dispatchedAt = new Date().toISOString();
3387
3582
  try {
3388
- const res = await this.controller.prompt(providerText, wrappedHandlers, item.attachments);
3583
+ let res = await this.supervisedPrompt(this.controller, item.turnId, "turn",
3584
+ // An owned conversation already resolved the parts and wrapped them with the provider-only
3585
+ // text (identity, out-of-band messages); otherwise the client resolves them.
3586
+ () => this.controller.prompt(owned?.providerParts
3587
+ ? { parts: unresolvedParts(owned.providerParts), handlers: wrappedHandlers }
3588
+ : item.messageParts
3589
+ ? { parts: item.messageParts, attachments: item.attachments, handlers: wrappedHandlers }
3590
+ : { text: item.text, attachments: item.attachments, handlers: wrappedHandlers }));
3591
+ if (res.cancel === "forced") {
3592
+ const messages = response.snapshot();
3593
+ res = { ...res, messages, text: response.text || chunks.join("") };
3594
+ }
3389
3595
  providerSettled = true;
3390
3596
  if (this.v2Transcript) {
3391
3597
  if (assistantOrdinal === 0) {
@@ -3451,8 +3657,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3451
3657
  v: 1,
3452
3658
  t: "msg",
3453
3659
  role: "assistant",
3454
- text: res.text,
3455
- messages: res.messages,
3660
+ ...legacyTranscriptMessages(res.messages, res.text),
3456
3661
  ts: Date.now(),
3457
3662
  usage: res.usage,
3458
3663
  stopReason: res.stopReason,
@@ -3478,6 +3683,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3478
3683
  ...(item.participantId ? { participantId: item.participantId } : {}),
3479
3684
  text: item.text,
3480
3685
  result,
3686
+ messageEnds,
3481
3687
  providerAttachment: this.providerAttachment,
3482
3688
  };
3483
3689
  try {
@@ -3525,6 +3731,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3525
3731
  ...(item.participantId ? { participantId: item.participantId } : {}),
3526
3732
  text: item.text,
3527
3733
  messages,
3734
+ messageEnds,
3528
3735
  error: err,
3529
3736
  }).catch((persistenceError) => {
3530
3737
  this.log.warn("owned_prompt_failure_persistence_failed", { error: String(persistenceError) });
@@ -3550,8 +3757,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3550
3757
  v: 1,
3551
3758
  t: "msg",
3552
3759
  role: "assistant",
3553
- text,
3554
- messages,
3760
+ ...legacyTranscriptMessages(messages, text),
3555
3761
  ts: Date.now(),
3556
3762
  stopReason: "error",
3557
3763
  status: "error",
@@ -3561,13 +3767,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
3561
3767
  // the rejection rather than only reaching event subscribers.
3562
3768
  // Already metered: the failure happened after the operation closed (a transcript or
3563
3769
  // catalog write), so the record stands and must not be minted a second time.
3564
- const record = closed ?? (await this.closeOperation(operation, "error", null, String(err)));
3770
+ const outcome = err instanceof OperationStalledError ? "cancelled" : "error";
3771
+ const record = closed ?? (await this.closeOperation(operation, outcome, null, String(err)));
3565
3772
  await this.ownerLifecycle?.meteringRecorded?.(record);
3566
3773
  if (this.v2Transcript && !transcriptClosed) {
3567
3774
  await this.finishV2Prompt("error", record, "unknown").catch(
3568
3775
  (persistenceError) => this.log.warn("transcript_terminal_write_failed", { error: String(persistenceError) }),
3569
3776
  );
3570
3777
  }
3778
+ if (err instanceof OperationStalledError) {
3779
+ err.messages = messages;
3780
+ err.metering = record;
3781
+ await this.ownerLifecycle?.operationFailed?.({ operationId: item.turnId, error: err }).catch((error) => {
3782
+ this.log.warn("operation_failure_recording_failed", { error: String(error) });
3783
+ });
3784
+ throw err;
3785
+ }
3571
3786
  throw new AgentSessionOperationError(item.turnId, record, err);
3572
3787
  }
3573
3788
  }
@@ -3685,6 +3900,180 @@ export class AgentConversation implements AgentClient, Bridgeable {
3685
3900
  return { before, after };
3686
3901
  }
3687
3902
 
3903
+ /** @internal Acquire a fresh leaf for checkpoint recovery without replacing this conversation. */
3904
+ async restartProviderFresh(): Promise<void> {
3905
+ await this.controller.forceStop();
3906
+ const result = await this.controller.startFresh();
3907
+ if (!result.sessionId) throw new Error("provider returned no fresh session");
3908
+ this.installProviderAttachment(result.sessionId, "runtime_only", true);
3909
+ }
3910
+
3911
+ private async ensureProvider(): Promise<void> {
3912
+ if (this.controller.isConnected) return;
3913
+ if (this.phase === "stopped") throw new Error("conversation is stopped");
3914
+ if (!this.continuationAcquired) throw new AgentSessionPromptBlockedError(["continuation_unavailable"]);
3915
+ const sessionId = this._internalSessionId;
3916
+ const attachment = this.providerAttachment;
3917
+ this.reconnecting = true;
3918
+ this.emitStateIfChanged();
3919
+ let via: "loaded" | "recovered" | "fresh" = "loaded";
3920
+ try {
3921
+ try {
3922
+ if (sessionId) await this.controller.reconnect(sessionId);
3923
+ else await this.controller.startFresh();
3924
+ } catch (error) {
3925
+ if (!sessionId) throw error;
3926
+ via = await this.continueWithoutProviderSession(sessionId, error);
3927
+ }
3928
+ if (this.state.phase === "stopped") {
3929
+ await this.controller.forceStop();
3930
+ throw new Error("conversation stopped during reconnect");
3931
+ }
3932
+ const loadedId = this.controller.currentSessionId;
3933
+ if (via === "loaded" && loadedId && loadedId !== this._internalSessionId) {
3934
+ this.installProviderAttachment(loadedId, "runtime_only", !sessionId);
3935
+ }
3936
+ this.emit({ kind: "provider_reconnected", via, internalSessionId: this._internalSessionId! });
3937
+ } catch (error) {
3938
+ await this.controller.forceStop().catch(() => {});
3939
+ if (this.continuationAcquired) {
3940
+ this.providerAttachment = attachment;
3941
+ this.setInternalSessionId(sessionId);
3942
+ }
3943
+ throw error;
3944
+ } finally {
3945
+ this.reconnecting = false;
3946
+ this.emitStateIfChanged();
3947
+ }
3948
+ }
3949
+
3950
+ /**
3951
+ * The provider session could not be loaded after the process was replaced. A transient failure is
3952
+ * thrown for the next operation to retry. When the provider no longer has the session, the
3953
+ * conversation's own rule decides, the same one it applies at open; when that rule has nothing left,
3954
+ * the conversation stops accepting prompts (`continuation_unavailable`) and the error says why.
3955
+ */
3956
+ private async continueWithoutProviderSession(sessionId: string, error: unknown): Promise<"recovered" | "fresh"> {
3957
+ const unavailable = (cause: unknown): never => {
3958
+ this.continuationAcquired = false;
3959
+ throw cause;
3960
+ };
3961
+ if (this.ownerLifecycle?.recoverInPlace) {
3962
+ try {
3963
+ await this.ownerLifecycle.recoverInPlace(error);
3964
+ return "recovered";
3965
+ } catch (failure) {
3966
+ const missing = failure instanceof ProviderSessionError && failure.code === "provider_session_missing";
3967
+ if (missing) unavailable(failure);
3968
+ throw failure;
3969
+ }
3970
+ }
3971
+ const loadFailed = (code: "provider_session_missing" | "provider_session_load_failed") =>
3972
+ new ProviderSessionError({
3973
+ agentSessionId: this.ownerAgentSessionId ?? this.agentSessionId as AgentSessionId,
3974
+ agentConversationId: this.agentConversationId,
3975
+ attemptId: `reconnect-${crypto.randomUUID()}`,
3976
+ internalSessionId: sessionId,
3977
+ source: "provider_session",
3978
+ code,
3979
+ recoverability: code === "provider_session_missing" ? "recoverable" : "retryable",
3980
+ cause: error,
3981
+ });
3982
+ if (!isMissingProviderSessionError(error)) throw loadFailed("provider_session_load_failed");
3983
+ if (this.v2Transcript) {
3984
+ const reconstruction = this.continuationStrategies.filter((strategy) => strategy.kind !== "load_internal_session");
3985
+ const report = await this.acquireContinuation(this.v2Transcript.checkpoint, reconstruction, error);
3986
+ if (report.outcome.kind === "unavailable") {
3987
+ unavailable(new ContinuationUnavailableError(report, { cause: error }));
3988
+ }
3989
+ return "recovered";
3990
+ }
3991
+ if (this.sessionLoadFailure === "error") unavailable(loadFailed("provider_session_missing"));
3992
+ const created = await this.controller.startFresh();
3993
+ if (!created.sessionId) throw new Error("harness returned no session id for a replacement session");
3994
+ this.installProviderAttachment(created.sessionId, "runtime_only", true);
3995
+ return "fresh";
3996
+ }
3997
+
3998
+ private cancelOperation(reason: CancelReason): void {
3999
+ if (this.activeSupervisor) this.activeSupervisor.cancel(reason);
4000
+ else this.controller.cancel();
4001
+ }
4002
+
4003
+ /** A supervised operation is cancelled at most once, so its cancellation is named after it. */
4004
+ private recordCancellation(
4005
+ operationId: string,
4006
+ state: "requested" | "resolved",
4007
+ reason: CancelReason,
4008
+ outcome?: CancelOutcome,
4009
+ ): void {
4010
+ if (this.v2Transcript) {
4011
+ this.presentation.queueEvent({
4012
+ kind: "cancellation",
4013
+ operationId,
4014
+ cancellationId: `${operationId}:cancellation`,
4015
+ event: state,
4016
+ reason,
4017
+ ...(outcome ? { outcome } : {}),
4018
+ });
4019
+ }
4020
+ if (!this.ownerAgentSessionId) return;
4021
+ this.queueOwnedRecord({
4022
+ recordId: `${operationId}:cancellation:${state}`,
4023
+ agentSessionId: this.ownerAgentSessionId,
4024
+ agentConversationId: this.agentConversationId,
4025
+ kind: "cancellation",
4026
+ timestamp: new Date().toISOString(),
4027
+ operationId,
4028
+ cancellationId: `${operationId}:cancellation`,
4029
+ state,
4030
+ reason,
4031
+ ...(outcome ? { outcome } : {}),
4032
+ });
4033
+ }
4034
+
4035
+ /** Run one provider request under its own supervisor: stage, stale conditions, cancel escalation. */
4036
+ private async supervisedPrompt(
4037
+ controller: AgentController,
4038
+ operationId: string,
4039
+ kind: "turn" | "internal_inference" | "recap",
4040
+ prompt: () => Promise<PromptResult>,
4041
+ ): Promise<PromptResult> {
4042
+ const limits = kind === "turn"
4043
+ ? this.operationLifecycle.turns
4044
+ : kind === "recap" ? this.operationLifecycle.recap : this.operationLifecycle.internalInference;
4045
+ const supervisor = new OperationSupervisor({
4046
+ prompt,
4047
+ subscribeOutput: (listener) => controller.subscribeOutput(listener),
4048
+ cancel: () => controller.cancel(),
4049
+ forceStop: () => controller.forceStop(),
4050
+ }, {
4051
+ operationId,
4052
+ kind,
4053
+ sessionId: controller.currentSessionId,
4054
+ cancelGraceMs: controller.cancelGraceMs,
4055
+ // A screen-scraped harness cannot report tools or permissions, so silence explains nothing.
4056
+ limits: controller.isDegraded ? { firstOutputMs: false, nextOutputMs: false, ...limits } : limits,
4057
+ onStageChanged: (activity) => {
4058
+ this.emit({ kind: "operation_stage_changed", activity });
4059
+ this.emitStateIfChanged();
4060
+ },
4061
+ onToolBoundary: () => this.steering.toolBoundary(operationId),
4062
+ onCancelRequested: (reason) => this.recordCancellation(operationId, "requested", reason),
4063
+ onCancelResolved: (reason, outcome) => this.recordCancellation(operationId, "resolved", reason, outcome),
4064
+ });
4065
+ this.activeSupervisor = supervisor;
4066
+ try {
4067
+ return await supervisor.run();
4068
+ } catch (error) {
4069
+ if (kind === "turn") this.providerFailedTurnId = operationId;
4070
+ throw error;
4071
+ } finally {
4072
+ this.activeSupervisor = null;
4073
+ this.emitStateIfChanged();
4074
+ }
4075
+ }
4076
+
3688
4077
  /**
3689
4078
  * Run a library-internal prompt through the same metering primitive as a user prompt.
3690
4079
  *
@@ -3703,6 +4092,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3703
4092
  target?: InternalPromptTarget,
3704
4093
  ): Promise<PromptResult> {
3705
4094
  const controller = target?.controller ?? this.controller;
4095
+ if (!target && !this.reconnecting) await this.ensureProvider();
3706
4096
  const metering = target?.metering ?? this.metering;
3707
4097
  const advertised = target ? activeModel(target.controller.configOptions) : this.advertisedModel;
3708
4098
  const reference = target ? resolveModelReference(target.adapterId, advertised) : null;
@@ -3737,8 +4127,11 @@ export class AgentConversation implements AgentClient, Bridgeable {
3737
4127
  }
3738
4128
  let closed = false;
3739
4129
  let transcriptClosed = false;
4130
+ const enclosingOperationId = this.runningOperationId;
4131
+ this.runningOperationId = operationId;
3740
4132
  try {
3741
- const result = await controller.prompt(text);
4133
+ const kind = operationKind === "conversation_checkpoint" ? "recap" : "internal_inference";
4134
+ const result = await this.supervisedPrompt(controller, operationId, kind, () => controller.prompt(text));
3742
4135
  const record = await this.closeOperation(
3743
4136
  operation,
3744
4137
  result.status,
@@ -3750,12 +4143,18 @@ export class AgentConversation implements AgentClient, Bridgeable {
3750
4143
  closed = true;
3751
4144
  await this.ownerLifecycle?.meteringRecorded?.(record);
3752
4145
  if (this.v2Transcript) {
4146
+ // A cancellation record queued during the prompt belongs before the reply and the settle.
4147
+ await this.presentation.drain();
3753
4148
  await this.v2Transcript.appendEvent({
3754
4149
  kind: "message",
3755
4150
  operationId,
3756
4151
  role: "assistant",
3757
4152
  text: formatResponseMessages(result.messages, "\n\n"),
3758
- structured: { version: 1, messages: result.messages },
4153
+ // Handoff transcripts stay text: the parts are not carried over.
4154
+ structured: {
4155
+ version: 1,
4156
+ messages: result.messages.map(({ messageId, text }) => ({ ...(messageId ? { messageId } : {}), text })),
4157
+ },
3759
4158
  stopReason: result.stopReason,
3760
4159
  status: result.status,
3761
4160
  });
@@ -3765,13 +4164,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
3765
4164
  return result;
3766
4165
  } catch (err) {
3767
4166
  if (!closed) {
3768
- const record = await this.closeOperation(operation, "error", null, String(err), metering);
4167
+ const outcome = err instanceof OperationStalledError ? "cancelled" : "error";
4168
+ const record = await this.closeOperation(operation, outcome, null, String(err), metering);
3769
4169
  records.push(record);
3770
4170
  closed = true;
3771
4171
  await this.ownerLifecycle?.meteringRecorded?.(record);
3772
4172
  }
3773
4173
  if (this.v2Transcript && !transcriptClosed) {
3774
4174
  const record = records[records.length - 1]!;
4175
+ await this.presentation.drain().catch(() => undefined);
3775
4176
  await this.v2Transcript.appendEvent({
3776
4177
  kind: "message",
3777
4178
  operationId,
@@ -3786,6 +4187,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
3786
4187
  );
3787
4188
  }
3788
4189
  throw err;
4190
+ } finally {
4191
+ this.runningOperationId = enclosingOperationId;
3789
4192
  }
3790
4193
  }
3791
4194
 
@@ -3893,6 +4296,12 @@ export class AgentConversation implements AgentClient, Bridgeable {
3893
4296
  }
3894
4297
 
3895
4298
  interrupt(options?: InterruptOptions): void {
4299
+ this.cancelRunning("interrupt", options);
4300
+ }
4301
+
4302
+ /** Stop the running operation, and with `clearQueue` everything queued behind it. */
4303
+ private cancelRunning(reason: "interrupt" | "stop", options?: InterruptOptions): void {
4304
+ // A stop closes the connection, so its turn fails and `endedBy` is never reported for it.
3896
4305
  this.steering.interrupted();
3897
4306
  if (options?.clearQueue) {
3898
4307
  const dropped = this.operations.clear();
@@ -3912,7 +4321,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3912
4321
  }
3913
4322
  this.emitStateIfChanged();
3914
4323
  }
3915
- this.controller.interrupt(options);
4324
+ this.cancelOperation(reason);
3916
4325
  }
3917
4326
 
3918
4327
  stop(): Promise<void> {
@@ -3942,6 +4351,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
3942
4351
  // candidate, and a recorded one is preserved by its provider row, so neither should
3943
4352
  // survive on the stopped object.
3944
4353
  this.clearProviderAttachment();
4354
+ this.detachControllerConnection?.();
4355
+ this.detachControllerConnection = null;
3945
4356
  await this.presentation.drain().catch(() => undefined);
3946
4357
  try {
3947
4358
  await this.transcriptWrite;
@@ -3958,7 +4369,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3958
4369
  });
3959
4370
  this.stopPromise = completion;
3960
4371
  try {
3961
- this.interrupt({ clearQueue: true });
4372
+ this.cancelRunning("stop", { clearQueue: true });
3962
4373
  } catch (error) {
3963
4374
  failures.push(error);
3964
4375
  }
@@ -4088,18 +4499,23 @@ export class AgentConversation implements AgentClient, Bridgeable {
4088
4499
  }
4089
4500
 
4090
4501
  // --- sessions (merged catalog + live) ----------------------------------------
4091
- /** The merged session list: our catalog ∪ the agent's live list (ACP mode). */
4502
+ /**
4503
+ * The merged session list: our catalog ∪ the agent's live list (ACP mode).
4504
+ *
4505
+ * A failed harness listing throws; it used to return the catalog half silently.
4506
+ *
4507
+ * @deprecated It mixes the library's conversations with the harness's sessions (for a harness-only
4508
+ * entry `agentSessionId` holds the harness id). Use the Agent API instead: `agent.conversations` for the library's
4509
+ * conversations and `agent.conversations.listProviderSessions()` for the harness's sessions with
4510
+ * their owners.
4511
+ */
4092
4512
  async listSessions(): Promise<MergedSession[]> {
4093
4513
  let agentEntries: SessionListEntry[] = [];
4094
4514
  if (
4095
4515
  !this.controller.isDegraded &&
4096
4516
  this.controller.capabilities.agent.sessionCapabilities.list
4097
4517
  ) {
4098
- try {
4099
- agentEntries = (await this.controller.listSessions()).sessions;
4100
- } catch {
4101
- /* agent list broken/empty — fall back to catalog only */
4102
- }
4518
+ agentEntries = (await this.controller.listSessions()).sessions;
4103
4519
  }
4104
4520
  if (this.sessions) return this.sessions.listMerged(agentEntries, this.adapterId);
4105
4521
  return agentEntries.map((e) => ({
@@ -4259,6 +4675,10 @@ export class AgentConversation implements AgentClient, Bridgeable {
4259
4675
  private emitStateIfChanged(): void {
4260
4676
  const state = this.state;
4261
4677
  const key = [
4678
+ state.pendingHold?.failedTurnId ?? "",
4679
+ state.providerConnection,
4680
+ state.operation?.stage ?? "",
4681
+ state.operation?.operationId ?? "",
4262
4682
  state.phase,
4263
4683
  state.queuedOperationCount,
4264
4684
  state.internalSessionId ?? "",
@@ -4334,6 +4754,9 @@ function ownHandoffOptions(options: HandoffOptions): HandoffOptions {
4334
4754
  ? {}
4335
4755
  : {
4336
4756
  adapter: Object.freeze({
4757
+ ...(options.target.adapter.cancelGraceMs === undefined
4758
+ ? {}
4759
+ : { cancelGraceMs: options.target.adapter.cancelGraceMs }),
4337
4760
  ...options.target.adapter,
4338
4761
  command: Object.freeze([...options.target.adapter.command]) as unknown as string[],
4339
4762
  ...(options.target.adapter.ptyCommand
@@ -4579,3 +5002,21 @@ function copyPromptResult(result: PromptResult): PromptResult {
4579
5002
  usage: result.usage ? Object.freeze({ ...result.usage }) : null,
4580
5003
  });
4581
5004
  }
5005
+
5006
+ /** Settle our wrapper too, so cancelled permission decisions are durably recorded. */
5007
+ async function permissionWithAbort(
5008
+ handler: () => PermissionOutcome | Promise<PermissionOutcome>,
5009
+ signal?: AbortSignal,
5010
+ ): Promise<PermissionOutcome> {
5011
+ if (signal?.aborted) return { outcome: "cancelled" };
5012
+ let abort!: () => void;
5013
+ const cancelled = new Promise<PermissionOutcome>((resolve) => {
5014
+ abort = () => resolve({ outcome: "cancelled" });
5015
+ signal?.addEventListener("abort", abort, { once: true });
5016
+ });
5017
+ try {
5018
+ return await Promise.race([Promise.resolve().then(handler), cancelled]);
5019
+ } finally {
5020
+ signal?.removeEventListener("abort", abort);
5021
+ }
5022
+ }