@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/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,156 @@ 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.** 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`:
132
+
133
+ ```ts
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 an incremental `delta` (re-sending the accumulated block
149
+ per chunk is quadratic — ~4 KB of text becomes ~800 KB over 400 chunks); everything else
150
+ crosses as a full record.
151
+
152
+ ```ts
153
+ // hub
154
+ import { wireFrames } from "@qlairoslabs/acp-client/activity";
155
+ onRecord: (result) => {
156
+ for (const frame of wireFrames(result)) socket.send(JSON.stringify(frame));
157
+ }
158
+
159
+ // browser
160
+ import { foldFrame, type AggregatedRecord } from "@qlairoslabs/acp-client/activity";
161
+ let records = new Map<string, AggregatedRecord>();
162
+ socket.onmessage = (e) => { records = foldFrame(records, JSON.parse(e.data)); };
163
+ ```
164
+
165
+ Send `wireFrames(result)`, not `delta ?? current`: when a thinking block ends because a tool
166
+ call started, that close rides in `emitted` while `current` is the tool — a client sending
167
+ only the latter never learns the block finished and renders a bubble that never stops.
168
+
169
+ The `/activity` subpath has **no runtime imports**, so it is safe to pull into a browser
170
+ bundle. Type-only imports work anywhere today; importing the *functions* needs a bundler
171
+ that accepts `.ts` sources (Vite does; Next needs `transpilePackages`) since this package
172
+ ships source rather than a build.
173
+
174
+ A client that connects **mid-turn** needs the turn so far, or a thinking delta arrives with
175
+ nothing to append to. Subscribe first, then replay, then filter by `seq`:
176
+
177
+ ```ts
178
+ const snap = session.activitySnapshot(); // { active, seq, records }
179
+ records = foldRecords(snap.records);
180
+ // then drop any streamed frame with frame.seq <= snap.seq — already reflected above
181
+ ```
182
+
183
+ `seq` never restarts, so that threshold stays valid across turns. Between turns
184
+ `activitySnapshot()` reports `active: false` with no records: a settled turn belongs to the
185
+ transcript, not to a replay.
186
+
187
+ ### Debugging: the raw protocol
188
+
189
+ When an agent does something inexplicable, `wire` gives you every line in both directions,
190
+ verbatim — including the `session/update` notifications the transport takes off the wire
191
+ before the SDK sees them, which no other hook can observe.
192
+
193
+ ```ts
194
+ import { createWireLog } from "@qlairoslabs/acp-client";
195
+
196
+ const session = await AgentSession.create({
197
+ adapter: ADAPTERS.kimi,
198
+ adapterId: "kimi",
199
+ wire: createWireLog({ path: "/tmp/acp-wire.jsonl" }), // or { console: "stderr" }
200
+ });
201
+ ```
202
+
203
+ The file is ndjson, one `WireEntry` per line, truncated per run so a log is one run's:
204
+
205
+ ```bash
206
+ # The conversation as a call sequence — the view that usually finds the problem
207
+ jq -r 'select(.dir!="err") | (.line|fromjson) as $m
208
+ | [.dir, ($m.method // (if $m.error then "error" else "result" end)),
209
+ ($m.params.update.sessionUpdate // "")] | @tsv' /tmp/acp-wire.jsonl | uniq -c
210
+ ```
211
+
212
+ ```
213
+ 1 out initialize
214
+ 1 in result
215
+ 1 out session/prompt
216
+ 1 in session/update tool_call
217
+ 161 in session/update tool_call_update ← one call, 161 resends
218
+ 1 in session/request_permission
219
+ 1 out result
220
+ 1 in fs/write_text_file
221
+ ```
222
+
223
+ That `161` is real, from a Kimi run: agents resend the whole growing tool input on every
224
+ update, which is exactly what the activity fold exists to absorb.
225
+
226
+ `dir` is `out` (to the agent's stdin), `in` (from its stdout) or `err` (its stderr). `line`
227
+ is never reserialized, so what you read is exactly what crossed the pipe. Or from the CLI:
228
+
229
+ ```bash
230
+ acp-client chat --wire # raw lines to stderr
231
+ acp-client chat --wire=/tmp/wire.jsonl # ndjson to a file (usable during a real conversation)
232
+ ```
233
+
234
+ Off unless you set it, and the library never enables it on its own: a wire log contains
235
+ everything the agent said, file contents and command output included.
236
+
237
+ ### Terminals and filesystem access
238
+
239
+ The client advertises the `terminal` and `fs` client capabilities and implements them:
240
+ agents route their shell commands through `terminal/create` and read/write files through
241
+ `fs/read_text_file` and `fs/write_text_file` on us. Terminal tool calls carry only a
242
+ `terminalId` over the wire; the client resolves the live output before handing you the
243
+ event, so `content` entries of type `terminal` come with `output`, `truncated` and
244
+ `exitStatus` filled in.
245
+
246
+ Commands run as child processes of your app, with your environment. To opt out — letting
247
+ the agent fall back to its own implementation — turn the capability off, which also stops
248
+ us advertising it:
249
+
250
+ ```ts
251
+ new AcpClient({
252
+ adapter: ADAPTERS.codex,
253
+ clientCapabilities: { terminal: false, fs: { writeTextFile: false } },
254
+ });
255
+ ```
256
+
106
257
  ### Durable sessions with a catalog
107
258
 
108
259
  `AgentSession` gives a conversation a stable id that persists across reconnects, and
@@ -141,8 +292,60 @@ chat transcript that can be read later without starting the agent. `transcriptPa
141
292
  exact file path chosen by the caller; `transcriptDir` lets the library write
142
293
  `<agentSessionId>.jsonl` inside that directory. Supplying both is a config error.
143
294
 
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.
295
+ The transcript stores user messages and final assistant replies. Set
296
+ `transcriptActivity: true` to also record tool calls, thinking and plans as `t:"activity"`
297
+ lines — `readTranscript()` still returns messages only, so read those back with
298
+ `readTranscriptLines()`.
299
+
300
+ Activity lines are **settled records, not raw deltas**: the session folds the stream and
301
+ writes checkpoints, so one shell command costs ~3 lines instead of ~15. Each line is
302
+ self-contained, and `reason` (`announced` / `input` / `settled` / `flushed` / `snapshot`)
303
+ says where in its lifecycle it was. Read them back folded — the same `recordId` last-wins
304
+ rule the live stream uses, so a reload shows what was watched:
305
+
306
+ ```ts
307
+ import { readActivityRecords, readTranscriptLines, toActivityRecord } from "@qlairoslabs/acp-client";
308
+
309
+ // just the activity state
310
+ const records = await readActivityRecords(path, { limit: 200 }); // newest 200, read backwards
311
+ for (const { recordId, reason, event } of records.values()) render(recordId, event);
312
+
313
+ // or interleave activity with messages on one timeline
314
+ for (const line of await readTranscriptLines(path, { limit: 200 })) {
315
+ if (line.t === "msg") renderMessage(line);
316
+ else if (line.t === "activity") renderActivity(toActivityRecord(line));
317
+ }
318
+ ```
319
+
320
+ With a `limit`, the file is read **backwards from the end in chunks**, so the cost is
321
+ proportional to the page you asked for rather than to the transcript's size. Page back by
322
+ passing the oldest returned `ts` as the next `before`.
323
+
324
+ `limit` counts what you actually asked for, not raw lines — `readTranscript(path, {limit: 20})`
325
+ is twenty **messages**, however many activity lines sit between them. Narrow it yourself with
326
+ `types`, which is what makes the budget meaningful for an interleaved view:
327
+
328
+ ```ts
329
+ // twenty things a chat UI would draw, with meta/raw noise excluded from the count
330
+ const page = await readTranscriptLines(path, { types: ["msg", "activity"], limit: 20 });
331
+ ```
332
+
333
+ The trade-off: on an activity-heavy transcript, twenty messages may span thousands of
334
+ activity lines, so the read walks back further to find them — in the worst case to the start
335
+ of the file. Cap what gets written with `transcriptActivity: { maxBytes }` if that matters.
336
+
337
+ `t:"msg"` delimits a turn (`msg(user) → activity… → msg(assistant)`), so a trailing user
338
+ message with no reply after it means that turn died in flight — and `reason:"flushed"`
339
+ records what it was doing when it did. Pass an object instead of `true` to tune it:
340
+
341
+ ```ts
342
+ transcriptActivity: {
343
+ kinds: ["tool", "thinking"], // default also includes plan, usage, mode, unknown
344
+ checkpointOnInput: true, // default: an extra line once a call knows its arguments
345
+ rawOutput: false, // default: it duplicates `content` byte for byte
346
+ maxBytes: 64_000, // default off: cap each string field, mark the line
347
+ }
348
+ ```
146
349
 
147
350
  ```ts
148
351
  import { AgentSession, ADAPTERS, readTranscript } from "@qlairoslabs/acp-client";
@@ -201,7 +404,8 @@ acp-client chat --adapter codex # pick an adapter
201
404
  acp-client chat --exec "docker exec -i my-container" # talk to an agent in a container
202
405
  acp-client chat --cwd /workspace --approve # auto-approve tool permissions
203
406
  acp-client chat --degraded # force degraded (PTY) mode
204
- acp-client chat -v | -d # verbose lifecycle / debug raw protocol
407
+ acp-client chat -v | -d # verbose lifecycle / debug payloads
408
+ acp-client chat --wire[=FILE] # dump every raw protocol line (stderr, or ndjson to FILE)
205
409
  ```
206
410
 
207
411
  Activity markers (thinking/tool) show by default; `--no-activity` disables them.
@@ -216,6 +420,7 @@ opt-in subpaths.
216
420
  | Import | Contents |
217
421
  |---|---|
218
422
  | `@qlairoslabs/acp-client` | Core: `AgentController`, `AgentSession`, `AcpClient`, `SessionManager`, `FileSessionStore`, `ADAPTERS`, loggers, types. |
423
+ | `@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. |
219
424
  | `@qlairoslabs/acp-client/repl` | `runRepl`, `createAgentCommands` (interactive layer). |
220
425
  | `@qlairoslabs/acp-client/degraded` | The PTY fallback transport (`Bun.spawn({ terminal })` + xterm parsing). |
221
426
  | `@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.1.5",
3
+ "version": "0.3.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",
@@ -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",