@qlairoslabs/acp-client 0.3.0 → 0.3.2

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
@@ -97,12 +97,23 @@ await agent.prompt("Find and fix the failing test.", {
97
97
  onChunk: (text) => process.stdout.write(text), // response text as it streams
98
98
  onActivity: (event) => render(event), // thinking / tool calls / plan / …
99
99
  onUpdate: (raw) => log(raw), // every raw session/update, unmapped
100
- onPermissionRequest: (req) => ({ outcome: "selected", optionId: req.options[0].optionId }),
100
+ onPermissionRequest: (req) => { // blocking — the agent waits
101
+ const allow = req.options.find((o) => o.kind === "allow_once");
102
+ return allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" };
103
+ },
101
104
  });
102
105
  ```
103
106
 
107
+ Always pick a permission option by **`kind`**, never by position or name. Option ids are
108
+ the agent's own strings, the order is the agent's choice — Claude lists its reject option
109
+ first — and `name` is prose meant for a human. The four kinds are `allow_once`,
110
+ `allow_always`, `reject_once`, `reject_always`; treat the `_always` pair as policy, since
111
+ they persist into the agent's settings and outlive the session.
112
+
104
113
  If you omit `onPermissionRequest`, the client falls back to the controller's
105
- `defaultPermission` (`"approve"` / `"cancel"`).
114
+ `defaultPermission` (`"approve"` / `"cancel"`). `"approve"` selects `allow_once`, or
115
+ `allow_always` if that is the only grant offered, and cancels if it finds neither — it
116
+ never guesses.
106
117
 
107
118
  Every session update except the response text reaches `onActivity`, discriminated by
108
119
  `kind`: `thinking`, `user_message`, `tool`, `tool_update`, `plan`, `plan_update`,
@@ -145,9 +156,10 @@ input resend the whole value each time.
145
156
  ### Sending activity over a wire
146
157
 
147
158
  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.
159
+ `foldFrame`. Thinking crosses as a full record on the chunk that OPENS a block and as an
160
+ incremental `delta` for every chunk after it (re-sending the accumulated block per chunk is
161
+ quadratic — ~4 KB of text becomes ~800 KB over 400 chunks); everything else crosses as a
162
+ full record.
151
163
 
152
164
  ```ts
153
165
  // hub
@@ -162,9 +174,16 @@ let records = new Map<string, AggregatedRecord>();
162
174
  socket.onmessage = (e) => { records = foldFrame(records, JSON.parse(e.data)); };
163
175
  ```
164
176
 
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.
177
+ Send `wireFrames(result)`, not `delta ?? current`, and don't reach past it into `result`:
178
+
179
+ - When a thinking block ends because a tool call started, that close rides in `emitted`
180
+ while `current` is the tool — a client sending only the latter never learns the block
181
+ finished and renders a bubble that never stops.
182
+ - `foldFrame` drops a delta whose base it has never seen (guessing at one is how you get
183
+ text stitched onto the wrong block). `wireFrames` sends the base first, so that never
184
+ happens on a subscriber who has been listening from the start.
185
+ - It never sends a record and a delta for the same `recordId` in one call. `foldFrame` has
186
+ no seq guard, so a consumer would append the same text twice.
168
187
 
169
188
  The `/activity` subpath has **no runtime imports**, so it is safe to pull into a browser
170
189
  bundle. Type-only imports work anywhere today; importing the *functions* needs a bundler
@@ -180,9 +199,10 @@ records = foldRecords(snap.records);
180
199
  // then drop any streamed frame with frame.seq <= snap.seq — already reflected above
181
200
  ```
182
201
 
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.
202
+ `seq` never restarts, so that threshold stays valid across turns. Before the first turn and
203
+ between turns `activitySnapshot()` reports `active: false` with no records: a settled turn
204
+ belongs to the transcript, not to a replay. `active` only knows what the aggregator has
205
+ been told — a hub that separately tracks which sessions are busy should trust itself.
186
206
 
