@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.
@@ -0,0 +1,540 @@
1
+ // Folds the ACP delta stream into full-state records.
2
+ //
3
+ // The protocol streams tool calls and thinking as deltas: a tool call is announced before
4
+ // its input is known, updates carry only changed fields, and `content` REPLACES rather
5
+ // than accumulates. Every consumer that renders activity has to fold that, and until now
6
+ // each one hand-rolled it from a README snippet. This module is that fold, published —
7
+ // the same relationship `updates.ts` has to the wire format: the library owns what the
8
+ // protocol MEANS, callers own what to draw.
9
+ //
10
+ // INVARIANT: exactly one aggregator per STREAM, for the life of that stream. Call
11
+ // `startTurn()` between turns rather than constructing a new one — `seq` must keep
12
+ // counting across turns, or a subscriber's discard threshold goes stale and silently eats
13
+ // the start of the next turn (see `snapshot`). `recordId`s for kinds the protocol doesn't
14
+ // identify are instance-local counters, so a second instance over the same stream would
15
+ // also mint different ids for the same thing. When using AgentSession, take its output —
16
+ // don't build a second one.
17
+ //
18
+ // SCOPE: ACP guarantees `toolCallId`, `planId` and `messageId` are unique "within a
19
+ // session", so ids derived from them are used verbatim. Everything else here is MINTED
20
+ // from a per-instance counter and is therefore only turn-unique — pass `idPrefix` to
21
+ // scope those, or a transcript spanning several turns will have a `think-1` per turn and
22
+ // last-wins folding will collapse them all into one.
23
+ //
24
+ // Pure by contract: no I/O, no runtime imports, erasable syntax only. A test enforces it,
25
+ // so this file stays safe to compile for a browser if a consumer ever needs to fold
26
+ // locally.
27
+
28
+ import type { ActivityEvent, ToolActivity } from "./types.ts";
29
+
30
+ /** Where a record sits in its lifecycle. Persisted, so readers can filter without folding. */
31
+ export type EmitReason =
32
+ | "announced" // first seen
33
+ | "input" // a tool call first learned its rawInput
34
+ | "settled" // terminal status reached, or a thinking block ended
35
+ | "flushed" // the turn ended with the record still open
36
+ | "snapshot"; // inherently complete on arrival
37
+
38
+ /** Full state of one thing that happened, identified for last-wins folding. */
39
+ export interface AggregatedRecord {
40
+ recordId: string;
41
+ /** Per-turn logical clock. Every frame from one apply() shares a seq. */
42
+ seq: number;
43
+ reason: EmitReason;
44
+ /** Always FULL state, never a delta. */
45
+ event: ActivityEvent;
46
+ }
47
+
48
+ /**
49
+ * The incremental piece, for kinds this module ACCUMULATES rather than replaces.
50
+ *
51
+ * Only thinking qualifies today. Tool calls are already cumulative on the wire — the
52
+ * agent resends the whole `content` each time — so a full record costs no more than the
53
+ * raw event. Thinking arrives as many small chunks, where re-sending the accumulated
54
+ * block per chunk is quadratic: ~4 KB of text becomes ~800 KB over 400 chunks.
55
+ *
56
+ * Never produced for the chunk that OPENS a block: a delta is an increment on state the
57
+ * consumer already has, and on the opening chunk there is none. That chunk's `current` is
58
+ * the base record, and it is exactly as small as the delta would have been.
59
+ */
60
+ export interface ActivityDelta {
61
+ recordId: string;
62
+ seq: number;
63
+ kind: "thinking";
64
+ append: string;
65
+ }
66
+
67
+ /** What a live transport carries. Records are self-contained; deltas need a base. */
68
+ export type ActivityFrame = AggregatedRecord | ActivityDelta;
69
+
70
+ export interface ApplyResult {
71
+ /** Full state of whatever this event touched. Null only if it produced no record. */
72
+ current: AggregatedRecord | null;
73
+ /**
74
+ * Set for accumulating kinds, EXCEPT on the event that opens the record. When present,
75
+ * prefer it over `current` on the wire; when null, `current` is what has to go, or the
76
+ * consumer never gets a base to append to.
77
+ */
78
+ delta: ActivityDelta | null;
79
+ /** Checkpoints worth persisting. Usually empty. */
80
+ emitted: AggregatedRecord[];
81
+ }
82
+
83
+ /** Everything known about the turn IN FLIGHT — for replaying to a late subscriber. */
84
+ export interface ActivitySnapshot {
85
+ /**
86
+ * Whether a turn is in flight. False before the first one and between turns, when
87
+ * `records` is empty.
88
+ *
89
+ * Distinguishes "no turn running" from "a turn that has not produced anything yet" —
90
+ * both return no records, but only the second means frames are coming. It reflects what
91
+ * this aggregator has been told: a caller that knows more (a hub tracking which sessions
92
+ * are busy, say) should trust itself over this.
93
+ */
94
+ active: boolean;
95
+ /**
96
+ * Frames with `seq <= this` are already reflected here and must be discarded.
97
+ *
98
+ * Monotonic for the life of the aggregator, ACROSS turns — so a consumer can store this
99
+ * threshold once and filter forever without knowing where turns begin. That is why
100
+ * `startTurn()` exists and why constructing a fresh aggregator per turn is wrong: the
101
+ * clock would restart and a stale threshold would silently drop the next turn's opening
102
+ * frames.
103
+ */
104
+ seq: number;
105
+ /**
106
+ * Empty between turns. A settled turn's records belong to the transcript, not to a
107
+ * replay: handing them to a client that connects mid-idle would put activity into its
108
+ * log before the surrounding messages have loaded — activity with no turn around it.
109
+ */
110
+ records: AggregatedRecord[];
111
+ }
112
+
113
+ export interface ActivityAggregatorOptions {
114
+ /**
115
+ * Emit an extra checkpoint the first time a tool call learns its `rawInput`. Default
116
+ * true: agents commonly announce a call long before they know its arguments (Kimi
117
+ * sends rawInput on update 13 of 14), so without this a crash mid-call persists a
118
+ * record that names the tool but not what it was doing.
119
+ */
120
+ checkpointOnInput?: boolean;
121
+ /**
122
+ * Namespace for MINTED record ids (`think-1`, `plan`, `usage`, …), which are otherwise
123
+ * only unique within this instance's turn. Ids the protocol guarantees session-unique
124
+ * are never prefixed.
125
+ *
126
+ * Sets the prefix for the FIRST turn; `startTurn()` sets it thereafter. Required
127
+ * whenever records outlive the turn — the transcript accumulates across turns, so
128
+ * `AgentSession` passes a per-turn value. That value must be stable across process
129
+ * restarts: an in-memory turn counter restarts at 0 when a session is resumed and would
130
+ * collide with ids already on disk. Use a timestamp or a random id.
131
+ */
132
+ idPrefix?: string;
133
+ }
134
+
135
+ /** Statuses ACP defines as terminal. */
136
+ const TERMINAL_STATUS = ["completed", "failed"];
137
+
138
+ /**
139
+ * Whether a tool call actually knows its arguments yet.
140
+ *
141
+ * Agents announce a call with a PLACEHOLDER — `rawInput: {}` is common (both Kimi and the
142
+ * test fixture do it) — and fill the real arguments in later. Treating the placeholder as
143
+ * "input known" would skip the input checkpoint, so a turn that died between learning the
144
+ * command and finishing it would persist a record naming the tool but not what it ran.
145
+ */
146
+ function hasInput(rawInput: unknown): boolean {
147
+ if (rawInput === undefined || rawInput === null) return false;
148
+ if (typeof rawInput === "string") return rawInput.length > 0;
149
+ if (Array.isArray(rawInput)) return rawInput.length > 0;
150
+ if (typeof rawInput === "object") return Object.keys(rawInput).length > 0;
151
+ return true;
152
+ }
153
+
154
+ export class ActivityAggregator {
155
+ private checkpointOnInput: boolean;
156
+ private idPrefix: string;
157
+ // False until the first event or `startTurn()`. A freshly constructed aggregator has not
158
+ // seen a turn, and saying otherwise puts a spinner in front of any client that connects
159
+ // while the session is still coming up — with no `flush()` ever coming to end it.
160
+ private turnOpen = false;
161
+ private seq = 0;
162
+ private records = new Map<string, AggregatedRecord>();
163
+ private calls = new Map<string, ToolActivity>();
164
+ private settled = new Set<string>();
165
+ private inputSeen = new Set<string>();
166
+ private thinking: { recordId: string; messageId?: string; text: string } | null = null;
167
+ private counters = new Map<string, number>();
168
+ private pendingUsage: ActivityEvent | null = null;
169
+
170
+ constructor(options: ActivityAggregatorOptions = {}) {
171
+ this.checkpointOnInput = options.checkpointOnInput !== false;
172
+ this.idPrefix = options.idPrefix ? `${options.idPrefix}:` : "";
173
+ }
174
+
175
+ /** Fold one live event. */
176
+ apply(event: ActivityEvent): ApplyResult {
177
+ this.seq++;
178
+ this.turnOpen = true; // an event IS a turn in flight, `startTurn()` or not
179
+
180
+ const emitted: AggregatedRecord[] = [];
181
+
182
+ // A thinking block ends when something else happens. Emit its close BEFORE the
183
+ // record that ended it, so append order matches causal order.
184
+ const closed = this.closeThinkingFor(event);
185
+ if (closed) emitted.push(closed);
186
+
187
+ switch (event.kind) {
188
+ case "thinking":
189
+ return this.foldThinking(event, emitted);
190
+ case "tool":
191
+ return this.foldTool(event, emitted);
192
+ case "tool_update":
193
+ return this.foldToolUpdate(event, emitted);
194
+ case "usage": {
195
+ // Coalesced: many per turn, only the last is worth persisting. `current` is still
196
+ // the live record so a caller can render a context meter.
197
+ this.pendingUsage = event;
198
+ return {
199
+ current: this.put(this.minted("usage"), "snapshot", event),
200
+ delta: null,
201
+ emitted,
202
+ };
203
+ }
204
+ default: {
205
+ const record = this.put(this.recordIdFor(event), "snapshot", event);
206
+ emitted.push(record);
207
+ return { current: record, delta: null, emitted };
208
+ }
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Close everything still open. Call once at turn end, on BOTH the success and error
214
+ * paths — an unsettled call written at its real status is the record of what the turn
215
+ * was doing when it died.
216
+ */
217
+ flush(): AggregatedRecord[] {
218
+ this.seq++;
219
+ const out: AggregatedRecord[] = [];
220
+
221
+ const closed = this.closeThinking();
222
+ if (closed) out.push(closed);
223
+
224
+ for (const [id, call] of this.calls) {
225
+ if (this.settled.has(id)) continue;
226
+ this.settled.add(id);
227
+ out.push(this.put(id, "flushed", call));
228
+ }
229
+
230
+ if (this.pendingUsage) {
231
+ out.push(this.put(this.minted("usage"), "snapshot", this.pendingUsage));
232
+ this.pendingUsage = null;
233
+ }
234
+ this.turnOpen = false;
235
+ return out;
236
+ }
237
+
238
+ /**
239
+ * Full state of the turn so far. A subscriber that joins mid-turn takes this, then
240
+ * discards any frame whose `seq` is not greater than the snapshot's — otherwise a
241
+ * thinking delta already folded into the snapshot would be applied twice.
242
+ *
243
+ * The threshold stays valid indefinitely: `seq` never restarts (see `startTurn`).
244
+ *
245
+ * Records are returned only while a turn is in flight — `flush()` ends it. The folded
246
+ * state of a finished turn is still readable via `tool()`/`tools()`, which are
247
+ * inspection accessors rather than the replay contract.
248
+ */
249
+ snapshot(): ActivitySnapshot {
250
+ return {
251
+ seq: this.seq,
252
+ active: this.turnOpen,
253
+ records: this.turnOpen ? [...this.records.values()] : [],
254
+ };
255
+ }
256
+
257
+ /**
258
+ * Begin a turn: clear per-turn state and set the prefix for MINTED record ids, while
259
+ * `seq` keeps counting. Use this instead of constructing a new aggregator.
260
+ *
261
+ * Call `flush()` FIRST — those records belong to the turn that is ending. Anything left
262
+ * open is returned here rather than dropped, but it would be persisted after that
263
+ * turn's assistant message, breaking the `msg`-delimits-turn ordering readers rely on.
264
+ * A correct caller always gets an empty array back.
265
+ */
266
+ startTurn(idPrefix?: string): AggregatedRecord[] {
267
+ const leftover = this.flush();
268
+ this.clearTurn();
269
+ this.idPrefix = idPrefix ? `${idPrefix}:` : "";
270
+ this.turnOpen = true;
271
+ return leftover;
272
+ }
273
+
274
+ /** Folded state of one tool call. */
275
+ tool(toolCallId: string): ToolActivity | undefined {
276
+ return this.calls.get(toolCallId);
277
+ }
278
+
279
+ /** Every tool call seen this turn, in first-seen order. */
280
+ tools(): ToolActivity[] {
281
+ return [...this.calls.values()];
282
+ }
283
+
284
+ /**
285
+ * Full reset, including the `seq` clock — for reusing the object on an unrelated
286
+ * stream. Any threshold a subscriber is holding becomes invalid, so this is NOT the
287
+ * between-turns call: use `startTurn()` for that.
288
+ */
289
+ reset(): void {
290
+ this.clearTurn();
291
+ this.seq = 0;
292
+ this.turnOpen = false;
293
+ }
294
+
295
+ private clearTurn(): void {
296
+ this.records.clear();
297
+ this.calls.clear();
298
+ this.settled.clear();
299
+ this.inputSeen.clear();
300
+ this.counters.clear();
301
+ this.thinking = null;
302
+ this.pendingUsage = null;
303
+ }
304
+
305
+ // --- folds ---------------------------------------------------------------------
306
+
307
+ private foldThinking(
308
+ event: Extract<ActivityEvent, { kind: "thinking" }>,
309
+ emitted: AggregatedRecord[],
310
+ ): ApplyResult {
311
+ // The opening chunk sends the RECORD, not a delta. A delta is an increment on state
312
+ // the consumer already has, and here it has none: `foldFrame` correctly drops a delta
313
+ // whose base it never saw, so opening with one means the whole block streams to
314
+ // nobody — it only appears once it closes and the settled record goes out.
315
+ const opening = !this.thinking;
316
+ if (!this.thinking) {
317
+ // `messageId` identifies the block when the agent sends one — most don't, so fall
318
+ // back to a per-turn counter. This is the instance-local id the one-aggregator
319
+ // invariant exists to protect.
320
+ // `messageId` is session-unique per ACP, so it needs no prefix; the counter does.
321
+ const recordId = event.messageId
322
+ ? `think-${event.messageId}`
323
+ : this.minted(`think-${this.nextCount("think")}`);
324
+ this.thinking = { recordId, messageId: event.messageId, text: "" };
325
+ }
326
+ this.thinking.text += event.text;
327
+
328
+ const full: ActivityEvent = this.thinking.messageId
329
+ ? { kind: "thinking", text: this.thinking.text, messageId: this.thinking.messageId }
330
+ : { kind: "thinking", text: this.thinking.text };
331
+
332
+ return {
333
+ current: this.put(this.thinking.recordId, "announced", full),
334
+ delta: opening
335
+ ? null
336
+ : {
337
+ recordId: this.thinking.recordId,
338
+ seq: this.seq,
339
+ kind: "thinking",
340
+ append: event.text,
341
+ },
342
+ emitted,
343
+ };
344
+ }
345
+
346
+ private foldTool(
347
+ event: Extract<ActivityEvent, { kind: "tool" }>,
348
+ emitted: AggregatedRecord[],
349
+ ): ApplyResult {
350
+ const call: ToolActivity = { ...event };
351
+ this.calls.set(call.toolCallId, call);
352
+ if (hasInput(call.rawInput)) this.inputSeen.add(call.toolCallId);
353
+
354
+ const terminal = TERMINAL_STATUS.indexOf(call.status) >= 0;
355
+ if (terminal) this.settled.add(call.toolCallId);
356
+
357
+ const record = this.put(call.toolCallId, terminal ? "settled" : "announced", call);
358
+ emitted.push(record);
359
+ return { current: record, delta: null, emitted };
360
+ }
361
+
362
+ private foldToolUpdate(
363
+ event: Extract<ActivityEvent, { kind: "tool_update" }>,
364
+ emitted: AggregatedRecord[],
365
+ ): ApplyResult {
366
+ const id = event.toolCallId;
367
+ const previous = this.calls.get(id);
368
+
369
+ // Spreading is the whole merge: `updates.ts` omits absent keys, so only the fields
370
+ // the agent actually changed are present. `content`/`locations` replace wholesale,
371
+ // which a spread also gets right.
372
+ const merged: ToolActivity = previous
373
+ ? { ...previous, ...event, kind: "tool" }
374
+ : {
375
+ ...event,
376
+ kind: "tool",
377
+ toolKind: event.toolKind ?? "other",
378
+ status: event.status ?? "in_progress",
379
+ };
380
+ this.calls.set(id, merged);
381
+
382
+ const terminal = TERMINAL_STATUS.indexOf(merged.status) >= 0;
383
+ let reason: EmitReason | null = null;
384
+
385
+ if (terminal && !this.settled.has(id)) {
386
+ this.settled.add(id);
387
+ this.inputSeen.add(id); // the settled record is a superset — no input checkpoint too
388
+ reason = "settled";
389
+ } else if (!previous) {
390
+ reason = "announced"; // an update for a call we never saw announced
391
+ } else if (this.checkpointOnInput && !this.inputSeen.has(id) && hasInput(merged.rawInput)) {
392
+ this.inputSeen.add(id);
393
+ reason = "input";
394
+ }
395
+
396
+ const record = this.put(id, reason ?? this.reasonOf(id, "announced"), merged);
397
+ if (reason) emitted.push(record);
398
+ return { current: record, delta: null, emitted };
399
+ }
400
+
401
+ // --- thinking boundary -----------------------------------------------------------
402
+
403
+ /**
404
+ * THE ONE INVENTED RULE. ACP has no block-end event, so a block ends when the next
405
+ * event isn't thinking, or when `messageId` changes ("a change in messageId indicates
406
+ * a new message has started"). `messageId` is optional and commonly absent, so the
407
+ * heuristic is the usual path. Everything else in this module is protocol-derived; if
408
+ * this rule ever changes, the transcript format version changes with it.
409
+ */
410
+ private closeThinkingFor(event: ActivityEvent): AggregatedRecord | null {
411
+ if (!this.thinking) return null;
412
+ if (event.kind === "thinking") {
413
+ const sameBlock = (event.messageId ?? null) === (this.thinking.messageId ?? null);
414
+ if (sameBlock) return null;
415
+ }
416
+ return this.closeThinking();
417
+ }
418
+
419
+ private closeThinking(): AggregatedRecord | null {
420
+ const block = this.thinking;
421
+ if (!block) return null;
422
+ this.thinking = null;
423
+ const event: ActivityEvent = block.messageId
424
+ ? { kind: "thinking", text: block.text, messageId: block.messageId }
425
+ : { kind: "thinking", text: block.text };
426
+ return this.put(block.recordId, "settled", event);
427
+ }
428
+
429
+ // --- identity --------------------------------------------------------------------
430
+
431
+ /**
432
+ * Ids the protocol guarantees session-unique (`planId`, `messageId`) pass through
433
+ * verbatim; ids we mint are scoped by `idPrefix`.
434
+ */
435
+ private recordIdFor(event: ActivityEvent): string {
436
+ switch (event.kind) {
437
+ case "plan_update":
438
+ case "plan_removed":
439
+ return `plan-${event.planId}`;
440
+ case "user_message":
441
+ return event.messageId
442
+ ? `msg-${event.messageId}`
443
+ : this.minted(`msg-${this.nextCount("msg")}`);
444
+ case "plan":
445
+ case "mode":
446
+ case "commands":
447
+ case "config":
448
+ case "session_info":
449
+ return this.minted(event.kind);
450
+ default:
451
+ return this.minted(`${event.kind}-${this.nextCount(event.kind)}`);
452
+ }
453
+ }
454
+
455
+ /** Namespace an id we invented. Protocol-given ids never go through here. */
456
+ private minted(id: string): string {
457
+ return `${this.idPrefix}${id}`;
458
+ }
459
+
460
+ private nextCount(key: string): number {
461
+ const next = (this.counters.get(key) ?? 0) + 1;
462
+ this.counters.set(key, next);
463
+ return next;
464
+ }
465
+
466
+ private reasonOf(recordId: string, fallback: EmitReason): EmitReason {
467
+ return this.records.get(recordId)?.reason ?? fallback;
468
+ }
469
+
470
+ private put(recordId: string, reason: EmitReason, event: ActivityEvent): AggregatedRecord {
471
+ const record: AggregatedRecord = { recordId, seq: this.seq, reason, event };
472
+ this.records.set(recordId, record);
473
+ return record;
474
+ }
475
+ }
476
+
477
+ // --- consumer-side folds -----------------------------------------------------------
478
+
479
+ /** True for the incremental wire shape. */
480
+ export function isActivityDelta(frame: ActivityFrame): frame is ActivityDelta {
481
+ return "append" in frame;
482
+ }
483
+
484
+ /**
485
+ * The PERSISTED fold — what a reader does with transcript lines. Genuinely one
486
+ * operation: transcript lines are always full records, never deltas.
487
+ *
488
+ * This is NOT `apply()`. Feeding records back through `apply()` would, for one, merge two
489
+ * separately-settled thinking blocks into a single block.
490
+ */
491
+ export function foldRecords(
492
+ records: Iterable<AggregatedRecord>,
493
+ into?: Map<string, AggregatedRecord>,
494
+ ): Map<string, AggregatedRecord> {
495
+ const map = into ?? new Map<string, AggregatedRecord>();
496
+ for (const record of records) map.set(record.recordId, record);
497
+ return map;
498
+ }
499
+
500
+ /**
501
+ * The LIVE fold — handles both wire shapes, so a consumer writes neither.
502
+ *
503
+ * A delta for a `recordId` with no base is dropped: it means the subscriber joined
504
+ * mid-block without taking a snapshot first (see `ActivityAggregator.snapshot`).
505
+ */
506
+ export function foldFrame(
507
+ map: Map<string, AggregatedRecord>,
508
+ frame: ActivityFrame,
509
+ ): Map<string, AggregatedRecord> {
510
+ if (!isActivityDelta(frame)) {
511
+ map.set(frame.recordId, frame);
512
+ return map;
513
+ }
514
+ const base = map.get(frame.recordId);
515
+ if (!base || base.event.kind !== "thinking") return map;
516
+ map.set(frame.recordId, {
517
+ ...base,
518
+ seq: frame.seq,
519
+ event: { ...base.event, text: base.event.text + frame.append },
520
+ });
521
+ return map;
522
+ }
523
+
524
+ /**
525
+ * What a live transport should send for one `apply()`, in order.
526
+ *
527
+ * `delta ?? current` alone is not enough: when a thinking block closes because a tool
528
+ * call arrived, the close is in `emitted` while `current` is the tool — a subscriber
529
+ * would never learn the block ended. Records already in `emitted` are not repeated.
530
+ *
531
+ * Never sends a record and a delta for the same `recordId` in one call: `foldFrame` has
532
+ * no seq guard, so the consumer would apply the same text twice. The opening chunk of a
533
+ * thinking block is a record (`delta` is null there); every chunk after it is a delta.
534
+ */
535
+ export function wireFrames(result: ApplyResult): ActivityFrame[] {
536
+ const frames: ActivityFrame[] = [...result.emitted];
537
+ const live: ActivityFrame | null = result.delta ?? result.current;
538
+ if (live && !frames.some((f) => f.recordId === live.recordId)) frames.push(live);
539
+ return frames;
540
+ }
package/src/adapters.ts CHANGED
@@ -22,7 +22,7 @@ export interface Adapter {
22
22
  */
23
23
  export const ADAPTERS = {
24
24
  kimi: { command: ["kimi", "acp"], ptyCommand: ["kimi"], displayName: "Kimi" },
25
- claude: { command: ["claude-agent-acp"], ptyCommand: ["claude"], displayName: "Claude" },
25
+ claude: { command: ["claude-code-acp"], ptyCommand: ["claude"], displayName: "Claude" },
26
26
  codex: { command: ["codex-acp"], ptyCommand: ["codex"], displayName: "Codex" },
27
27
  gemini: { command: ["gemini", "--acp", "--stdio"], ptyCommand: ["gemini"], displayName: "Gemini" },
28
28
  copilot: { command: ["copilot", "--acp", "--stdio"], ptyCommand: ["copilot"], displayName: "Copilot" },