@qlairoslabs/acp-client 0.10.0 → 0.10.2

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.
package/CONSUMER_GUIDE.md CHANGED
@@ -293,6 +293,91 @@ first streams provisionally, then arrives as a committed `tool_call`. Detached
293
293
  `AgentConversation` instances without an owning `Agent` are outside this bus, and a
294
294
  consumer-direct `persistence.records.append()` is not observed.
295
295
 
296
+ ### Conversation error records
297
+
298
+ Important runtime failures are stored as an immutable `error` record in the same ordered
299
+ timeline as messages, activities, and metering references — and delivered live through
300
+ `agent.events`. An error is a system timeline item, not a message:
301
+
302
+ ```ts
303
+ const errors = (await agent.persistence.records.list(conversation.id, {
304
+ kinds: ["error"],
305
+ })).records;
306
+
307
+ for (const record of errors) {
308
+ if (record.kind !== "error") continue;
309
+ // record.source, record.code, record.recoverability, record.message
310
+ // record.operationId / transitionId / internalSessionId correlate it with the failure
311
+ }
312
+ ```
313
+
314
+ `source` is one of `provider_session`, `transport`, `operation`, `recovery`. `code` is an
315
+ open string; the library exports `CONVERSATION_ERROR_CODES` for the codes it owns and
316
+ readers must tolerate unknown future values. `recoverability` describes the failed
317
+ operation, not a promise:
318
+
319
+ - `retryable` — repeating the same action may succeed.
320
+ - `recoverable` — another action (checkpoint recovery, a fresh provider session) may
321
+ continue the logical conversation.
322
+ - `terminal` — the library knows of no supported continuation.
323
+ - `unknown` — evidence is insufficient to choose.
324
+
325
+ `message` is a sanitized display fallback; it never carries a stack trace, credentials, a
326
+ prompt, environment values, or a raw provider payload. At raw capture, allow-listed
327
+ provider detail is available in `details`. Canonical capture defaults to
328
+ `capture.error = "content"` (metadata drops the message; `none` stores nothing); the audit
329
+ destination has its own independent `auditLog.capture.error`.
330
+
331
+ A failed `conversations.open()` throws `ProviderSessionError` instead of returning a
332
+ conversation. It carries the same `code`, `attemptId`, `recoverability`, and — when
333
+ canonical capture accepted it — `recordId` as the durable row, plus
334
+ `agentConversationId` (always, even for a generated id) so the caller can find the
335
+ conversation. If writing the record also fails, that failure is attached as
336
+ `recordingError` and the provider diagnosis stays primary. The failed provider mapping is
337
+ kept as evidence and is not deleted; recovery or a future fresh-session operation
338
+ supersedes it. A `session/load` failure that is recoverable and has a usable checkpoint
339
+ still recovers, with the error recorded before the recovery action.
340
+
341
+ ### Append an assistant message without a turn
342
+
343
+ `conversations.appendAssistantMessage()` adds a completed assistant message the provider
344
+ did not produce — for example, a notification the agent sends from another channel. It
345
+ runs no turn and needs no live provider session:
346
+
347
+ ```ts
348
+ const record = await agent.conversations.appendAssistantMessage(conversation.id, {
349
+ text: "Your build finished; 3 tests failed.",
350
+ consumerMetadata: { kind: "send_message_to_user" },
351
+ });
352
+ ```
353
+
354
+ The record is an ordinary `message` with `role: "assistant"` and `status: "completed"`,
355
+ published on `agent.events` and returned by history reads like any other message. Its
356
+ envelope `metadata` carries `origin: "out_of_band"` (exported as
357
+ `OUT_OF_BAND_MESSAGE_ORIGIN`; `isOutOfBandMessage(record)` tests it), so readers and
358
+ audits can tell it apart from provider output.
359
+
360
+ The provider learns about it on the conversation's next turn. That turn's provider text
361
+ carries every out-of-band message appended since the user message of the last completed
362
+ turn, in a `<messages-you-sent>` block between any identity preamble and
363
+ `<current-message>`. Only the user's own text is persisted as the user message. Rules:
364
+
365
+ - A failed turn does not count as delivery; the next turn carries the messages again.
366
+ - A message appended while a turn is running reaches the provider on the following turn.
367
+ - A recovery seed covers messages through `recoveredThroughSequence`, so they are not
368
+ repeated after recovery. A loaded provider session is treated like one that never
369
+ closed.
370
+ - A turn that completes without an assistant message does not advance delivery, so its
371
+ pending messages are repeated once more.
372
+ - The block is capped at `OUT_OF_BAND_PROMPT_MAX_CHARS`; the oldest messages are dropped
373
+ first with an omission note. The transcript always keeps all of them.
374
+
375
+ Other conversations of the same agent see the message through identity like any other
376
+ canonical message. Appending requires `capture.message` of `"content"` or `"raw"`, since
377
+ the provider could not be told otherwise; it rejects blank text and unknown or deleted
378
+ conversations. Backends without `records.listRecent` scan the conversation's messages
379
+ forward to find the last completed turn.
380
+
296
381
  ### Agent audit log
