@qlairoslabs/acp-client 0.1.5 → 0.3.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/src/types.ts CHANGED
@@ -2,6 +2,8 @@
2
2
  // These are what every client (AcpClient, and later PtyClient) produces, so callers
3
3
  // render against these regardless of which mode is active. See SPEC.md.
4
4
 
5
+ import type { ApplyResult } from "./activity.ts";
6
+
5
7
  /**
6
8
  * A slash command the AGENT itself exposes (e.g. codex /model, kimi /sessions), learned
7
9
  * from the `available_commands_update` notification. Invoke with the `//name` passthrough.
@@ -37,23 +39,123 @@ export interface PromptResult {
37
39
  usage: Usage | null;
38
40
  }
39
41
 
42
+ /**
43
+ * One line of raw traffic between us and the agent process — the debugging view.
44
+ *
45
+ * `line` is the ndjson VERBATIM, never reserialized, so what you read is exactly what
46
+ * crossed the pipe (reserializing can mangle numbers we never parse). Notifications the
47
+ * transport intercepts before the SDK are included: this is the wire, not our model of it.
48
+ */
49
+ export interface WireEntry {
50
+ /** `in` from the agent's stdout, `out` to its stdin, `err` from its stderr. */
51
+ dir: "in" | "out" | "err";
52
+ ts: number;
53
+ line: string;
54
+ }
55
+
56
+ /** A raw content block: "text" | "image" | "audio" | "resource" | "resource_link". */
57
+ export interface ContentBlock {
58
+ type: string;
59
+ [key: string]: unknown;
60
+ }
61
+
62
+ /** A file location a tool call touched — enables "follow along" UIs. */
63
+ export interface ToolLocation {
64
+ path: string;
65
+ line?: number;
66
+ }
67
+
68
+ /** How a terminal command ended. Both fields are null while it is still running. */
69
+ export interface TerminalExitStatus {
70
+ exitCode: number | null;
71
+ signal: string | null;
72
+ }
73
+
74
+ /**
75
+ * Output produced by a tool call. Mirrors the protocol's three shapes; anything we
76
+ * don't recognize is preserved verbatim as `other` rather than dropped.
77
+ *
78
+ * `terminal` content names a live terminal the AGENT is driving through us. We resolve
79
+ * its output before handing the event to the caller, so `output`/`exitStatus` are
80
+ * populated whenever the terminal is still ours to read.
81
+ */
82
+ export type ToolContent =
83
+ | { type: "content"; content: ContentBlock; /** Convenience: set for text blocks. */ text?: string }
84
+ | { type: "diff"; path: string; oldText: string | null; newText: string }
85
+ | {
86
+ type: "terminal";
87
+ terminalId: string;
88
+ output?: string;
89
+ truncated?: boolean;
90
+ exitStatus?: TerminalExitStatus | null;
91
+ }
92
+ | { type: "other"; raw: unknown };
93
+
94
+ /**
95
+ * A tool call the agent started. The protocol lets an agent announce a call before it
96
+ * knows much about it, so most fields fill in later via `tool_update`.
97
+ */
98
+ export interface ToolActivity {
99
+ kind: "tool";
100
+ toolCallId: string;
101
+ title?: string;
102
+ toolKind: string;
103
+ status: string;
104
+ rawInput?: unknown;
105
+ rawOutput?: unknown;
106
+ content?: ToolContent[];
107
+ locations?: ToolLocation[];
108
+ }
109
+
110
+ /**
111
+ * A change to an in-flight tool call. Only the fields the agent actually changed are
112
+ * present — an absent field means "unchanged", NOT "empty". `content` and `locations`
113
+ * REPLACE the previous collections when present.
114
+ */
115
+ export interface ToolUpdateActivity {
116
+ kind: "tool_update";
117
+ toolCallId: string;
118
+ status?: string;
119
+ title?: string;
120
+ toolKind?: string;
121
+ rawInput?: unknown;
122
+ rawOutput?: unknown;
123
+ content?: ToolContent[];
124
+ locations?: ToolLocation[];
125
+ }
126
+
40
127
  /**
41
128
  * Real-time, observation-only events during a turn — separate from the response text.
42
129
  * Fire-and-forget; the caller renders them if it wants. (Permission requests are NOT
43
130
  * here — they are blocking and handled via PromptHandlers.onPermissionRequest.)
131
+ *
132
+ * Every session update except `agent_message_chunk` (which is the response text) maps to
133
+ * one of these; unrecognized kinds arrive as `unknown` with the raw payload attached, so
134
+ * a newer agent can never silently starve the caller of activity.
44
135
  */
