@qlairoslabs/acp-client 0.4.0 → 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.
@@ -0,0 +1,500 @@
1
+ # Consumer guide
2
+
3
+ This guide is for applications that embed `@qlairoslabs/acp-client`, especially
4
+ orchestrators that keep several agents alive at once. The library supplies the ACP
5
+ connection and stable-session primitives; the consumer owns the collection of live
6
+ `AgentSession` objects and decides whether operations appear as slash commands, buttons,
7
+ HTTP endpoints, jobs, or something else.
8
+
9
+ The package currently requires Bun 1.3.5 or newer.
10
+
11
+ ## The three operation layers
12
+
13
+ Keep these layers separate in consumer code:
14
+
15
+ | Layer | Owner | Library surface | Typical operations |
16
+ |---|---|---|---|
17
+ | Logical session management | Consumer | `SessionManager`, `SessionStore`, `AgentSession.create()` | Create, catalog, list, reopen, stop, and select `AgentSession` objects |
18
+ | Stable session control | `AgentSession` | The live `AgentSession` instance | Prompt, observe state, interrupt, handoff, bridge, stop |
19
+ | Active harness session | ACP provider | `internalSessionCommands`, `executeInternalSessionCommand()`, `session.connection` | Run advertised commands and use provider capabilities/configuration |
20
+
21
+ An `agentSessionId` is the stable consumer-facing identity. An `internalSessionId` belongs
22
+ to the currently active provider thread and may change during a handoff or mode change.
23
+
24
+ ```text
25
+ consumer registry
26
+ └── AgentSession agent-7 stable object and agentSessionId
27
+ └── internal session abc replaceable provider thread
28
+ ```
29
+
30
+ ## Install and import
31
+
32
+ ```bash
33
+ bun add @qlairoslabs/acp-client
34
+ ```
35
+
36
+ Core session APIs come from the package root:
37
+
38
+ ```ts
39
+ import {
40
+ AgentSession,
41
+ ADAPTERS,
42
+ FileSessionStore,
43
+ SessionManager,
44
+ type Adapter,
45
+ type AgentSessionNotification,
46
+ type PromptHandlers,
47
+ } from "@qlairoslabs/acp-client";
48
+ ```
49
+
50
+ Reusable interactive helpers are intentionally in a separate entry point:
51
+
52
+ ```ts
53
+ import {
54
+ createAgentSessionCommands,
55
+ dispatchReplInput,
56
+ parseReplInput,
57
+ runAgentSessionRepl,
58
+ } from "@qlairoslabs/acp-client/repl";
59
+ ```
60
+
61
+ ## Resolve adapters in the consumer
62
+
63
+ An adapter only describes how to launch a harness. Presets are provided, but consumers
64
+ can supply any `Adapter` object.
65
+
66
+ ```ts
67
+ const adapters: Record<string, Adapter> = {
68
+ codex: ADAPTERS.codex,
69
+ claude: ADAPTERS.claude,
70
+ internal: {
71
+ command: ["internal-agent", "--acp"],
72
+ ptyCommand: ["internal-agent"],
73
+ displayName: "Internal agent",
74
+ },
75
+ };
76
+
77
+ function resolveAdapter(adapterId: string): Adapter {
78
+ const adapter = adapters[adapterId];
79
+ if (!adapter) throw new Error(`Unknown adapter: ${adapterId}`);
80
+ return adapter;
81
+ }
82
+ ```
83
+
84
+ The catalog stores `adapterId`, not executable configuration. This resolver therefore
85
+ belongs to the consumer.
86
+
87
+ ## Create the catalog and live-session registry
88
+
89
+ `SessionManager` is a metadata catalog, not a registry of running objects and not a
90
+ transcript store. Use `FileSessionStore` locally or implement `SessionStore` over the
91
+ consumer's database.
92
+
93
+ ```ts
94
+ const sessionManager = new SessionManager(
95
+ new FileSessionStore("/absolute/path/to/session-catalog"),
96
+ );
97
+
98
+ const liveSessions = new Map<string, AgentSession>();
99
+ ```
100
+
101
+ The manager exposes:
102
+
103
+ ```ts
104
+ await sessionManager.record(input);
105
+ await sessionManager.get(agentSessionId);
106
+ await sessionManager.list();
107
+ await sessionManager.delete(agentSessionId);
108
+ await sessionManager.listMerged(providerSessions, adapterId);
109
+ ```
110
+
111
+ Normally the consumer does not call `record()` directly. An `AgentSession` given
112
+ `sessions: sessionManager` records itself on startup and updates the record when its
113
+ provider identity, mode, title, or transcript location changes.
114
+
115
+ ## Create a logical session
116
+
117
+ ```ts
118
+ async function createSession(adapterId: string): Promise<AgentSession> {
119
+ const session = await AgentSession.create({
120
+ adapter: resolveAdapter(adapterId),
121
+ adapterId,
122
+ providerSession: { kind: "new" },
123
+ sessions: sessionManager,
124
+ transcriptDir: "/absolute/path/to/transcripts",
125
+ cwd: process.cwd(),
126
+ defaultPermission: "cancel",
127
+ });
128
+
129
+ liveSessions.set(session.agentSessionId, session);
130
+ return session;
131
+ }
132
+ ```
133
+
134
+ If `agentSessionId` is omitted, the library creates one. Always return or store
135
+ `session.agentSessionId`; do not use `internalSessionId` as the orchestrator's key.
136
+
137
+ `providerSession` is explicit:
138
+
139
+ ```ts
140
+ { kind: "new" }
141
+ { kind: "load", internalSessionId, onFailure?: "error" | "new" }
142
+ ```
143
+
144
+ Loading fails closed by default. Use `onFailure: "new"` only when replacing a missing
145
+ provider thread is deliberate policy.
146
+
147
+ ## Reopen a cataloged session
148
+
149
+ `SessionManager.get()` returns routing metadata. It does not start a process. Reopening is
150
+ consumer composition because only the consumer knows how to resolve adapters and where to
151
+ keep live objects.
152
+
153
+ ```ts
154
+ async function reopenSession(agentSessionId: string): Promise<AgentSession> {
155
+ const existing = liveSessions.get(agentSessionId);
156
+ if (existing) return existing;
157
+
158
+ const record = await sessionManager.get(agentSessionId);
159
+ if (!record) throw new Error(`Unknown AgentSession: ${agentSessionId}`);
160
+
161
+ const session = await AgentSession.create({
162
+ adapter: resolveAdapter(record.adapter),
163
+ adapterId: record.adapter,
164
+ agentSessionId: record.agentSessionId,
165
+ providerSession: record.internalSessionId
166
+ ? {
167
+ kind: "load",
168
+ internalSessionId: record.internalSessionId,
169
+ onFailure: "error",
170
+ }
171
+ : { kind: "new" },
172
+ mode: record.mode,
173
+ cwd: record.cwd,
174
+ title: record.title,
175
+ sessions: sessionManager,
176
+ ...(record.transcriptPath
177
+ ? { transcriptPath: record.transcriptPath }
178
+ : {}),
179
+ });
180
+
181
+ liveSessions.set(session.agentSessionId, session);
182
+ return session;
183
+ }
184
+ ```
185
+
186
+ Transcript existence never selects a provider thread. `transcriptPath` and
187
+ `transcriptDir` only select history storage.
188
+
189
+ ## List and select sessions
190
+
191
+ Use the manager to list the consumer's catalog without starting a harness:
192
+
193
+ ```ts
194
+ const catalog = await sessionManager.list();
195
+ ```
196
+
197
+ Once a session is connected, `session.listSessions()` merges that catalog with the active
198
+ adapter's ACP `session/list` response when the harness supports it:
199
+
200
+ ```ts
201
+ const rows = await session.listSessions();
202
+
203
+ for (const row of rows) {
204
+ console.log(
205
+ row.agentSessionId,
206
+ row.internalSessionId,
207
+ row.adapter,
208
+ row.source, // "catalog" | "agent" | "both"
209
+ );
210
+ }
211
+ ```
212
+
213
+ Selecting which `AgentSession` receives the next operation is consumer state. The library
214
+ does not maintain a global “current AgentSession.”
215
+
216
+ ## Prompt and stream a turn
217
+
218
+ ```ts
219
+ const result = await session.prompt("Inspect the failing tests.", {
220
+ onChunk: (text) => process.stdout.write(text),
221
+ onActivity: (event) => renderRawActivity(event),
222
+ onRecord: (folded) => publishFoldedActivity(folded),
223
+ onUpdate: (rawUpdate) => debugProtocolUpdate(rawUpdate),
224
+ onPermissionRequest: (request) => {
225
+ const allow = request.options.find((option) => option.kind === "allow_once");
226
+ return allow
227
+ ? { outcome: "selected", optionId: allow.optionId }
228
+ : { outcome: "cancelled" };
229
+ },
230
+ });
231
+
232
+ console.log(result.status, result.stopReason, result.text, result.usage);
233
+ ```
234
+
235
+ Prompts and handoffs on one `AgentSession` are serialized. The consumer does not need a
236
+ separate mutex for them.
237
+
238
+ ## Observe state without polling
239
+
240
+ Read the current snapshot first, then subscribe to future notifications:
241
+
242
+ ```ts
243
+ function attachSession(session: AgentSession): () => void {
244
+ publishState(session.state);
245
+
246
+ return session.subscribe((notification: AgentSessionNotification) => {
247
+ publishNotification(notification);
248
+
249
+ switch (notification.event.kind) {
250
+ case "state_changed":
251
+ publishState(notification.event.state);
252
+ break;
253
+ case "turn_completed":
254
+ case "turn_failed":
255
+ case "handoff_completed":
256
+ case "handoff_failed":
257
+ scheduleDependentWork(session.agentSessionId);
258
+ break;
259
+ }
260
+ });
261
+ }
262
+ ```
263
+
264
+ Useful snapshots are:
265
+
266
+ ```ts
267
+ session.state;
268
+ session.isBusy;
269
+ session.queuedOperationCount;
270
+ ```
271
+
272
+ Notifications carry a monotonically increasing `seq`, timestamp, and stable
273
+ `agentSessionId`. A listener exception is isolated from the operation.
274
+
275
+ ## Interrupt and stop
276
+
277
+ ```ts
278
+ session.interrupt(); // cancel the active operation
279
+ session.interrupt({ clearQueue: true }); // also discard queued operations
280
+
281
+ await session.stop();
282
+ liveSessions.delete(session.agentSessionId);
283
+ ```
284
+
285
+ `stop()` is terminal for that object. Reopen from the catalog to obtain a new live object
286
+ with the same logical identity.
287
+
288
+ ## Handoff within the current harness
289
+
290
+ ```ts
291
+ const result = await session.handoff();
292
+ ```
293
+
294
+ Without options, the old provider thread generates a portable summary. The session then
295
+ creates a new provider thread and introduces that summary through a user prompt.
296
+
297
+ The consumer may provide an already-generated summary:
298
+
299
+ ```ts
300
+ const result = await session.handoff({
301
+ summary: "Objective, decisions, current state, and next steps...",
302
+ });
303
+ ```
304
+
305
+ The following remains true:
306
+
307
+ ```ts
308
+ result.agentSessionId === session.agentSessionId;
309
+ result.toInternalSessionId === session.internalSessionId;
310
+ ```
311
+
312
+ Current limitations are important:
313
+
314
+ - Handoff only creates a new thread on the current adapter/harness.
315
+ - The summary-generation prompt is currently fixed unless generation is bypassed by
316
+ supplying `summary`.
317
+ - The new-thread introduction prompt is currently fixed.
318
+ - The introduction is an ordinary user prompt, not a system prompt.
319
+ - ACP `session/new` has no portable system-prompt field.
320
+ - Handoff requires normal ACP mode.
321
+
322
+ Cross-adapter handoff and independently configurable summary/introduction policies should
323
+ be treated as future API work, not emulated by mutating `internalSessionId` in consumer
324
+ code.
325
+
326
+ ## Discover and execute harness commands
327
+
328
+ Commands advertised by the active ACP harness are exposed as immutable metadata:
329
+
330
+ ```ts
331
+ for (const command of session.internalSessionCommands) {
332
+ console.log(command.name, command.description, command.input?.hint);
333
+ }
334
+ ```
335
+
336
+ Changes also arrive through the session listener as
337
+ `internal_session_commands_changed`.
338
+
339
+ Execute one explicitly without including the leading slash:
340
+
341
+ ```ts
342
+ await session.executeInternalSessionCommand("usage");
343
+ await session.executeInternalSessionCommand("status", "verbose");
344
+ ```
345
+
346
+ ACP represents these commands as ordinary prompts. The named method makes consumer intent
347
+ explicit and keeps the operation in the session queue, transcript, and lifecycle events.
348
+ Advertisement is discovery, not an allow-list: a harness may accept a command before it
349
+ advertises it.
350
+
351
+ ## Reuse the AgentSession local command set
352
+
353
+ The same local handlers used by the opinionated one-session REPL are public:
354
+
355
+ ```ts
356
+ const localCommands = createAgentSessionCommands({
357
+ session,
358
+ note: (message) => showNotice(message),
359
+ });
360
+
361
+ const handled = await localCommands.onSlashCommand("state", []);
362
+ ```
363
+
364
+ The built-in set currently handles:
365
+
366
+ ```text
367
+ /help
368
+ /session
369
+ /state
370
+ /commands
371
+ /handoff [SUMMARY]
372
+ /bridge
373
+ ```
374
+
375
+ `/exit` is handled by the REPL loop rather than the command factory.
376
+
377
+ The factory currently exposes the handler, not a declarative metadata array for local
378
+ commands. A consumer can reuse the handler directly; a custom command palette must define
379
+ its own local labels/descriptions for now. Harness commands do have declarative metadata
380
+ through `session.internalSessionCommands`.
381
+
382
+ ## Run the opinionated single-session REPL
383
+
384
+ ```ts
385
+ try {
386
+ await runAgentSessionRepl(session, {
387
+ activity: true,
388
+ spinner: true,
389
+ note: (message) => process.stderr.write(`${message}\n`),
390
+ onSlashCommand: async (command, args) => {
391
+ // Consumer-local extension, tried after the built-in AgentSession commands.
392
+ if (command !== "tag") return false;
393
+ await addTag(session.agentSessionId, args.join(" "));
394
+ return true;
395
+ },
396
+ });
397
+ } finally {
398
+ await session.stop();
399
+ }
400
+ ```
401
+
402
+ Input routing is deliberately unambiguous:
403
+
404
+ ```text
405
+ ordinary text -> session.prompt(...)
406
+ /command -> local AgentSession command
407
+ //command [input] -> session.executeInternalSessionCommand(...)
408
+ ```
409
+
410
+ An unknown `/command` is rejected locally and never falls through to the harness.
411
+
412
+ ## Reuse routing in a custom UI
413
+
414
+ Consumers do not need to use readline. `parseReplInput()` and `dispatchReplInput()` are
415
+ terminal-independent:
416
+
417
+ ```ts
418
+ const local = createAgentSessionCommands({ session, note: showNotice });
419
+ const promptHandlers: PromptHandlers = {
420
+ onChunk: (text) => renderText(text),
421
+ onActivity: (event) => renderActivity(event),
422
+ };
423
+
424
+ await dispatchReplInput(parseReplInput(input), {
425
+ prompt: async (text) => {
426
+ await session.prompt(text, promptHandlers);
427
+ },
428
+ localCommand: (command, args) => local.onSlashCommand(command, args),
429
+ internalSessionCommand: async (command, value) => {
430
+ await session.executeInternalSessionCommand(command, value, promptHandlers);
431
+ },
432
+ unknownLocalCommand: (command) => {
433
+ showNotice(`Unknown local command: /${command}`);
434
+ },
435
+ missingInternalSessionCommand: () => {
436
+ showNotice("A command name is required after //");
437
+ },
438
+ });
439
+ ```
440
+
441
+ A graphical consumer may skip slash parsing entirely and bind these operations directly
442
+ to buttons, menus, RPC methods, or orchestration events.
443
+
444
+ ## Use the lower-level control plane when needed
445
+
446
+ `session.connection` exposes the live `AgentController` for operations that do not belong
447
+ to the stable session abstraction:
448
+
449
+ ```ts
450
+ session.capabilities;
451
+ session.configOptions;
452
+ await session.setConfig("model", "some-model");
453
+ await session.authenticate(methodId, { onOutput: showAuthOutput });
454
+
455
+ const controller = session.connection;
456
+ await controller.listSessions();
457
+ await controller.loadSession(internalSessionId);
458
+ ```
459
+
460
+ Use controller session-switching methods carefully: they operate directly on the provider
461
+ thread. Prefer `AgentSession` methods when a stable logical-session equivalent exists, so
462
+ the catalog, lifecycle notifications, and transcript remain coherent.
463
+
464
+ ## Transcript policy
465
+
466
+ Choose exactly one history destination:
467
+
468
+ ```ts
469
+ transcriptPath: "/absolute/path/to/conversation.jsonl"
470
+ // or
471
+ transcriptDir: "/absolute/path/to/transcripts"
472
+ ```
473
+
474
+ Omit both to disable transcript writes. This does not disable prompting, handoff, catalog
475
+ management, or lifecycle notifications.
476
+
477
+ Enable settled activity records when the consumer needs tool/thinking/plan history:
478
+
479
+ ```ts
480
+ transcriptActivity: {
481
+ checkpointOnInput: true,
482
+ rawOutput: false,
483
+ maxBytes: 64_000,
484
+ }
485
+ ```
486
+
487
+ Use `readTranscript()` for logical user/assistant messages and `readTranscriptLines()` for
488
+ the complete typed stream, including activity and handoff boundaries.
489
+
490
+ ## Recommended ownership rules
491
+
492
+ - Key orchestration state by `agentSessionId`, never `internalSessionId`.
493
+ - Keep the map of live `AgentSession` objects in the consumer.
494
+ - Treat `SessionManager` as routing metadata, not a process manager.
495
+ - Read `session.state` before subscribing to notifications.
496
+ - Use `executeInternalSessionCommand()` instead of constructing slash prompts manually.
497
+ - Keep consumer/local commands separate from harness commands in the UI.
498
+ - Resolve adapters in the consumer and fail explicitly on unknown adapter ids.
499
+ - Stop every live session during consumer shutdown.
500
+ - Do not infer provider loading from transcript filenames or contents.
package/README.md CHANGED
@@ -68,6 +68,10 @@ bun add -g @qlairoslabs/acp-client
68
68
 
