@qlairoslabs/acp-client 0.10.1 → 0.11.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 (42) hide show
  1. package/CONSUMER_GUIDE.md +252 -0
  2. package/README.md +0 -3
  3. package/package.json +1 -1
  4. package/src/agent/adoption/config.ts +57 -0
  5. package/src/agent/adoption/index.ts +8 -0
  6. package/src/agent/adoption/provider-session-delete.ts +27 -0
  7. package/src/agent/adoption/provider-sessions.ts +73 -0
  8. package/src/agent/adoption/recap.ts +15 -0
  9. package/src/agent/adoption/replay.ts +84 -0
  10. package/src/agent/config.ts +182 -0
  11. package/src/agent/conversation-manager.ts +1006 -0
  12. package/src/agent/manager-settings.ts +46 -0
  13. package/src/agent/persisted-lifecycle.ts +309 -0
  14. package/src/agent/persistence-policy/index.ts +8 -0
  15. package/src/agent/persistence-policy/resolver.ts +118 -0
  16. package/src/agent/persistence-policy/types.ts +50 -0
  17. package/src/agent/record-capture.ts +243 -0
  18. package/src/agent-conversation-contracts.ts +11 -0
  19. package/src/agent-conversation-errors.ts +24 -0
  20. package/src/agent-conversation-owner.ts +7 -0
  21. package/src/agent-conversation-queue.ts +23 -0
  22. package/src/agent-session.ts +236 -66
  23. package/src/agent.ts +63 -1223
  24. package/src/audit/config.ts +29 -0
  25. package/src/audit/index.ts +1 -0
  26. package/src/checkpointing/contracts.ts +2 -0
  27. package/src/checkpointing/persistence/sqlite-repository.ts +13 -0
  28. package/src/checkpointing/strategy.ts +11 -5
  29. package/src/client.ts +25 -2
  30. package/src/controller.ts +3 -0
  31. package/src/index.ts +24 -0
  32. package/src/internal-inference/contracts.ts +23 -0
  33. package/src/internal-inference/coordination/manager.ts +22 -8
  34. package/src/persistence/backend.ts +17 -0
  35. package/src/persistence/sqlite-backend.ts +30 -4
  36. package/src/persistence/sqlite-provider-sessions.ts +35 -0
  37. package/src/persistence/sqlite-schema.ts +13 -3
  38. package/src/steering/combine.ts +56 -0
  39. package/src/steering/contracts.ts +84 -0
  40. package/src/steering/controller.ts +205 -0
  41. package/src/steering/index.ts +14 -0
  42. package/src/transport/acp-transport.ts +11 -0
@@ -162,6 +162,15 @@ import type {
162
162
  TranscriptContinuationBuilderContext,
163
163
  } from "./agent-conversation-contracts.ts";
164
164
  import { AgentConversationQueue } from "./agent-conversation-queue.ts";
165
+ import type { ImportedTurn } from "./agent/adoption/replay.ts";
166
+ import {
167
+ SteeringController,
168
+ type PendingMessage,
169
+ type PendingMessageId,
170
+ type PromptDelivery,
171
+ type PromptHandle,
172
+ type SteeringPrompt,
173
+ } from "./steering/index.ts";
165
174
  import { AgentConversationPresentation } from "./agent-conversation-presentation.ts";
