@qlairoslabs/acp-client 0.2.0 → 0.3.1

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
@@ -109,29 +109,139 @@ Every session update except the response text reaches `onActivity`, discriminate
109
109
  `plan_removed`, `commands`, `mode`, `usage`, `session_info`, `config`, and `unknown` for
110
110
  anything the protocol adds later (the raw payload rides along on `raw`).
111
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`:
112
+ **Tool calls arrive incrementally.** Agents announce a call before they know much about it
113
+ and fill it in afterwards, so the command, the diff and the output usually land on a later
114
+ `tool_update` — not on the initial `tool`. `event.content` is where the output lives —
115
+ `{type:"content"}` (with `text` pre-extracted for text blocks), `{type:"diff"}`,
116
+ `{type:"terminal"}`, or `{type:"other"}` with the raw payload for shapes we don't model.
117
+
118
+ You don't have to merge that yourself. `onRecord` hands you **full state** on every event:
119
+
120
+ ```ts
121
+ await session.prompt("Find and fix the failing test.", {
122
+ onRecord: ({ current, emitted }) => {
123
+ if (current) render(current.recordId, current.event); // always complete, never a delta
124
+ // `emitted` is the subset worth keeping: announced → input → settled
125
+ },
126
+ });
127
+ ```
128
+
129
+ `onRecord` is `AgentSession`-only, because the session runs exactly **one** aggregator for
130
+ its lifetime and that is what makes `recordId`s stable. Holding a raw `AcpClient`? Build one
131
+ aggregator per stream and feed it from `onActivity`:
115
132
 
116
133
  ```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
- }
134
+ import { ActivityAggregator } from "@qlairoslabs/acp-client/activity";
135
+
136
+ const agg = new ActivityAggregator();
137
+ onActivity: (event) => render(agg.apply(event));
138
+ ```
139
+
140
+ If you do merge deltas by hand, two rules matter: absent fields mean *unchanged* (so
141
+ spreading is right), and `content`/`locations` **replace** the previous collection wholesale
142
+ — the schema says "replace the content collection", and agents that stream a growing tool
143
+ input resend the whole value each time.
144
+
145
+ ### Sending activity over a wire
146
+
147
+ For a hub forwarding activity to a browser, send `wireFrames(result)` and fold with
148
+ `foldFrame`. Thinking crosses as a full record on the chunk that OPENS a block and as an
149
+ incremental `delta` for every chunk after it (re-sending the accumulated block per chunk is
150
+ quadratic — ~4 KB of text becomes ~800 KB over 400 chunks); everything else crosses as a
151
+ full record.
152
+
153
+ ```ts
154
+ // hub
155
+ import { wireFrames } from "@qlairoslabs/acp-client/activity";
156
+ onRecord: (result) => {
157
+ for (const frame of wireFrames(result)) socket.send(JSON.stringify(frame));
129
158
  }