297
382
 
298
383
  An SQLite-backed `Agent` can copy selected observations into an independently located,
@@ -835,6 +920,105 @@ deprecated `result.text` property is only a compatibility projection and inserts
835
920
  line between messages. `formatResponseMessages()` makes any deliberate flattening policy
836
921
  consumer-owned.
837
922
 
923
+ ## Send a message while a turn is running
924
+
925
+ A prompt sent while a turn runs waits. How it waits is its **delivery**:
926
+
927
+ - `"queue"` (the default): it runs after the running turn ends, as its own turn.
928
+ - `"steer"`: it is delivered at the next tool boundary. The library cancels the running turn once a
929
+ tool call has settled and nothing else is running, then sends the message, so the agent gets the
930
+ information without losing the work it has done. If the turn ends first, the message is sent as the
931
+ next prompt, so a message is never delivered later than the end of the turn. A text-only turn is not
932
+ cut short: use `interrupt()` for that.
933
+
934
+ ```ts
935
+ const turn = conversation.prompt("Refactor the parser.");
936
+
937
+ // A second message, sent while the first turn is running.
938
+ const note = conversation.prompt({ text: "Also keep the public API unchanged.", delivery: "steer" });
939
+
940
+ const first = await turn; // stopReason "cancelled", endedBy "steer", followedBy [note.id]
941
+ const answer = await note; // the turn that carried the message
942
+ ```
943
+
944
+ `prompt()` and `promptFrom()` return a handle: the promise of that prompt's result, plus `id` and
945
+ `withdraw()`. A prompt that does not have to wait runs immediately and `delivery` has no effect.
946
+
947
+ Set the default for prompts that do not say, per Agent or per conversation. It is `"queue"` unless you
948
+ change it:
949
+
950
+ ```ts
951
+ const agent = await Agent.open({
952
+ // ...
953
+ conversationDefaults: { busyDelivery: "steer" },
954
+ });
955
+ ```
956
+
957
+ ### What waits, and in what order
958
+
959
+ The conversation keeps one FIFO. A `steer` message is appended like any other, so a `queue` message sent
960
+ earlier keeps its place ahead of it. At a boundary the library only delivers a message if the head of the
961
+ queue is a `steer` message.
962
+
963
+ **Consecutive `steer` messages at the head are sent as one prompt**, so the agent sees the whole
964
+ correction at once:
965
+
966
+ ```text
967
+ > working...
968
+ Also, remember x
969
+ and y
970
+ and z
971
+ no, actually forget about y and z <- the agent receives all four together
972
+ ```
973
+
974
+ The text is the messages in order, separated by a blank line; the library adds nothing, not even sender
975
+ names. It is one operation with one metering record, and every message's promise resolves with the same
976
+ result. Each original message is still stored as its own user message, with its own `participantId` and
977
+ `consumerMetadata`, so a consumer can render or filter them from its own metadata. Each message's
978
+ streaming handlers receive the events of the shared turn.
979
+
980
+ ```ts
981
+ conversation.pendingMessages; // what waits, in the order it will be sent
982
+ conversation.withdraw(note.id); // take a message back; also note.withdraw()
983
+ conversation.interrupt(); // cancel now; pending steer messages are then sent
984
+ conversation.interrupt({ clearQueue: true }); // cancel and drop what waits
985
+ ```
986
+
987
+ A withdrawn or dropped message settles as a cancelled prompt (`stopReason: "cancelled"`, `usage: null`,
988
+ `metering: null`).
989
+
990
+ ### Events and results
991
+
992
+ Messages that had to wait emit events on the conversation event stream:
993
+
994
+ | Event | Meaning |
995
+ |---|---|
996
+ | `message_pending { id, delivery }` | Accepted and waiting. `delivery` is the mode in effect: `"queue"` while the running operation is not a consumer prompt turn (a handoff, a configuration change). |
997
+ | `message_delivered { ids, via, turnId }` | Sent to the agent. `ids` lists every message in the prompt; `via` is `"tool_boundary"`, `"interrupt"` or `"turn_end"`. |
998
+ | `message_withdrawn { id }` | Removed before delivery. |
999
+
1000
+ A turn cancelled by steering or by `interrupt()` carries `endedBy: "steer" | "interrupt"` and
1001
+ `followedBy` (the messages sent after it). They are set only when the provider really stopped the turn:
1002
+ if the turn finished by itself before the cancel took effect, neither is present.
1003
+
1004
+ ### Limits to know about
1005
+
1006
+ Cancelling is the only control ACP offers during a turn, so what a harness does with the cancelled turn
1007
+ is its own. Measured with the `test11-steerTurn` smoke test:
1008
+
1009
+ - Work the agent has completed is kept: the follow-up continues the task rather than restarting it.
1010
+ - Codex: a shell command already running keeps running after the cancel, and text the agent was
1011
+ streaming when cancelled is dropped from its context. OpenCode aborts the command.
1012
+ - Usage reported over ACP for a cancelled turn is unreliable (OpenCode reports 0 over ACP for a turn
1013
+ whose inference had completed). Only a certified metering integration sees the real spend, so with
1014
+ plain ACP telemetry a steered conversation can under-count the cancelled turn.
1015
+ - Codex reports usage in a way the cumulative-counter check can reject: the turn after a cancel was
1016
+ recorded with status `counter_reset` and no attributed tokens in testing. This looks like a property of
1017
+ Codex usage reporting rather than of steering (see the `s9` control in `test11-steerTurn`).
1018
+ - `status` and the stored message status follow what the provider reported: a turn the provider ended
1019
+ normally despite a late cancel is `completed`, and `endedBy` is absent.
1020
+ - Pending messages live in memory only. They are lost if the process stops, like queued prompts.
1021
+
838
1022
  ## Observe state, context, and usage