187
207
  ### Debugging: the raw protocol
188
208
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
package/src/activity.ts CHANGED
@@ -52,6 +52,10 @@ export interface AggregatedRecord {
52
52
  * agent resends the whole `content` each time — so a full record costs no more than the
53
53
  * raw event. Thinking arrives as many small chunks, where re-sending the accumulated
54
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.
55
59
  */
56
60
  export interface ActivityDelta {
57
61
  recordId: string;
@@ -66,7 +70,11 @@ export type ActivityFrame = AggregatedRecord | ActivityDelta;
66
70
  export interface ApplyResult {
67
71
  /** Full state of whatever this event touched. Null only if it produced no record. */
68
72
  current: AggregatedRecord | null;
69
- /** Set for accumulating kinds. When present, prefer it over `current` on the wire. */
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
+ */
70
78
  delta: ActivityDelta | null;
71
79
  /** Checkpoints worth persisting. Usually empty. */
72
80
  emitted: AggregatedRecord[];
@@ -75,10 +83,13 @@ export interface ApplyResult {
75
83
  /** Everything known about the turn IN FLIGHT — for replaying to a late subscriber. */
76
84
  export interface ActivitySnapshot {
77
85
  /**
78
- * Whether a turn is in flight. False between turns, when `records` is empty.
86
+ * Whether a turn is in flight. False before the first one and between turns, when
87
+ * `records` is empty.
79
88
  *
80
89
  * Distinguishes "no turn running" from "a turn that has not produced anything yet" —
81
- * both return no records, but only the second means frames are coming.
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.
82
93
  */
83
94
  active: boolean;
84
95
  /**
@@ -143,7 +154,10 @@ function hasInput(rawInput: unknown): boolean {
143
154
  export class ActivityAggregator {
144
155
  private checkpointOnInput: boolean;
145
156
  private idPrefix: string;
146
- private turnOpen = true;
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;
147
161
  private seq = 0;
148
162
  private records = new Map<string, AggregatedRecord>();
149
163
  private calls = new Map<string, ToolActivity>();
@@ -161,6 +175,8 @@ export class ActivityAggregator {
161
175
  /** Fold one live event. */
162
176
  apply(event: ActivityEvent): ApplyResult {
163
177
  this.seq++;
178
+ this.turnOpen = true; // an event IS a turn in flight, `startTurn()` or not
179
+
164
180
  const emitted: AggregatedRecord[] = [];
165
181
 
166
182
  // A thinking block ends when something else happens. Emit its close BEFORE the
@@ -273,7 +289,7 @@ export class ActivityAggregator {
273
289
  reset(): void {
274
290
  this.clearTurn();
275
291
  this.seq = 0;
276
- this.turnOpen = true;
292
+ this.turnOpen = false;
277
293
  }
278
294
 
279
295
  private clearTurn(): void {
@@ -292,6 +308,11 @@ export class ActivityAggregator {
292
308
  event: Extract<ActivityEvent, { kind: "thinking" }>,
293
309
  emitted: AggregatedRecord[],
294
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;
295
316
  if (!this.thinking) {
296
317
  // `messageId` identifies the block when the agent sends one — most don't, so fall
297
318
  // back to a per-turn counter. This is the instance-local id the one-aggregator
@@ -310,12 +331,14 @@ export class ActivityAggregator {
310
331
 
311
332
  return {
312
333
  current: this.put(this.thinking.recordId, "announced", full),
313
- delta: {
314
- recordId: this.thinking.recordId,
315
- seq: this.seq,
316
- kind: "thinking",
317
- append: event.text,
318
- },
334
+ delta: opening
335
+ ? null
336
+ : {
337
+ recordId: this.thinking.recordId,
338
+ seq: this.seq,
339
+ kind: "thinking",
340
+ append: event.text,
341
+ },
319
342
  emitted,
320
343
  };
321
344
  }
@@ -324,6 +347,15 @@ export class ActivityAggregator {
324
347
  event: Extract<ActivityEvent, { kind: "tool" }>,
325
348
  emitted: AggregatedRecord[],
326
349
  ): ApplyResult {
350
+ // A RE-announcement is an update in disguise. Claude announces every call twice — once
351
+ // with `rawInput: {}`, then again with the real arguments, both as `tool_call` rather
352
+ // than `tool_call_update`. Taking the second as a fresh announce would replace the
353
+ // stored call (losing whatever the re-announce omits) and spend a second `announced`
354
+ // line where every other agent spends `input`.
355
+ if (this.calls.has(event.toolCallId)) {
356
+ return this.foldToolUpdate({ ...event, kind: "tool_update" }, emitted);
357
+ }
358
+
327
359
  const call: ToolActivity = { ...event };
328
360
  this.calls.set(call.toolCallId, call);
329
361
  if (hasInput(call.rawInput)) this.inputSeen.add(call.toolCallId);
@@ -504,6 +536,10 @@ export function foldFrame(
504
536
  * `delta ?? current` alone is not enough: when a thinking block closes because a tool
505
537
  * call arrived, the close is in `emitted` while `current` is the tool — a subscriber
506
538
  * would never learn the block ended. Records already in `emitted` are not repeated.
539
+ *
540
+ * Never sends a record and a delta for the same `recordId` in one call: `foldFrame` has
541
+ * no seq guard, so the consumer would apply the same text twice. The opening chunk of a
542
+ * thinking block is a record (`delta` is null there); every chunk after it is a delta.
507
543
  */
508
544
  export function wireFrames(result: ApplyResult): ActivityFrame[] {
509
545
  const frames: ActivityFrame[] = [...result.emitted];
package/src/adapters.ts CHANGED
@@ -19,11 +19,20 @@ export interface Adapter {
19
19
  * Convenient presets. NOT exhaustive and NOT authoritative — a caller can always pass
20
20
  * a raw `{ command: [...] }`. These only encode how to start the binary; they say
21
21
  * nothing about what the agent supports.
22
+ *
23
+ * A wrong command here surfaces as a connect timeout, which reads like a library fault, so
24
+ * the marked entries are the ones actually spawned and verified. `claude` was
25
+ * `claude-agent-acp` until it wasn't: the ACP bridge for Claude Code ships as
26
+ * `@zed-industries/claude-code-acp`, and the `claude` CLI itself speaks no ACP. Check
27
+ * `which <command>` before assuming the library is at fault.
22
28
  */
23
29
  export const ADAPTERS = {
24
- kimi: { command: ["kimi", "acp"], ptyCommand: ["kimi"], displayName: "Kimi" },
25
- claude: { command: ["claude-agent-acp"], ptyCommand: ["claude"], displayName: "Claude" },
30
+ kimi: { command: ["kimi", "acp"], ptyCommand: ["kimi"], displayName: "Kimi" }, // verified
31
+ // verified — @zed-industries/claude-code-acp. NOT `claude-agent-acp`, and not the `claude` CLI.
32
+ claude: { command: ["claude-code-acp"], ptyCommand: ["claude"], displayName: "Claude" },
33
+ // verified — @agentclientprotocol/codex-acp. The `codex` CLI has no `acp` subcommand.
26
34
  codex: { command: ["codex-acp"], ptyCommand: ["codex"], displayName: "Codex" },
35
+ // Below: from each project's docs, not spawned here. Correct at time of writing, unverified.
27
36
  gemini: { command: ["gemini", "--acp", "--stdio"], ptyCommand: ["gemini"], displayName: "Gemini" },
28
37
  copilot: { command: ["copilot", "--acp", "--stdio"], ptyCommand: ["copilot"], displayName: "Copilot" },
29
38
  opencode: { command: ["opencode", "acp"], ptyCommand: ["opencode"], displayName: "OpenCode" },
@@ -453,6 +453,15 @@ export class AgentSession implements AgentClient, Bridgeable {
453
453
  get configOptions(): ConfigOptions {
454
454
  return this.controller.configOptions;
455
455
  }
456
+ /**
457
+ * Set one of the agent's own session options — the `configOptions` it advertised on
458
+ * connect. This is where per-agent knobs live that are NOT launch flags and NOT
459
+ * environment: Codex exposes `reasoning_effort` (low…ultra), `model`, and `mode` this
460
+ * way, so it is the only route to them once the process is running.
461
+ */
462
+ setConfig(configId: string, value: unknown): Promise<void> {
463
+ return this.controller.setConfig(configId, value);
464
+ }
456
465
  get agentCommands(): AgentCommand[] {
457
466
  return this.controller.agentCommands;
458
467
  }
package/src/client.ts CHANGED
@@ -673,11 +673,20 @@ export class AcpClient implements AgentClient {
673
673
  }
674
674
 
675
675
  private defaultOutcome(request: PermissionRequest): PermissionOutcome {
676
- if ((this.config.defaultPermission ?? "cancel") === "approve") {
677
- const first = request.options[0];
678
- if (first) return { outcome: "selected", optionId: first.optionId };
679
- }
680
- return { outcome: "cancelled" };
676
+ if ((this.config.defaultPermission ?? "cancel") !== "approve") return { outcome: "cancelled" };
677
+
678
+ // By KIND, never by position. Agents order their options differently and Claude leads
679
+ // with reject, so taking `options[0]` auto-REFUSED every call it meant to approve.
680
+ //
681
+ // `allow_once` first is deliberate: `allow_always` writes a rule into the agent's own
682
+ // settings that outlives this session, and an auto-approver must not quietly make
683
+ // policy on the user's behalf. It is the fallback, never the preference.
684
+ const allow =
685
+ request.options.find((o) => o.kind === "allow_once") ??
686
+ request.options.find((o) => o.kind === "allow_always");
687
+
688
+ // Nothing recognizable to approve: refuse rather than guess. Guessing is the bug above.
689
+ return allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" };
681
690
  }
682
691
  }
683
692
 
package/src/index.ts CHANGED
@@ -129,6 +129,7 @@ export type {
129
129
  PlanEntry,
130
130
  PermissionRequest,
131
131
  PermissionOutcome,
132
+ PermissionOptionKind,
132
133
  Usage,
133
134
  Attachment,
134
135
  SessionListEntry,
package/src/types.ts CHANGED
@@ -168,11 +168,27 @@ export type PermissionOutcome =
168
168
  | { outcome: "selected"; optionId: string }
169
169
  | { outcome: "cancelled" };
170
170
 
171
+ /**
172
+ * What an option DOES, independent of what it is called or where it sits in the list.
173
+ * The only safe thing to branch on: `name` is prose and the order is the agent's whim
174
+ * (Claude puts its reject option first). `allow_always` and `reject_always` persist into
175
+ * the agent's own settings and outlive the session — treat them as policy, not answers.
176
+ *
177
+ * The open arm keeps a kind we don't know yet from failing to typecheck; branch with a
178
+ * fallback rather than assuming the four.
179
+ */
180
+ export type PermissionOptionKind =
181
+ | "allow_once"
182
+ | "allow_always"
183
+ | "reject_once"
184
+ | "reject_always"
185
+ | (string & {});
186
+
171
187
  /** A permission request surfaced to the caller. The agent BLOCKS until this resolves. */
172
188
  export interface PermissionRequest {
173
189
  toolCallId: string;
174
190
  title?: string;
175
- options: Array<{ optionId: string; name: string; kind: string }>;
191
+ options: Array<{ optionId: string; name: string; kind: PermissionOptionKind }>;
176
192
  /** The raw SDK request, for callers that need fields we haven't surfaced. */
177
193
  raw: unknown;
178
194
  }