159
+
160
+ // browser
161
+ import { foldFrame, type AggregatedRecord } from "@qlairoslabs/acp-client/activity";
162
+ let records = new Map<string, AggregatedRecord>();
163
+ socket.onmessage = (e) => { records = foldFrame(records, JSON.parse(e.data)); };
164
+ ```
165
+
166
+ Send `wireFrames(result)`, not `delta ?? current`, and don't reach past it into `result`:
167
+
168
+ - When a thinking block ends because a tool call started, that close rides in `emitted`
169
+ while `current` is the tool — a client sending only the latter never learns the block
170
+ finished and renders a bubble that never stops.
171
+ - `foldFrame` drops a delta whose base it has never seen (guessing at one is how you get
172
+ text stitched onto the wrong block). `wireFrames` sends the base first, so that never
173
+ happens on a subscriber who has been listening from the start.
174
+ - It never sends a record and a delta for the same `recordId` in one call. `foldFrame` has
175
+ no seq guard, so a consumer would append the same text twice.
176
+
177
+ The `/activity` subpath has **no runtime imports**, so it is safe to pull into a browser
178
+ bundle. Type-only imports work anywhere today; importing the *functions* needs a bundler
179
+ that accepts `.ts` sources (Vite does; Next needs `transpilePackages`) since this package
180
+ ships source rather than a build.
181
+
182
+ A client that connects **mid-turn** needs the turn so far, or a thinking delta arrives with
183
+ nothing to append to. Subscribe first, then replay, then filter by `seq`:
184
+
185
+ ```ts
186
+ const snap = session.activitySnapshot(); // { active, seq, records }
187
+ records = foldRecords(snap.records);
188
+ // then drop any streamed frame with frame.seq <= snap.seq — already reflected above
189
+ ```
190
+
191
+ `seq` never restarts, so that threshold stays valid across turns. Before the first turn and
192
+ between turns `activitySnapshot()` reports `active: false` with no records: a settled turn
193
+ belongs to the transcript, not to a replay. `active` only knows what the aggregator has
194
+ been told — a hub that separately tracks which sessions are busy should trust itself.
195
+
196
+ ### Debugging: the raw protocol
197
+
198
+ When an agent does something inexplicable, `wire` gives you every line in both directions,
199
+ verbatim — including the `session/update` notifications the transport takes off the wire
200
+ before the SDK sees them, which no other hook can observe.
201
+
202
+ ```ts
203
+ import { createWireLog } from "@qlairoslabs/acp-client";
204
+
205
+ const session = await AgentSession.create({
206
+ adapter: ADAPTERS.kimi,
207
+ adapterId: "kimi",
208
+ wire: createWireLog({ path: "/tmp/acp-wire.jsonl" }), // or { console: "stderr" }
209
+ });
130
210
  ```
131
211
 
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.
212
+ The file is ndjson, one `WireEntry` per line, truncated per run so a log is one run's:
213
+
214
+ ```bash
215
+ # The conversation as a call sequence — the view that usually finds the problem
216
+ jq -r 'select(.dir!="err") | (.line|fromjson) as $m
217
+ | [.dir, ($m.method // (if $m.error then "error" else "result" end)),
218
+ ($m.params.update.sessionUpdate // "")] | @tsv' /tmp/acp-wire.jsonl | uniq -c
219
+ ```
220
+
221
+ ```
222
+ 1 out initialize
223
+ 1 in result
224
+ 1 out session/prompt
225
+ 1 in session/update tool_call
226
+ 161 in session/update tool_call_update ← one call, 161 resends
227
+ 1 in session/request_permission
228
+ 1 out result
229
+ 1 in fs/write_text_file
230
+ ```
231
+
232
+ That `161` is real, from a Kimi run: agents resend the whole growing tool input on every
233
+ update, which is exactly what the activity fold exists to absorb.
234
+
235
+ `dir` is `out` (to the agent's stdin), `in` (from its stdout) or `err` (its stderr). `line`
236
+ is never reserialized, so what you read is exactly what crossed the pipe. Or from the CLI:
237
+
238
+ ```bash
239
+ acp-client chat --wire # raw lines to stderr
240
+ acp-client chat --wire=/tmp/wire.jsonl # ndjson to a file (usable during a real conversation)
241
+ ```
242
+
243
+ Off unless you set it, and the library never enables it on its own: a wire log contains
244
+ everything the agent said, file contents and command output included.
135
245
 
136
246
  ### Terminals and filesystem access
137
247
 
@@ -196,6 +306,56 @@ The transcript stores user messages and final assistant replies. Set
196
306
  lines — `readTranscript()` still returns messages only, so read those back with
197
307
  `readTranscriptLines()`.
198
308
 
309
+ Activity lines are **settled records, not raw deltas**: the session folds the stream and
310
+ writes checkpoints, so one shell command costs ~3 lines instead of ~15. Each line is
311
+ self-contained, and `reason` (`announced` / `input` / `settled` / `flushed` / `snapshot`)
312
+ says where in its lifecycle it was. Read them back folded — the same `recordId` last-wins
313
+ rule the live stream uses, so a reload shows what was watched:
314
+
315
+ ```ts
316
+ import { readActivityRecords, readTranscriptLines, toActivityRecord } from "@qlairoslabs/acp-client";
317
+
318
+ // just the activity state
319
+ const records = await readActivityRecords(path, { limit: 200 }); // newest 200, read backwards
320
+ for (const { recordId, reason, event } of records.values()) render(recordId, event);
321
+
322
+ // or interleave activity with messages on one timeline
323
+ for (const line of await readTranscriptLines(path, { limit: 200 })) {
324
+ if (line.t === "msg") renderMessage(line);
325
+ else if (line.t === "activity") renderActivity(toActivityRecord(line));
326
+ }
327
+ ```
328
+
329
+ With a `limit`, the file is read **backwards from the end in chunks**, so the cost is
330
+ proportional to the page you asked for rather than to the transcript's size. Page back by
331
+ passing the oldest returned `ts` as the next `before`.
332
+
333
+ `limit` counts what you actually asked for, not raw lines — `readTranscript(path, {limit: 20})`
334
+ is twenty **messages**, however many activity lines sit between them. Narrow it yourself with
335
+ `types`, which is what makes the budget meaningful for an interleaved view:
336
+
337
+ ```ts
338
+ // twenty things a chat UI would draw, with meta/raw noise excluded from the count
339
+ const page = await readTranscriptLines(path, { types: ["msg", "activity"], limit: 20 });
340
+ ```
341
+
342
+ The trade-off: on an activity-heavy transcript, twenty messages may span thousands of
343
+ activity lines, so the read walks back further to find them — in the worst case to the start
344
+ of the file. Cap what gets written with `transcriptActivity: { maxBytes }` if that matters.
345
+
346
+ `t:"msg"` delimits a turn (`msg(user) → activity… → msg(assistant)`), so a trailing user
347
+ message with no reply after it means that turn died in flight — and `reason:"flushed"`
348
+ records what it was doing when it did. Pass an object instead of `true` to tune it:
349
+
350
+ ```ts
351
+ transcriptActivity: {
352
+ kinds: ["tool", "thinking"], // default also includes plan, usage, mode, unknown
353
+ checkpointOnInput: true, // default: an extra line once a call knows its arguments
354
+ rawOutput: false, // default: it duplicates `content` byte for byte
355
+ maxBytes: 64_000, // default off: cap each string field, mark the line
356
+ }
357
+ ```
358
+
199
359
  ```ts
200
360
  import { AgentSession, ADAPTERS, readTranscript } from "@qlairoslabs/acp-client";
201
361
 
@@ -253,7 +413,8 @@ acp-client chat --adapter codex # pick an adapter
253
413
  acp-client chat --exec "docker exec -i my-container" # talk to an agent in a container
254
414
  acp-client chat --cwd /workspace --approve # auto-approve tool permissions
255
415
  acp-client chat --degraded # force degraded (PTY) mode
256
- acp-client chat -v | -d # verbose lifecycle / debug raw protocol
416
+ acp-client chat -v | -d # verbose lifecycle / debug payloads
417
+ acp-client chat --wire[=FILE] # dump every raw protocol line (stderr, or ndjson to FILE)
257
418
  ```
258
419
 
259
420
  Activity markers (thinking/tool) show by default; `--no-activity` disables them.
@@ -268,6 +429,7 @@ opt-in subpaths.
268
429
  | Import | Contents |
269
430
  |---|---|
270
431
  | `@qlairoslabs/acp-client` | Core: `AgentController`, `AgentSession`, `AcpClient`, `SessionManager`, `FileSessionStore`, `ADAPTERS`, loggers, types. |
432
+ | `@qlairoslabs/acp-client/activity` | `ActivityAggregator`, `foldRecords`, `foldFrame`, `wireFrames` — the delta→full-state fold. No runtime imports, so it is safe to compile for a browser. |
271
433
  | `@qlairoslabs/acp-client/repl` | `runRepl`, `createAgentCommands` (interactive layer). |
272
434
  | `@qlairoslabs/acp-client/degraded` | The PTY fallback transport (`Bun.spawn({ terminal })` + xterm parsing). |
273
435
  | `@qlairoslabs/acp-client/parser` | Terminal-output parsers used by degraded mode. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -36,6 +36,7 @@
36
36
  ],
37
37
  "exports": {
38
38
  ".": "./src/index.ts",
39
+ "./activity": "./src/activity.ts",
39
40
  "./repl": "./src/repl/index.ts",
40
41
  "./degraded": "./src/degraded/index.ts",
41
42
  "./parser": "./src/parser/index.ts",