@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
package/src/response.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { ResponseChunk, ResponseMessage } from "./types.ts";
2
+ import type { ResolvedPart } from "./media/parts.ts";
2
3
 
3
4
  export interface IncomingResponseChunk {
5
+ part?: ResolvedPart;
4
6
  text: string;
5
7
  messageId?: string;
6
8
  /** Supplied when an upstream client already resolved the boundary. */
@@ -33,12 +35,18 @@ export function joinResponseMessages(messages: readonly ResponseMessage[]): stri
33
35
  }
34
36
 
35
37
  /**
36
- * Fold response deltas without inventing separators. Only a change between two explicit
37
- * ACP message ids proves that a new assistant message started; missing ids remain part of
38
- * the current message because no boundary can be inferred safely.
38
+ * Fold response deltas without inventing separators. A new assistant message starts when the
39
+ * explicit ACP message id changes, or after `closeMessage()` (a tool call ended the text before
40
+ * it). Otherwise missing ids remain part of the current message: no boundary can be inferred.
39
41
  */
40
42
  export class ResponseAccumulator {
41
- private readonly entries: Array<{ messageId?: string; text: string }> = [];
43
+ private readonly entries: Array<{ messageId?: string; text: string; parts?: ResolvedPart[] }> = [];
44
+ private closed = false;
45
+
46
+ /** End the current message: the next chunk starts a new one, whatever its id. */
47
+ closeMessage(): void {
48
+ if (this.entries.length > 0) this.closed = true;
49
+ }
42
50
 
43
51
  append(chunk: IncomingResponseChunk): ResponseChunk {
44
52
  let current = this.entries.at(-1);
@@ -49,7 +57,8 @@ export class ResponseAccumulator {
49
57
  chunk.messageId !== current.messageId);
50
58
  // The first observed chunk necessarily starts our first entry, even if a malformed
51
59
  // upstream callback says otherwise.
52
- const startsMessage = !current || (chunk.startsMessage ?? inferredStart);
60
+ const startsMessage = !current || this.closed || (chunk.startsMessage ?? inferredStart);
61
+ this.closed = false;
53
62
 
54
63
  if (startsMessage) {
55
64
  current = chunk.messageId === undefined
@@ -64,9 +73,23 @@ export class ResponseAccumulator {
64
73
  entry.text += chunk.text;
65
74
  }
66
75
 
76
+ // A message keeps parts once it has media: its text before the first media part becomes the first
77
+ // text part, and later text extends the last text part.
78
+ const entry = this.entries.at(-1)!;
79
+ if (chunk.part) {
80
+ if (!entry.parts) {
81
+ const earlier = entry.text.slice(0, entry.text.length - chunk.text.length);
82
+ entry.parts = earlier && !startsMessage ? [{ kind: "text", text: earlier }] : [];
83
+ }
84
+ entry.parts.push(chunk.part);
85
+ } else if (entry.parts && chunk.text) {
86
+ const last = entry.parts.at(-1);
87
+ if (last?.kind === "text") entry.parts[entry.parts.length - 1] = { ...last, text: last.text + chunk.text };
88
+ else entry.parts.push({ kind: "text", text: chunk.text });
89
+ }
67
90
  return chunk.messageId === undefined
68
- ? { text: chunk.text, startsMessage }
69
- : { text: chunk.text, messageId: chunk.messageId, startsMessage };
91
+ ? { text: chunk.text, startsMessage, ...(chunk.part ? { part: chunk.part } : {}) }
92
+ : { text: chunk.text, messageId: chunk.messageId, startsMessage, ...(chunk.part ? { part: chunk.part } : {}) };
70
93
  }
71
94
 
72
95
  /** @deprecated Prefer `snapshot()` and preserve the distinct response messages. */
@@ -74,9 +97,18 @@ export class ResponseAccumulator {
74
97
  return joinResponseMessages(this.entries);
75
98
  }
76
99
 
100
+ /** The parts of the message being received, when it has any media. */
101
+ currentParts(): readonly ResolvedPart[] | undefined {
102
+ const parts = this.entries.at(-1)?.parts;
103
+ return parts ? Object.freeze([...parts]) : undefined;
104
+ }
105
+
77
106
  snapshot(): readonly ResponseMessage[] {
78
107
  return Object.freeze(
79
- this.entries.map((entry) => Object.freeze({ ...entry })),
108
+ this.entries.map((entry) => Object.freeze({
109
+ ...entry,
110
+ ...(entry.parts ? { parts: Object.freeze([...entry.parts]) } : {}),
111
+ })),
80
112
  );
81
113
  }
82
114
  }
@@ -1,5 +1,6 @@
1
1
  import type { PromptHandlers } from "../types.ts";
2
- import type { PromptPart, SteeringPrompt } from "./contracts.ts";
2
+ import type { CombinedMessage, SteeringPrompt } from "./contracts.ts";
3
+ import { attachmentParts } from "../media/acp.ts";
3
4
 
4
5
  /** Text of a combined prompt: the messages in order, separated by a blank line. Nothing is added. */
5
6
  export const COMBINED_TEXT_SEPARATOR = "\n\n";
@@ -24,10 +25,12 @@ export function mergeHandlers(list: readonly (PromptHandlers | undefined)[]): Pr
24
25
  return merged;
25
26
  }
