@qlairoslabs/acp-client 0.2.0 → 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/transcript.ts CHANGED
@@ -1,6 +1,33 @@
1
- import { appendFile, mkdir, readFile } from "node:fs/promises";
1
+ // The chat transcript: one JSON object per line, append-only, readable without starting
2
+ // the agent. Deliberately lightweight and harness-agnostic — it is not a replacement for
3
+ // whatever full-fidelity record the provider keeps.
4
+ //
5
+ // FILE CONTRACT
6
+ //
7
+ // - `t:"msg"` DELIMITS A TURN. A turn is `msg(user) → activity… → msg(assistant)`; writes
8
+ // serialize in call order, so that nesting always holds. A trailing user message with no
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.
11
+ // - `t:"activity"` lines are SETTLED RECORDS, not raw deltas. FOLD THEM LAST-WINS ON
12
+ // `recordId` — `foldRecords()` from `./activity.ts` is exactly that, and is the only
13
+ // supported way to read them. A tool call normally writes 2–3 lines (announced → input →
14
+ // settled); later lines supersede earlier ones with the same `recordId`. `reason` lets a
15
+ // compact view take only `settled`/`flushed` without folding at all.
16
+ // - `reason:"flushed"` means the turn ended with that record still open, written at its
17
+ // real status. It is NOT `settled`.
18
+ // - Lines with neither `recordId` nor `reason` are raw activity deltas written by 0.2.x, from
19
+ // before this format. Those two fields are the discriminator, which is why `v` is still 1.
20
+ // - Unrecognized `t` values and malformed lines are SKIPPED, never fatal: a partially
21
+ // written final line (torn write) costs that line only.
22
+ // - `ts` is wall-clock milliseconds and is the ordering key ACROSS types, so a reader can
23
+ // interleave `msg` and `activity` on one timeline.
24
+ //
25
+ // Any future change to fold semantics or line meaning bumps `v`.
26
+
27
+ import { appendFile, mkdir, open, readFile, type FileHandle } from "node:fs/promises";
2
28
  import { dirname } from "node:path";
3
- import type { PromptResult, Usage } from "./types.ts";
29
+ import { foldRecords, type AggregatedRecord, type EmitReason } from "./activity.ts";
30
+ import type { ActivityEvent, PromptResult, Usage } from "./types.ts";
4
31
 
5
32
  export type TranscriptRole = "user" | "assistant";
6
33
 
@@ -24,11 +51,22 @@ export interface TranscriptMessageLine {
24
51
  status?: PromptResult["status"];
25
52
  }
26
53
 
54
+ /**
55
+ * One aggregated activity record, flattened: the `ActivityEvent`'s own fields sit at the
56
+ * top level beside the envelope. Fold last-wins on `recordId` (see the file contract at
57
+ * the top of this module).
58
+ */
27
59
  export interface TranscriptActivityLine {
28
60
  v: 1;
29
61
  t: "activity";
30
62
  ts: number;
31
63
  kind: string;
64
+ /** Fold key. Absent on raw activity lines written by 0.2.x. */
65
+ recordId?: string;
66
+ /** Lifecycle position. Absent on raw activity lines written by 0.2.x. */
67
+ reason?: EmitReason;
68
+ /** Set when `maxBytes` clipped a field on this line. */
69
+ truncated?: boolean;
32
70
  [key: string]: unknown;
33
71
  }
34
72
 
@@ -63,10 +101,37 @@ export type TranscriptEntry = TranscriptMessageLine;
63
101
  export interface ReadTranscriptOptions {
64
102
  /** Return entries with `ts` lower than this cursor. */
65
103
  before?: number;
66
- /** Return at most this many entries. Keeps the newest matching entries. */
104
+ /**
105
+ * Return at most this many entries, keeping the NEWEST matching ones.
106
+ *
107
+ * `limit` counts entries that SURVIVE `types` — ask for twenty messages and you get
108
+ * twenty messages, however many activity lines sit between them.
109
+ *
110
+ * With a limit the file is read backwards from EOF in chunks, so the cost is
111
+ * proportional to the region that holds `limit` matches rather than to the whole
112
+ * transcript. Narrow `types` on an activity-heavy file widens that region: twenty
113
+ * messages may span thousands of activity lines, and in the worst case the read reaches
114
+ * the start of the file — which is what every read did before the tail read existed.
115
+ */
67
116
  limit?: number;
117
+ /**
118
+ * Keep only these line types. Omit for everything recognized.
119
+ *
120
+ * This is what makes `limit` mean what you asked for. `["msg", "activity"]` is the
121
+ * interleaved chat view; `meta` and `raw` are noise a renderer would discard anyway,
122
+ * and excluding them here stops them consuming the budget.
123
+ */
124
+ types?: Array<TranscriptLine["t"]>;
68
125
  }
