@qlairoslabs/acp-client 0.4.0 → 0.4.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,500 @@
1
+ # Consumer guide
2
+
3
+ This guide is for applications that embed `@qlairoslabs/acp-client`, especially
4
+ orchestrators that keep several agents alive at once. The library supplies the ACP
5
+ connection and stable-session primitives; the consumer owns the collection of live
6
+ `AgentSession` objects and decides whether operations appear as slash commands, buttons,
7
+ HTTP endpoints, jobs, or something else.
8
+
9
+ The package currently requires Bun 1.3.5 or newer.
10
+
11
+ ## The three operation layers
12
+
13
+ Keep these layers separate in consumer code:
14
+
15
+ | Layer | Owner | Library surface | Typical operations |
16
+ |---|---|---|---|
17
+ | Logical session management | Consumer | `SessionManager`, `SessionStore`, `AgentSession.create()` | Create, catalog, list, reopen, stop, and select `AgentSession` objects |
18
+ | Stable session control | `AgentSession` | The live `AgentSession` instance | Prompt, observe state, interrupt, handoff, bridge, stop |
19
+ | Active harness session | ACP provider | `internalSessionCommands`, `executeInternalSessionCommand()`, `session.connection` | Run advertised commands and use provider capabilities/configuration |
20
+
21
+ An `agentSessionId` is the stable consumer-facing identity. An `internalSessionId` belongs
22
+ to the currently active provider thread and may change during a handoff or mode change.
23
+
24
+ ```text
25
+ consumer registry
26
+ └── AgentSession agent-7 stable object and agentSessionId
27
+ └── internal session abc replaceable provider thread
28
+ ```
29
+
30
+ ## Install and import
31
+
32
+ ```bash
33
+ bun add @qlairoslabs/acp-client
34
+ ```
35
+
36
+ Core session APIs come from the package root:
37
+
38
+ ```ts
39
+ import {
40
+ AgentSession,
41
+ ADAPTERS,
42
+ FileSessionStore,
43
+ SessionManager,
44
+ type Adapter,
45
+ type AgentSessionNotification,
46
+ type PromptHandlers,
47
+ } from "@qlairoslabs/acp-client";
48
+ ```
49
+
50
+ Reusable interactive helpers are intentionally in a separate entry point:
51
+
52
+ ```ts
53
+ import {
54
+ createAgentSessionCommands,
55
+ dispatchReplInput,
56
+ parseReplInput,
57
+ runAgentSessionRepl,
58
+ } from "@qlairoslabs/acp-client/repl";
59
+ ```
60
+
61
+ ## Resolve adapters in the consumer
62
+
63
+ An adapter only describes how to launch a harness. Presets are provided, but consumers
64
+ can supply any `Adapter` object.
65
+
66
+ ```ts
67
+ const adapters: Record<string, Adapter> = {
68
+ codex: ADAPTERS.codex,
69
+ claude: ADAPTERS.claude,
70
+ internal: {
71
+ command: ["internal-agent", "--acp"],
72
+ ptyCommand: ["internal-agent"],
73
+ displayName: "Internal agent",
74
+ },
75
+ };
76
+
77
+ function resolveAdapter(adapterId: string): Adapter {
78
+ const adapter = adapters[adapterId];
79
+ if (!adapter) throw new Error(`Unknown adapter: ${adapterId}`);
80
+ return adapter;
81
+ }
82
+ ```
83
+
84
+ The catalog stores `adapterId`, not executable configuration. This resolver therefore
85
+ belongs to the consumer.
86
+
87
+ ## Create the catalog and live-session registry
88
+
89
+ `SessionManager` is a metadata catalog, not a registry of running objects and not a
90
+ transcript store. Use `FileSessionStore` locally or implement `SessionStore` over the
91
+ consumer's database.
92
+
93
+ ```ts
94
+ const sessionManager = new SessionManager(
95
+ new FileSessionStore("/absolute/path/to/session-catalog"),
96
+ );
97
+
98
+ const liveSessions = new Map<string, AgentSession>();
99
+ ```
100
+
101
+ The manager exposes:
102
+
103
+ ```ts
104
+ await sessionManager.record(input);
105
+ await sessionManager.get(agentSessionId);
106
+ await sessionManager.list();
107
+ await sessionManager.delete(agentSessionId);
108
+ await sessionManager.listMerged(providerSessions, adapterId);
109
+ ```
110
+
111
+ Normally the consumer does not call `record()` directly. An `AgentSession` given
112
+ `sessions: sessionManager` records itself on startup and updates the record when its
113
+ provider identity, mode, title, or transcript location changes.
114
+
115
+ ## Create a logical session
116
+
117
+ ```ts
118
+ async function createSession(adapterId: string): Promise<AgentSession> {
119
+ const session = await AgentSession.create({
120
+ adapter: resolveAdapter(adapterId),
121
+ adapterId,
122
+ providerSession: { kind: "new" },
123
+ sessions: sessionManager,
124
+ transcriptDir: "/absolute/path/to/transcripts",
125
+ cwd: process.cwd(),
126
+ defaultPermission: "cancel",
127
+ });
128
+
129
+ liveSessions.set(session.agentSessionId, session);
130
+ return session;
131
+ }
132
+ ```
133
+
134
+ If `agentSessionId` is omitted, the library creates one. Always return or store
135
+ `session.agentSessionId`; do not use `internalSessionId` as the orchestrator's key.
136
+
137
+ `providerSession` is explicit:
138
+
139
+ ```ts
140
+ { kind: "new" }
141
+ { kind: "load", internalSessionId, onFailure?: "error" | "new" }
142
+ ```
143
+
144
+ Loading fails closed by default. Use `onFailure: "new"` only when replacing a missing
145
+ provider thread is deliberate policy.
146
+
147
+ ## Reopen a cataloged session
148
+
149
+ `SessionManager.get()` returns routing metadata. It does not start a process. Reopening is
150
+ consumer composition because only the consumer knows how to resolve adapters and where to
151
+ keep live objects.
152
+
153
+ ```ts
154
+ async function reopenSession(agentSessionId: string): Promise<AgentSession> {
155
+ const existing = liveSessions.get(agentSessionId);
156
+ if (existing) return existing;
157
+
158
+ const record = await sessionManager.get(agentSessionId);
159
+ if (!record) throw new Error(`Unknown AgentSession: ${agentSessionId}`);
160
+
161
+ const session = await AgentSession.create({
162
+ adapter: resolveAdapter(record.adapter),
163
+ adapterId: record.adapter,
164
+ agentSessionId: record.agentSessionId,
165
+ providerSession: record.internalSessionId
166
+ ? {
167
+ kind: "load",
168
+ internalSessionId: record.internalSessionId,
169
+ onFailure: "error",
170
+ }
171
+ : { kind: "new" },
172
+ mode: record.mode,
173
+ cwd: record.cwd,
174
+ title: record.title,
175
+ sessions: sessionManager,
176
+ ...(record.transcriptPath
177
+ ? { transcriptPath: record.transcriptPath }
178
+ : {}),
179
+ });
180
+
181
+ liveSessions.set(session.agentSessionId, session);
182
+ return session;
183
+ }
184
+ ```
185
+
186
+ Transcript existence never selects a provider thread. `transcriptPath` and
187
+ `transcriptDir` only select history storage.
188
+
189
+ ## List and select sessions
190
+
191
+ Use the manager to list the consumer's catalog without starting a harness:
192
+
193
+ ```ts
194
+ const catalog = await sessionManager.list();
195
+ ```
196
+
197
+ Once a session is connected, `session.listSessions()` merges that catalog with the active
198
+ adapter's ACP `session/list` response when the harness supports it:
199
+
200
+ ```ts
201
+ const rows = await session.listSessions();
202
+
203
+ for (const row of rows) {
204
+ console.log(
205
+ row.agentSessionId,
206
+ row.internalSessionId,
207
+ row.adapter,
208
+ row.source, // "catalog" | "agent" | "both"
209
+ );
210
+ }
211
+ ```
212
+
213
+ Selecting which `AgentSession` receives the next operation is consumer state. The library
214
+ does not maintain a global “current AgentSession.”
215
+
216
+ ## Prompt and stream a turn
217
+
218
+ ```ts
219
+ const result = await session.prompt("Inspect the failing tests.", {
220
+ onChunk: (text) => process.stdout.write(text),
221
+ onActivity: (event) => renderRawActivity(event),
222
+ onRecord: (folded) => publishFoldedActivity(folded),
223
+ onUpdate: (rawUpdate) => debugProtocolUpdate(rawUpdate),
224
+ onPermissionRequest: (request) => {
225
+ const allow = request.options.find((option) => option.kind === "allow_once");
226
+ return allow
227
+ ? { outcome: "selected", optionId: allow.optionId }
228
+ : { outcome: "cancelled" };
229
+ },
230
+ });
231
+
232
+ console.log(result.status, result.stopReason, result.text, result.usage);
233
+ ```
234
+
235
+ Prompts and handoffs on one `AgentSession` are serialized. The consumer does not need a
236
+ separate mutex for them.
237
+
238
+ ## Observe state without polling
239
+
240
+ Read the current snapshot first, then subscribe to future notifications:
241
+
242
+ ```ts
243
+ function attachSession(session: AgentSession): () => void {
244
+ publishState(session.state);
245
+
246
+ return session.subscribe((notification: AgentSessionNotification) => {
247
+ publishNotification(notification);
248
+
249
+ switch (notification.event.kind) {
250
+ case "state_changed":
251
+ publishState(notification.event.state);
252
+ break;
253
+ case "turn_completed":
254
+ case "turn_failed":
255
+ case "handoff_completed":
256
+ case "handoff_failed":
257
+ scheduleDependentWork(session.agentSessionId);
258
+ break;
259
+ }
260
+ });
261
+ }
262
+ ```
263
+
264
+ Useful snapshots are:
265
+
266
+ ```ts
267
+ session.state;
268
+ session.isBusy;
269
+ session.queuedOperationCount;
270
+ ```
271
+
272
+ Notifications carry a monotonically increasing `seq`, timestamp, and stable
273
+ `agentSessionId`. A listener exception is isolated from the operation.
274
+
275
+ ## Interrupt and stop
276
+
277
+ ```ts
278
+ session.interrupt(); // cancel the active operation
279
+ session.interrupt({ clearQueue: true }); // also discard queued operations
280
+
281
+ await session.stop();
282
+ liveSessions.delete(session.agentSessionId);
283
+ ```
284
+
285
+ `stop()` is terminal for that object. Reopen from the catalog to obtain a new live object
286
+ with the same logical identity.
287
+
288
+ ## Handoff within the current harness
289
+
290
+ ```ts
291
+ const result = await session.handoff();
292
+ ```
293
+
294
+ Without options, the old provider thread generates a portable summary. The session then
295
+ creates a new provider thread and introduces that summary through a user prompt.
296
+
297
+ The consumer may provide an already-generated summary:
298
+
299
+ ```ts
300
+ const result = await session.handoff({
301
+ summary: "Objective, decisions, current state, and next steps...",
302
+ });
303
+ ```
304
+
305
+ The following remains true:
306
+
307
+ ```ts
308
+ result.agentSessionId === session.agentSessionId;
309
+ result.toInternalSessionId === session.internalSessionId;
310
+ ```
311
+
312
+ Current limitations are important:
313
+
314
+ - Handoff only creates a new thread on the current adapter/harness.
315
+ - The summary-generation prompt is currently fixed unless generation is bypassed by
316
+ supplying `summary`.
317
+ - The new-thread introduction prompt is currently fixed.
318
+ - The introduction is an ordinary user prompt, not a system prompt.
319
+ - ACP `session/new` has no portable system-prompt field.
320
+ - Handoff requires normal ACP mode.
321
+
322
+ Cross-adapter handoff and independently configurable summary/introduction policies should
323
+ be treated as future API work, not emulated by mutating `internalSessionId` in consumer
324
+ code.
325
+
326
+ ## Discover and execute harness commands
327
+
328
+ Commands advertised by the active ACP harness are exposed as immutable metadata:
329
+
330
+ ```ts
331
+ for (const command of session.internalSessionCommands) {
332
+ console.log(command.name, command.description, command.input?.hint);
333
+ }
334
+ ```
335
+
336
+ Changes also arrive through the session listener as
337
+ `internal_session_commands_changed`.
338
+
339
+ Execute one explicitly without including the leading slash:
340
+
341
+ ```ts
342
+ await session.executeInternalSessionCommand("usage");
343
+ await session.executeInternalSessionCommand("status", "verbose");
344
+ ```
345
+
346
+ ACP represents these commands as ordinary prompts. The named method makes consumer intent
347
+ explicit and keeps the operation in the session queue, transcript, and lifecycle events.
348
+ Advertisement is discovery, not an allow-list: a harness may accept a command before it
349
+ advertises it.
350
+
351
+ ## Reuse the AgentSession local command set
352
+
353
+ The same local handlers used by the opinionated one-session REPL are public:
354
+
355
+ ```ts
356
+ const localCommands = createAgentSessionCommands({
357
+ session,
358
+ note: (message) => showNotice(message),
359
+ });
360
+
361
+ const handled = await localCommands.onSlashCommand("state", []);
362
+ ```
363
+
364
+ The built-in set currently handles:
365
+
366
+ ```text
367
+ /help
368
+ /session
369
+ /state
370
+ /commands
371
+ /handoff [SUMMARY]
372
+ /bridge
373
+ ```
374
+
375
+ `/exit` is handled by the REPL loop rather than the command factory.
376
+
377
+ The factory currently exposes the handler, not a declarative metadata array for local
378
+ commands. A consumer can reuse the handler directly; a custom command palette must define
379
+ its own local labels/descriptions for now. Harness commands do have declarative metadata
380
+ through `session.internalSessionCommands`.
381
+
382
+ ## Run the opinionated single-session REPL
383
+
384
+ ```ts
385
+ try {
386
+ await runAgentSessionRepl(session, {
387
+ activity: true,
388
+ spinner: true,
389
+ note: (message) => process.stderr.write(`${message}\n`),
390
+ onSlashCommand: async (command, args) => {
391
+ // Consumer-local extension, tried after the built-in AgentSession commands.
392
+ if (command !== "tag") return false;
393
+ await addTag(session.agentSessionId, args.join(" "));
394
+ return true;
395
+ },
396
+ });
397
+ } finally {
398
+ await session.stop();
399
+ }
400
+ ```
401
+
402
+ Input routing is deliberately unambiguous:
403
+
404
+ ```text
405
+ ordinary text -> session.prompt(...)
406
+ /command -> local AgentSession command
407
+ //command [input] -> session.executeInternalSessionCommand(...)
408
+ ```
409
+
410
+ An unknown `/command` is rejected locally and never falls through to the harness.
411
+
412
+ ## Reuse routing in a custom UI
413
+
414
+ Consumers do not need to use readline. `parseReplInput()` and `dispatchReplInput()` are
415
+ terminal-independent:
416
+
417
+ ```ts
418
+ const local = createAgentSessionCommands({ session, note: showNotice });
419
+ const promptHandlers: PromptHandlers = {
420
+ onChunk: (text) => renderText(text),
421
+ onActivity: (event) => renderActivity(event),
422
+ };
423
+
424
+ await dispatchReplInput(parseReplInput(input), {
425
+ prompt: async (text) => {
426
+ await session.prompt(text, promptHandlers);
427
+ },
428
+ localCommand: (command, args) => local.onSlashCommand(command, args),
429
+ internalSessionCommand: async (command, value) => {
430
+ await session.executeInternalSessionCommand(command, value, promptHandlers);
431
+ },
432
+ unknownLocalCommand: (command) => {
433
+ showNotice(`Unknown local command: /${command}`);
434
+ },
435
+ missingInternalSessionCommand: () => {
436
+ showNotice("A command name is required after //");
437
+ },
438
+ });
439
+ ```
440
+
441
+ A graphical consumer may skip slash parsing entirely and bind these operations directly
442
+ to buttons, menus, RPC methods, or orchestration events.
443
+
444
+ ## Use the lower-level control plane when needed
445
+
446
+ `session.connection` exposes the live `AgentController` for operations that do not belong
447
+ to the stable session abstraction:
448
+
449
+ ```ts
450
+ session.capabilities;
451
+ session.configOptions;
452
+ await session.setConfig("model", "some-model");
453
+ await session.authenticate(methodId, { onOutput: showAuthOutput });
454
+
455
+ const controller = session.connection;
456
+ await controller.listSessions();
457
+ await controller.loadSession(internalSessionId);
458
+ ```
459
+
460
+ Use controller session-switching methods carefully: they operate directly on the provider
461
+ thread. Prefer `AgentSession` methods when a stable logical-session equivalent exists, so
462
+ the catalog, lifecycle notifications, and transcript remain coherent.
463
+
464
+ ## Transcript policy
465
+
466
+ Choose exactly one history destination:
467
+
468
+ ```ts
469
+ transcriptPath: "/absolute/path/to/conversation.jsonl"
470
+ // or
471
+ transcriptDir: "/absolute/path/to/transcripts"
472
+ ```
473
+
474
+ Omit both to disable transcript writes. This does not disable prompting, handoff, catalog
475
+ management, or lifecycle notifications.
476
+
477
+ Enable settled activity records when the consumer needs tool/thinking/plan history:
478
+
479
+ ```ts
480
+ transcriptActivity: {
481
+ checkpointOnInput: true,
482
+ rawOutput: false,
483
+ maxBytes: 64_000,
484
+ }
485
+ ```
486
+
487
+ Use `readTranscript()` for logical user/assistant messages and `readTranscriptLines()` for
488
+ the complete typed stream, including activity and handoff boundaries.
489
+
490
+ ## Recommended ownership rules
491
+
492
+ - Key orchestration state by `agentSessionId`, never `internalSessionId`.
493
+ - Keep the map of live `AgentSession` objects in the consumer.
494
+ - Treat `SessionManager` as routing metadata, not a process manager.
495
+ - Read `session.state` before subscribing to notifications.
496
+ - Use `executeInternalSessionCommand()` instead of constructing slash prompts manually.
497
+ - Keep consumer/local commands separate from harness commands in the UI.
498
+ - Resolve adapters in the consumer and fail explicitly on unknown adapter ids.
499
+ - Stop every live session during consumer shutdown.
500
+ - Do not infer provider loading from transcript filenames or contents.
package/README.md CHANGED
@@ -68,6 +68,10 @@ bun add -g @qlairoslabs/acp-client
68
68
 