26
27
 
27
- function partOf(prompt: SteeringPrompt): PromptPart {
28
+ function partOf(prompt: SteeringPrompt): CombinedMessage {
28
29
  return {
29
30
  id: prompt.turnId,
30
31
  text: prompt.text,
32
+ messageParts: prompt.messageParts,
33
+ attachments: prompt.attachments,
31
34
  ...(prompt.participantId ? { participantId: prompt.participantId } : {}),
32
35
  ...(prompt.consumerMetadata !== undefined ? { consumerMetadata: prompt.consumerMetadata } : {}),
33
36
  };
@@ -42,13 +45,17 @@ export function combinePrompts<T extends SteeringPrompt>(run: readonly T[]): T {
42
45
  const [head] = run;
43
46
  if (!head) throw new Error("cannot combine an empty run of prompts");
44
47
  if (run.length === 1) return head;
45
- const attachments = run.flatMap((prompt) => prompt.attachments ?? []);
46
48
  const handlers = mergeHandlers(run.map((prompt) => prompt.handlers));
47
49
  return {
48
50
  ...head,
49
51
  text: run.map((prompt) => prompt.text).join(COMBINED_TEXT_SEPARATOR),
50
52
  parts: run.map(partOf),
51
- ...(attachments.length > 0 ? { attachments } : { attachments: undefined }),
53
+ messageParts: run.flatMap((prompt, index) => [
54
+ ...(index ? [{ kind: "text" as const, text: COMBINED_TEXT_SEPARATOR }] : []),
55
+ ...(prompt.messageParts ?? [{ kind: "text" as const, text: prompt.text }]),
56
+ ...attachmentParts(prompt.attachments),
57
+ ]),
58
+ attachments: undefined,
52
59
  ...(handlers ? { handlers } : { handlers: undefined }),
53
60
  resolve: (result) => run.forEach((prompt) => prompt.resolve(result)),
54
61
  reject: (error) => run.forEach((prompt) => prompt.reject(error)),
@@ -1,6 +1,7 @@
1
1
  import type { AgentSessionPromptResult } from "../agent-conversation-contracts.ts";
2
2
  import type { PersistenceJsonValue } from "../persistence/backend.ts";
3
3
  import type { Attachment, PromptHandlers } from "../types.ts";
4
+ import type { MessagePart } from "../media/parts.ts";
4
5
 
5
6
  /**
6
7
  * How a prompt sent while a turn is running waits.
@@ -15,10 +16,10 @@ export type PromptDelivery = "steer" | "queue";
15
16
  export type PendingMessageId = string;
16
17
 
17
18
  /** Why a pending message was delivered when it was. */
18
- export type MessageDeliveryVia = "tool_boundary" | "interrupt" | "turn_end";
19
+ export type MessageDeliveryVia = "tool_boundary" | "interrupt" | "turn_end" | "stall";
19
20
 
20
21
  /** Why a turn was cancelled. Reported only when the turn really ended cancelled. */
21
- export type PromptEndedBy = "steer" | "interrupt";
22
+ export type PromptEndedBy = "steer" | "interrupt" | "stalled" | "error";
22
23
 
23
24
  export interface PendingMessage {
24
25
  readonly id: PendingMessageId;
@@ -26,6 +27,7 @@ export interface PendingMessage {
26
27
  readonly delivery: PromptDelivery;
27
28
  readonly participantId?: string;
28
29
  readonly text: string;
30
+ readonly heldBy?: string;
29
31
  }
30
32
 
31
33
  /**
@@ -40,6 +42,8 @@ export interface PromptHandle extends Promise<AgentSessionPromptResult> {
40
42
 
41
43
  /** Events about messages that wait. They go on the conversation event stream. */
42
44
  export type MessageEvent =
45
+ | { readonly kind: "message_held"; readonly id: PendingMessageId; readonly failedTurnId: string }
46
+ | { readonly kind: "message_released"; readonly id: PendingMessageId; readonly failedTurnId: string }
43
47
  | {
44
48
  readonly kind: "message_pending";
45
49
  readonly id: PendingMessageId;
@@ -57,13 +61,18 @@ export type MessageEvent =
57
61
  | { readonly kind: "message_withdrawn"; readonly id: PendingMessageId };
58
62
 
59
63
  /** One original message of a combined prompt. */
60
- export interface PromptPart {
64
+ export interface CombinedMessage {
65
+ readonly messageParts?: readonly MessagePart[];
66
+ readonly attachments?: readonly Attachment[];
61
67
  readonly id: PendingMessageId;
62
68
  readonly text: string;
63
69
  readonly participantId?: string;
64
70
  readonly consumerMetadata?: PersistenceJsonValue;
65
71
  }
66
72
 
73
+ /** @deprecated Use CombinedMessage. */
74
+ export type PromptPart = CombinedMessage;
75
+
67
76
  /** The fields of a queued prompt that steering reads and writes. */
68
77
  export interface SteeringPrompt {
69
78
  readonly kind: "prompt";
@@ -77,8 +86,9 @@ export interface SteeringPrompt {
77
86
  consumerMetadata?: PersistenceJsonValue;
78
87
  handlers?: PromptHandlers;
79
88
  attachments?: Attachment[];
89
+ messageParts?: readonly MessagePart[];
80
90
  /** Present only on a combined prompt: the original messages, in order. */
81
- parts?: readonly PromptPart[];
91
+ parts?: readonly CombinedMessage[];
82
92
  resolve: (result: AgentSessionPromptResult) => void;
83
93
  reject: (error: unknown) => void;
84
94
  }
@@ -1,3 +1,4 @@
1
+ import { ToolTracker } from "../operations/activity-tracker.ts";
1
2
  import type { AgentSessionPromptResult } from "../agent-conversation-contracts.ts";
2
3
  import type { AgentConversationQueue } from "../agent-conversation-queue.ts";
3
4
  import type { ActivityEvent } from "../types.ts";
@@ -24,11 +25,10 @@ export interface SteeringHost<T extends { readonly kind: string }> {
24
25
 
25
26
  interface ActiveTurn {
26
27
  readonly turnId: string;
27
- readonly tools: Map<string, string>;
28
+ readonly tools: ToolTracker;
28
29
  endedBy?: PromptEndedBy;
29
30
  }
30
31
 
31
- const TERMINAL = new Set(["completed", "failed"]);
32
32
 
33
33
  /** A prompt the consumer started and that steering may cancel. Hidden or internal turns are not. */
34
34
  function isConsumerPrompt<T extends { readonly kind: string }>(item: T): item is T & SteeringPrompt {
@@ -40,29 +40,88 @@ function isConsumerPrompt<T extends { readonly kind: string }>(item: T): item is
40
40
  *
41
41
  * There is one FIFO (the conversation's operations queue). This class adds a delivery mode to the
42
42
  * prompts in it, watches the running turn for a tool boundary, and sends the head of the queue by
43
- * cancelling the turn. It never reorders the queue and never cancels anything but a consumer prompt.
43
+ * cancelling the turn. It skips held queue messages after failures and only cancels consumer prompts.
44
44
  */
45
45
  export class SteeringController<T extends { readonly kind: string }> {
46
46
  #active: ActiveTurn | null = null;
47
+ #heldBy: string | null = null;
47
48
  /** How the previous turn ended, for the `via` of the next delivery. */
48
49
  #previousEndedBy: PromptEndedBy | null = null;
50
+ /** Where `takeNext()` took the last item from: the items after it in the FIFO start there. */
51
+ #takenAt = 0;
49
52
 
50
53
  constructor(
51
54
  private readonly host: SteeringHost<T>,
52
55
  readonly defaultDelivery: PromptDelivery,
53
56
  ) {}
54
57
 
58
+ /** The failed turn holding the queue, if any. */
59
+ get hold(): { readonly failedTurnId: string } | null {
60
+ return this.#heldBy ? Object.freeze({ failedTurnId: this.#heldBy }) : null;
61
+ }
62
+
63
+ /** Whether an item may run now: everything except a queued message during a hold. */
64
+ #eligible(item: T): boolean {
65
+ return !this.#heldBy || !isConsumerPrompt(item) || item.delivery !== "queue";
66
+ }
67
+
68
+ get hasRunnable(): boolean {
69
+ return this.host.queue.snapshot().some((item) => this.#eligible(item));
70
+ }
71
+
72
+ /** The next item that may run, removed from the queue. */
73
+ takeNext(): T | undefined {
74
+ this.#takenAt = this.host.queue.snapshot().findIndex((item) => this.#eligible(item));
75
+ return this.host.queue.remove((item) => this.#eligible(item));
76
+ }
77
+
78
+ /** The steers the next delivery would combine. */
79
+ followingSteers(): readonly string[] {
80
+ return this.#headRun().map((item) => item.turnId);
81
+ }
82
+
83
+ /**
84
+ * A turn the provider received ended `stalled` or `error`: every happy-path queued message is held,
85
+ * and steers may repair the turn. A prompt that failed before reaching the provider calls
86
+ * `turnEnded(undefined)` instead and holds nothing.
87
+ */
88
+ failed(turnId: string, reason: "stalled" | "error"): void {
89
+ this.#previousEndedBy = reason;
90
+ this.#heldBy = turnId;
91
+ for (const item of this.#queuedMessages()) {
92
+ this.host.emit({ kind: "message_held", id: item.turnId, failedTurnId: turnId });
93
+ }
94
+ this.#active = null;
95
+ this.host.emitState();
96
+ }
97
+ #release(): void {
98
+ const failedTurnId = this.#heldBy;
99
+ if (!failedTurnId) return;
100
+ this.#heldBy = null;
101
+ for (const item of this.#queuedMessages()) {
102
+ this.host.emit({ kind: "message_released", id: item.turnId, failedTurnId });
103
+ }
104
+ this.host.emitState();
105
+ }
106
+
107
+ #queuedMessages(): SteeringPrompt[] {
108
+ return this.host.queue.snapshot().filter(isConsumerPrompt).filter((item) => item.delivery === "queue");
109
+ }
110
+
55
111
  resolveDelivery(requested: PromptDelivery | undefined): PromptDelivery {
56
112
  return requested ?? this.defaultDelivery;
57
113
  }
58
114
 
59
115
  /** The mode in effect for a message accepted now. */
60
116
  effectiveDelivery(requested: PromptDelivery): PromptDelivery {
61
- return this.#active ? requested : "queue";
117
+ return this.#active || this.#heldBy ? requested : "queue";
62
118
  }
63
119
 
64
120
  /** Called when a prompt has been queued. Only prompts that had to wait are reported. */
65
121
  accepted(item: SteeringPrompt): void {
122
+ if (this.#heldBy && item.delivery === "queue") {
123
+ this.host.emit({ kind: "message_held", id: item.turnId, failedTurnId: this.#heldBy });
124
+ }
66
125
  if (!item.waited) return;
67
126
  this.host.emit({
68
127
  kind: "message_pending",
@@ -74,7 +133,7 @@ export class SteeringController<T extends { readonly kind: string }> {
74
133
  // --- the running turn --------------------------------------------------------------------
75
134
 
76
135
  turnStarted(item: SteeringPrompt): void {
77
- this.#active = item.operationKind === "prompt" ? { turnId: item.turnId, tools: new Map() } : null;
136
+ this.#active = item.operationKind === "prompt" ? { turnId: item.turnId, tools: new ToolTracker() } : null;
78
137
  }
79
138
 
80
139
  /** Activity of the running turn. A tool call settling is where a steer message is delivered. */
@@ -82,13 +141,12 @@ export class SteeringController<T extends { readonly kind: string }> {
82
141
  const active = this.#active;
83
142
  if (!active || active.turnId !== turnId) return;
84
143
  if (event.kind !== "tool" && event.kind !== "tool_update") return;
85
- const previous = active.tools.get(event.toolCallId);
86
- const status = event.status ?? previous ?? "pending";
87
- active.tools.set(event.toolCallId, status);
88
- const settled = TERMINAL.has(status) && !(previous !== undefined && TERMINAL.has(previous));
89
- if (!settled) return;
90
- const inFlight = [...active.tools.values()].some((value) => !TERMINAL.has(value));
91
- if (!inFlight) this.#boundary(active);
144
+ const settled = active.tools.observe(event);
145
+ if (settled && active.tools.inFlight === 0) this.#boundary(active);
146
+ }
147
+
148
+ toolBoundary(turnId: string): void {
149
+ if (this.#active?.turnId === turnId) this.#boundary(this.#active);
92
150
  }
93
151
 
94
152
  /** A tool call has settled and nothing else is running: send the head of the queue if it steers. */
@@ -105,8 +163,13 @@ export class SteeringController<T extends { readonly kind: string }> {
105
163
  if (this.#active && !this.#active.endedBy) this.#active.endedBy = "interrupt";
106
164
  }
107
165
 
108
- /** The turn finished. `endedBy` is reported only if the provider really stopped the turn. */
166
+ /**
167
+ * The turn finished. `endedBy` is reported only if the provider really stopped the turn. Only a
168
+ * consumer turn that completes releases a hold; internal prompts do not.
169
+ */
109
170
  turnEnded(stopReason: string | undefined): void {
171
+ if (stopReason === "stalled" || stopReason === "error") return;
172
+ if (this.#active && stopReason && stopReason !== "cancelled") this.#release();
110
173
  const endedBy = this.#active?.endedBy;
111
174
  this.#previousEndedBy = endedBy && stopReason === "cancelled" ? endedBy : null;
112
175
  this.#active = null;
@@ -124,15 +187,24 @@ export class SteeringController<T extends { readonly kind: string }> {
124
187
 
125
188
  /**
126
189
  * Called when a prompt reaches the head of the queue. A run of consecutive `steer` messages is
127
- * sent as one prompt; anything else is sent as it is.
190
+ * sent as one prompt; anything else is sent as it is. The run stops at the next queued message,
191
+ * held or not: steers sent after it run after it.
128
192
  */
129
- prepareRun(head: SteeringPrompt): SteeringPrompt {
130
- const run = head.operationKind === "prompt" && head.delivery === "steer"
131
- ? [head, ...(this.host.queue.takeWhile((item) => isConsumerPrompt(item) && item.delivery === "steer") as unknown as SteeringPrompt[])]
132
- : [head];
193
+ prepareRun(
194
+ head: SteeringPrompt,
195
+ deliver: (event: MessageEvent) => void = (event) => this.host.emit(event),
196
+ ): SteeringPrompt {
197
+ const run = [head];
198
+ if (head.operationKind === "prompt" && head.delivery === "steer") {
199
+ for (;;) {
200
+ const next = this.host.queue.snapshot()[this.#takenAt];
201
+ if (!next || !isConsumerPrompt(next) || next.delivery !== "steer") break;
202
+ run.push(this.host.queue.remove((item) => item === next) as unknown as SteeringPrompt);
203
+ }
204
+ }
133
205
  const waited = run.filter((item) => item.waited);
134
206
  if (waited.length > 0) {
135
- this.host.emit({
207
+ deliver({
136
208
  kind: "message_delivered",
137
209
  ids: waited.map((item) => item.turnId),
138
210
  via: this.#via(),
@@ -145,16 +217,18 @@ export class SteeringController<T extends { readonly kind: string }> {
145
217
  }
146
218
 
147
219
  #via(): MessageDeliveryVia {
148
- return this.#previousEndedBy === "steer"
220
+ return this.#previousEndedBy === "stalled" ? "stall" : this.#previousEndedBy === "steer"
149
221
  ? "tool_boundary"
150
222
  : this.#previousEndedBy === "interrupt"
151
223
  ? "interrupt"
152
224
  : "turn_end";
153
225
  }
154
226
 
227
+ /** The steers the next delivery would combine: from the first runnable item up to the next queued message. */
155
228
  #headRun(): SteeringPrompt[] {
229
+ const queued = this.host.queue.snapshot();
156
230
  const run: SteeringPrompt[] = [];
157
- for (const item of this.host.queue.snapshot()) {
231
+ for (const item of queued.slice(Math.max(0, queued.findIndex((item) => this.#eligible(item))))) {
158
232
  if (!isConsumerPrompt(item) || item.delivery !== "steer") break;
159
233
  run.push(item);
160
234
  }
@@ -168,6 +242,7 @@ export class SteeringController<T extends { readonly kind: string }> {
168
242
  return this.host.queue.snapshot().filter(isConsumerPrompt).map((item) => ({
169
243
  id: item.turnId,
170
244
  delivery: item.delivery,
245
+ ...(this.#heldBy && item.delivery === "queue" ? { heldBy: this.#heldBy } : {}),
171
246
  ...(item.participantId ? { participantId: item.participantId } : {}),
172
247
  text: item.text,
173
248
  }));
@@ -9,6 +9,7 @@ export type {
9
9
  PromptDelivery,
10
10
  PromptEndedBy,
11
11
  PromptHandle,
12
+ CombinedMessage,
12
13
  PromptPart,
13
14
  SteeringPrompt,
14
15
  } from "./contracts.ts";
@@ -29,6 +29,7 @@ export interface AcpTransportOptions {
29
29
  * takes these off the wire itself rather than going through the SDK. See
30
30
  * `interceptUpdates` for why.
31
31
  */
32
+ onRequest?: (sessionId: string | null) => void;
32
33
  onUpdate?: (notification: schema.SessionNotification) => void;
33
34
  /** The agent asked for permission (blocking — must resolve to an outcome). */
34
35
  onPermissionRequest?: (
@@ -56,6 +57,8 @@ export interface AcpTransportOptions {
56
57
  * our interpretation, and the SDK sees neither the lines we intercept nor what it wrote.
57
58
  */
58
59
  onWire?: (entry: WireEntry) => void;
60
+ /** The ACP connection closed, whatever the cause (exit, crash or stop()). */
61
+ onDisconnect?: () => void;
59
62
  /** The process exited unexpectedly (not via stop()). */
60
63
  onCrash?: (code: number | null) => void;
61
64
  }
@@ -71,6 +74,8 @@ export class AcpTransport {
71
74
  this.disposeLaunch = onceDispose(opts.launch.dispose);
72
75
  }
73
76
 
77
+ get isConnected(): boolean { return !!this.connection && !this.connection.signal.aborted; }
78
+
74
79
  async start(): Promise<void> {
75
80
  if (this.proc) return;
76
81
 
@@ -109,6 +114,7 @@ export class AcpTransport {
109
114
  this.tap = tap;
110
115
  const handler = new ClientHandler(this.opts);
111
116
  this.connection = new acp.ClientSideConnection(() => handler, stream);
117
+ this.connection.signal.addEventListener("abort", () => this.opts.onDisconnect?.(), { once: true });
112
118
 
113
119
  if (proc.stderr) this.pumpStderr(proc.stderr as ReadableStream<Uint8Array>);
114
120
 
@@ -349,16 +355,21 @@ class ClientHandler implements acp.Client {
349
355
  writeTextFile?: acp.Client["writeTextFile"];
350
356
 
351
357
  constructor(private opts: AcpTransportOptions) {
352
- if (opts.onReadTextFile) this.readTextFile = (p) => opts.onReadTextFile!(p);
353
- if (opts.onWriteTextFile) this.writeTextFile = (p) => opts.onWriteTextFile!(p);
358
+ // Every request from the agent is output for the operation lifecycle.
359
+ const observed = <P extends { sessionId: string }, R>(handle: (p: P) => R) => (p: P): R => {
360
+ opts.onRequest?.(p.sessionId);
361
+ return handle(p);
362
+ };
363
+ if (opts.onReadTextFile) this.readTextFile = observed(opts.onReadTextFile);
364
+ if (opts.onWriteTextFile) this.writeTextFile = observed(opts.onWriteTextFile);
354
365
 
355
366
  const terminals = opts.terminals;
356
367
  if (terminals) {
357
- this.createTerminal = (p) => terminals.create(p);
358
- this.terminalOutput = (p) => terminals.output(p);
359
- this.waitForTerminalExit = (p) => terminals.waitForExit(p);
360
- this.killTerminal = (p) => terminals.kill(p);
361
- this.releaseTerminal = (p) => terminals.release(p);
368
+ this.createTerminal = observed((p) => terminals.create(p));
369
+ this.terminalOutput = observed((p) => terminals.output(p));
370
+ this.waitForTerminalExit = observed((p) => terminals.waitForExit(p));
371
+ this.killTerminal = observed((p) => terminals.kill(p));
372
+ this.releaseTerminal = observed((p) => terminals.release(p));
362
373
  }
363
374
  }
364
375
 
package/src/types.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ResolvedPart } from "./media/parts.ts";
1
2
  // Core shared types — the OUTPUT contract.
2
3
  // These are what every client (AcpClient, and later PtyClient) produces, so callers
3
4
  // render against these regardless of which mode is active. See SPEC.md.
@@ -58,6 +59,7 @@ export type Usage = TokenUsage;
58
59
  * call RESOLVES (not rejects) with whatever partial text arrived.
59
60
  */
60
61
  export interface PromptResult {
62
+ readonly cancel?: "acknowledged" | "forced";
61
63
  /**
62
64
  * Legacy lossy projection of `messages`, separated by one blank line.
63
65
  * @deprecated Use `messages`, preserving each logical ACP response message. Consumers
@@ -78,6 +80,8 @@ export interface PromptResult {
78
80
 
79
81
  /** One boundary-aware delta from an ACP `agent_message_chunk`. */
80
82
  export interface ResponseChunk {
83
+ /** Non-text delta; text remains the compatibility projection. */
84
+ part?: ResolvedPart;
81
85
  text: string;
82
86
  messageId?: string;
83
87
  /** True when this chunk begins a new assistant message. */
@@ -86,6 +90,8 @@ export interface ResponseChunk {
86
90
 
87
91
  /** One assistant message assembled from consecutive ACP response chunks. */
88
92
  export interface ResponseMessage {
93
+ /** Ordered normalized parts, present for messages containing media. */
94
+ parts?: readonly ResolvedPart[];
89
95
  messageId?: string;
90
96
  text: string;
91
97
  }
@@ -273,6 +279,7 @@ export interface PromptHandlers {
273
279
  */
274
280
  onPermissionRequest?: (
275
281
  request: PermissionRequest,
282
+ signal?: AbortSignal,
276
283
  ) => PermissionOutcome | Promise<PermissionOutcome>;
277
284
  }
278
285
 
package/src/updates.ts CHANGED
@@ -20,6 +20,7 @@ import type {
20
20
  ToolUpdateActivity,
21
21
  ResponseChunk,
22
22
  } from "./types.ts";
23
+ import { acpToPart } from "./media/acp.ts";
23
24
 
24
25
  /** A response delta preserving its ACP message id, or null for any other update. */
25
26
  export function extractResponseChunk(
@@ -29,10 +30,9 @@ export function extractResponseChunk(
29
30
  if (u.sessionUpdate !== "agent_message_chunk") return null;
30
31
  const content = u.content;
31
32
  const text = content?.type === "text" ? (content.text ?? "") : "";
32
- if (!text) return null;
33
- return u.messageId == null
34
- ? { text }
35
- : { text, messageId: String(u.messageId) };
33
+ const part = content && content.type !== "text" ? acpToPart(content as schema.ContentBlock) : undefined;
34
+ if (!text && !part) return null;
35
+ return { text, ...(part ? { part } : {}), ...(u.messageId == null ? {} : { messageId: String(u.messageId) }) };
36
36
  }
37
37
 
38
38
  /** @deprecated Prefer `extractResponseChunk` when message boundaries matter. */