69
69
  ## Usage
70
70
 
71
+ For an orchestration-oriented walkthrough covering catalog ownership, reopening logical
72
+ sessions, lifecycle listeners, handoff, harness commands, and reusable command routing,
73
+ see the [consumer guide](./CONSUMER_GUIDE.md).
74
+
71
75
  ### One-shot prompt
72
76
 
73
77
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.4.0",
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",
@@ -32,7 +32,8 @@
32
32
  "access": "public"
33
33
  },
34
34
  "files": [
35
- "src"
35
+ "src",
36
+ "CONSUMER_GUIDE.md"
36
37
  ],
37
38
  "exports": {
38
39
  ".": "./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;
@@ -287,16 +288,11 @@ export class AcpClient implements AgentClient {
287
288
  let sessionId: string;
288
289
 
289
290
  if (resumeId && this.capabilities.agent.loadSession) {
290
- this.beginCommandTransition();
291
291
  try {
292
- await transport.loadSession({ sessionId: resumeId, cwd, mcpServers } as schema.LoadSessionRequest);
293
- sessionId = resumeId;
294
- this._sessionId = sessionId;
295
- this.finishCommandTransition(sessionId);
296
- resumed = true;
297
- this.log.info("session_loaded", { sessionId });
292
+ const result = await this.loadSessionInternal(transport, resumeId, { mcpServers });
293
+ sessionId = result.sessionId;
294
+ resumed = result.resumed;
298
295
  } catch (err) {
299
- this.abortCommandTransition();
300
296
  this.log.warn("session_load_failed", { sessionId: resumeId, error: String(err) });
301
297
  if (loadFailure === "error") throw err;
302
298
  sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
@@ -319,6 +315,14 @@ export class AcpClient implements AgentClient {
319
315
  if (!this.capabilities.agent.loadSession) {
320
316
  throw new Error("agent does not advertise session/load (loadSession)");
321
317
  }
318
+ return this.loadSessionInternal(transport, sessionId, options);
319
+ }
320
+
321
+ private async loadSessionInternal(
322
+ transport: AcpTransport,
323
+ sessionId: string,
324
+ options: SwitchSessionOptions = {},
325
+ ): Promise<ConnectResult> {
322
326
  this.beginCommandTransition();
323
327
  this.replay = { sessionId, onUpdate: options.onUpdate };
324
328
  let res: schema.LoadSessionResponse;
@@ -335,12 +339,13 @@ export class AcpClient implements AgentClient {
335
339
  } finally {
336
340
  this.replay = null;
337
341
  }
342
+ const configOptions = parseConfigOptions(res.configOptions);
338
343
  this._sessionId = sessionId;
344
+ this._configOptions = configOptions;
339
345
  this.finishCommandTransition(sessionId);
340
- this._configOptions = parseConfigOptions(res.configOptions);
341
346
  this.log.info("session_loaded", {
342
347
  sessionId,
343
- configOptions: [...this._configOptions.keys()],
348
+ configOptions: [...configOptions.keys()],
344
349
  });
345
350
  this.log.debug("session_load_response", { response: res });
346
351
  return { sessionId, resumed: true };
@@ -588,7 +593,11 @@ export class AcpClient implements AgentClient {
588
593
  }
589
594
  if (contentBlocks.length === 0) contentBlocks.push({ type: "text", text: "" });
590
595
 
591
- this.active = { chunks: [], handlers: item.handlers, cancelled: false };
596
+ this.active = {
597
+ response: new ResponseAccumulator(),
598
+ handlers: item.handlers,
599
+ cancelled: false,
600
+ };
592
601
  const t0 = Date.now();
593
602
  this.log.debug("prompt_start", { chars: item.text.length });
594
603
  this.log.debug("prompt_request", { sessionId: this._sessionId, prompt: contentBlocks });
@@ -600,7 +609,8 @@ export class AcpClient implements AgentClient {
600
609
  this.log.debug("prompt_response", { response: res });
601
610
 
602
611
  const cancelled = this.active.cancelled;
603
- const text = this.active.chunks.join("");
612
+ const text = this.active.response.text;
613
+ const messages = this.active.response.snapshot();
604
614
  this.log[text.length === 0 && !cancelled ? "warn" : "info"]("prompt_end", {
605
615
  stopReason: res.stopReason,
606
616
  status: cancelled ? "cancelled" : "completed",
@@ -609,6 +619,7 @@ export class AcpClient implements AgentClient {
609
619
  });
610
620
  return {
611
621
  text,
622
+ messages,
612
623
  stopReason: res.stopReason,
613
624
  status: cancelled ? "cancelled" : "completed",
614
625
  usage: (res.usage ?? null) as PromptResult["usage"],
@@ -622,7 +633,13 @@ export class AcpClient implements AgentClient {
622
633
  if (options.clearQueue) {
623
634
  const dropped = this.queue.splice(0);
624
635
  for (const item of dropped) {
625
- 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
+ });
626
643
  }
627
644
  }
628
645
  if (this.active && this.transport && this._sessionId) {
@@ -683,10 +700,11 @@ export class AcpClient implements AgentClient {
683
700
 
684
701
  this.active.handlers?.onUpdate?.(notification);
685
702
 
686
- const text = extractChunkText(update);
687
- if (text) {
688
- this.active.chunks.push(text);
689
- 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);
690
708
  }
691
709
  const activity = toActivityEvent(update);
692
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. */