@qlairoslabs/acp-client 0.4.1 → 0.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.4.1",
3
+ "version": "0.4.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",
@@ -19,6 +19,7 @@ import type { Capabilities } from "./capabilities.ts";
19
19
  import type { ConfigOptions } from "./config-options.ts";
20
20
  import type { ConnectResult } from "./client.ts";
21
21
  import { noopLogger, type Logger } from "./logger.ts";
22
+ import { ResponseAccumulator } from "./response.ts";
22
23
  import type { SessionManager, MergedSession } from "./session-manager.ts";
23
24
  import {
24
25
  appendTranscriptLine,
@@ -638,6 +639,7 @@ export class AgentSession implements AgentClient, Bridgeable {
638
639
  });
639
640
 
640
641
  const chunks: string[] = [];
642
+ const response = new ResponseAccumulator();
641
643
  const wrappedHandlers: PromptHandlers = {
642
644
  ...item.handlers,
643
645
  // Fired from here, from the one aggregator this session owns — nothing below needs
@@ -647,6 +649,10 @@ export class AgentSession implements AgentClient, Bridgeable {
647
649
  chunks.push(chunk);
648
650
  item.handlers?.onChunk?.(chunk);
649
651
  },
652
+ onResponseChunk: (chunk) => {
653
+ response.append(chunk);
654
+ item.handlers?.onResponseChunk?.(chunk);
655
+ },
650
656
  onActivity: (event) => {
651
657
  const result = this.aggregator.apply(event);
652
658
  if (this.transcriptActivity) {
@@ -673,6 +679,7 @@ export class AgentSession implements AgentClient, Bridgeable {
673
679
  t: "msg",
674
680
  role: "assistant",
675
681
  text: res.text,
682
+ messages: res.messages,
676
683
  ts: Date.now(),
677
684
  usage: res.usage,
678
685
  stopReason: res.stopReason,
@@ -683,11 +690,19 @@ export class AgentSession implements AgentClient, Bridgeable {
683
690
  // Easy to miss, and the whole point of R4: a turn that died mid-tool still records
684
691
  // what it was doing, at its real status.
685
692
  this.endTurn(item.handlers);
693
+ const text = chunks.join("");
694
+ const structured = response.snapshot();
695
+ const messages = structured.length > 0
696
+ ? structured
697
+ : text
698
+ ? Object.freeze([{ text }])
699
+ : Object.freeze([]);
686
700
  await this.appendTranscript({
687
701
  v: 1,
688
702
  t: "msg",
689
703
  role: "assistant",
690
- text: chunks.join(""),
704
+ text,
705
+ messages,
691
706
  ts: Date.now(),
692
707
  stopReason: "error",
693
708
  status: "error",
@@ -789,7 +804,13 @@ export class AgentSession implements AgentClient, Bridgeable {
789
804
  const dropped = this.queue.splice(0);
790
805
  for (const item of dropped) {
791
806
  if (item.kind === "prompt") {
792
- item.resolve({ text: "", stopReason: "cancelled", status: "cancelled", usage: null });
807
+ item.resolve({
808
+ text: "",
809
+ messages: Object.freeze([]),
810
+ stopReason: "cancelled",
811
+ status: "cancelled",
812
+ usage: null,
813
+ });
793
814
  } else {
794
815
  item.reject(new Error("handoff cancelled before it started"));
795
816
  }
@@ -946,8 +967,12 @@ export class AgentSession implements AgentClient, Bridgeable {
946
967
 
947
968
  /** Do not let one notification observer mutate the PromptResult another observer sees. */
948
969
  function copyPromptResult(result: PromptResult): PromptResult {
970
+ const messages = result.messages ?? (result.text ? [{ text: result.text }] : []);
949
971
  return Object.freeze({
950
972
  ...result,
973
+ messages: Object.freeze(
974
+ messages.map((message) => Object.freeze({ ...message })),
975
+ ),
951
976
  usage: result.usage ? Object.freeze({ ...result.usage }) : null,
952
977
  });
953
978
  }
package/src/client.ts CHANGED
@@ -18,7 +18,8 @@ import {
18
18
  type ClientCapabilityConfig,
19
19
  } from "./capabilities.ts";
20
20
  import { parseConfigOptions, type ConfigOptions } from "./config-options.ts";
21
- import { extractChunkText, toActivityEvent, toAvailableCommands } from "./updates.ts";
21
+ import { extractResponseChunk, toActivityEvent, toAvailableCommands } from "./updates.ts";
22
+ import { ResponseAccumulator } from "./response.ts";
22
23
  import { TerminalRegistry } from "./terminals.ts";
23
24
  import { readTextFile, writeTextFile } from "./fs-access.ts";
24
25
  import { NotConnectedError } from "./errors.ts";
@@ -129,7 +130,7 @@ export class AcpClient implements AgentClient {
129
130
 
130
131
  // Per-turn streaming state (only the in-flight turn).
131
132
  private active: {
132
- chunks: string[];
133
+ response: ResponseAccumulator;
133
134
  handlers?: PromptHandlers;
134
135
  cancelled: boolean;
135
136
  } | null = null;
@@ -592,7 +593,11 @@ export class AcpClient implements AgentClient {
592
593
  }
593
594
  if (contentBlocks.length === 0) contentBlocks.push({ type: "text", text: "" });
594
595
 
595
- this.active = { chunks: [], handlers: item.handlers, cancelled: false };
596
+ this.active = {
597
+ response: new ResponseAccumulator(),
598
+ handlers: item.handlers,
599
+ cancelled: false,
600
+ };
596
601
  const t0 = Date.now();
597
602
  this.log.debug("prompt_start", { chars: item.text.length });
598
603
  this.log.debug("prompt_request", { sessionId: this._sessionId, prompt: contentBlocks });
@@ -604,7 +609,8 @@ export class AcpClient implements AgentClient {
604
609
  this.log.debug("prompt_response", { response: res });
605
610
 
606
611
  const cancelled = this.active.cancelled;
607
- const text = this.active.chunks.join("");
612
+ const text = this.active.response.text;
613
+ const messages = this.active.response.snapshot();
608
614
  this.log[text.length === 0 && !cancelled ? "warn" : "info"]("prompt_end", {
609
615
  stopReason: res.stopReason,
610
616
  status: cancelled ? "cancelled" : "completed",
@@ -613,6 +619,7 @@ export class AcpClient implements AgentClient {
613
619
  });
614
620
  return {
615
621
  text,
622
+ messages,
616
623
  stopReason: res.stopReason,
617
624
  status: cancelled ? "cancelled" : "completed",
618
625
  usage: (res.usage ?? null) as PromptResult["usage"],
@@ -626,7 +633,13 @@ export class AcpClient implements AgentClient {
626
633
  if (options.clearQueue) {
627
634
  const dropped = this.queue.splice(0);
628
635
  for (const item of dropped) {
629
- item.resolve({ text: "", stopReason: "cancelled", status: "cancelled", usage: null });
636
+ item.resolve({
637
+ text: "",
638
+ messages: Object.freeze([]),
639
+ stopReason: "cancelled",
640
+ status: "cancelled",
641
+ usage: null,
642
+ });
630
643
  }
631
644
  }
632
645
  if (this.active && this.transport && this._sessionId) {
@@ -687,10 +700,11 @@ export class AcpClient implements AgentClient {
687
700
 
688
701
  this.active.handlers?.onUpdate?.(notification);
689
702
 
690
- const text = extractChunkText(update);
691
- if (text) {
692
- this.active.chunks.push(text);
693
- this.active.handlers?.onChunk?.(text);
703
+ const responseChunk = extractResponseChunk(update);
704
+ if (responseChunk) {
705
+ const chunk = this.active.response.append(responseChunk);
706
+ this.active.handlers?.onResponseChunk?.(chunk);
707
+ this.active.handlers?.onChunk?.(chunk.text);
694
708
  }
695
709
  const activity = toActivityEvent(update);
696
710
  if (activity) this.active.handlers?.onActivity?.(this.enrich(activity));
@@ -277,12 +277,16 @@ export class PtyClient implements AgentClient, Bridgeable {
277
277
  }
278
278
 
279
279
  const status = turn.cancelled ? "cancelled" : "completed";
280
- if (text) turn.handlers?.onChunk?.(text);
280
+ const messages = text ? Object.freeze([{ text }]) : Object.freeze([]);
281
+ if (text) {
282
+ turn.handlers?.onResponseChunk?.({ text, startsMessage: true });
283
+ turn.handlers?.onChunk?.(text);
284
+ }
281
285
  this.log[text.length === 0 && !turn.cancelled ? "warn" : "info"]("pty_turn_end", {
282
286
  status,
283
287
  chars: text.length,
284
288
  });
285
- turn.resolve({ text, stopReason, status, usage: null });
289
+ turn.resolve({ text, messages, stopReason, status, usage: null });
286
290
  }
287
291
 
288
292
  /** Resolve once the screen has been idle for settleMs (used to drain the banner). */
package/src/index.ts CHANGED
@@ -69,7 +69,7 @@ export type {
69
69
  TerminalRegistryOptions,
70
70
  } from "./terminals.ts";
71
71
 
72
- export { extractChunkText, toActivityEvent } from "./updates.ts";
72
+ export { extractChunkText, extractResponseChunk, toActivityEvent } from "./updates.ts";
73
73
 
74
74
  export {
75
75
  ActivityAggregator,
@@ -132,6 +132,8 @@ export type { Logger, LogLevel, ConsoleLoggerOptions } from "./logger.ts";
132
132
  export type {
133
133
  PromptResult,
134
134
  PromptHandlers,
135
+ ResponseChunk,
136
+ ResponseMessage,
135
137
  ActivityEvent,
136
138
  ToolActivity,
137
139
  ToolUpdateActivity,
@@ -0,0 +1,56 @@
1
+ import type { ResponseChunk, ResponseMessage } from "./types.ts";
2
+
3
+ export interface IncomingResponseChunk {
4
+ text: string;
5
+ messageId?: string;
6
+ /** Supplied when an upstream client already resolved the boundary. */
7
+ startsMessage?: boolean;
8
+ }
9
+
10
+ /**
11
+ * Fold response deltas without inventing separators. Only a change between two explicit
12
+ * ACP message ids proves that a new assistant message started; missing ids remain part of
13
+ * the current message because no boundary can be inferred safely.
14
+ */
15
+ export class ResponseAccumulator {
16
+ private readonly entries: Array<{ messageId?: string; text: string }> = [];
17
+
18
+ append(chunk: IncomingResponseChunk): ResponseChunk {
19
+ let current = this.entries.at(-1);
20
+ const inferredStart =
21
+ !current ||
22
+ (chunk.messageId !== undefined &&
23
+ current.messageId !== undefined &&
24
+ chunk.messageId !== current.messageId);
25
+ // The first observed chunk necessarily starts our first entry, even if a malformed
26
+ // upstream callback says otherwise.
27
+ const startsMessage = !current || (chunk.startsMessage ?? inferredStart);
28
+
29
+ if (startsMessage) {
30
+ current = chunk.messageId === undefined
31
+ ? { text: chunk.text }
32
+ : { messageId: chunk.messageId, text: chunk.text };
33
+ this.entries.push(current);
34
+ } else {
35
+ const entry = current!;
36
+ if (entry.messageId === undefined && chunk.messageId !== undefined) {
37
+ entry.messageId = chunk.messageId;
38
+ }
39
+ entry.text += chunk.text;
40
+ }
41
+
42
+ return chunk.messageId === undefined
43
+ ? { text: chunk.text, startsMessage }
44
+ : { text: chunk.text, messageId: chunk.messageId, startsMessage };
45
+ }
46
+
47
+ get text(): string {
48
+ return this.entries.map((entry) => entry.text).join("");
49
+ }
50
+
51
+ snapshot(): readonly ResponseMessage[] {
52
+ return Object.freeze(
53
+ this.entries.map((entry) => Object.freeze({ ...entry })),
54
+ );
55
+ }
56
+ }
package/src/transcript.ts CHANGED
@@ -7,7 +7,8 @@
7
7
  // - `t:"msg"` DELIMITS A TURN. A turn is `msg(user) → activity… → msg(assistant)`; writes
8
8
  // serialize in call order, so that nesting always holds. A trailing user message with no
9
9
  // assistant message after it means the turn DIED IN FLIGHT (crash, kill, cancel) — the
10
- // activity lines inside it are the record of what it was doing.
10
+ // activity lines inside it are the record of what it was doing. Assistant lines retain
11
+ // their legacy flat `text` and may also carry structured `messages` with ACP boundaries.
11
12
  // - `t:"activity"` lines are SETTLED RECORDS, not raw deltas. FOLD THEM LAST-WINS ON
12
13
  // `recordId` — `foldRecords()` from `./activity.ts` is exactly that, and is the only
13
14
  // supported way to read them. A tool call normally writes 2–3 lines (announced → input →
@@ -31,7 +32,7 @@
31
32
  import { appendFile, mkdir, open, readFile, type FileHandle } from "node:fs/promises";
32
33
  import { dirname } from "node:path";
33
34
  import { foldRecords, type AggregatedRecord, type EmitReason } from "./activity.ts";
34
- import type { ActivityEvent, PromptResult, Usage } from "./types.ts";
35
+ import type { ActivityEvent, PromptResult, ResponseMessage, Usage } from "./types.ts";
35
36
 
36
37
  export type TranscriptRole = "user" | "assistant";
37
38
 
@@ -49,6 +50,8 @@ export interface TranscriptMessageLine {
49
50
  t: "msg";
50
51
  role: TranscriptRole;
51
52
  text: string;
53
+ /** Assistant-message boundaries when supplied by the live client. */
54
+ messages?: readonly ResponseMessage[];
52
55
  ts: number;
53
56
  usage?: Usage | null;
54
57
  stopReason?: string;
@@ -359,7 +362,9 @@ function isTranscriptLine(value: unknown): value is TranscriptLine {
359
362
  case "msg":
360
363
  return (
361
364
  (value.role === "user" || value.role === "assistant") &&
362
- typeof value.text === "string"
365
+ typeof value.text === "string" &&
366
+ (value.messages === undefined ||
367
+ (Array.isArray(value.messages) && value.messages.every(isResponseMessage)))
363
368
  );
364
369
  case "activity":
365
370
  return typeof value.kind === "string";
@@ -381,6 +386,14 @@ function isTranscriptLine(value: unknown): value is TranscriptLine {
381
386
  }
382
387
  }
383
388
 
389
+ function isResponseMessage(value: unknown): value is ResponseMessage {
390
+ return (
391
+ isRecord(value) &&
392
+ typeof value.text === "string" &&
393
+ (value.messageId === undefined || typeof value.messageId === "string")
394
+ );
395
+ }
396
+
384
397
  function isTranscriptMessageLine(value: TranscriptLine): value is TranscriptMessageLine {
385
398
  return value.t === "msg";
386
399
  }
package/src/types.ts CHANGED
@@ -39,14 +39,30 @@ export interface Usage {
39
39
  * call RESOLVES (not rejects) with whatever partial text arrived.
40
40
  */
41
41
  export interface PromptResult {
42
- /** Accumulated response text (partial if cancelled). */
42
+ /** Legacy flattened projection of `messages` (partial if cancelled). */
43
43
  text: string;
44
+ /** Assistant messages in protocol order, preserving ACP `messageId` boundaries. */
45
+ messages: readonly ResponseMessage[];
44
46
  /** Raw protocol stop reason: "end_turn" | "cancelled" | "max_tokens" | ... */
45
47
  stopReason: string;
46
48
  status: "completed" | "cancelled" | "error";
47
49
  usage: Usage | null;
48
50
  }
49
51
 
52
+ /** One boundary-aware delta from an ACP `agent_message_chunk`. */
53
+ export interface ResponseChunk {
54
+ text: string;
55
+ messageId?: string;
56
+ /** True when this chunk begins a new assistant message. */
57
+ startsMessage: boolean;
58
+ }
59
+
60
+ /** One assistant message assembled from consecutive ACP response chunks. */
61
+ export interface ResponseMessage {
62
+ messageId?: string;
63
+ text: string;
64
+ }
65
+
50
66
  /**
51
67
  * One line of raw traffic between us and the agent process — the debugging view.
52
68
  *
@@ -203,8 +219,10 @@ export interface PermissionRequest {
203
219
 
204
220
  /** Per-prompt callbacks. All optional. */
205
221
  export interface PromptHandlers {
206
- /** Partial response text (agent_message_chunk) as it streams. */
222
+ /** Legacy text-only response stream. Prefer `onResponseChunk` when boundaries matter. */
207
223
  onChunk?: (text: string) => void;
224
+ /** Boundary-aware response stream preserving ACP `messageId`. */
225
+ onResponseChunk?: (chunk: ResponseChunk) => void;
208
226
  /** Observation-only activity (thinking, tool calls, plan) as RAW protocol deltas. */
209
227
  onActivity?: (event: ActivityEvent) => void;
210
228
  /**
package/src/updates.ts CHANGED
@@ -18,14 +18,26 @@ import type {
18
18
  ToolContent,
19
19
  ToolLocation,
20
20
  ToolUpdateActivity,
21
+ ResponseChunk,
21
22
  } from "./types.ts";
22
23
 
23
- /** Response text from an agent_message_chunk, or "" for any other update. */
24
- export function extractChunkText(update: schema.SessionUpdate): string {
24
+ /** A response delta preserving its ACP message id, or null for any other update. */
25
+ export function extractResponseChunk(
26
+ update: schema.SessionUpdate,
27
+ ): Omit<ResponseChunk, "startsMessage"> | null {
25
28
  const u = update as Record<string, any>;
26
- if (u.sessionUpdate !== "agent_message_chunk") return "";
29
+ if (u.sessionUpdate !== "agent_message_chunk") return null;
27
30
  const content = u.content;
28
- return content?.type === "text" ? (content.text ?? "") : "";
31
+ 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) };
36
+ }
37
+
38
+ /** @deprecated Prefer `extractResponseChunk` when message boundaries matter. */
39
+ export function extractChunkText(update: schema.SessionUpdate): string {
40
+ return extractResponseChunk(update)?.text ?? "";
29
41
  }
30
42
 
31
43
  /** Map an update to an ActivityEvent, or null if it carries no observable activity. */