45
136
  export type ActivityEvent =
46
- | { 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[] };
137
+ | { kind: "thinking"; text: string; messageId?: string }
138
+ /** The agent echoed back user input — session/load replay, or a queued message. */
139
+ | { kind: "user_message"; text: string; messageId?: string }
140
+ | ToolActivity
141
+ | ToolUpdateActivity
142
+ /** Full plan snapshot: replaces any previous plan. */
143
+ | { kind: "plan"; entries: PlanEntry[] }
144
+ /** Per-plan update (experimental protocol extension). */
145
+ | { kind: "plan_update"; planId: string; plan: unknown }
146
+ | { kind: "plan_removed"; planId: string }
147
+ /** The agent's slash commands changed; also reflected in `client.agentCommands`. */
148
+ | { kind: "commands"; commands: AgentCommand[] }
149
+ /** The agent switched session mode. */
150
+ | { kind: "mode"; modeId: string }
151
+ /** Context-window accounting. `used`/`size` are tokens. */
152
+ | { kind: "usage"; used: number; size: number; cost?: unknown }
153
+ /** The agent retitled the session or bumped its activity timestamp. */
154
+ | { kind: "session_info"; title?: string | null; updatedAt?: string | null }
155
+ /** Config options changed; also reflected in `client.configOptions`. */
156
+ | { kind: "config"; configOptions: unknown }
157
+ /** A session update we don't model. The raw notification payload is attached. */
158
+ | { kind: "unknown"; sessionUpdate: string; raw: unknown };
57
159
 