69
69
  ## Usage
70
70
 
71
+ For an orchestration-oriented walkthrough covering catalog ownership, reopening logical
72
+ sessions, lifecycle listeners, handoff, harness commands, and reusable command routing,
73
+ see the [consumer guide](./CONSUMER_GUIDE.md).
74
+
71
75
  ### One-shot prompt
72
76
 
73
77
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.4.0",
3
+ "version": "0.4.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",
@@ -32,7 +32,8 @@
32
32
  "access": "public"
33
33
  },
34
34
  "files": [
35
- "src"
35
+ "src",
36
+ "CONSUMER_GUIDE.md"
36
37
  ],
37
38
  "exports": {
38
39
  ".": "./src/index.ts",
package/src/client.ts CHANGED
@@ -287,16 +287,11 @@ export class AcpClient implements AgentClient {
287
287
  let sessionId: string;
288
288
 
289
289
  if (resumeId && this.capabilities.agent.loadSession) {
290
- this.beginCommandTransition();
291
290
  try {
292
- await transport.loadSession({ sessionId: resumeId, cwd, mcpServers } as schema.LoadSessionRequest);
293
- sessionId = resumeId;
294
- this._sessionId = sessionId;
295
- this.finishCommandTransition(sessionId);
296
- resumed = true;
297
- this.log.info("session_loaded", { sessionId });
291
+ const result = await this.loadSessionInternal(transport, resumeId, { mcpServers });
292
+ sessionId = result.sessionId;
293
+ resumed = result.resumed;
298
294
  } catch (err) {
299
- this.abortCommandTransition();
300
295
  this.log.warn("session_load_failed", { sessionId: resumeId, error: String(err) });
301
296
  if (loadFailure === "error") throw err;
302
297
  sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
@@ -319,6 +314,14 @@ export class AcpClient implements AgentClient {
319
314
  if (!this.capabilities.agent.loadSession) {
320
315
  throw new Error("agent does not advertise session/load (loadSession)");
321
316
  }
317
+ return this.loadSessionInternal(transport, sessionId, options);
318
+ }
319
+
320
+ private async loadSessionInternal(
321
+ transport: AcpTransport,
322
+ sessionId: string,
323
+ options: SwitchSessionOptions = {},
324
+ ): Promise<ConnectResult> {
322
325
  this.beginCommandTransition();
323
326
  this.replay = { sessionId, onUpdate: options.onUpdate };
324
327
  let res: schema.LoadSessionResponse;
@@ -335,12 +338,13 @@ export class AcpClient implements AgentClient {
335
338
  } finally {
336
339
  this.replay = null;
337
340
  }
341
+ const configOptions = parseConfigOptions(res.configOptions);
338
342
  this._sessionId = sessionId;
343
+ this._configOptions = configOptions;
339
344
  this.finishCommandTransition(sessionId);
340
- this._configOptions = parseConfigOptions(res.configOptions);
341
345
  this.log.info("session_loaded", {
342
346
  sessionId,
343
- configOptions: [...this._configOptions.keys()],
347
+ configOptions: [...configOptions.keys()],
344
348
  });
345
349
  this.log.debug("session_load_response", { response: res });
346
350
  return { sessionId, resumed: true };