166
175
  import {
167
176
  HANDOFF_SUMMARY_PROMPT,
@@ -179,6 +188,8 @@ export {
179
188
  ContinuationUnavailableError,
180
189
  DirectAuditPersistenceUnsupportedError,
181
190
  ProviderSessionError,
191
+ ProviderSessionInUseError,
192
+ ProviderSessionListUnsupportedError,
182
193
  } from "./agent-conversation-errors.ts";
183
194
  export type { ProviderSessionErrorDetails } from "./agent-conversation-errors.ts";
184
195
  export type {
@@ -216,18 +227,9 @@ export type {
216
227
  TranscriptContinuationBuilderContext,
217
228
  } from "./agent-conversation-contracts.ts";
218
229
 
219
- interface PromptQueueItem {
220
- kind: "prompt";
221
- turnId: string;
230
+ interface PromptQueueItem extends SteeringPrompt {
222
231
  /** How this operation is classified in its metering record. */
223
232
  operationKind: MeteredOperationKind;
224
- text: string;
225
- participantId?: string;
226
- consumerMetadata?: PersistenceJsonValue;
227
- handlers?: PromptHandlers;
228
- attachments?: Attachment[];
229
- resolve: (r: AgentSessionPromptResult) => void;
230
- reject: (e: unknown) => void;
231
233
  }
232
234
 
233
235
  /** Object-form prompt input for per-message consumer metadata on Agent-owned conversations. */
@@ -236,6 +238,8 @@ export interface AgentConversationPromptInput {
236
238
  readonly consumerMetadata?: PersistenceJsonValue;
237
239
  readonly handlers?: PromptHandlers;
238
240
  readonly attachments?: Attachment[];
241
+ /** How this prompt waits if a turn is running. Defaults to the conversation's `busyDelivery`. */
242
+ readonly delivery?: PromptDelivery;
239
243
  }
240
244
 
241
245
  export interface AgentConversationAttributedPromptInput extends AgentConversationPromptInput {
@@ -322,6 +326,11 @@ export interface AgentSessionConfig {
322
326
  /** Default MCP servers bound at session creation/switch, unless a call overrides them. */
323
327
  mcpServers?: schema.McpServer[];
324
328
  defaultPermission?: "approve" | "cancel";
329
+ /**
330
+ * How a prompt sent while a turn is running waits when the prompt does not say. `queue` runs it after
331
+ * the turn ends; `steer` delivers it at the next tool boundary. Default `queue`.
332
+ */
333
+ busyDelivery?: PromptDelivery;
325
334
  clientInfo?: { name: string; title?: string; version?: string };
326
335
  /** What we let the agent do through us (terminals, filesystem). All on by default. */
327
336
  clientCapabilities?: AgentControllerConfig["clientCapabilities"];
@@ -449,6 +458,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
449
458
  private readonly log: Logger;
450
459
  private transcriptWrite: Promise<void> = Promise.resolve();
451
460
  private readonly operations = new AgentConversationQueue<QueueItem>();
461
+ private readonly steering: SteeringController<QueueItem>;
452
462
  private stopPromise: Promise<void> | null = null;
453
463
  private phase: AgentSessionPhase = "idle";
454
464
  private notificationSeq = 0;
@@ -543,6 +553,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
543
553
  ?? (isAgentSessionId(this.agentSessionId) ? this.agentSessionId : null);
544
554
  this.ownerLifecycle = config.ownerLifecycle;
545
555
  this.defaultPermission = config.defaultPermission ?? "cancel";
556
+ this.steering = new SteeringController<QueueItem>(
557
+ {
558
+ queue: this.operations,
559
+ emit: (event) => this.emit(event),
560
+ cancelProviderTurn: () => this.controller.interrupt(),
561
+ emitState: () => this.emitStateIfChanged(),
562
+ },
563
+ config.busyDelivery ?? "queue",
564
+ );
546
565
  this._participants = (config.participants ?? []).map((participant) => Object.freeze({ ...participant }));
547
566
  this._adapterId = config.adapterId;
548
567
  this.activeAdapter = config.adapter;
@@ -625,6 +644,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
625
644
  sessionLoadFailure: providerSession.kind === "load"
626
645
  ? providerSession.onFailure ?? "error"
627
646
  : undefined,
647
+ ...(providerSession.kind === "load" && providerSession.onReplay
648
+ ? { onSessionReplay: providerSession.onReplay }
649
+ : {}),
628
650
  });
629
651
  this.bindController(this.controller);
630
652
  }
@@ -633,7 +655,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
633
655
  adapter: Adapter,
634
656
  adapterId: string,
635
657
  mode: AgentMode,
636
- startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure"> = {},
658
+ startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure" | "onSessionReplay"> = {},
637
659
  ): AgentController {
638
660
  return new AgentController({
639
661
  ...this.controllerDefaults,
@@ -1770,48 +1792,67 @@ export class AgentConversation implements AgentClient, Bridgeable {
1770
1792
  }
1771
1793
 
1772
1794
  // --- AgentClient -------------------------------------------------------------
1773
- prompt(input: AgentConversationPromptInput): Promise<AgentSessionPromptResult>;
1795
+ prompt(input: AgentConversationPromptInput): PromptHandle;
1774
1796
  prompt(
1775
1797
  text: string,
1776
1798
  handlers?: PromptHandlers,
1777
1799
  attachments?: Attachment[],
1778
- ): Promise<AgentSessionPromptResult>;
1779
- async prompt(
1800
+ ): PromptHandle;
1801
+ prompt(
1780
1802
  input: string | AgentConversationPromptInput,
1781
1803
  handlers?: PromptHandlers,
1782
1804
  attachments?: Attachment[],
1783
- ): Promise<AgentSessionPromptResult> {
1805
+ ): PromptHandle {
1784
1806
  return typeof input === "string"
1785
1807
  ? this.enqueuePrompt(input, "prompt", handlers, attachments)
1786
- : this.enqueuePrompt(input.text, "prompt", input.handlers, input.attachments, undefined, input.consumerMetadata);
1808
+ : this.enqueuePrompt(
1809
+ input.text, "prompt", input.handlers, input.attachments,
1810
+ undefined, input.consumerMetadata, input.delivery,
1811
+ );
1812
+ }
1813
+
1814
+ /** Messages waiting behind the running operation, in the order they will be sent. */
1815
+ get pendingMessages(): readonly PendingMessage[] {
1816
+ return this.steering.pending();
1817
+ }
1818
+
1819
+ /** Take back a message that has not been sent yet. Returns whether it was still pending. */
1820
+ withdraw(id: PendingMessageId): boolean {
1821
+ return this.steering.withdraw(id);
1787
1822
  }
1788
1823
 
1789
1824
  /** Prompt while attributing the caller to a stable participant identity. */
1790
- promptFrom(input: AgentConversationAttributedPromptInput): Promise<AgentSessionPromptResult>;
1825
+ promptFrom(input: AgentConversationAttributedPromptInput): PromptHandle;
1791
1826
  promptFrom(
1792
1827
  participantId: string,
1793
1828
  text: string,
1794
1829
  handlers?: PromptHandlers,
1795
1830
  attachments?: Attachment[],
1796
- ): Promise<AgentSessionPromptResult>;
1831
+ ): PromptHandle;
1797
1832
  promptFrom(
1798
1833
  input: string | AgentConversationAttributedPromptInput,
1799
1834
  text?: string,
1800
1835
  handlers?: PromptHandlers,
1801
1836
  attachments?: Attachment[],
1802
- ): Promise<AgentSessionPromptResult> {
1837
+ ): PromptHandle {
1803
1838
  if (typeof input !== "string") {
1804
- if (!input.participantId.trim()) return Promise.reject(new Error("participant id cannot be blank"));
1839
+ if (!input.participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
1805
1840
  return this.enqueuePrompt(
1806
1841
  input.text, "prompt", input.handlers, input.attachments,
1807
- input.participantId.trim(), input.consumerMetadata,
1842
+ input.participantId.trim(), input.consumerMetadata, input.delivery,
1808
1843
  );
1809
1844
  }
1810
1845
  const participantId = input;
1811
- if (!participantId.trim()) return Promise.reject(new Error("participant id cannot be blank"));
1846
+ if (!participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
1812
1847
  return this.enqueuePrompt(text!, "prompt", handlers, attachments, participantId.trim());
1813
1848
  }
1814
1849
 
1850
+ private rejectedPrompt(error: Error): PromptHandle {
1851
+ const id = this.mintTurnId();
1852
+ const rejected = Promise.reject<AgentSessionPromptResult>(error);
1853
+ return Object.assign(rejected, { id, withdraw: () => false });
1854
+ }
1855
+
1815
1856
  private enqueuePrompt(
1816
1857
  text: string,
1817
1858
  operationKind: MeteredOperationKind,
@@ -1819,8 +1860,10 @@ export class AgentConversation implements AgentClient, Bridgeable {
1819
1860
  attachments?: Attachment[],
1820
1861
  participantId?: string,
1821
1862
  consumerMetadata?: PersistenceJsonValue,
1822
- ): Promise<AgentSessionPromptResult> {
1823
- return new Promise<AgentSessionPromptResult>((resolve, reject) => {
1863
+ delivery?: PromptDelivery,
1864
+ ): PromptHandle {
1865
+ const id = this.mintTurnId();
1866
+ const promise = new Promise<AgentSessionPromptResult>((resolve, reject) => {
1824
1867
  if (this.phase === "stopped") {
1825
1868
  reject(new Error("AgentSession is stopped"));
1826
1869
  return;
@@ -1840,10 +1883,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
1840
1883
  reject(error);
1841
1884
  return;
1842
1885
  }
1843
- this.operations.enqueue({
1886
+ // Anything already running or queued means this prompt has to wait.
1887
+ const waited = this.operations.isDraining || this.operations.queuedCount > 0;
1888
+ const item: PromptQueueItem = {
1844
1889
  kind: "prompt",
1845
- turnId: this.mintTurnId(),
1890
+ turnId: id,
1846
1891
  operationKind,
1892
+ delivery: this.steering.resolveDelivery(delivery),
1893
+ waited,
1847
1894
  text,
1848
1895
  ...(participantId ? { participantId } : {}),
1849
1896
  ...(stableConsumerMetadata !== undefined ? { consumerMetadata: stableConsumerMetadata } : {}),
@@ -1851,10 +1898,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
1851
1898
  attachments,
1852
1899
  resolve,
1853
1900
  reject,
1854
- });
1901
+ };
1902
+ this.operations.enqueue(item);
1903
+ this.steering.accepted(item);
1855
1904
  this.emitStateIfChanged();
1856
1905
  void this.pump();
1857
1906
  });
1907
+ return Object.assign(promise, { id, withdraw: () => this.steering.withdraw(id) });
1858
1908
  }
1859
1909
 
1860
1910
  /**
@@ -1930,6 +1980,114 @@ export class AgentConversation implements AgentClient, Bridgeable {
1930
1980
  });
1931
1981
  }
1932
1982
 
1983
+ /**
1984
+ * @internal Store the history of an adopted provider session as records, as if its turns had run here.
1985
+ * Messages and activity (tool calls, thoughts) go through the same folding and the same capture policy as a
1986
+ * live turn; nothing is sent to the provider. Imported records carry `imported: true` in their metadata and
1987
+ * the time of the import, since a replay has no timestamps.
1988
+ */
1989
+ async importHistory(turns: readonly ImportedTurn[], importId: string): Promise<void> {
1990
+ const lifecycle = this.ownerLifecycle;
1991
+ if (!this.ownerAgentSessionId || !lifecycle?.record) return;
1992
+ const user = await lifecycle.importParticipant?.();
1993
+ for (const [index, turn] of turns.entries()) {
1994
+ const turnId = `${importId}-${index + 1}`;
1995
+ this.beginTurn(turnId);
1996
+ let users = 0;
1997
+ let assistants = 0;
1998
+ for (const item of turn.items) {
1999
+ if (item.kind === "activity") {
2000
+ this.queueActivityRecords(turnId, this.presentation.applyActivity(item.event).emitted);
2001
+ continue;
2002
+ }
2003
+ // A message settles any reasoning before it, as in a live turn.
2004
+ const settled = this.presentation.closeReasoningBoundary();
2005
+ if (settled) this.queueActivityRecords(turnId, [settled]);
2006
+ const metadata = JSON.stringify({
2007
+ operationId: turnId,
2008
+ imported: true,
2009
+ ...(item.messageId ? { providerMessageId: item.messageId } : {}),
2010
+ });
2011
+ if (item.kind === "user") {
2012
+ users += 1;
2013
+ await this.recordOwned({
2014
+ recordId: users === 1 ? `${turnId}:user` : `${turnId}:user:${users}`,
2015
+ agentSessionId: this.ownerAgentSessionId,
2016
+ agentConversationId: this.agentConversationId,
2017
+ kind: "message",
2018
+ timestamp: new Date().toISOString(),
2019
+ role: "user",
2020
+ ...(user ? { participantId: user.id } : {}),
2021
+ content: item.text,
2022
+ status: "completed",
2023
+ metadata,
2024
+ });
2025
+ } else {
2026
+ assistants += 1;
2027
+ await this.recordOwned({
2028
+ recordId: `${turnId}:assistant:${assistants}`,
2029
+ agentSessionId: this.ownerAgentSessionId,
2030
+ agentConversationId: this.agentConversationId,
2031
+ kind: "message",
2032
+ timestamp: new Date().toISOString(),
2033
+ role: "assistant",
2034
+ logicalMessageId: `message:${turnId}:assistant:${assistants}`,
2035
+ content: item.text,
2036
+ status: "completed",
2037
+ metadata,
2038
+ });
2039
+ }
2040
+ }
2041
+ this.endTurn(turnId);
2042
+ }
2043
+ await this.ownerRecordWrite;
2044
+ }
2045
+
2046
+ /**
2047
+ * @internal Ask the provider session to summarize its own history, as a hidden turn: the exchange is metered
2048
+ * and leaves a native action record, but is not a message of this conversation. Used right after an adoption,
2049
+ * before the conversation is handed to its owner, so nothing can interleave with it.
2050
+ */
2051
+ async requestRecap(instruction: string, recapId: string): Promise<string> {
2052
+ if (!instruction.trim()) throw new Error("recap instruction cannot be blank");
2053
+ const records: OperationMeteringRecord[] = [];
2054
+ await this.recordNativeAction(recapId, "adoption_recap", "started");
2055
+ try {
2056
+ const result = await this.meteredInternalPrompt(recapId, "conversation_checkpoint", instruction, records);
2057
+ if (result.status !== "completed") throw new Error(`adoption recap ${result.status}`);
2058
+ const summary = formatResponseMessages(result.messages, "\n\n").trim();
2059
+ if (!summary) throw new Error("adoption recap returned an empty summary");
2060
+ await this.recordNativeAction(recapId, "adoption_recap", "completed", { output: { chars: summary.length } });
2061
+ return summary;
2062
+ } catch (error) {
2063
+ await this.recordNativeAction(recapId, "adoption_recap", "failed", {
2064
+ error: error instanceof Error ? error.message : String(error),
2065
+ }).catch(() => undefined);
2066
+ throw error;
2067
+ }
2068
+ }
2069
+
2070
+ /**
2071
+ * @internal Store a recap as an assistant message, marked with `origin` in its metadata so it can be told
2072
+ * from something the model said in a turn. It goes through the same capture policy as every message, and
2073
+ * identity delivers it to the Agent's other conversations like any other.
2074
+ */
2075
+ async recordRecap(summary: string, recapId: string, origin: string): Promise<void> {
2076
+ if (!this.ownerAgentSessionId || !this.ownerLifecycle?.record) return;
2077
+ await this.recordOwned({
2078
+ recordId: `${recapId}:assistant:1`,
2079
+ agentSessionId: this.ownerAgentSessionId,
2080
+ agentConversationId: this.agentConversationId,
2081
+ kind: "message",
2082
+ timestamp: new Date().toISOString(),
2083
+ role: "assistant",
2084
+ logicalMessageId: `message:${recapId}:assistant:1`,
2085
+ content: summary,
2086
+ status: "completed",
2087
+ metadata: JSON.stringify({ operationId: recapId, origin, imported: true }),
2088
+ });
2089
+ }
2090
+
1933
2091
  /** @internal Seed a newly created provider thread from a durable recovery checkpoint. */
1934
2092
  async seedRecoveryContext(text: string): Promise<PromptResult> {
1935
2093
  if (!text.trim()) throw new Error("recovery context cannot be blank");
@@ -1995,18 +2153,25 @@ export class AgentConversation implements AgentClient, Bridgeable {
1995
2153
  : "switching_mode";
1996
2154
  this.emitStateIfChanged();
1997
2155
  if (item.kind === "prompt") {
1998
- this.emit({ kind: "turn_started", turnId: item.turnId });
2156
+ // 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;
2158
+ this.steering.turnStarted(prompt);
2159
+ this.emit({ kind: "turn_started", turnId: prompt.turnId });
2160
+ let stopReason: string | undefined;
1999
2161
  try {
2000
- const result = await this.runPrompt(item);
2162
+ const result = await this.runPrompt(prompt);
2163
+ stopReason = result.stopReason;
2001
2164
  this.emit({
2002
2165
  kind: "turn_completed",
2003
- turnId: item.turnId,
2166
+ turnId: prompt.turnId,
2004
2167
  result: copyPromptResult(result),
2005
2168
  });
2006
- item.resolve(result);
2169
+ prompt.resolve(result);
2007
2170
  } catch (err) {
2008
- this.emit({ kind: "turn_failed", turnId: item.turnId, error: String(err) });
2009
- item.reject(err);
2171
+ this.emit({ kind: "turn_failed", turnId: prompt.turnId, error: String(err) });
2172
+ prompt.reject(err);
2173
+ } finally {
2174
+ this.steering.turnEnded(stopReason);
2010
2175
  }
2011
2176
  } else if (item.kind === "handoff") {
2012
2177
  try {
@@ -3014,11 +3179,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
3014
3179
  targetProviderContextId,
3015
3180
  ...(item.participantId ? { participantId: item.participantId } : {}),
3016
3181
  ...(item.consumerMetadata !== undefined ? { consumerMetadata: item.consumerMetadata } : {}),
3182
+ ...(item.parts ? { parts: item.parts } : {}),
3017
3183
  text: item.text,
3018
3184
  })
3019
3185
  : undefined;
3020
- if (owned?.participant && !this._participants.some((participant) => participant.id === owned.participant!.id)) {
3021
- this._participants = [...this._participants, Object.freeze({ ...owned.participant })];
3186
+ for (const participant of owned?.participants ?? (owned?.participant ? [owned.participant] : [])) {
3187
+ if (!this._participants.some((known) => known.id === participant.id)) {
3188
+ this._participants = [...this._participants, Object.freeze({ ...participant })];
3189
+ }
3022
3190
  }
3023
3191
  const providerText = owned?.providerText ?? item.text;
3024
3192
  this.beginTurn(item.turnId);
@@ -3031,16 +3199,21 @@ export class AgentConversation implements AgentClient, Bridgeable {
3031
3199
  operation = await this.openMeteredOperation(item);
3032
3200
  await this.v2Transcript.beginOperation(item.turnId, persistenceOperationKind(item.operationKind));
3033
3201
  transcriptStarted = true;
3034
- const userRecord = await this.v2Transcript.appendPresentationEvent({
3035
- kind: "message",
3036
- operationId: item.turnId,
3037
- role: "user",
3038
- text: item.text,
3039
- status: "completed",
3040
- presentation: { id: `message:${item.turnId}:user`, revision: 1 },
3041
- });
3202
+ // A combined prompt shows each original message, as it was sent.
3203
+ const userTexts = item.parts ? item.parts.map((part) => part.text) : [item.text];
3204
+ const userRecords = [];
3205
+ for (const [index, text] of userTexts.entries()) {
3206
+ userRecords.push(await this.v2Transcript.appendPresentationEvent({
3207
+ kind: "message",
3208
+ operationId: item.turnId,
3209
+ role: "user",
3210
+ text,
3211
+ status: "completed",
3212
+ presentation: { id: `message:${item.turnId}:user${index === 0 ? "" : `:${index + 1}`}`, revision: 1 },
3213
+ }));
3214
+ }
3042
3215
  await this.v2Transcript.syncBeforeDispatch();
3043
- this.presentation.emitPersistedRecord(userRecord);
3216
+ for (const userRecord of userRecords) this.presentation.emitPersistedRecord(userRecord);
3044
3217
  } catch (error) {
3045
3218
  this.endTurn(item.turnId, item.handlers);
3046
3219
  if (transcriptStarted) {
@@ -3161,6 +3334,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3161
3334
  // The message snapshot must enter the shared queue before an activity first seen
3162
3335
  // after it. Later activity revisions keep their original presentation position.
3163
3336
  flushAssistantMessage("in_progress");
3337
+ this.steering.observeActivity(item.turnId, event);
3164
3338
  const result = this.presentation.applyActivity(event);
3165
3339
  this.queueActivityRecords(item.turnId, result.emitted);
3166
3340
  item.handlers?.onRecord?.(result);
@@ -3285,7 +3459,12 @@ export class AgentConversation implements AgentClient, Bridgeable {
3285
3459
  status: res.status,
3286
3460
  });
3287
3461
  }
3288
- const result = Object.freeze({ ...res, operationId: item.turnId, metering: record });
3462
+ const result = Object.freeze({
3463
+ ...res,
3464
+ operationId: item.turnId,
3465
+ metering: record,
3466
+ ...this.steering.resultFields(item.turnId, res.stopReason),
3467
+ });
3289
3468
  await this.ownerRecordWrite;
3290
3469
  if (this.ownerLifecycle) {
3291
3470
  const completed = {
@@ -3714,31 +3893,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
3714
3893
  }
3715
3894
 
3716
3895
  interrupt(options?: InterruptOptions): void {
3896
+ this.steering.interrupted();
3717
3897
  if (options?.clearQueue) {
3718
3898
  const dropped = this.operations.clear();
3899
+ // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
3900
+ // metering record is minted (§16).
3901
+ this.steering.dropped(dropped.filter((item): item is PromptQueueItem => item.kind === "prompt"));
3719
3902
  for (const item of dropped) {
3720
- if (item.kind === "prompt") {
3721
- // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
3722
- // metering record is minted (§16).
3723
- item.resolve({
3724
- text: "",
3725
- messages: Object.freeze([]),
3726
- stopReason: "cancelled",
3727
- status: "cancelled",
3728
- usage: null,
3729
- operationId: item.turnId,
3730
- metering: null,
3731
- });
3732
- } else {
3733
- const label = item.kind === "handoff"
3734
- ? "handoff"
3735
- : item.kind === "set_config" || item.kind === "resolve_config"
3736
- ? "configuration change"
3737
- : item.kind === "resolve_recovery"
3738
- ? "recovery resolution"
3903
+ if (item.kind === "prompt") continue;
3904
+ const label = item.kind === "handoff"
3905
+ ? "handoff"
3906
+ : item.kind === "set_config" || item.kind === "resolve_config"
3907
+ ? "configuration change"
3908
+ : item.kind === "resolve_recovery"
3909
+ ? "recovery resolution"
3739
3910
  : "mode change";
3740
- item.reject(new Error(`${label} cancelled before it started`));
3741
- }
3911
+ item.reject(new Error(`${label} cancelled before it started`));
3742
3912
  }
3743
3913
  this.emitStateIfChanged();
3744
3914
  }