58
160
  export interface PlanEntry {
59
161
  content: string;
@@ -79,8 +181,23 @@ export interface PermissionRequest {
79
181
  export interface PromptHandlers {
80
182
  /** Partial response text (agent_message_chunk) as it streams. */
81
183
  onChunk?: (text: string) => void;
82
- /** Observation-only activity (thinking, tool calls, plan). */
184
+ /** Observation-only activity (thinking, tool calls, plan) as RAW protocol deltas. */
83
185
  onActivity?: (event: ActivityEvent) => void;
186
+ /**
187
+ * The same activity, FOLDED into full-state records — see `src/activity.ts`. Prefer this
188
+ * over hand-rolling the merge: `current` is always complete state, `emitted` is the
189
+ * subset worth persisting, `delta` is the incremental piece for thinking.
190
+ *
191
+ * Only fires when prompting through `AgentSession`, which runs exactly one aggregator
192
+ * per session. A caller holding a raw `AcpClient` owns its own aggregator and calls
193
+ * `apply()` from `onActivity`.
194
+ */
195
+ onRecord?: (result: ApplyResult) => void;
196
+ /**
197
+ * Every raw `session/update` notification for this turn, before any mapping. The
198
+ * escape hatch for protocol fields the ActivityEvent contract doesn't model yet.
199
+ */
200
+ onUpdate?: (notification: unknown) => void;
84
201
  /**
85
202
  * Blocking permission request. Must return an outcome. If omitted, the client
86
203
  * 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,137 @@ 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
+
39
+ // `messageId` is optional in ContentChunk but authoritative when present: "a change
40
+ // in messageId indicates a new message has started". It is the only protocol-given
41
+ // way to bound a thinking block, so carry it through.
21
42
  case "agent_thought_chunk": {
22
- const text = u.content?.type === "text" ? (u.content.text ?? "") : "";
23
- return text ? { kind: "thinking", text } : null;
43
+ const text = blockText(u.content);
44
+ if (!text) return null;
45
+ return u.messageId != null
46
+ ? { kind: "thinking", text, messageId: String(u.messageId) }
47
+ : { kind: "thinking", text };
24
48
  }
25
- case "tool_call":
26
- return {
49
+
50
+ case "user_message_chunk": {
51
+ const text = blockText(u.content);
52
+ if (!text) return null;
53
+ return u.messageId != null
54
+ ? { kind: "user_message", text, messageId: String(u.messageId) }
55
+ : { kind: "user_message", text };
56
+ }
57
+
58
+ case "tool_call": {
59
+ const event: ToolActivity = {
27
60
  kind: "tool",
28
61
  toolCallId: u.toolCallId,
29
- title: u.title,
30
62
  toolKind: u.kind ?? "other",
31
63
  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
64
  };
65
+ if (u.title != null) event.title = u.title;
66
+ if (u.rawInput !== undefined && u.rawInput !== null) event.rawInput = u.rawInput;
67
+ if (u.rawOutput !== undefined && u.rawOutput !== null) event.rawOutput = u.rawOutput;
68
+ if (Array.isArray(u.content)) event.content = toToolContent(u.content);
69
+ if (Array.isArray(u.locations)) event.locations = toToolLocations(u.locations);
70
+ return event;
71
+ }
72
+
73
+ case "tool_call_update": {
74
+ // Every field but toolCallId is optional here, and the wire encodes "unchanged"
75
+ // as either absent or null. Copying only what's present is what lets a caller
76
+ // merge safely; the old code invented `status: "in_progress"` and dropped the
77
+ // command, output and diff entirely.
78
+ const event: ToolUpdateActivity = { kind: "tool_update", toolCallId: u.toolCallId };
79
+ if (u.status != null) event.status = u.status;
80
+ if (u.title != null) event.title = u.title;
81
+ if (u.kind != null) event.toolKind = u.kind;
82
+ if (u.rawInput !== undefined && u.rawInput !== null) event.rawInput = u.rawInput;
83
+ if (u.rawOutput !== undefined && u.rawOutput !== null) event.rawOutput = u.rawOutput;
84
+ if (Array.isArray(u.content)) event.content = toToolContent(u.content);
85
+ if (Array.isArray(u.locations)) event.locations = toToolLocations(u.locations);
86
+ return event;
87
+ }
88
+
40
89
  case "plan":
41
90
  return { kind: "plan", entries: (u.entries ?? []) as PlanEntry[] };
91
+ case "plan_update":
92
+ return { kind: "plan_update", planId: u.id, plan: u.plan };
93
+ case "plan_removed":
94
+ return { kind: "plan_removed", planId: u.id };
95
+
96
+ case "available_commands_update":
97
+ return { kind: "commands", commands: toAgentCommands(u.availableCommands) };
98
+ case "current_mode_update":
99
+ return { kind: "mode", modeId: u.currentModeId };
100
+ case "config_option_update":
101
+ return { kind: "config", configOptions: u.configOptions };
102
+
103
+ case "usage_update":
104
+ return {
105
+ kind: "usage",
106
+ used: Number(u.used ?? 0),
107
+ size: Number(u.size ?? 0),
108
+ ...(u.cost != null ? { cost: u.cost } : {}),
109
+ };
110
+
111
+ case "session_info_update":
112
+ return { kind: "session_info", title: u.title ?? null, updatedAt: u.updatedAt ?? null };
113
+
42
114
  default:
43
- return null;
115
+ return {
116
+ kind: "unknown",
117
+ sessionUpdate: String(u.sessionUpdate ?? "unknown"),
118
+ raw: update,
119
+ };
44
120
  }
45
121
  }
122
+
123
+ /** Slash commands from an available_commands_update payload. */
124
+ export function toAgentCommands(raw: unknown): AgentCommand[] {
125
+ if (!Array.isArray(raw)) return [];
126
+ return raw.map((c: Record<string, any>) => ({
127
+ name: c?.name,
128
+ description: c?.description ?? "",
129
+ }));
130
+ }
131
+
132
+ /** Normalize a ToolCallContent[] — keeping unrecognized shapes verbatim. */
133
+ export function toToolContent(raw: unknown[]): ToolContent[] {
134
+ return raw.map((item): ToolContent => {
135
+ const c = item as Record<string, any>;
136
+ switch (c?.type) {
137
+ case "content": {
138
+ const block = (c.content ?? {}) as ContentBlock;
139
+ const text = blockText(block);
140
+ return text ? { type: "content", content: block, text } : { type: "content", content: block };
141
+ }
142
+ case "diff":
143
+ return {
144
+ type: "diff",
145
+ path: c.path,
146
+ oldText: c.oldText ?? null,
147
+ newText: c.newText ?? "",
148
+ };
149
+ case "terminal":
150
+ return { type: "terminal", terminalId: c.terminalId };
151
+ default:
152
+ return { type: "other", raw: item };
153
+ }
154
+ });
155
+ }
156
+
157
+ function toToolLocations(raw: unknown[]): ToolLocation[] {
158
+ return raw.map((item) => {
159
+ const l = item as Record<string, any>;
160
+ return l?.line != null ? { path: l.path, line: l.line } : { path: l?.path };
161
+ });
162
+ }
163
+
164
+ /** Text out of a ContentBlock, or "" when it isn't a text block. */
165
+ function blockText(block: unknown): string {
166
+ const b = block as Record<string, any> | null | undefined;
167
+ return b?.type === "text" ? (b.text ?? "") : "";
168
+ }
@@ -0,0 +1,85 @@
1
+ // A ready-made sink for the raw protocol traffic (`WireEntry`), for when an agent does
2
+ // something inexplicable and the structured logs aren't enough.
3
+ //
4
+ // The library never turns this on by itself: a wire log contains everything the agent said,
5
+ // including file contents and command output, so it is the caller's decision where that
6
+ // goes and for how long.
7
+
8
+ import { appendFile, mkdir, writeFile } from "node:fs/promises";
9
+ import { dirname } from "node:path";
10
+ import type { WireEntry } from "./types.ts";
11
+
12
+ export interface WireLogOptions {
13
+ /**
14
+ * Append ndjson here — one `WireEntry` per line, so `jq` works on it directly. Created
15
+ * (with parent directories) and TRUNCATED on the first write, so a run's log is that
16
+ * run's, not an accumulation of every run.
17
+ */
18
+ path?: string;
19
+ /**
20
+ * Also print a one-line-per-message summary. `true` and `"stderr"` mean stderr, which is
21
+ * the right default — stdout usually carries the agent's streamed reply.
22
+ */
23
+ console?: boolean | "stderr" | "stdout";
24
+ /**
25
+ * Truncate a line longer than this before printing/writing (a file read or a terminal
26
+ * dump can be megabytes). Default 4000 for the console, unlimited for the file.
27
+ */
28
+ maxLineBytes?: number;
29
+ }
30
+
31
+ const ARROW: Record<WireEntry["dir"], string> = { out: "→", in: "←", err: "!" };
32
+
33
+ // Hoisted: `clip` runs on every line of the protocol stream.
34
+ const encoder = new TextEncoder();
35
+ const decoder = new TextDecoder();
36
+
37
+ /**
38
+ * Build a `WireEntry` sink for `wire` on `AgentSession`/`AgentController`/`AcpClient`.
39
+ *
40
+ * Writes are chained rather than awaited by the caller: the tap sits in the middle of the
41
+ * protocol stream, so blocking it on disk would stall the conversation. Ordering is
42
+ * preserved because each append waits for the previous one.
43
+ */
44
+ export function createWireLog(options: WireLogOptions = {}): (entry: WireEntry) => void {
45
+ const target = options.console === "stdout" ? "stdout" : "stderr";
46
+ const toConsole = options.console !== undefined && options.console !== false;
47
+ const consoleMax = options.maxLineBytes ?? 4000;
48
+ const fileMax = options.maxLineBytes;
49
+
50
+ let chain: Promise<void> = Promise.resolve();
51
+ let started = false;
52
+
53
+ return (entry) => {
54
+ if (toConsole) {
55
+ const text = `${ARROW[entry.dir]} ${clip(entry.line, consoleMax)}\n`;
56
+ if (target === "stdout") process.stdout.write(text);
57
+ else process.stderr.write(text);
58
+ }
59
+
60
+ const path = options.path;
61
+ if (!path) return;
62
+ const line = `${JSON.stringify(
63
+ fileMax == null ? entry : { ...entry, line: clip(entry.line, fileMax) },
64
+ )}\n`;
65
+ chain = chain
66
+ .catch(() => {})
67
+ .then(async () => {
68
+ if (!started) {
69
+ started = true;
70
+ await mkdir(dirname(path), { recursive: true });
71
+ await writeFile(path, "");
72
+ }
73
+ await appendFile(path, line, "utf8");
74
+ });
75
+ };
76
+ }
77
+
78
+ /** Clip on a code-point boundary and say how much was dropped. */
79
+ function clip(line: string, maxBytes: number): string {
80
+ const bytes = encoder.encode(line);
81
+ if (bytes.length <= maxBytes) return line;
82
+ let end = maxBytes;
83
+ while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;
84
+ return `${decoder.decode(bytes.subarray(0, end))}… [+${bytes.length - end}B]`;
85
+ }