839
1023
 
840
1024
  Read a snapshot first, then subscribe to changes:
package/README.md CHANGED
@@ -575,6 +575,3 @@ bun test # unit tests
575
575
  bun run check # typecheck + test
576
576
  ```
577
577
 
578
- ## License
579
-
580
- [MIT](./LICENSE) © Facundo Hannoch
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.10.0",
3
+ "version": "0.10.2",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -58,7 +58,9 @@
58
58
  "check": "bun run typecheck && bun test",
59
59
  "pack:dry": "bun pm pack --dry-run",
60
60
  "generate:pricing": "bun run scripts/generate-pricing-catalog.ts",
61
- "pricing:list": "bun run scripts/list-pricing.ts"
61
+ "pricing:list": "bun run scripts/list-pricing.ts",
62
+ "adapters:check": "bun run scripts/adapters.ts",
63
+ "adapters:update": "bun run scripts/adapters.ts --update"
62
64
  },
63
65
  "engines": {
64
66
  "bun": ">=1.3.5"
@@ -1,4 +1,5 @@
1
1
  import type { AgentMode } from "./controller.ts";
2
+ import type { MessageEvent, PendingMessageId, PromptEndedBy } from "./steering/contracts.ts";
2
3
  import type { Adapter } from "./adapters.ts";
3
4
  import type { ContextWindowStatus, ProviderCostSnapshot } from "./metering/context.ts";
4
5
  import type { OperationMeteringRecord } from "./metering/record.ts";
@@ -204,6 +205,7 @@ export type AgentSessionEvent =
204
205
  | { kind: "turn_started"; turnId: string }
205
206
  | { kind: "turn_completed"; turnId: string; result: PromptResult }
206
207
  | { kind: "turn_failed"; turnId: string; error: string }
208
+ | MessageEvent
207
209
  | { kind: "presentation_recorded"; item: TranscriptPresentationItem }
208
210
  | { kind: "internal_session_commands_changed"; commands: readonly InternalSessionCommand[] }
209
211
  | { kind: "handoff_started"; handoffId: string; fromInternalSessionId: string | null }
@@ -252,6 +254,13 @@ export interface AgentSessionPromptResult extends PromptResult {
252
254
  readonly operationId: string;
253
255
  /** Null only when a queued prompt was cancelled before provider dispatch. */
254
256
  readonly metering: OperationMeteringRecord | null;
257
+ /**
258
+ * Why this turn was cancelled, when steering or `interrupt()` cancelled it and the provider really
259
+ * stopped it (`stopReason: "cancelled"`). Absent when the turn ended on its own.
260
+ */
261
+ readonly endedBy?: PromptEndedBy;
262
+ /** The messages sent after this turn was cancelled by steering or `interrupt()`, in order. */
263
+ readonly followedBy?: readonly PendingMessageId[];
255
264
  }
256
265
 
257
266
  /** Ordered envelope delivered to every current AgentSession subscriber. */
@@ -3,6 +3,7 @@ import type { Adapter } from "./adapters.ts";
3
3
  import type { AgentMode } from "./controller.ts";
4
4
  import type { NewConversationRecord, ParticipantRef, PersistenceJsonValue } from "./persistence/backend.ts";
5
5
  import type { AgentSessionPromptResult } from "./agent-conversation-contracts.ts";
6
+ import type { PromptPart } from "./steering/contracts.ts";
6
7
  import type { ResponseMessage } from "./types.ts";
7
8
  import type { OperationMeteringRecord } from "./metering/record.ts";
8
9
  import type { AgentSessionMeteringState } from "./metering/state.ts";
@@ -19,12 +20,16 @@ export interface OwnedPromptInput {
19
20
  readonly targetProviderContextId?: string;
20
21
  readonly participantId?: string;
21
22
  readonly consumerMetadata?: PersistenceJsonValue;
23
+ /** Present when several messages were combined into this one prompt: each is recorded as sent. */
24
+ readonly parts?: readonly PromptPart[];
22
25
  readonly text: string;
23
26
  }
24
27
 
25
28
  export interface OwnedPromptPreparation {
26
29
  readonly providerText?: string;
27
30
  readonly participant?: ParticipantRef;
31
+ /** Every participant of a combined prompt, in order. `participant` is the first. */
32
+ readonly participants?: readonly ParticipantRef[];
28
33
  readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
29
34
  }
30
35
 
@@ -25,6 +25,29 @@ export class AgentConversationQueue<T> {
25
25
  return this.#items.splice(0);
26
26
  }
27
27
 
28
+ /** The next queued item, without removing it. */
29
+ peek(): T | undefined {
30
+ return this.#items[0];
31
+ }
32
+
33
+ /** Queued (not active) work in FIFO order. The returned array is a copy. */
34
+ snapshot(): readonly T[] {
35
+ return [...this.#items];
36
+ }
37
+
38
+ /** Remove and return the first queued item the predicate accepts, if any. */
39
+ remove(predicate: (item: T) => boolean): T | undefined {
40
+ const index = this.#items.findIndex(predicate);
41
+ return index < 0 ? undefined : this.#items.splice(index, 1)[0];
42
+ }
43
+
44
+ /** Remove and return the consecutive items at the head of the queue the predicate accepts. */
45
+ takeWhile(predicate: (item: T) => boolean): T[] {
46
+ let count = 0;
47
+ while (count < this.#items.length && predicate(this.#items[count]!)) count += 1;
48
+ return this.#items.splice(0, count);
49
+ }
50
+
28
51
  /**
29
52
  * Drain every item serially. Concurrent calls share the active drain; an item
30
53
  * enqueued by an active operation is observed by the same loop.
@@ -162,6 +162,14 @@ import type {
162
162
  TranscriptContinuationBuilderContext,
163
163
  } from "./agent-conversation-contracts.ts";
164
164
  import { AgentConversationQueue } from "./agent-conversation-queue.ts";
165
+ import {
166
+ SteeringController,
167
+ type PendingMessage,
168
+ type PendingMessageId,
169
+ type PromptDelivery,
170
+ type PromptHandle,
171
+ type SteeringPrompt,
172
+ } from "./steering/index.ts";
165
173
  import { AgentConversationPresentation } from "./agent-conversation-presentation.ts";
166
174
  import {
167
175
  HANDOFF_SUMMARY_PROMPT,
@@ -178,7 +186,9 @@ export {
178
186
  AgentSessionPromptBlockedError,
179
187
  ContinuationUnavailableError,
180
188
  DirectAuditPersistenceUnsupportedError,
189
+ ProviderSessionError,
181
190
  } from "./agent-conversation-errors.ts";
191
+ export type { ProviderSessionErrorDetails } from "./agent-conversation-errors.ts";
182
192
  export type {
183
193
  AgentConversationEvent,
184
194
  AgentConversationListener,
@@ -214,18 +224,9 @@ export type {
214
224
  TranscriptContinuationBuilderContext,
215
225
  } from "./agent-conversation-contracts.ts";
216
226
 
217
- interface PromptQueueItem {
218
- kind: "prompt";
219
- turnId: string;
227
+ interface PromptQueueItem extends SteeringPrompt {
220
228
  /** How this operation is classified in its metering record. */
221
229
  operationKind: MeteredOperationKind;
222
- text: string;
223
- participantId?: string;
224
- consumerMetadata?: PersistenceJsonValue;
225
- handlers?: PromptHandlers;
226
- attachments?: Attachment[];
227
- resolve: (r: AgentSessionPromptResult) => void;
228
- reject: (e: unknown) => void;
229
230
  }
230
231
 
231
232
  /** Object-form prompt input for per-message consumer metadata on Agent-owned conversations. */
@@ -234,6 +235,8 @@ export interface AgentConversationPromptInput {
234
235
  readonly consumerMetadata?: PersistenceJsonValue;
235
236
  readonly handlers?: PromptHandlers;
236
237
  readonly attachments?: Attachment[];
238
+ /** How this prompt waits if a turn is running. Defaults to the conversation's `busyDelivery`. */
239
+ readonly delivery?: PromptDelivery;
237
240
  }
238
241
 
239
242
  export interface AgentConversationAttributedPromptInput extends AgentConversationPromptInput {
@@ -320,6 +323,11 @@ export interface AgentSessionConfig {
320
323
  /** Default MCP servers bound at session creation/switch, unless a call overrides them. */
321
324
  mcpServers?: schema.McpServer[];
322
325
  defaultPermission?: "approve" | "cancel";
326
+ /**
327
+ * How a prompt sent while a turn is running waits when the prompt does not say. `queue` runs it after
328
+ * the turn ends; `steer` delivers it at the next tool boundary. Default `queue`.
329
+ */
330
+ busyDelivery?: PromptDelivery;
323
331
  clientInfo?: { name: string; title?: string; version?: string };
324
332
  /** What we let the agent do through us (terminals, filesystem). All on by default. */
325
333
  clientCapabilities?: AgentControllerConfig["clientCapabilities"];
@@ -447,6 +455,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
447
455
  private readonly log: Logger;
448
456
  private transcriptWrite: Promise<void> = Promise.resolve();
449
457
  private readonly operations = new AgentConversationQueue<QueueItem>();
458
+ private readonly steering: SteeringController<QueueItem>;
450
459
  private stopPromise: Promise<void> | null = null;
451
460
  private phase: AgentSessionPhase = "idle";
452
461
  private notificationSeq = 0;
@@ -541,6 +550,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
541
550
  ?? (isAgentSessionId(this.agentSessionId) ? this.agentSessionId : null);
542
551
  this.ownerLifecycle = config.ownerLifecycle;
543
552
  this.defaultPermission = config.defaultPermission ?? "cancel";
553
+ this.steering = new SteeringController<QueueItem>(
554
+ {
555
+ queue: this.operations,
556
+ emit: (event) => this.emit(event),
557
+ cancelProviderTurn: () => this.controller.interrupt(),
558
+ emitState: () => this.emitStateIfChanged(),
559
+ },
560
+ config.busyDelivery ?? "queue",
561
+ );
544
562
  this._participants = (config.participants ?? []).map((participant) => Object.freeze({ ...participant }));
545
563
  this._adapterId = config.adapterId;
546
564
  this.activeAdapter = config.adapter;
@@ -1768,48 +1786,67 @@ export class AgentConversation implements AgentClient, Bridgeable {
1768
1786
  }
1769
1787
 
1770
1788
  // --- AgentClient -------------------------------------------------------------
1771
- prompt(input: AgentConversationPromptInput): Promise<AgentSessionPromptResult>;
1789
+ prompt(input: AgentConversationPromptInput): PromptHandle;
1772
1790
  prompt(
1773
1791
  text: string,
1774
1792
  handlers?: PromptHandlers,
1775
1793
  attachments?: Attachment[],
1776
- ): Promise<AgentSessionPromptResult>;
1777
- async prompt(
1794
+ ): PromptHandle;
1795
+ prompt(
1778
1796
  input: string | AgentConversationPromptInput,
1779
1797
  handlers?: PromptHandlers,
1780
1798
  attachments?: Attachment[],
1781
- ): Promise<AgentSessionPromptResult> {
1799
+ ): PromptHandle {
1782
1800
  return typeof input === "string"
1783
1801
  ? this.enqueuePrompt(input, "prompt", handlers, attachments)
1784
- : this.enqueuePrompt(input.text, "prompt", input.handlers, input.attachments, undefined, input.consumerMetadata);
1802
+ : this.enqueuePrompt(
1803
+ input.text, "prompt", input.handlers, input.attachments,
1804
+ undefined, input.consumerMetadata, input.delivery,
1805
+ );
1806
+ }
1807
+
1808
+ /** Messages waiting behind the running operation, in the order they will be sent. */
1809
+ get pendingMessages(): readonly PendingMessage[] {
1810
+ return this.steering.pending();
1811
+ }
1812
+
1813
+ /** Take back a message that has not been sent yet. Returns whether it was still pending. */
1814
+ withdraw(id: PendingMessageId): boolean {
1815
+ return this.steering.withdraw(id);
1785
1816
  }
1786
1817
 
1787
1818
  /** Prompt while attributing the caller to a stable participant identity. */
1788
- promptFrom(input: AgentConversationAttributedPromptInput): Promise<AgentSessionPromptResult>;
1819
+ promptFrom(input: AgentConversationAttributedPromptInput): PromptHandle;
1789
1820
  promptFrom(
1790
1821
  participantId: string,
1791
1822
  text: string,
1792
1823
  handlers?: PromptHandlers,
1793
1824
  attachments?: Attachment[],
1794
- ): Promise<AgentSessionPromptResult>;
1825
+ ): PromptHandle;
1795
1826
  promptFrom(
1796
1827
  input: string | AgentConversationAttributedPromptInput,
1797
1828
  text?: string,
1798
1829
  handlers?: PromptHandlers,
1799
1830
  attachments?: Attachment[],
1800
- ): Promise<AgentSessionPromptResult> {
1831
+ ): PromptHandle {
1801
1832
  if (typeof input !== "string") {
1802
- if (!input.participantId.trim()) return Promise.reject(new Error("participant id cannot be blank"));
1833
+ if (!input.participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
1803
1834
  return this.enqueuePrompt(
1804
1835
  input.text, "prompt", input.handlers, input.attachments,
1805
- input.participantId.trim(), input.consumerMetadata,
1836
+ input.participantId.trim(), input.consumerMetadata, input.delivery,
1806
1837
  );
1807
1838
  }
1808
1839
  const participantId = input;
1809
- if (!participantId.trim()) return Promise.reject(new Error("participant id cannot be blank"));
1840
+ if (!participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
1810
1841
  return this.enqueuePrompt(text!, "prompt", handlers, attachments, participantId.trim());
1811
1842
  }
1812
1843
 
1844
+ private rejectedPrompt(error: Error): PromptHandle {
1845
+ const id = this.mintTurnId();
1846
+ const rejected = Promise.reject<AgentSessionPromptResult>(error);
1847
+ return Object.assign(rejected, { id, withdraw: () => false });
1848
+ }
1849
+
1813
1850
  private enqueuePrompt(
1814
1851
  text: string,
1815
1852
  operationKind: MeteredOperationKind,
@@ -1817,8 +1854,10 @@ export class AgentConversation implements AgentClient, Bridgeable {
1817
1854
  attachments?: Attachment[],
1818
1855
  participantId?: string,
1819
1856
  consumerMetadata?: PersistenceJsonValue,
1820
- ): Promise<AgentSessionPromptResult> {
1821
- return new Promise<AgentSessionPromptResult>((resolve, reject) => {
1857
+ delivery?: PromptDelivery,
1858
+ ): PromptHandle {
1859
+ const id = this.mintTurnId();
1860
+ const promise = new Promise<AgentSessionPromptResult>((resolve, reject) => {
1822
1861
  if (this.phase === "stopped") {
1823
1862
  reject(new Error("AgentSession is stopped"));
1824
1863
  return;
@@ -1838,10 +1877,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
1838
1877
  reject(error);
1839
1878
  return;
1840
1879
  }
1841
- this.operations.enqueue({
1880
+ // Anything already running or queued means this prompt has to wait.
1881
+ const waited = this.operations.isDraining || this.operations.queuedCount > 0;
1882
+ const item: PromptQueueItem = {
1842
1883
  kind: "prompt",
1843
- turnId: this.mintTurnId(),
1884
+ turnId: id,
1844
1885
  operationKind,
1886
+ delivery: this.steering.resolveDelivery(delivery),
1887
+ waited,
1845
1888
  text,
1846
1889
  ...(participantId ? { participantId } : {}),
1847
1890
  ...(stableConsumerMetadata !== undefined ? { consumerMetadata: stableConsumerMetadata } : {}),
@@ -1849,10 +1892,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
1849
1892
  attachments,
1850
1893
  resolve,
1851
1894
  reject,
1852
- });
1895
+ };
1896
+ this.operations.enqueue(item);
1897
+ this.steering.accepted(item);
1853
1898
  this.emitStateIfChanged();
1854
1899
  void this.pump();
1855
1900
  });
1901
+ return Object.assign(promise, { id, withdraw: () => this.steering.withdraw(id) });
1856
1902
  }
1857
1903
 
1858
1904
  /**
@@ -1993,18 +2039,25 @@ export class AgentConversation implements AgentClient, Bridgeable {
1993
2039
  : "switching_mode";
1994
2040
  this.emitStateIfChanged();
1995
2041
  if (item.kind === "prompt") {
1996
- this.emit({ kind: "turn_started", turnId: item.turnId });
2042
+ // A run of steer messages at the head of the queue goes out as one prompt.
2043
+ const prompt = this.steering.prepareRun(item) as PromptQueueItem;
2044
+ this.steering.turnStarted(prompt);
2045
+ this.emit({ kind: "turn_started", turnId: prompt.turnId });
2046
+ let stopReason: string | undefined;
1997
2047
  try {
1998
- const result = await this.runPrompt(item);
2048
+ const result = await this.runPrompt(prompt);
2049
+ stopReason = result.stopReason;
1999
2050
  this.emit({
2000
2051
  kind: "turn_completed",
2001
- turnId: item.turnId,
2052
+ turnId: prompt.turnId,
2002
2053
  result: copyPromptResult(result),
2003
2054
  });
2004
- item.resolve(result);
2055
+ prompt.resolve(result);
2005
2056
  } catch (err) {
2006
- this.emit({ kind: "turn_failed", turnId: item.turnId, error: String(err) });
2007
- item.reject(err);
2057
+ this.emit({ kind: "turn_failed", turnId: prompt.turnId, error: String(err) });
2058
+ prompt.reject(err);
2059
+ } finally {
2060
+ this.steering.turnEnded(stopReason);
2008
2061
  }
2009
2062
  } else if (item.kind === "handoff") {
2010
2063
  try {
@@ -3012,11 +3065,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
3012
3065
  targetProviderContextId,
3013
3066
  ...(item.participantId ? { participantId: item.participantId } : {}),
3014
3067
  ...(item.consumerMetadata !== undefined ? { consumerMetadata: item.consumerMetadata } : {}),
3068
+ ...(item.parts ? { parts: item.parts } : {}),
3015
3069
  text: item.text,
3016
3070
  })
3017
3071
  : undefined;
3018
- if (owned?.participant && !this._participants.some((participant) => participant.id === owned.participant!.id)) {
3019
- this._participants = [...this._participants, Object.freeze({ ...owned.participant })];
3072
+ for (const participant of owned?.participants ?? (owned?.participant ? [owned.participant] : [])) {
3073
+ if (!this._participants.some((known) => known.id === participant.id)) {
3074
+ this._participants = [...this._participants, Object.freeze({ ...participant })];
3075
+ }
3020
3076
  }
3021
3077
  const providerText = owned?.providerText ?? item.text;
3022
3078
  this.beginTurn(item.turnId);
@@ -3029,16 +3085,21 @@ export class AgentConversation implements AgentClient, Bridgeable {
3029
3085
  operation = await this.openMeteredOperation(item);
3030
3086
  await this.v2Transcript.beginOperation(item.turnId, persistenceOperationKind(item.operationKind));
3031
3087
  transcriptStarted = true;
3032
- const userRecord = await this.v2Transcript.appendPresentationEvent({
3033
- kind: "message",
3034
- operationId: item.turnId,
3035
- role: "user",
3036
- text: item.text,
3037
- status: "completed",
3038
- presentation: { id: `message:${item.turnId}:user`, revision: 1 },
3039
- });
3088
+ // A combined prompt shows each original message, as it was sent.
3089
+ const userTexts = item.parts ? item.parts.map((part) => part.text) : [item.text];
3090
+ const userRecords = [];
3091
+ for (const [index, text] of userTexts.entries()) {
3092
+ userRecords.push(await this.v2Transcript.appendPresentationEvent({
3093
+ kind: "message",
3094
+ operationId: item.turnId,
3095
+ role: "user",
3096
+ text,
3097
+ status: "completed",
3098
+ presentation: { id: `message:${item.turnId}:user${index === 0 ? "" : `:${index + 1}`}`, revision: 1 },
3099
+ }));
3100
+ }
3040
3101
  await this.v2Transcript.syncBeforeDispatch();
3041
- this.presentation.emitPersistedRecord(userRecord);
3102
+ for (const userRecord of userRecords) this.presentation.emitPersistedRecord(userRecord);
3042
3103
  } catch (error) {
3043
3104
  this.endTurn(item.turnId, item.handlers);
3044
3105
  if (transcriptStarted) {
@@ -3159,6 +3220,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3159
3220
  // The message snapshot must enter the shared queue before an activity first seen
3160
3221
  // after it. Later activity revisions keep their original presentation position.
3161
3222
  flushAssistantMessage("in_progress");
3223
+ this.steering.observeActivity(item.turnId, event);
3162
3224
  const result = this.presentation.applyActivity(event);
3163
3225
  this.queueActivityRecords(item.turnId, result.emitted);
3164
3226
  item.handlers?.onRecord?.(result);
@@ -3283,7 +3345,12 @@ export class AgentConversation implements AgentClient, Bridgeable {
3283
3345
  status: res.status,
3284
3346
  });
3285
3347
  }
3286
- const result = Object.freeze({ ...res, operationId: item.turnId, metering: record });
3348
+ const result = Object.freeze({
3349
+ ...res,
3350
+ operationId: item.turnId,
3351
+ metering: record,
3352
+ ...this.steering.resultFields(item.turnId, res.stopReason),
3353
+ });
3287
3354
  await this.ownerRecordWrite;
3288
3355
  if (this.ownerLifecycle) {
3289
3356
  const completed = {
@@ -3712,31 +3779,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
3712
3779
  }
3713
3780
 
3714
3781
  interrupt(options?: InterruptOptions): void {
3782
+ this.steering.interrupted();
3715
3783
  if (options?.clearQueue) {
3716
3784
  const dropped = this.operations.clear();
3785
+ // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
3786
+ // metering record is minted (§16).
3787
+ this.steering.dropped(dropped.filter((item): item is PromptQueueItem => item.kind === "prompt"));
3717
3788
  for (const item of dropped) {
3718
- if (item.kind === "prompt") {
3719
- // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
3720
- // metering record is minted (§16).
3721
- item.resolve({
3722
- text: "",
3723
- messages: Object.freeze([]),
3724
- stopReason: "cancelled",
3725
- status: "cancelled",
3726
- usage: null,
3727
- operationId: item.turnId,
3728
- metering: null,
3729
- });
3730
- } else {
3731
- const label = item.kind === "handoff"
3732
- ? "handoff"
3733
- : item.kind === "set_config" || item.kind === "resolve_config"
3734
- ? "configuration change"
3735
- : item.kind === "resolve_recovery"
3736
- ? "recovery resolution"
3789
+ if (item.kind === "prompt") continue;
3790
+ const label = item.kind === "handoff"
3791
+ ? "handoff"
3792
+ : item.kind === "set_config" || item.kind === "resolve_config"
3793
+ ? "configuration change"
3794
+ : item.kind === "resolve_recovery"
3795
+ ? "recovery resolution"
3737
3796
  : "mode change";
3738
- item.reject(new Error(`${label} cancelled before it started`));
3739
- }
3797
+ item.reject(new Error(`${label} cancelled before it started`));
3740
3798
  }
3741
3799
  this.emitStateIfChanged();
3742
3800
  }