@qlairoslabs/acp-client 0.1.5 → 0.2.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.
package/README.md CHANGED
@@ -95,7 +95,8 @@ await agent.stop();
95
95
  ```ts
96
96
  await agent.prompt("Find and fix the failing test.", {
97
97
  onChunk: (text) => process.stdout.write(text), // response text as it streams
98
- onActivity: (event) => console.error("·", event.type), // thinking / tool calls / plan
98
+ onActivity: (event) => render(event), // thinking / tool calls / plan / …
99
+ onUpdate: (raw) => log(raw), // every raw session/update, unmapped
99
100
  onPermissionRequest: (req) => ({ outcome: "selected", optionId: req.options[0].optionId }),
100
101
  });
101
102
  ```
@@ -103,6 +104,55 @@ await agent.prompt("Find and fix the failing test.", {
103
104
  If you omit `onPermissionRequest`, the client falls back to the controller's
104
105
  `defaultPermission` (`"approve"` / `"cancel"`).
105
106
 
107
+ Every session update except the response text reaches `onActivity`, discriminated by
108
+ `kind`: `thinking`, `user_message`, `tool`, `tool_update`, `plan`, `plan_update`,
109
+ `plan_removed`, `commands`, `mode`, `usage`, `session_info`, `config`, and `unknown` for
110
+ anything the protocol adds later (the raw payload rides along on `raw`).
111
+
112
+ **Tool calls arrive incrementally, and you must merge them.** Agents announce a call
113
+ before they know much about it and fill it in afterwards, so the command, the diff and
114
+ the output usually land on a later `tool_update` — not on the initial `tool`:
115
+
116
+ ```ts
117
+ const calls = new Map<string, ToolActivity>();
118
+
119
+ onActivity: (event) => {
120
+ if (event.kind === "tool") calls.set(event.toolCallId, event);
121
+ if (event.kind === "tool_update") {
122
+ // Only the fields the agent CHANGED are present. Absent means unchanged —
123
+ // spreading is exactly right. `content` and `locations` REPLACE wholesale
124
+ // (the schema says "replace the content collection"): never concatenate them,
125
+ // agents that stream a growing tool input resend the whole value each time.
126
+ const call = calls.get(event.toolCallId);
127
+ if (call) calls.set(event.toolCallId, { ...call, ...event, kind: "tool" });
128
+ }
129
+ }
130
+ ```
131
+
132
+ `event.content` is where the output lives — `{type:"content"}` (with `text` pre-extracted
133
+ for text blocks), `{type:"diff"}`, `{type:"terminal"}`, or `{type:"other"}` with the raw
134
+ payload for shapes we don't model.
135
+
136
+ ### Terminals and filesystem access
137
+
138
+ The client advertises the `terminal` and `fs` client capabilities and implements them:
139
+ agents route their shell commands through `terminal/create` and read/write files through
140
+ `fs/read_text_file` and `fs/write_text_file` on us. Terminal tool calls carry only a
141
+ `terminalId` over the wire; the client resolves the live output before handing you the
142
+ event, so `content` entries of type `terminal` come with `output`, `truncated` and
143
+ `exitStatus` filled in.
144
+
145
+ Commands run as child processes of your app, with your environment. To opt out — letting
146
+ the agent fall back to its own implementation — turn the capability off, which also stops
147
+ us advertising it:
148
+
149
+ ```ts
150
+ new AcpClient({
151
+ adapter: ADAPTERS.codex,
152
+ clientCapabilities: { terminal: false, fs: { writeTextFile: false } },
153
+ });
154
+ ```
155
+
106
156
  ### Durable sessions with a catalog
107
157
 
108
158
  `AgentSession` gives a conversation a stable id that persists across reconnects, and
@@ -141,8 +191,10 @@ chat transcript that can be read later without starting the agent. `transcriptPa
141
191
  exact file path chosen by the caller; `transcriptDir` lets the library write
142
192
  `<agentSessionId>.jsonl` inside that directory. Supplying both is a config error.
143
193
 
144
- The transcript stores user messages and final assistant replies only; tool calls,
145
- thinking, plans, and raw protocol replay remain in the harness session.
194
+ The transcript stores user messages and final assistant replies. Set
195
+ `transcriptActivity: true` to also record tool calls, thinking and plans as `t:"activity"`
196
+ lines — `readTranscript()` still returns messages only, so read those back with
197
+ `readTranscriptLines()`.
146
198
 
147
199
  ```ts
148
200
  import { AgentSession, ADAPTERS, readTranscript } from "@qlairoslabs/acp-client";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.1.5",
3
+ "version": "0.2.0",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -9,7 +9,7 @@
9
9
  // Adapter lives HERE, not on the controller: switching adapter = a new AgentSession (the
10
10
  // agent dies on switch). Mode-swap (degrade/upgrade) stays within one AgentSession.
11
11
 
12
- import { AgentController, type AgentMode } from "./controller.ts";
12
+ import { AgentController, type AgentControllerConfig, type AgentMode } from "./controller.ts";
13
13
  import type * as schema from "@agentclientprotocol/sdk";
14
14
  import { join } from "node:path";
15
15
  import type { Adapter } from "./adapters.ts";
@@ -50,6 +50,8 @@ export interface AgentSessionConfig {
50
50
  mcpServers?: schema.McpServer[];
51
51
  defaultPermission?: "approve" | "cancel";
52
52
  clientInfo?: { name: string; title?: string; version?: string };
53
+ /** What we let the agent do through us (terminals, filesystem). All on by default. */
54
+ clientCapabilities?: AgentControllerConfig["clientCapabilities"];
53
55
  logger?: Logger;
54
56
  /** Optional catalog. When present, the session records itself here. */
55
57
  sessions?: SessionManager;
@@ -57,6 +59,12 @@ export interface AgentSessionConfig {
57
59
  transcriptPath?: string;
58
60
  /** Directory for a library-named transcript file: `<agentSessionId>.jsonl`. */
59
61
  transcriptDir?: string;
62
+ /**
63
+ * Also record activity (thinking, tool calls and their output, plans) as `t:"activity"`
64
+ * lines. Off by default — it makes transcripts much larger, and `readTranscript()`
65
+ * ignores them either way; read them with `readTranscriptLines()`.
66
+ */
67
+ transcriptActivity?: boolean;
60
68
  /** Our stable AgentSession id. Minted if omitted; pass a record's agentSessionId to resume. */
61
69
  agentSessionId?: string;
62
70
  /** ACP/harness session to load on start (resume an existing provider conversation). */
@@ -72,6 +80,7 @@ export class AgentSession implements AgentClient, Bridgeable {
72
80
  private readonly controller: AgentController;
73
81
  private readonly sessions?: SessionManager;
74
82
  private readonly transcriptPath?: string;
83
+ private readonly transcriptActivity: boolean;
75
84
  private readonly log: Logger;
76
85
  private transcriptWrite: Promise<void> = Promise.resolve();
77
86
  private queue: QueueItem[] = [];
@@ -93,6 +102,7 @@ export class AgentSession implements AgentClient, Bridgeable {
93
102
  (config.transcriptDir
94
103
  ? join(config.transcriptDir, `${encodeURIComponent(this.agentSessionId)}.jsonl`)
95
104
  : undefined);
105
+ this.transcriptActivity = config.transcriptActivity === true;
96
106
  this.log = config.logger ?? noopLogger;
97
107
  this._mode = config.mode ?? "normal";
98
108
  this._cwd = config.cwd;
@@ -109,6 +119,7 @@ export class AgentSession implements AgentClient, Bridgeable {
109
119
  mcpServers: config.mcpServers,
110
120
  defaultPermission: config.defaultPermission,
111
121
  clientInfo: config.clientInfo,
122
+ clientCapabilities: config.clientCapabilities,
112
123
  logger: config.logger,
113
124
  });
114
125
  }
@@ -201,6 +212,15 @@ export class AgentSession implements AgentClient, Bridgeable {
201
212
  chunks.push(chunk);
202
213
  item.handlers?.onChunk?.(chunk);
203
214
  },
215
+ onActivity: (event) => {
216
+ if (this.transcriptActivity) {
217
+ // Fire and forget: activity is observational, and appendTranscript already
218
+ // serializes writes — blocking the agent's update stream on disk would stall
219
+ // streaming for the caller.
220
+ void this.appendTranscript({ v: 1, t: "activity", ts: Date.now(), ...event });
221
+ }
222
+ item.handlers?.onActivity?.(event);
223
+ },
204
224
  };
205
225
 
206
226
  try {
@@ -56,14 +56,41 @@ export interface AgentCapabilities {
56
56
  };
57
57
  }
58
58
 
59
- /** The client capabilities we always advertise. Kept in one place. */
59
+ /**
60
+ * What the caller lets us do on the agent's behalf. Advertising a capability is a
61
+ * PROMISE to implement it — an agent that believes we have terminals will route every
62
+ * shell command through `terminal/create` and render nothing if we can't answer. So
63
+ * these flags gate the handlers and the advertisement together.
64
+ */
65
+ export interface ClientCapabilityConfig {
66
+ fs?: { readTextFile?: boolean; writeTextFile?: boolean };
67
+ terminal?: boolean;
68
+ }
69
+
70
+ /** The client capabilities we advertise by default — everything we implement. */
60
71
  export const CLIENT_CAPABILITIES: ClientCapabilities = {
61
72
  fs: { readTextFile: true, writeTextFile: true },
62
73
  terminal: true,
63
74
  };
64
75
 
76
+ /** Resolve caller overrides against the defaults. Omitted = default (enabled). */
77
+ export function buildClientCapabilities(
78
+ config?: ClientCapabilityConfig,
79
+ ): ClientCapabilities {
80
+ return {
81
+ fs: {
82
+ readTextFile: config?.fs?.readTextFile ?? CLIENT_CAPABILITIES.fs.readTextFile,
83
+ writeTextFile: config?.fs?.writeTextFile ?? CLIENT_CAPABILITIES.fs.writeTextFile,
84
+ },
85
+ terminal: config?.terminal ?? CLIENT_CAPABILITIES.terminal,
86
+ };
87
+ }
88
+
65
89
  /** Parse a raw InitializeResponse into our nested Capabilities model. */
66
- export function parseCapabilities(init: schema.InitializeResponse): Capabilities {
90
+ export function parseCapabilities(
91
+ init: schema.InitializeResponse,
92
+ client: ClientCapabilities = CLIENT_CAPABILITIES,
93
+ ): Capabilities {
67
94
  const a = (init.agentCapabilities ?? {}) as Record<string, any>;
68
95
  const prompt = a.promptCapabilities ?? {};
69
96
  const mcp = a.mcpCapabilities ?? {};
@@ -73,7 +100,7 @@ export function parseCapabilities(init: schema.InitializeResponse): Capabilities
73
100
  return {
74
101
  protocolVersion: init.protocolVersion,
75
102
  agentInfo,
76
- client: CLIENT_CAPABILITIES,
103
+ client,
77
104
  agent: {
78
105
  loadSession: a.loadSession === true,
79
106
  promptCapabilities: {
package/src/client.ts CHANGED
@@ -12,15 +12,20 @@ import { buildSpawnCommand } from "./adapters.ts";
12
12
  import { AcpTransport } from "./transport/acp-transport.ts";
13
13
  import {
14
14
  parseCapabilities,
15
- CLIENT_CAPABILITIES,
15
+ buildClientCapabilities,
16
16
  type Capabilities,
17
+ type ClientCapabilities,
18
+ type ClientCapabilityConfig,
17
19
  } from "./capabilities.ts";
18
20
  import { parseConfigOptions, type ConfigOptions } from "./config-options.ts";
19
- import { extractChunkText, toActivityEvent } from "./updates.ts";
21
+ import { extractChunkText, toActivityEvent, toAgentCommands } from "./updates.ts";
22
+ import { TerminalRegistry } from "./terminals.ts";
23
+ import { readTextFile, writeTextFile } from "./fs-access.ts";
20
24
  import { NotConnectedError } from "./errors.ts";
21
25
  import { noopLogger, type Logger } from "./logger.ts";
22
26
  import type { AgentClient, InterruptOptions } from "./agent-client.ts";
23
27
  import type {
28
+ ActivityEvent,
24
29
  PromptResult,
25
30
  PromptHandlers,
26
31
  PermissionRequest,
@@ -28,6 +33,7 @@ import type {
28
33
  Attachment,
29
34
  SessionListPage,
30
35
  AgentCommand,
36
+ ToolContent,
31
37
  } from "./types.ts";
32
38
 
33
39
  export interface AcpClientConfig {
@@ -45,6 +51,12 @@ export interface AcpClientConfig {
45
51
  defaultPermission?: "approve" | "cancel";
46
52
  /** Identification sent in initialize. */
47
53
  clientInfo?: { name: string; title?: string; version?: string };
54
+ /**
55
+ * What we let the agent do through us: filesystem reads/writes and terminals. All
56
+ * enabled by default. Disabling one stops us advertising it, so the agent falls back
57
+ * to its own implementation instead of calling a method we won't answer.
58
+ */
59
+ clientCapabilities?: ClientCapabilityConfig;
48
60
  /** Diagnostics sink. Omit for a silent library. */
49
61
  logger?: Logger;
50
62
  }
@@ -114,10 +126,15 @@ export class AcpClient implements AgentClient {
114
126
  // caller can show it — auth output almost always arrives on stderr, not the protocol.
115
127
  private authStderrSink: ((line: string) => void) | null = null;
116
128
 
129
+ // Terminals the AGENT is driving through us. Null when the capability is disabled.
130
+ private terminals: TerminalRegistry | null = null;
131
+
117
132
  private readonly log: Logger;
133
+ private readonly clientCapabilities: ClientCapabilities;
118
134
 
119
135
  constructor(private config: AcpClientConfig) {
120
136
  this.log = config.logger ?? noopLogger;
137
+ this.clientCapabilities = buildClientCapabilities(config.clientCapabilities);
121
138
  }
122
139
 
123
140
  // --- introspection (populated by connect) -------------------------------------
@@ -164,6 +181,15 @@ export class AcpClient implements AgentClient {
164
181
 
165
182
  this.log.info("connect", { command, dockerExec: isDockerExec });
166
183
 
184
+ const caps = this.clientCapabilities;
185
+ this.terminals = caps.terminal
186
+ ? new TerminalRegistry({
187
+ cwd: this.config.cwd,
188
+ env: this.config.env,
189
+ logger: this.config.logger,
190
+ })
191
+ : null;
192
+
167
193
  const transport = new AcpTransport({
168
194
  command,
169
195
  // docker exec resolves paths inside the container's namespace — don't pass a host cwd.
@@ -171,6 +197,16 @@ export class AcpClient implements AgentClient {
171
197
  env: this.config.env,
172
198
  onUpdate: (n) => this.handleUpdate(n),
173
199
  onPermissionRequest: (p) => this.handlePermission(p),
200
+ onReadTextFile: caps.fs.readTextFile
201
+ ? async (p) => ({ content: await readTextFile(p) })
202
+ : undefined,
203
+ onWriteTextFile: caps.fs.writeTextFile
204
+ ? async (p) => {
205
+ await writeTextFile(p);
206
+ return {};
207
+ }
208
+ : undefined,
209
+ terminals: this.terminals ? this.terminalHandlers(this.terminals) : undefined,
174
210
  onStderr: (line) => {
175
211
  this.log.debug("agent_stderr", { line });
176
212
  this.authStderrSink?.(line);
@@ -187,7 +223,7 @@ export class AcpClient implements AgentClient {
187
223
  const init = await transport.raceExit(
188
224
  transport.initialize({
189
225
  protocolVersion: PROTOCOL_VERSION,
190
- clientCapabilities: CLIENT_CAPABILITIES as unknown as schema.ClientCapabilities,
226
+ clientCapabilities: caps as unknown as schema.ClientCapabilities,
191
227
  clientInfo: this.config.clientInfo ?? {
192
228
  name: "acp-lib",
193
229
  title: "ACP Lib",
@@ -195,7 +231,7 @@ export class AcpClient implements AgentClient {
195
231
  },
196
232
  } as schema.InitializeRequest),
197
233
  );
198
- this._capabilities = parseCapabilities(init);
234
+ this._capabilities = parseCapabilities(init, caps);
199
235
  this.log.info("initialized", {
200
236
  agent: this._capabilities.agentInfo?.name,
201
237
  protocolVersion: this._capabilities.protocolVersion,
@@ -422,10 +458,29 @@ export class AcpClient implements AgentClient {
422
458
  const t = this.transport;
423
459
  this.transport = null;
424
460
  this._sessionId = null;
461
+ this.terminals?.releaseAll();
462
+ this.terminals = null;
425
463
  if (t) await t.stop();
426
464
  this.log.info("stopped", {});
427
465
  }
428
466
 
467
+ /** Adapt the registry to the transport's async handler shape. */
468
+ private terminalHandlers(registry: TerminalRegistry) {
469
+ return {
470
+ create: async (p: schema.CreateTerminalRequest) => ({
471
+ terminalId: registry.create(p as Parameters<TerminalRegistry["create"]>[0]),
472
+ }),
473
+ output: async (p: schema.TerminalOutputRequest) => {
474
+ const { output, truncated, exitStatus } = registry.output(p.terminalId);
475
+ return { output, truncated, exitStatus };
476
+ },
477
+ waitForExit: async (p: schema.WaitForTerminalExitRequest) =>
478
+ registry.waitForExit(p.terminalId),
479
+ kill: async (p: schema.KillTerminalRequest) => registry.kill(p.terminalId),
480
+ release: async (p: schema.ReleaseTerminalRequest) => registry.release(p.terminalId),
481
+ };
482
+ }
483
+
429
484
  // --- prompting ----------------------------------------------------------------
430
485
 
431
486
  prompt(
@@ -544,9 +599,7 @@ export class AcpClient implements AgentClient {
544
599
  this._configOptions = parseConfigOptions((update as Record<string, any>).configOptions);
545
600
  }
546
601
  if (kind === "available_commands_update") {
547
- this._agentCommands = ((update as Record<string, any>).availableCommands ?? []).map(
548
- (c: Record<string, any>) => ({ name: c.name, description: c.description ?? "" }),
549
- );
602
+ this._agentCommands = toAgentCommands((update as Record<string, any>).availableCommands);
550
603
  }
551
604
 
552
605
  if (!this.active) {
@@ -557,13 +610,37 @@ export class AcpClient implements AgentClient {
557
610
  }
558
611
  if (notification.sessionId && notification.sessionId !== this._sessionId) return;
559
612
 
613
+ this.active.handlers?.onUpdate?.(notification);
614
+
560
615
  const text = extractChunkText(update);
561
616
  if (text) {
562
617
  this.active.chunks.push(text);
563
618
  this.active.handlers?.onChunk?.(text);
564
619
  }
565
620
  const activity = toActivityEvent(update);
566
- if (activity) this.active.handlers?.onActivity?.(activity);
621
+ if (activity) this.active.handlers?.onActivity?.(this.enrich(activity));
622
+ }
623
+
624
+ /**
625
+ * Fill in terminal output on tool-call content. The agent only sends a `terminalId`
626
+ * (it's polling us for the bytes), so without this the caller sees a tool call it
627
+ * cannot render — the terminal is OURS, and only we can read it.
628
+ */
629
+ private enrich(event: ActivityEvent): ActivityEvent {
630
+ if (event.kind !== "tool" && event.kind !== "tool_update") return event;
631
+ const registry = this.terminals;
632
+ if (!registry || !event.content?.some((c) => c.type === "terminal")) return event;
633
+
634
+ const content = event.content.map((c): ToolContent => {
635
+ if (c.type !== "terminal" || !registry.has(c.terminalId)) return c;
636
+ try {
637
+ const snapshot = registry.output(c.terminalId);
638
+ return { ...c, ...snapshot };
639
+ } catch {
640
+ return c; // released between the check and the read
641
+ }
642
+ });
643
+ return { ...event, content };
567
644
  }
568
645
 
569
646
  private async handlePermission(
package/src/controller.ts CHANGED
@@ -38,6 +38,8 @@ export interface AgentControllerConfig {
38
38
  mcpServers?: schema.McpServer[];
39
39
  defaultPermission?: "approve" | "cancel";
40
40
  clientInfo?: AcpClientConfig["clientInfo"];
41
+ /** What we let the agent do through us (terminals, filesystem). All on by default. */
42
+ clientCapabilities?: AcpClientConfig["clientCapabilities"];
41
43
  logger?: Logger;
42
44
  }
43
45
 
@@ -369,6 +371,7 @@ export class AgentController implements AgentClient {
369
371
  sessionId,
370
372
  defaultPermission: this.config.defaultPermission,
371
373
  clientInfo: this.config.clientInfo,
374
+ clientCapabilities: this.config.clientCapabilities,
372
375
  logger: this.config.logger,
373
376
  });
374
377
  // connect() is fatal (no connection = nothing to do). startSession() is NOT: an
@@ -0,0 +1,38 @@
1
+ // Client-side filesystem access (ACP `fs/read_text_file`, `fs/write_text_file`).
2
+ //
3
+ // We advertise the fs capabilities, so these must actually work — previously the
4
+ // transport answered every read with `{content: ""}` and silently discarded writes,
5
+ // which reads to an agent as "the file is empty" / "the write succeeded".
6
+
7
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import { dirname } from "node:path";
9
+
10
+ export interface ReadTextFileParams {
11
+ path: string;
12
+ /** 1-based line to start from. */
13
+ line?: number | null;
14
+ /** Maximum number of lines to return. */
15
+ limit?: number | null;
16
+ }
17
+
18
+ export interface WriteTextFileParams {
19
+ path: string;
20
+ content: string;
21
+ }
22
+
23
+ /** Read a file, honouring the protocol's optional line window. */
24
+ export async function readTextFile(params: ReadTextFileParams): Promise<string> {
25
+ const content = await readFile(params.path, "utf8");
26
+ if (params.line == null && params.limit == null) return content;
27
+
28
+ const lines = content.split("\n");
29
+ const start = Math.max((params.line ?? 1) - 1, 0);
30
+ const end = params.limit != null ? start + Math.max(params.limit, 0) : lines.length;
31
+ return lines.slice(start, end).join("\n");
32
+ }
33
+
34
+ /** Write a file, creating parent directories as needed. */
35
+ export async function writeTextFile(params: WriteTextFileParams): Promise<void> {
36
+ await mkdir(dirname(params.path), { recursive: true });
37
+ await writeFile(params.path, params.content, "utf8");
38
+ }
package/src/index.ts CHANGED
@@ -41,12 +41,23 @@ export type {
41
41
  export { ADAPTERS, buildSpawnCommand } from "./adapters.ts";
42
42
  export type { Adapter, AdapterPreset } from "./adapters.ts";
43
43
 
44
+ export { buildClientCapabilities, CLIENT_CAPABILITIES } from "./capabilities.ts";
44
45
  export type {
45
46
  Capabilities,
46
47
  ClientCapabilities,
48
+ ClientCapabilityConfig,
47
49
  AgentCapabilities,
48
50
  AuthMethod,
49
51
  } from "./capabilities.ts";
52
+
53
+ export { TerminalRegistry, UnknownTerminalError } from "./terminals.ts";
54
+ export type {
55
+ CreateTerminalParams,
56
+ TerminalOutput,
57
+ TerminalRegistryOptions,
58
+ } from "./terminals.ts";
59
+
60
+ export { extractChunkText, toActivityEvent } from "./updates.ts";
50
61
  export type {
51
62
  ConfigOption,
52
63
  ConfigOptions,
@@ -87,6 +98,12 @@ export type {
87
98
  PromptResult,
88
99
  PromptHandlers,
89
100
  ActivityEvent,
101
+ ToolActivity,
102
+ ToolUpdateActivity,
103
+ ToolContent,
104
+ ToolLocation,
105
+ TerminalExitStatus,
106
+ ContentBlock,
90
107
  PlanEntry,
91
108
  PermissionRequest,
92
109
  PermissionOutcome,
package/src/repl/repl.ts CHANGED
@@ -304,9 +304,19 @@ function activityMarker(e: ActivityEvent): string | null {
304
304
  return "thinking";
305
305
  case "tool":
306
306
  return `tool:${e.title ?? e.toolKind}`;
307
+ case "tool_update":
308
+ // Only the terminal states are worth a marker; progress ticks are too noisy.
309
+ return e.status === "completed" || e.status === "failed"
310
+ ? `tool:${e.title ?? e.toolCallId} ${e.status}`
311
+ : null;
307
312
  case "plan":
313
+ case "plan_update":
308
314
  return "plan";
315
+ case "mode":
316
+ return `mode:${e.modeId}`;
317
+ case "usage":
318
+ return `context:${e.used}/${e.size}`;
309
319
  default:
310
- return null; // tool_update is too noisy to surface
320
+ return null; // bookkeeping updates — nothing for a one-line marker to say
311
321
  }
312
322
  }
@@ -0,0 +1,273 @@
1
+ /// <reference types="bun" />
2
+ // Client-side terminals (ACP `terminal/*`). The agent asks US to run a command and then
3
+ // polls for output; the tool call it emits carries only a `terminalId`, so without this
4
+ // the whole execute-tool path produces empty UI.
5
+ //
6
+ // We advertise `terminal` in client capabilities, so per spec we MUST implement all five
7
+ // methods. See https://agentclientprotocol.com/protocol/terminals.
8
+
9
+ import type { Logger } from "./logger.ts";
10
+ import { noopLogger } from "./logger.ts";
11
+ import type { TerminalExitStatus } from "./types.ts";
12
+
13
+ export interface CreateTerminalParams {
14
+ command: string;
15
+ args?: string[];
16
+ cwd?: string | null;
17
+ env?: Array<{ name: string; value: string }>;
18
+ /** Bytes of output to retain; older output is dropped from the FRONT. */
19
+ outputByteLimit?: number | null;
20
+ }
21
+
22
+ export interface TerminalOutput {
23
+ output: string;
24
+ truncated: boolean;
25
+ exitStatus: TerminalExitStatus | null;
26
+ }
27
+
28
+ export interface TerminalRegistryOptions {
29
+ /** Fallback cwd when the agent doesn't specify one. */
30
+ cwd?: string;
31
+ /** Extra env for every terminal, merged over process.env. */
32
+ env?: Record<string, string>;
33
+ logger?: Logger;
34
+ }
35
+
36
+ /** Thrown when the agent references a terminal that was released or never existed. */
37
+ export class UnknownTerminalError extends Error {
38
+ constructor(terminalId: string) {
39
+ super(`unknown terminalId: ${terminalId}`);
40
+ this.name = "UnknownTerminalError";
41
+ }
42
+ }
43
+
44
+ interface Chunk {
45
+ text: string;
46
+ bytes: number;
47
+ }
48
+
49
+ interface Entry {
50
+ id: string;
51
+ proc: ReturnType<typeof Bun.spawn>;
52
+ chunks: Chunk[];
53
+ /** Memoized `chunks.join("")`; nulled on every write. */
54
+ joined: string | null;
55
+ totalBytes: number;
56
+ limit: number | null;
57
+ truncated: boolean;
58
+ exitStatus: TerminalExitStatus | null;
59
+ exited: Promise<TerminalExitStatus>;
60
+ // Structural: Bun's and node:stream/web's reader types differ, and we only cancel.
61
+ readers: Array<{ cancel(): Promise<unknown> }>;
62
+ }
63
+
64
+ /**
65
+ * How long to keep draining output after the process exits. A killed shell can leave a
66
+ * grandchild holding the pipe, so EOF may never come — waiting on it unboundedly would
67
+ * hang `terminal/wait_for_exit` and with it the agent's whole turn.
68
+ */
69
+ const DRAIN_GRACE_MS = 250;
70
+
71
+ export class TerminalRegistry {
72
+ private readonly terminals = new Map<string, Entry>();
73
+ private seq = 0;
74
+ private readonly log: Logger;
75
+
76
+ constructor(private readonly options: TerminalRegistryOptions = {}) {
77
+ this.log = options.logger ?? noopLogger;
78
+ }
79
+
80
+ /** Spawn a command and return its terminal id. Output accumulates until released. */
81
+ create(params: CreateTerminalParams): string {
82
+ const id = `term-${++this.seq}`;
83
+ const env: Record<string, string> = {
84
+ ...(process.env as Record<string, string>),
85
+ ...(this.options.env ?? {}),
86
+ };
87
+ for (const v of params.env ?? []) env[v.name] = v.value;
88
+
89
+ const proc = Bun.spawn([params.command, ...(params.args ?? [])], {
90
+ cwd: params.cwd ?? this.options.cwd,
91
+ env,
92
+ stdin: "ignore",
93
+ stdout: "pipe",
94
+ stderr: "pipe",
95
+ });
96
+
97
+ const entry: Entry = {
98
+ id,
99
+ proc,
100
+ chunks: [],
101
+ joined: null,
102
+ totalBytes: 0,
103
+ limit: params.outputByteLimit ?? null,
104
+ truncated: false,
105
+ exitStatus: null,
106
+ exited: Promise.resolve({ exitCode: null, signal: null }),
107
+ readers: [],
108
+ };
109
+
110
+ // stdout and stderr are interleaved in arrival order — that's what a terminal is.
111
+ const pumps = [
112
+ this.pump(entry, proc.stdout as ReadableStream<Uint8Array>),
113
+ this.pump(entry, proc.stderr as ReadableStream<Uint8Array>),
114
+ ];
115
+
116
+ entry.exited = (async () => {
117
+ const code = await proc.exited;
118
+ // Drain whatever was still buffered before reporting the exit status, so a caller
119
+ // that waits for exit and then reads output never races the last few bytes.
120
+ await Promise.race([Promise.allSettled(pumps), Bun.sleep(DRAIN_GRACE_MS)]);
121
+ const status: TerminalExitStatus = {
122
+ exitCode: proc.signalCode ? null : (code ?? null),
123
+ signal: proc.signalCode ?? null,
124
+ };
125
+ entry.exitStatus = status;
126
+ this.log.debug("terminal_exit", { terminalId: id, ...status });
127
+ return status;
128
+ })();
129
+ void entry.exited.catch(() => {});
130
+
131
+ this.terminals.set(id, entry);
132
+ this.log.debug("terminal_create", { terminalId: id, command: params.command, args: params.args });
133
+ return id;
134
+ }
135
+
136
+ /**
137
+ * Current output and exit status. Fully synchronous — it reads a buffer the background
138
+ * pumps fill, and never waits on the process. That matters beyond convenience: this is
139
+ * called while dispatching session updates, so an await here would let one wedged
140
+ * command stall every subsequent update on the connection.
141
+ */
142
+ output(terminalId: string): TerminalOutput {
143
+ const entry = this.require(terminalId);
144
+ // Joining is O(buffered bytes) and a live terminal is read once per update that
145
+ // references it, so hold the result until the next write.
146
+ entry.joined ??= entry.chunks.map((c) => c.text).join("");
147
+ return {
148
+ output: entry.joined,
149
+ truncated: entry.truncated,
150
+ exitStatus: entry.exitStatus,
151
+ };
152
+ }
153
+
154
+ /** Resolve once the command exits. */
155
+ waitForExit(terminalId: string): Promise<TerminalExitStatus> {
156
+ return this.require(terminalId).exited;
157
+ }
158
+
159
+ /** Kill the command but keep the id valid, so output stays readable. */
160
+ kill(terminalId: string): void {
161
+ const entry = this.require(terminalId);
162
+ try {
163
+ entry.proc.kill("SIGKILL");
164
+ } catch {
165
+ /* already exited */
166
+ }
167
+ }
168
+
169
+ /** Kill and forget. The id becomes invalid for every other method. */
170
+ release(terminalId: string): void {
171
+ const entry = this.terminals.get(terminalId);
172
+ if (!entry) return;
173
+ this.terminals.delete(terminalId);
174
+ try {
175
+ entry.proc.kill("SIGKILL");
176
+ } catch {
177
+ /* already exited */
178
+ }
179
+ // Cancel explicitly: a surviving grandchild can hold the pipes open indefinitely.
180
+ for (const reader of entry.readers) void reader.cancel().catch(() => {});
181
+ entry.readers = [];
182
+ this.log.debug("terminal_release", { terminalId });
183
+ }
184
+
185
+ /** Tear everything down (client stop). */
186
+ releaseAll(): void {
187
+ for (const id of [...this.terminals.keys()]) this.release(id);
188
+ }
189
+
190
+ /** True while the id is still ours to read — used to enrich tool-call content. */
191
+ has(terminalId: string): boolean {
192
+ return this.terminals.has(terminalId);
193
+ }
194
+
195
+ private require(terminalId: string): Entry {
196
+ const entry = this.terminals.get(terminalId);
197
+ if (!entry) throw new UnknownTerminalError(terminalId);
198
+ return entry;
199
+ }
200
+
201
+ private async pump(entry: Entry, stream: ReadableStream<Uint8Array> | null): Promise<void> {
202
+ if (!stream) return;
203
+ const reader = stream.getReader();
204
+ entry.readers.push(reader);
205
+ const dec = new TextDecoder();
206
+ try {
207
+ for (;;) {
208
+ const { value, done } = await reader.read();
209
+ if (done) break;
210
+ this.append(entry, dec.decode(value, { stream: true }));
211
+ }
212
+ const tail = dec.decode();
213
+ if (tail) this.append(entry, tail);
214
+ } catch (err) {
215
+ this.log.debug("terminal_read_failed", { terminalId: entry.id, error: String(err) });
216
+ }
217
+ }
218
+
219
+ private append(entry: Entry, text: string): void {
220
+ if (!text) return;
221
+ entry.joined = null;
222
+ entry.chunks.push({ text, bytes: Buffer.byteLength(text, "utf8") });
223
+ entry.totalBytes += Buffer.byteLength(text, "utf8");
224
+ this.trim(entry);
225
+ }
226
+
227
+ /**
228
+ * Enforce outputByteLimit by dropping from the FRONT, whole chunks first, then a
229
+ * character-boundary cut inside the oldest surviving chunk (per spec: truncation must
230
+ * not split a character, even if that leaves us slightly under the limit).
231
+ */
232
+ private trim(entry: Entry): void {
233
+ const limit = entry.limit;
234
+ if (limit == null || limit < 0) return;
235
+ while (entry.totalBytes > limit && entry.chunks.length > 0) {
236
+ const first = entry.chunks[0]!;
237
+ if (entry.totalBytes - first.bytes >= limit) {
238
+ entry.chunks.shift();
239
+ entry.totalBytes -= first.bytes;
240
+ entry.truncated = true;
241
+ continue;
242
+ }
243
+ const drop = entry.totalBytes - limit;
244
+ const cut = charBoundaryCut(first.text, drop);
245
+ const kept = first.text.slice(cut);
246
+ const keptBytes = Buffer.byteLength(kept, "utf8");
247
+ entry.totalBytes -= first.bytes - keptBytes;
248
+ entry.truncated = true;
249
+ if (kept) {
250
+ entry.chunks[0] = { text: kept, bytes: keptBytes };
251
+ } else {
252
+ entry.chunks.shift();
253
+ }
254
+ break;
255
+ }
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Smallest index such that dropping `text[0..index)` sheds at least `dropBytes` bytes,
261
+ * landing on a code-point boundary.
262
+ */
263
+ function charBoundaryCut(text: string, dropBytes: number): number {
264
+ let shed = 0;
265
+ let i = 0;
266
+ while (i < text.length && shed < dropBytes) {
267
+ const code = text.codePointAt(i)!;
268
+ const width = code > 0xffff ? 2 : 1;
269
+ shed += Buffer.byteLength(text.slice(i, i + width), "utf8");
270
+ i += width;
271
+ }
272
+ return i;
273
+ }
@@ -7,6 +7,17 @@ import * as acp from "@agentclientprotocol/sdk";
7
7
  import type * as schema from "@agentclientprotocol/sdk";
8
8
  import { ProcessCrashError } from "../errors.ts";
9
9
 
10
+ /** The five `terminal/*` methods a client that advertises `terminal: true` must serve. */
11
+ export interface TerminalHandlers {
12
+ create(params: schema.CreateTerminalRequest): Promise<schema.CreateTerminalResponse>;
13
+ output(params: schema.TerminalOutputRequest): Promise<schema.TerminalOutputResponse>;
14
+ waitForExit(
15
+ params: schema.WaitForTerminalExitRequest,
16
+ ): Promise<schema.WaitForTerminalExitResponse>;
17
+ kill(params: schema.KillTerminalRequest): Promise<void>;
18
+ release(params: schema.ReleaseTerminalRequest): Promise<void>;
19
+ }
20
+
10
21
  export interface AcpTransportOptions {
11
22
  /** Full command to spawn: [...execPrefix, ...adapter.command]. */
12
23
  command: string[];
@@ -14,7 +25,11 @@ export interface AcpTransportOptions {
14
25
  cwd?: string;
15
26
  env?: Record<string, string>;
16
27
 
17
- /** A session/update notification arrived. */
28
+ /**
29
+ * A session/update notification arrived, exactly as the agent sent it — the transport
30
+ * takes these off the wire itself rather than going through the SDK. See
31
+ * `interceptUpdates` for why.
32
+ */
18
33
  onUpdate?: (notification: schema.SessionNotification) => void;
19
34
  /** The agent asked for permission (blocking — must resolve to an outcome). */
20
35
  onPermissionRequest?: (
@@ -28,6 +43,12 @@ export interface AcpTransportOptions {
28
43
  onWriteTextFile?: (
29
44
  params: schema.WriteTextFileRequest,
30
45
  ) => Promise<schema.WriteTextFileResponse>;
46
+ /**
47
+ * `terminal/*`. Supplied together or not at all — the SDK answers an unimplemented
48
+ * terminal method with a null result rather than an error, which reads to the agent
49
+ * as a malformed response, so a partial implementation is worse than none.
50
+ */
51
+ terminals?: TerminalHandlers;
31
52
  /** A line of stderr from the process. */
32
53
  onStderr?: (line: string) => void;
33
54
  /** The process exited unexpectedly (not via stop()). */
@@ -59,7 +80,9 @@ export class AcpTransport {
59
80
 
60
81
  const stream = acp.ndJsonStream(
61
82
  stdinTransform.writable,
62
- proc.stdout as ReadableStream<Uint8Array>,
83
+ interceptUpdates(proc.stdout as ReadableStream<Uint8Array>, (m) =>
84
+ this.opts.onUpdate?.(m.params as schema.SessionNotification),
85
+ ),
63
86
  );
64
87
  const handler = new ClientHandler(this.opts);
65
88
  this.connection = new acp.ClientSideConnection(() => handler, stream);
@@ -162,10 +185,90 @@ export class AcpTransport {
162
185
  }
163
186
  }
164
187
 
165
- /** Routes SDK client-side callbacks to the transport's option handlers. */
188
+ /**
189
+ * Split the agent's ndjson into `session/update` (ours) and everything else (the SDK's).
190
+ *
191
+ * Updates are handed to `onMessage` verbatim and NOT forwarded downstream: the SDK
192
+ * validates them against a zod copy of the update union, so anything newer than the
193
+ * installed SDK is rejected outright with a console.error, and unmodelled fields on
194
+ * known updates are stripped. Notifications carry no response, so intercepting them is
195
+ * invisible to the agent — every request/response line still flows through untouched.
196
+ */
197
+ function interceptUpdates(
198
+ source: ReadableStream<Uint8Array>,
199
+ onMessage: (message: Record<string, any>) => void,
200
+ ): ReadableStream<Uint8Array> {
201
+ const dec = new TextDecoder();
202
+ const enc = new TextEncoder();
203
+ let buf = "";
204
+
205
+ // Re-emits the ORIGINAL line text — reserializing risks mangling numbers we never read.
206
+ const handle = (line: string, controller: TransformStreamDefaultController<Uint8Array>) => {
207
+ if (!line) return;
208
+ let message: Record<string, any> | undefined;
209
+ try {
210
+ message = JSON.parse(line);
211
+ } catch {
212
+ /* not JSON — let the SDK report it */
213
+ }
214
+ if (message?.method === "session/update" && message.id === undefined) {
215
+ onMessage(message);
216
+ return;
217
+ }
218
+ controller.enqueue(enc.encode(`${line}\n`));
219
+ };
220
+
221
+ return source.pipeThrough(
222
+ new TransformStream<Uint8Array, Uint8Array>({
223
+ transform(chunk, controller) {
224
+ buf += dec.decode(chunk, { stream: true });
225
+ let i: number;
226
+ while ((i = buf.indexOf("\n")) >= 0) {
227
+ const line = buf.slice(0, i).trim();
228
+ buf = buf.slice(i + 1);
229
+ handle(line, controller);
230
+ }
231
+ },
232
+ flush(controller) {
233
+ buf += dec.decode();
234
+ handle(buf.trim(), controller);
235
+ buf = "";
236
+ },
237
+ }),
238
+ );
239
+ }
240
+
241
+ /**
242
+ * Routes SDK client-side callbacks to the transport's option handlers.
243
+ *
244
+ * Methods are attached in the CONSTRUCTOR rather than declared, because the SDK probes
245
+ * `client.method?.()` — a declared-but-stubbed method makes us look capable while
246
+ * answering with nonsense. Absent is the honest signal for "not implemented".
247
+ */
166
248
  class ClientHandler implements acp.Client {
167
- constructor(private opts: AcpTransportOptions) {}
249
+ createTerminal?: acp.Client["createTerminal"];
250
+ terminalOutput?: acp.Client["terminalOutput"];
251
+ waitForTerminalExit?: acp.Client["waitForTerminalExit"];
252
+ killTerminal?: acp.Client["killTerminal"];
253
+ releaseTerminal?: acp.Client["releaseTerminal"];
254
+ readTextFile?: acp.Client["readTextFile"];
255
+ writeTextFile?: acp.Client["writeTextFile"];
256
+
257
+ constructor(private opts: AcpTransportOptions) {
258
+ if (opts.onReadTextFile) this.readTextFile = (p) => opts.onReadTextFile!(p);
259
+ if (opts.onWriteTextFile) this.writeTextFile = (p) => opts.onWriteTextFile!(p);
260
+
261
+ const terminals = opts.terminals;
262
+ if (terminals) {
263
+ this.createTerminal = (p) => terminals.create(p);
264
+ this.terminalOutput = (p) => terminals.output(p);
265
+ this.waitForTerminalExit = (p) => terminals.waitForExit(p);
266
+ this.killTerminal = (p) => terminals.kill(p);
267
+ this.releaseTerminal = (p) => terminals.release(p);
268
+ }
269
+ }
168
270
 
271
+ /** Safety net: `interceptUpdates` normally takes these before the SDK sees them. */
169
272
  async sessionUpdate(params: schema.SessionNotification): Promise<void> {
170
273
  this.opts.onUpdate?.(params);
171
274
  }
@@ -176,18 +279,4 @@ class ClientHandler implements acp.Client {
176
279
  if (this.opts.onPermissionRequest) return this.opts.onPermissionRequest(params);
177
280
  return { outcome: { outcome: "cancelled" } };
178
281
  }
179
-
180
- async readTextFile(
181
- params: schema.ReadTextFileRequest,
182
- ): Promise<schema.ReadTextFileResponse> {
183
- if (this.opts.onReadTextFile) return this.opts.onReadTextFile(params);
184
- return { content: "" };
185
- }
186
-
187
- async writeTextFile(
188
- params: schema.WriteTextFileRequest,
189
- ): Promise<schema.WriteTextFileResponse> {
190
- if (this.opts.onWriteTextFile) return this.opts.onWriteTextFile(params);
191
- return {};
192
- }
193
282
  }
package/src/types.ts CHANGED
@@ -37,23 +37,109 @@ export interface PromptResult {
37
37
  usage: Usage | null;
38
38
  }
39
39
 
40
+ /** A raw content block: "text" | "image" | "audio" | "resource" | "resource_link". */
41
+ export interface ContentBlock {
42
+ type: string;
43
+ [key: string]: unknown;
44
+ }
45
+
46
+ /** A file location a tool call touched — enables "follow along" UIs. */
47
+ export interface ToolLocation {
48
+ path: string;
49
+ line?: number;
50
+ }
51
+
52
+ /** How a terminal command ended. Both fields are null while it is still running. */
53
+ export interface TerminalExitStatus {
54
+ exitCode: number | null;
55
+ signal: string | null;
56
+ }
57
+
58
+ /**
59
+ * Output produced by a tool call. Mirrors the protocol's three shapes; anything we
60
+ * don't recognize is preserved verbatim as `other` rather than dropped.
61
+ *
62
+ * `terminal` content names a live terminal the AGENT is driving through us. We resolve
63
+ * its output before handing the event to the caller, so `output`/`exitStatus` are
64
+ * populated whenever the terminal is still ours to read.
65
+ */
66
+ export type ToolContent =
67
+ | { type: "content"; content: ContentBlock; /** Convenience: set for text blocks. */ text?: string }
68
+ | { type: "diff"; path: string; oldText: string | null; newText: string }
69
+ | {
70
+ type: "terminal";
71
+ terminalId: string;
72
+ output?: string;
73
+ truncated?: boolean;
74
+ exitStatus?: TerminalExitStatus | null;
75
+ }
76
+ | { type: "other"; raw: unknown };
77
+
78
+ /**
79
+ * A tool call the agent started. The protocol lets an agent announce a call before it
80
+ * knows much about it, so most fields fill in later via `tool_update`.
81
+ */
82
+ export interface ToolActivity {
83
+ kind: "tool";
84
+ toolCallId: string;
85
+ title?: string;
86
+ toolKind: string;
87
+ status: string;
88
+ rawInput?: unknown;
89
+ rawOutput?: unknown;
90
+ content?: ToolContent[];
91
+ locations?: ToolLocation[];
92
+ }
93
+
94
+ /**
95
+ * A change to an in-flight tool call. Only the fields the agent actually changed are
96
+ * present — an absent field means "unchanged", NOT "empty". `content` and `locations`
97
+ * REPLACE the previous collections when present.
98
+ */
99
+ export interface ToolUpdateActivity {
100
+ kind: "tool_update";
101
+ toolCallId: string;
102
+ status?: string;
103
+ title?: string;
104
+ toolKind?: string;
105
+ rawInput?: unknown;
106
+ rawOutput?: unknown;
107
+ content?: ToolContent[];
108
+ locations?: ToolLocation[];
109
+ }
110
+
40
111
  /**
41
112
  * Real-time, observation-only events during a turn — separate from the response text.
42
113
  * Fire-and-forget; the caller renders them if it wants. (Permission requests are NOT
43
114
  * here — they are blocking and handled via PromptHandlers.onPermissionRequest.)
115
+ *
116
+ * Every session update except `agent_message_chunk` (which is the response text) maps to
117
+ * one of these; unrecognized kinds arrive as `unknown` with the raw payload attached, so
118
+ * a newer agent can never silently starve the caller of activity.
44
119
  */
45
120
  export type ActivityEvent =
46
121
  | { kind: "thinking"; text: string }
47
- | {
48
- kind: "tool";
49
- toolCallId: string;
50
- title?: string;
51
- toolKind: string;
52
- status: string;
53
- rawInput?: unknown;
54
- }
55
- | { kind: "tool_update"; toolCallId: string; status: string }
56
- | { kind: "plan"; entries: PlanEntry[] };
122
+ /** The agent echoed back user input — session/load replay, or a queued message. */
123
+ | { kind: "user_message"; text: string }
124
+ | ToolActivity
125
+ | ToolUpdateActivity
126
+ /** Full plan snapshot: replaces any previous plan. */
127
+ | { kind: "plan"; entries: PlanEntry[] }
128
+ /** Per-plan update (experimental protocol extension). */
129
+ | { kind: "plan_update"; planId: string; plan: unknown }
130
+ | { kind: "plan_removed"; planId: string }
131
+ /** The agent's slash commands changed; also reflected in `client.agentCommands`. */
132
+ | { kind: "commands"; commands: AgentCommand[] }
133
+ /** The agent switched session mode. */
134
+ | { kind: "mode"; modeId: string }
135
+ /** Context-window accounting. `used`/`size` are tokens. */
136
+ | { kind: "usage"; used: number; size: number; cost?: unknown }
137
+ /** The agent retitled the session or bumped its activity timestamp. */
138
+ | { kind: "session_info"; title?: string | null; updatedAt?: string | null }
139
+ /** Config options changed; also reflected in `client.configOptions`. */
140
+ | { kind: "config"; configOptions: unknown }
141
+ /** A session update we don't model. The raw notification payload is attached. */
142
+ | { kind: "unknown"; sessionUpdate: string; raw: unknown };
57
143
 
58
144
  export interface PlanEntry {
59
145
  content: string;
@@ -81,6 +167,11 @@ export interface PromptHandlers {
81
167
  onChunk?: (text: string) => void;
82
168
  /** Observation-only activity (thinking, tool calls, plan). */
83
169
  onActivity?: (event: ActivityEvent) => void;
170
+ /**
171
+ * Every raw `session/update` notification for this turn, before any mapping. The
172
+ * escape hatch for protocol fields the ActivityEvent contract doesn't model yet.
173
+ */
174
+ onUpdate?: (notification: unknown) => void;
84
175
  /**
85
176
  * Blocking permission request. Must return an outcome. If omitted, the client
86
177
  * falls back to its configured `defaultPermission`.
package/src/updates.ts CHANGED
@@ -2,9 +2,23 @@
2
2
  // `agent_message_chunk` → response text; everything else → ActivityEvent.
3
3
  // See SPEC.md "Protocol facts": all agent→client events are session/update,
4
4
  // discriminated by `sessionUpdate`.
5
+ //
6
+ // Two rules govern this file:
7
+ // 1. NOTHING is dropped. An update we don't model becomes `{kind:"unknown", raw}`.
8
+ // 2. On tool_call_update, absent/null means UNCHANGED — never invent a value. The
9
+ // caller merges updates onto the tool call it already has.
5
10
 
6
11
  import type * as schema from "@agentclientprotocol/sdk";
7
- import type { ActivityEvent, PlanEntry } from "./types.ts";
12
+ import type {
13
+ ActivityEvent,
14
+ AgentCommand,
15
+ ContentBlock,
16
+ PlanEntry,
17
+ ToolActivity,
18
+ ToolContent,
19
+ ToolLocation,
20
+ ToolUpdateActivity,
21
+ } from "./types.ts";
8
22
 
9
23
  /** Response text from an agent_message_chunk, or "" for any other update. */
10
24
  export function extractChunkText(update: schema.SessionUpdate): string {
@@ -18,28 +32,128 @@ export function extractChunkText(update: schema.SessionUpdate): string {
18
32
  export function toActivityEvent(update: schema.SessionUpdate): ActivityEvent | null {
19
33
  const u = update as Record<string, any>;
20
34
  switch (u.sessionUpdate) {
35
+ // The response text itself — delivered through onChunk, not as activity.
36
+ case "agent_message_chunk":
37
+ return null;
38
+
21
39
  case "agent_thought_chunk": {
22
- const text = u.content?.type === "text" ? (u.content.text ?? "") : "";
40
+ const text = blockText(u.content);
23
41
  return text ? { kind: "thinking", text } : null;
24
42
  }
25
- case "tool_call":
26
- return {
43
+
44
+ case "user_message_chunk": {
45
+ const text = blockText(u.content);
46
+ return text ? { kind: "user_message", text } : null;
47
+ }
48
+
49
+ case "tool_call": {
50
+ const event: ToolActivity = {
27
51
  kind: "tool",
28
52
  toolCallId: u.toolCallId,
29
- title: u.title,
30
53
  toolKind: u.kind ?? "other",
31
54
  status: u.status ?? "pending",
32
- rawInput: u.rawInput ?? undefined,
33
- };
34
- case "tool_call_update":
35
- return {
36
- kind: "tool_update",
37
- toolCallId: u.toolCallId,
38
- status: u.status ?? "in_progress",
39
55
  };
56
+ if (u.title != null) event.title = u.title;
57
+ if (u.rawInput !== undefined && u.rawInput !== null) event.rawInput = u.rawInput;
58
+ if (u.rawOutput !== undefined && u.rawOutput !== null) event.rawOutput = u.rawOutput;
59
+ if (Array.isArray(u.content)) event.content = toToolContent(u.content);
60
+ if (Array.isArray(u.locations)) event.locations = toToolLocations(u.locations);
61
+ return event;
62
+ }
63
+
64
+ case "tool_call_update": {
65
+ // Every field but toolCallId is optional here, and the wire encodes "unchanged"
66
+ // as either absent or null. Copying only what's present is what lets a caller
67
+ // merge safely; the old code invented `status: "in_progress"` and dropped the
68
+ // command, output and diff entirely.
69
+ const event: ToolUpdateActivity = { kind: "tool_update", toolCallId: u.toolCallId };
70
+ if (u.status != null) event.status = u.status;
71
+ if (u.title != null) event.title = u.title;
72
+ if (u.kind != null) event.toolKind = u.kind;
73
+ if (u.rawInput !== undefined && u.rawInput !== null) event.rawInput = u.rawInput;
74
+ if (u.rawOutput !== undefined && u.rawOutput !== null) event.rawOutput = u.rawOutput;
75
+ if (Array.isArray(u.content)) event.content = toToolContent(u.content);
76
+ if (Array.isArray(u.locations)) event.locations = toToolLocations(u.locations);
77
+ return event;
78
+ }
79
+
40
80
  case "plan":
41
81
  return { kind: "plan", entries: (u.entries ?? []) as PlanEntry[] };
82
+ case "plan_update":
83
+ return { kind: "plan_update", planId: u.id, plan: u.plan };
84
+ case "plan_removed":
85
+ return { kind: "plan_removed", planId: u.id };
86
+
87
+ case "available_commands_update":
88
+ return { kind: "commands", commands: toAgentCommands(u.availableCommands) };
89
+ case "current_mode_update":
90
+ return { kind: "mode", modeId: u.currentModeId };
91
+ case "config_option_update":
92
+ return { kind: "config", configOptions: u.configOptions };
93
+
94
+ case "usage_update":
95
+ return {
96
+ kind: "usage",
97
+ used: Number(u.used ?? 0),
98
+ size: Number(u.size ?? 0),
99
+ ...(u.cost != null ? { cost: u.cost } : {}),
100
+ };
101
+
102
+ case "session_info_update":
103
+ return { kind: "session_info", title: u.title ?? null, updatedAt: u.updatedAt ?? null };
104
+
42
105
  default:
43
- return null;
106
+ return {
107
+ kind: "unknown",
108
+ sessionUpdate: String(u.sessionUpdate ?? "unknown"),
109
+ raw: update,
110
+ };
44
111
  }
45
112
  }
113
+
114
+ /** Slash commands from an available_commands_update payload. */
115
+ export function toAgentCommands(raw: unknown): AgentCommand[] {
116
+ if (!Array.isArray(raw)) return [];
117
+ return raw.map((c: Record<string, any>) => ({
118
+ name: c?.name,
119
+ description: c?.description ?? "",
120
+ }));
121
+ }
122
+
123
+ /** Normalize a ToolCallContent[] — keeping unrecognized shapes verbatim. */
124
+ export function toToolContent(raw: unknown[]): ToolContent[] {
125
+ return raw.map((item): ToolContent => {
126
+ const c = item as Record<string, any>;
127
+ switch (c?.type) {
128
+ case "content": {
129
+ const block = (c.content ?? {}) as ContentBlock;
130
+ const text = blockText(block);
131
+ return text ? { type: "content", content: block, text } : { type: "content", content: block };
132
+ }
133
+ case "diff":
134
+ return {
135
+ type: "diff",
136
+ path: c.path,
137
+ oldText: c.oldText ?? null,
138
+ newText: c.newText ?? "",
139
+ };
140
+ case "terminal":
141
+ return { type: "terminal", terminalId: c.terminalId };
142
+ default:
143
+ return { type: "other", raw: item };
144
+ }
145
+ });
146
+ }
147
+
148
+ function toToolLocations(raw: unknown[]): ToolLocation[] {
149
+ return raw.map((item) => {
150
+ const l = item as Record<string, any>;
151
+ return l?.line != null ? { path: l.path, line: l.line } : { path: l?.path };
152
+ });
153
+ }
154
+
155
+ /** Text out of a ContentBlock, or "" when it isn't a text block. */
156
+ function blockText(block: unknown): string {
157
+ const b = block as Record<string, any> | null | undefined;
158
+ return b?.type === "text" ? (b.text ?? "") : "";
159
+ }