69
126
 
127
+ /** Backwards read granularity. Big enough that a typical page needs one or two reads. */
128
+ const TAIL_CHUNK_BYTES = 64 * 1024;
129
+
130
+ const LF = 0x0a;
131
+
132
+ /** Views from `subarray` keep the source's buffer kind; pin the loose form. */
133
+ type Bytes = Uint8Array<ArrayBufferLike>;
134
+
70
135
  export async function appendTranscriptLine(
71
136
  path: string,
72
137
  line: TranscriptLine,
@@ -75,20 +140,36 @@ export async function appendTranscriptLine(
75
140
  await appendFile(path, `${JSON.stringify(line)}\n`, "utf8");
76
141
  }
77
142
 
78
- /** Read the message projection of a transcript. Meta/activity/raw lines are skipped. */
143
+ /**
144
+ * Read the message projection of a transcript. Meta/activity/raw lines are skipped, and
145
+ * `limit` counts MESSAGES — the entries this returns — not lines.
146
+ *
147
+ * `types` is forced: this function is the message projection, so honouring a caller's
148
+ * `types` would be incoherent.
149
+ */
79
150
  export async function readTranscript(
80
151
  path: string,
81
152
  options: ReadTranscriptOptions = {},
82
153
  ): Promise<TranscriptEntry[]> {
83
- const lines = await readTranscriptLines(path, options);
154
+ const lines = await readTranscriptLines(path, { ...options, types: ["msg"] });
84
155
  return lines.filter(isTranscriptMessageLine);
85
156
  }
86
157
 
87
- /** Read all recognized transcript lines, preserving oldest-first order. */
158
+ /**
159
+ * Read all recognized transcript lines, preserving oldest-first order.
160
+ *
161
+ * `before` + `limit` are the pagination contract: page back through a conversation by
162
+ * passing the oldest returned `ts` as the next `before`.
163
+ */
88
164
  export async function readTranscriptLines(
89
165
  path: string,
90
166
  options: ReadTranscriptOptions = {},
91
167
  ): Promise<TranscriptLine[]> {
168
+ const types = options.types ? new Set<string>(options.types) : undefined;
169
+ if (options.limit != null && options.limit >= 0) {
170
+ return readTail(path, options.limit, options.before, types);
171
+ }
172
+
92
173
  let content: string;
93
174
  try {
94
175
  content = await readFile(path, "utf8");
@@ -98,20 +179,151 @@ export async function readTranscriptLines(
98
179
 
99
180
  const out: TranscriptLine[] = [];
100
181
  for (const raw of content.split(/\r?\n/)) {
101
- if (!raw.trim()) continue;
102
- try {
103
- const line = JSON.parse(raw) as unknown;
104
- if (!isTranscriptLine(line)) continue;
105
- if (options.before != null && line.ts >= options.before) continue;
106
- out.push(line);
107
- } catch {
108
- /* skip malformed lines */
182
+ const line = parseTranscriptLine(raw, options.before, types);
183
+ if (line) out.push(line);
184
+ }
185
+ return out;
186
+ }
187
+
188
+ /**
189
+ * Un-flatten one activity line back into the record it was written from.
190
+ *
191
+ * Null for a line that predates this format (no `recordId`/`reason`) — those are raw
192
+ * deltas and cannot be folded. `seq` is 0: it is a live-stream ordering device for the
193
+ * mid-turn join, never a file field.
194
+ *
195
+ * Exported because a reader that interleaves `msg` and `activity` on one `ts` timeline
196
+ * needs per-line conversion; use `readActivityRecords` if you only want the folded state.
197
+ */
198
+ export function toActivityRecord(line: TranscriptActivityLine): AggregatedRecord | null {
199
+ if (!line.recordId || !line.reason) return null;
200
+ const { v, t, ts, recordId, reason, ...event } = line;
201
+ return { recordId, reason, seq: 0, event: event as unknown as ActivityEvent };
202
+ }
203
+
204
+ /**
205
+ * The folded activity state of a transcript: everything that happened, one entry per
206
+ * `recordId`, last write winning. This is THE read path for activity — the same fold the
207
+ * live stream uses, so a reload shows what was watched.
208
+ */
209
+ export async function readActivityRecords(
210
+ path: string,
211
+ options: ReadTranscriptOptions = {},
212
+ ): Promise<Map<string, AggregatedRecord>> {
213
+ const records: AggregatedRecord[] = [];
214
+ // `types` forced for the same reason as readTranscript: `limit` should count the thing
215
+ // this returns. Note the newest N activity lines always carry the LATEST state of what
216
+ // they cover, since a later line supersedes an earlier one with the same `recordId`.
217
+ for (const line of await readTranscriptLines(path, { ...options, types: ["activity"] })) {
218
+ if (line.t !== "activity") continue;
219
+ const record = toActivityRecord(line);
220
+ if (record) records.push(record);
221
+ }
222
+ return foldRecords(records);
223
+ }
224
+
225
+ /**
226
+ * The newest `limit` matching lines, read backwards from EOF.
227
+ *
228
+ * Accumulates RAW BYTES and decodes only the assembled tail, so a multi-byte character
229
+ * split across a chunk boundary is whole again before anyone looks at it. The leading
230
+ * fragment of each block is a line whose beginning we haven't read yet, so it is carried
231
+ * into the next iteration rather than parsed.
232
+ */
233
+ async function readTail(
234
+ path: string,
235
+ limit: number,
236
+ before?: number,
237
+ types?: Set<string>,
238
+ ): Promise<TranscriptLine[]> {
239
+ if (limit === 0) return [];
240
+
241
+ let handle: FileHandle;
242
+ try {
243
+ handle = await open(path, "r");
244
+ } catch {
245
+ return [];
246
+ }
247
+
248
+ try {
249
+ const { size } = await handle.stat();
250
+ const newestFirst: TranscriptLine[] = [];
251
+ const decoder = new TextDecoder();
252
+ let end = size;
253
+ let carry: Bytes = new Uint8Array(0);
254
+
255
+ while (end > 0 && newestFirst.length < limit) {
256
+ const start = Math.max(0, end - TAIL_CHUNK_BYTES);
257
+ const block = concatBytes(await readBytes(handle, start, end - start), carry);
258
+ end = start;
259
+
260
+ let body: Bytes;
261
+ if (start === 0) {
262
+ body = block; // reached the beginning: nothing is partial any more
263
+ carry = new Uint8Array(0);
264
+ } else {
265
+ const firstBreak = block.indexOf(LF);
266
+ if (firstBreak < 0) {
267
+ carry = block; // a single line longer than one chunk
268
+ continue;
269
+ }
270
+ carry = block.subarray(0, firstBreak);
271
+ body = block.subarray(firstBreak + 1);
272
+ }
273
+
274
+ const raws = decoder.decode(body).split(/\r?\n/);
275
+ for (let i = raws.length - 1; i >= 0 && newestFirst.length < limit; i--) {
276
+ const line = parseTranscriptLine(raws[i]!, before, types);
277
+ if (line) newestFirst.push(line);
278
+ }
109
279
  }
280
+
281
+ return newestFirst.reverse();
282
+ } finally {
283
+ await handle.close();
110
284
  }
285
+ }
111
286
 
112
- if (options.limit != null && options.limit >= 0 && out.length > options.limit) {
113
- return out.slice(out.length - options.limit);
287
+ /**
288
+ * One line → a recognized entry, or null (blank, malformed, unknown, or filtered out).
289
+ *
290
+ * Every rejection happens HERE, which is what makes `limit` count survivors: both read
291
+ * paths tally what this returns, so narrowing `types` narrows what the budget is spent on
292
+ * without either loop knowing about it.
293
+ */
294
+ function parseTranscriptLine(
295
+ raw: string,
296
+ before?: number,
297
+ types?: Set<string>,
298
+ ): TranscriptLine | null {
299
+ if (!raw.trim()) return null;
300
+ try {
301
+ const line = JSON.parse(raw) as unknown;
302
+ if (!isTranscriptLine(line)) return null;
303
+ if (types && !types.has(line.t)) return null;
304
+ if (before != null && line.ts >= before) return null;
305
+ return line;
306
+ } catch {
307
+ return null; // skip malformed lines
114
308
  }
309
+ }
310
+
311
+ async function readBytes(handle: FileHandle, start: number, length: number): Promise<Uint8Array> {
312
+ const buf = new Uint8Array(length);
313
+ let read = 0;
314
+ while (read < length) {
315
+ const { bytesRead } = await handle.read(buf, read, length - read, start + read);
316
+ if (bytesRead <= 0) break;
317
+ read += bytesRead;
318
+ }
319
+ return read === length ? buf : buf.subarray(0, read);
320
+ }
321
+
322
+ function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
323
+ if (b.length === 0) return a;
324
+ const out = new Uint8Array(a.length + b.length);
325
+ out.set(a, 0);
326
+ out.set(b, a.length);
115
327
  return out;
116
328
  }
117
329
 
@@ -6,6 +6,7 @@
6
6
  import * as acp from "@agentclientprotocol/sdk";
7
7
  import type * as schema from "@agentclientprotocol/sdk";
8
8
  import { ProcessCrashError } from "../errors.ts";
9
+ import type { WireEntry } from "../types.ts";
9
10
 
10
11
  /** The five `terminal/*` methods a client that advertises `terminal: true` must serve. */
11
12
  export interface TerminalHandlers {
@@ -51,6 +52,12 @@ export interface AcpTransportOptions {
51
52
  terminals?: TerminalHandlers;
52
53
  /** A line of stderr from the process. */
53
54
  onStderr?: (line: string) => void;
55
+ /**
56
+ * Every raw line in either direction, for debugging. This is the ONLY view of the
57
+ * traffic that is complete: `onUpdate` sees notifications after mapping, the logger sees
58
+ * our interpretation, and the SDK sees neither the lines we intercept nor what it wrote.
59
+ */
60
+ onWire?: (entry: WireEntry) => void;
54
61
  /** The process exited unexpectedly (not via stop()). */
55
62
  onCrash?: (code: number | null) => void;
56
63
  }
@@ -59,6 +66,7 @@ export class AcpTransport {
59
66
  private proc: ReturnType<typeof Bun.spawn> | null = null;
60
67
  private connection: acp.ClientSideConnection | null = null;
61
68
  private stopping = false;
69
+ private tap?: (dir: WireEntry["dir"], line: string) => void;
62
70
 
63
71
  constructor(private opts: AcpTransportOptions) {}
64
72
 
@@ -78,12 +86,19 @@ export class AcpTransport {
78
86
  });
79
87
  this.proc = proc;
80
88
 
89
+ const wire = this.opts.onWire;
90
+ const tap = wire ? (dir: WireEntry["dir"], line: string) => wire({ dir, ts: Date.now(), line }) : undefined;
91
+
81
92
  const stream = acp.ndJsonStream(
82
- stdinTransform.writable,
83
- interceptUpdates(proc.stdout as ReadableStream<Uint8Array>, (m) =>
84
- this.opts.onUpdate?.(m.params as schema.SessionNotification),
93
+ // Outgoing bytes are forwarded untouched; the tap only reads them on the way past.
94
+ tap ? tapOutgoing(stdinTransform.writable, (line) => tap("out", line)) : stdinTransform.writable,
95
+ interceptUpdates(
96
+ proc.stdout as ReadableStream<Uint8Array>,
97
+ (m) => this.opts.onUpdate?.(m.params as schema.SessionNotification),
98
+ tap && ((line) => tap("in", line)),
85
99
  ),
86
100
  );
101
+ this.tap = tap;
87
102
  const handler = new ClientHandler(this.opts);
88
103
  this.connection = new acp.ClientSideConnection(() => handler, stream);
89
104
 
@@ -177,14 +192,50 @@ export class AcpTransport {
177
192
  while ((i = buf.indexOf("\n")) >= 0) {
178
193
  const line = buf.slice(0, i).trim();
179
194
  buf = buf.slice(i + 1);
180
- if (line) this.opts.onStderr?.(line);
195
+ if (line) this.emitStderr(line);
181
196
  }
182
197
  }
183
198
  const tail = buf.trim();
184
- if (tail) this.opts.onStderr?.(tail);
199
+ if (tail) this.emitStderr(tail);
200
+ }
201
+
202
+ private emitStderr(line: string): void {
203
+ this.tap?.("err", line);
204
+ this.opts.onStderr?.(line);
185
205
  }
186
206
  }
187
207
 
208
+ /**
209
+ * Wrap a writable so every line written through it is reported, then forwarded BYTE FOR
210
+ * BYTE. The SDK owns serialization; this only looks.
211
+ */
212
+ function tapOutgoing(
213
+ target: WritableStream<Uint8Array>,
214
+ onLine: (line: string) => void,
215
+ ): WritableStream<Uint8Array> {
216
+ const writer = target.getWriter();
217
+ const dec = new TextDecoder();
218
+ let buf = "";
219
+ return new WritableStream<Uint8Array>({
220
+ async write(chunk) {
221
+ buf += dec.decode(chunk, { stream: true });
222
+ let i: number;
223
+ while ((i = buf.indexOf("\n")) >= 0) {
224
+ const line = buf.slice(0, i).trim();
225
+ buf = buf.slice(i + 1);
226
+ if (line) onLine(line);
227
+ }
228
+ await writer.write(chunk);
229
+ },
230
+ async close() {
231
+ await writer.close();
232
+ },
233
+ async abort(reason) {
234
+ await writer.abort(reason);
235
+ },
236
+ });
237
+ }
238
+
188
239
  /**
189
240
  * Split the agent's ndjson into `session/update` (ours) and everything else (the SDK's).
190
241
  *
@@ -197,6 +248,7 @@ export class AcpTransport {
197
248
  function interceptUpdates(
198
249
  source: ReadableStream<Uint8Array>,
199
250
  onMessage: (message: Record<string, any>) => void,
251
+ onLine?: (line: string) => void,
200
252
  ): ReadableStream<Uint8Array> {
201
253
  const dec = new TextDecoder();
202
254
  const enc = new TextEncoder();
@@ -205,6 +257,8 @@ function interceptUpdates(
205
257
  // Re-emits the ORIGINAL line text — reserializing risks mangling numbers we never read.
206
258
  const handle = (line: string, controller: TransformStreamDefaultController<Uint8Array>) => {
207
259
  if (!line) return;
260
+ // Before the split, so the debug view includes what we take off the wire ourselves.
261
+ onLine?.(line);
208
262
  let message: Record<string, any> | undefined;
209
263
  try {
210
264
  message = JSON.parse(line);
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,6 +39,20 @@ 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
+
40
56
  /** A raw content block: "text" | "image" | "audio" | "resource" | "resource_link". */
41
57
  export interface ContentBlock {
42
58
  type: string;
@@ -118,9 +134,9 @@ export interface ToolUpdateActivity {
118
134
  * a newer agent can never silently starve the caller of activity.
119
135
  */
120
136
  export type ActivityEvent =
121
- | { kind: "thinking"; text: string }
137
+ | { kind: "thinking"; text: string; messageId?: string }
122
138
  /** The agent echoed back user input — session/load replay, or a queued message. */
123
- | { kind: "user_message"; text: string }
139
+ | { kind: "user_message"; text: string; messageId?: string }
124
140
  | ToolActivity
125
141
  | ToolUpdateActivity
126
142
  /** Full plan snapshot: replaces any previous plan. */
@@ -165,8 +181,18 @@ export interface PermissionRequest {
165
181
  export interface PromptHandlers {
166
182
  /** Partial response text (agent_message_chunk) as it streams. */
167
183
  onChunk?: (text: string) => void;
168
- /** Observation-only activity (thinking, tool calls, plan). */
184
+ /** Observation-only activity (thinking, tool calls, plan) as RAW protocol deltas. */
169
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;
170
196
  /**
171
197
  * Every raw `session/update` notification for this turn, before any mapping. The
172
198
  * escape hatch for protocol fields the ActivityEvent contract doesn't model yet.
package/src/updates.ts CHANGED
@@ -36,14 +36,23 @@ export function toActivityEvent(update: schema.SessionUpdate): ActivityEvent | n
36
36
  case "agent_message_chunk":
37
37
  return null;
38
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.
39
42
  case "agent_thought_chunk": {
40
43
  const text = blockText(u.content);
41
- return text ? { kind: "thinking", text } : null;
44
+ if (!text) return null;
45
+ return u.messageId != null
46
+ ? { kind: "thinking", text, messageId: String(u.messageId) }
47
+ : { kind: "thinking", text };
42
48
  }
43
49
 
44
50
  case "user_message_chunk": {
45
51
  const text = blockText(u.content);
46
- return text ? { kind: "user_message", text } : null;
52
+ if (!text) return null;
53
+ return u.messageId != null
54
+ ? { kind: "user_message", text, messageId: String(u.messageId) }
55
+ : { kind: "user_message", text };
47
56
  }
48
57
 
49
58
  case "tool_call": {
@@ -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
+ }