@qlairoslabs/acp-client 0.6.0 → 0.7.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.
Files changed (44) hide show
  1. package/CONSUMER_GUIDE.md +618 -291
  2. package/README.md +25 -0
  3. package/package.json +1 -1
  4. package/src/agent-session.ts +2188 -96
  5. package/src/cli/index.ts +33 -5
  6. package/src/cli/managed.ts +220 -0
  7. package/src/command-descriptors.ts +22 -0
  8. package/src/controller.ts +87 -37
  9. package/src/index.ts +229 -3
  10. package/src/metering/engine.ts +9 -1
  11. package/src/metering/record.ts +2 -1
  12. package/src/persistence/activity-projection.ts +71 -0
  13. package/src/persistence/audit-log-reader.ts +506 -0
  14. package/src/persistence/audit-runtime.ts +162 -0
  15. package/src/persistence/checkpoint.ts +304 -0
  16. package/src/persistence/config.ts +538 -0
  17. package/src/persistence/configuration-state.ts +191 -0
  18. package/src/persistence/deletion.ts +227 -0
  19. package/src/persistence/file-registry-store.ts +740 -0
  20. package/src/persistence/integrity.ts +147 -0
  21. package/src/persistence/legacy-registry-import.ts +240 -0
  22. package/src/persistence/managed-checkpoint.ts +81 -0
  23. package/src/persistence/managed-creation.ts +456 -0
  24. package/src/persistence/managed-load.ts +172 -0
  25. package/src/persistence/managed-registry.ts +57 -0
  26. package/src/persistence/migration.ts +298 -0
  27. package/src/persistence/paths.ts +172 -0
  28. package/src/persistence/projection.ts +373 -0
  29. package/src/persistence/reconfiguration.ts +453 -0
  30. package/src/persistence/records.ts +873 -0
  31. package/src/persistence/reducer.ts +498 -0
  32. package/src/persistence/registry.ts +446 -0
  33. package/src/persistence/restoration.ts +689 -0
  34. package/src/persistence/session-log-writer.ts +480 -0
  35. package/src/persistence/state-runtime.ts +176 -0
  36. package/src/persistence/transcript-reader.ts +980 -0
  37. package/src/persistence/transcript-runtime.ts +667 -0
  38. package/src/persistence/transcript-scanner.ts +385 -0
  39. package/src/persistence/truncation.ts +276 -0
  40. package/src/repl/agent-session-commands.ts +74 -1
  41. package/src/repl/commands.ts +1 -1
  42. package/src/repl/index.ts +7 -1
  43. package/src/session-manager.ts +257 -7
  44. package/src/transcript.ts +3 -3
package/CONSUMER_GUIDE.md CHANGED
@@ -1,30 +1,38 @@
1
1
  # Consumer guide
2
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.
3
+ This guide is for applications embedding `@qlairoslabs/acp-client`, especially
4
+ orchestrators that own several logical agent sessions. The library owns ACP communication,
5
+ one live session's operation queue, metering, and optional persistence. The consumer owns
6
+ its collection of live objects, adapter resolution, user interface, and application policy.
8
7
 
9
- The package currently requires Bun 1.3.5 or newer.
8
+ The package requires Bun 1.3.5 or newer.
10
9
 
11
- ## The three operation layers
10
+ ## Mental model
12
11
 
13
- Keep these layers separate in consumer code:
12
+ There are three different operation layers:
14
13
 
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 |
14
+ | Layer | Main API | Examples |
15
+ |---|---|---|
16
+ | Logical-session management | `SessionManager` | Create, list, load, restore, reconfigure, and delete logical sessions |
17
+ | One stable logical session | `AgentSession` | Prompt, interrupt, handoff, observe state, change configuration, and bridge |
18
+ | Active harness thread | ACP and `internalSessionCommands` | Harness-specific commands such as `/usage` and `/model` |
20
19
 
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.
20
+ An `agentSessionId` is the stable identity exposed to the consumer. An
21
+ `internalSessionId` identifies the current provider or harness thread. Handoff and other
22
+ thread replacements may change the latter without changing the former.
23
23
 
24
24
  ```text
25
- consumer registry
26
- └── AgentSession agent-7 stable object and agentSessionId
27
- └── internal session abc replaceable provider thread
25
+ consumer
26
+ └── SessionManager
27
+ └── AgentSession agent-7 stable logical identity
28
+ └── internal thread abc replaceable harness identity
29
+ ```
30
+
31
+ `SessionManager` persists and discovers logical sessions. It does not retain live
32
+ `AgentSession` objects. An orchestrator normally keeps those separately:
33
+
34
+ ```ts
35
+ const liveSessions = new Map<string, AgentSession>();
28
36
  ```
29
37
 
30
38
  ## Install and import
@@ -33,26 +41,26 @@ consumer registry
33
41
  bun add @qlairoslabs/acp-client
34
42
  ```
35
43
 
36
- Core session APIs come from the package root:
37
-
38
44
  ```ts
39
45
  import {
40
- AgentSession,
41
46
  ADAPTERS,
42
- FileSessionStore,
47
+ AgentSession,
48
+ AuditLogReader,
43
49
  SessionManager,
50
+ TranscriptReader,
44
51
  type Adapter,
45
52
  type AgentSessionNotification,
46
53
  type PromptHandlers,
47
54
  } from "@qlairoslabs/acp-client";
48
55
  ```
49
56
 
50
- Reusable interactive helpers are intentionally in a separate entry point:
57
+ Interactive helpers are a separate entry point:
51
58
 
52
59
  ```ts
53
60
  import {
54
61
  createAgentSessionCommands,
55
62
  dispatchReplInput,
63
+ getAgentSessionCommands,
56
64
  parseReplInput,
57
65
  runAgentSessionRepl,
58
66
  } from "@qlairoslabs/acp-client/repl";
@@ -60,11 +68,12 @@ import {
60
68
 
61
69
  ## Resolve adapters in the consumer
62
70
 
63
- An adapter only describes how to launch a harness. Presets are provided, but consumers
64
- can supply any `Adapter` object.
71
+ An adapter only tells the library how to launch a harness. Capabilities, authentication,
72
+ configuration, and harness commands are discovered after ACP initialization.
65
73
 
66
74
  ```ts
67
75
  const adapters: Record<string, Adapter> = {
76
+ opencode: ADAPTERS.opencode,
68
77
  codex: ADAPTERS.codex,
69
78
  claude: ADAPTERS.claude,
70
79
  pi: ADAPTERS.pi,
@@ -82,58 +91,57 @@ function resolveAdapter(adapterId: string): Adapter {
82
91
  }
83
92
  ```
84
93
 
85
- The catalog stores `adapterId`, not executable configuration. This resolver therefore
86
- belongs to the consumer.
94
+ The managed registry stores `adapterId`, not executable configuration or credentials.
95
+ Consequently, loading a session still requires the consumer to resolve that ID.
87
96
 
88
- Presets do not encode a provider's features. After the process starts, the library
89
- discovers capabilities, authentication methods, configuration, sessions, and harness
90
- commands through ACP. The Pi preset targets `@automatalabs/pi-acp`, which embeds Pi through
91
- its published SDK and installs the `pi-acp` executable. The native `pi` command is used
92
- only for interactive PTY mode.
97
+ ## Choose direct or managed sessions
93
98
 
94
- Install the preset executable globally with `npm install -g @automatalabs/pi-acp`, or use
95
- `{ command: ["npx", "-y", "@automatalabs/pi-acp"] }` as a custom adapter.
99
+ Use a direct `AgentSession` when the application wants a transient ACP connection or owns
100
+ all persistence externally. Direct sessions perform no V2 persistence by default.
96
101
 
97
- ## Create the catalog and live-session registry
102
+ Use `SessionManager.open()` when the library should maintain a durable logical-session
103
+ registry and transcripts. Calling `SessionManager.open()` is the opt-in to managed local
104
+ persistence.
98
105
 
99
- `SessionManager` is a metadata catalog, not a registry of running objects and not a
100
- transcript store. Use `FileSessionStore` locally or implement `SessionStore` over the
101
- consumer's database.
106
+ For most orchestrators, the managed path is the recommended starting point.
102
107
 
103
- ```ts
104
- const sessionManager = new SessionManager(
105
- new FileSessionStore("/absolute/path/to/session-catalog"),
106
- );
108
+ ## Open a managed session manager
107
109
 
108
- const liveSessions = new Map<string, AgentSession>();
110
+ ```ts
111
+ const sessions = await SessionManager.open({
112
+ root: "/absolute/path/to/application-state",
113
+ sessionDefaults: {
114
+ transcript: { preset: "activity" },
115
+ auditLog: false,
116
+ },
117
+ });
109
118
  ```
110
119
 
111
- The manager exposes:
120
+ Root resolution is:
112
121
 
113
- ```ts
114
- await sessionManager.record(input);
115
- await sessionManager.get(agentSessionId);
116
- await sessionManager.list();
117
- await sessionManager.delete(agentSessionId);
118
- await sessionManager.listMerged(providerSessions, adapterId);
119
- ```
122
+ 1. An explicit `root`.
123
+ 2. `ACP_CLIENT_HOME`.
124
+ 3. `~/.acp-client`.
120
125
 
121
- Normally the consumer does not call `record()` directly. An `AgentSession` given
122
- `sessions: sessionManager` records itself on startup and updates the record when its
123
- provider identity, mode, title, or transcript location changes.
126
+ The default managed configuration enables an `activity` transcript and disables the
127
+ independent audit log. A session can override manager defaults unless a manager constraint
128
+ forbids the resulting configuration. For example, a product that must always retain
129
+ continuation history can separately set `sessionConstraints.transcript` to `"required"`;
130
+ that manager will intentionally reject the registry-only example below.
124
131
 
125
- ## Create a logical session
132
+ ## Create a managed logical session
126
133
 
127
134
  ```ts
128
135
  async function createSession(adapterId: string): Promise<AgentSession> {
129
- const session = await AgentSession.create({
136
+ const session = await sessions.createAgentSession({
130
137
  adapter: resolveAdapter(adapterId),
131
138
  adapterId,
132
- providerSession: { kind: "new" },
133
- sessions: sessionManager,
134
- transcriptDir: "/absolute/path/to/transcripts",
135
139
  cwd: process.cwd(),
140
+ title: "Repository agent",
136
141
  defaultPermission: "cancel",
142
+ persistence: {
143
+ transcript: { preset: "activity" },
144
+ },
137
145
  });
138
146
 
139
147
  liveSessions.set(session.agentSessionId, session);
@@ -141,264 +149,578 @@ async function createSession(adapterId: string): Promise<AgentSession> {
141
149
  }
142
150
  ```
143
151
 
144
- If `agentSessionId` is omitted, the library creates one. Always return or store
145
- `session.agentSessionId`; do not use `internalSessionId` as the orchestrator's key.
152
+ `agentSessionId` and `creationId` are generated when omitted. A consumer that needs
153
+ idempotent retries across process failure may supply stable values itself.
146
154
 
147
- `providerSession` is explicit:
155
+ To create a registry-only session:
148
156
 
149
157
  ```ts
150
- { kind: "new" }
151
- { kind: "load", internalSessionId, onFailure?: "error" | "new" }
158
+ const session = await sessions.createAgentSession({
159
+ adapter: ADAPTERS.opencode,
160
+ adapterId: "opencode",
161
+ persistence: {
162
+ transcript: false,
163
+ auditLog: false,
164
+ },
165
+ });
152
166
  ```
153
167
 
154
- Loading fails closed by default. Use `onFailure: "new"` only when replacing a missing
155
- provider thread is deliberate policy.
168
+ Registry-only mode preserves continuation state but not conversational history. It cannot
169
+ reconstruct the conversation if the provider thread becomes unavailable.
156
170
 
157
- ## Reopen a cataloged session
171
+ Managed creation and loading currently require normal ACP mode. Managed degraded/PTY
172
+ sessions are not implemented.
158
173
 
159
- `SessionManager.get()` returns routing metadata. It does not start a process. Reopening is
160
- consumer composition because only the consumer knows how to resolve adapters and where to
161
- keep live objects.
174
+ ## Prompt and stream a turn
162
175
 
163
176
  ```ts
164
- async function reopenSession(agentSessionId: string): Promise<AgentSession> {
165
- const existing = liveSessions.get(agentSessionId);
166
- if (existing) return existing;
177
+ const handlers: PromptHandlers = {
178
+ onChunk: (text) => process.stdout.write(text),
179
+ onActivity: (event) => renderActivity(event),
180
+ onRecord: (record) => publishFoldedActivity(record),
181
+ onPermissionRequest: (request) => {
182
+ const allow = request.options.find((option) => option.kind === "allow_once");
183
+ return allow
184
+ ? { outcome: "selected", optionId: allow.optionId }
185
+ : { outcome: "cancelled" };
186
+ },
187
+ };
167
188
 
168
- const record = await sessionManager.get(agentSessionId);
169
- if (!record) throw new Error(`Unknown AgentSession: ${agentSessionId}`);
189
+ const result = await session.prompt("Inspect the failing tests.", handlers);
170
190
 
171
- const session = await AgentSession.create({
172
- adapter: resolveAdapter(record.adapter),
173
- adapterId: record.adapter,
174
- agentSessionId: record.agentSessionId,
175
- providerSession: record.internalSessionId
176
- ? {
177
- kind: "load",
178
- internalSessionId: record.internalSessionId,
179
- onFailure: "error",
180
- }
181
- : { kind: "new" },
182
- mode: record.mode,
183
- cwd: record.cwd,
184
- title: record.title,
185
- sessions: sessionManager,
186
- ...(record.transcriptPath
187
- ? { transcriptPath: record.transcriptPath }
188
- : {}),
189
- });
191
+ console.log(result.status);
192
+ console.log(result.text);
193
+ console.log(result.operationId);
194
+ console.log(result.metering);
195
+ ```
190
196
 
191
- liveSessions.set(session.agentSessionId, session);
192
- return session;
193
- }
197
+ Prompts, configuration changes, handoffs, and other mutations are serialized by each
198
+ `AgentSession`. Multiple different `AgentSession` objects may operate concurrently.
199
+
200
+ ## Observe state, context, and usage
201
+
202
+ Read a snapshot first, then subscribe to changes:
203
+
204
+ ```ts
205
+ publishState(session.state);
206
+
207
+ const unsubscribe = session.subscribe((notification: AgentSessionNotification) => {
208
+ publishNotification(notification);
209
+
210
+ if (notification.event.kind === "state_changed") {
211
+ publishState(notification.event.state);
212
+ }
213
+
214
+ if (notification.event.kind === "metering_recorded") {
215
+ persistBillingMetadata(notification.event.record);
216
+ }
217
+ });
194
218
  ```
195
219
 
196
- Transcript existence never selects a provider thread. `transcriptPath` and
197
- `transcriptDir` only select history storage.
220
+ Useful live properties include:
221
+
222
+ ```ts
223
+ session.state;
224
+ session.isBusy;
225
+ session.queuedOperationCount;
226
+ session.contextWindow; // active thread only, or null
227
+ session.providerCost; // provider telemetry, not asserted invoice truth
228
+ session.meteringSnapshot; // logical-session totals and coverage
229
+ session.model;
230
+ session.providerId;
231
+ ```
198
232
 
199
- ## List and select sessions
233
+ `contextWindow` describes the latest usage observation for the active internal thread. It
234
+ is cleared after a handoff until the new thread reports its context. Metering totals belong
235
+ to the stable logical session and continue across internal-thread changes.
200
236
 
201
- Use the manager to list the consumer's catalog without starting a harness:
237
+ Each completed token-consuming operation carries its own `OperationMeteringRecord`. Store
238
+ that record in the consumer's billing or analytics system if it is financially relevant;
239
+ do not use the transcript as an authoritative billing ledger.
240
+
241
+ Metering defaults to `best_effort` with the pinned models.dev pricing catalog. The other
242
+ enforcement modes have narrower meanings:
243
+
244
+ - `telemetry_required` stops after missing or invalid ACP usage, but ACP telemetry is not a
245
+ billing guarantee.
246
+ - `billing_required` requires a registered certified per-inference integration. Plain ACP
247
+ usage can never satisfy it.
202
248
 
203
249
  ```ts
204
- const catalog = await sessionManager.list();
250
+ const session = await sessions.createAgentSession({
251
+ adapter: ADAPTERS.opencode,
252
+ adapterId: "opencode",
253
+ metering: {
254
+ enforcement: "best_effort",
255
+ },
256
+ });
205
257
  ```
206
258
 
207
- Once a session is connected, `session.listSessions()` merges that catalog with the active
208
- adapter's ACP `session/list` response when the harness supports it:
259
+ Subscription authentication is not inferred as a metering mode. Treat subscription usage
260
+ as informative telemetry; use a certified integration and consumer-controlled API billing
261
+ when token costs must be enforceable.
262
+
263
+ ## Interrupt, stop, and own live objects
209
264
 
210
265
  ```ts
211
- const rows = await session.listSessions();
266
+ session.interrupt();
267
+ session.interrupt({ clearQueue: true });
212
268
 
213
- for (const row of rows) {
214
- console.log(
215
- row.agentSessionId,
216
- row.internalSessionId,
217
- row.adapter,
218
- row.source, // "catalog" | "agent" | "both"
219
- );
220
- }
269
+ await session.stop();
270
+ liveSessions.delete(session.agentSessionId);
221
271
  ```
222
272
 
223
- Selecting which `AgentSession` receives the next operation is consumer state. The library
224
- does not maintain a global “current AgentSession.”
273
+ `stop()` is terminal for that object. The logical session remains in the manager and can
274
+ later be loaded into a new live object.
225
275
 
226
- ## Prompt and stream a turn
276
+ ## List and inspect managed sessions
277
+
278
+ Listing is cursor-paginated and does not start a harness:
227
279
 
228
280
  ```ts
229
- const result = await session.prompt("Inspect the failing tests.", {
230
- onChunk: (text) => process.stdout.write(text),
231
- onActivity: (event) => renderRawActivity(event),
232
- onRecord: (folded) => publishFoldedActivity(folded),
233
- onUpdate: (rawUpdate) => debugProtocolUpdate(rawUpdate),
234
- onPermissionRequest: (request) => {
235
- const allow = request.options.find((option) => option.kind === "allow_once");
236
- return allow
237
- ? { outcome: "selected", optionId: allow.optionId }
238
- : { outcome: "cancelled" };
239
- },
281
+ const page = await sessions.listAgentSessions({
282
+ limit: 100,
283
+ includeDeleted: false,
284
+ order: "updated_desc",
240
285
  });
241
286
 
242
- console.log(result.status, result.stopReason, result.text, result.usage);
287
+ for (const item of page.sessions) {
288
+ console.log(item.agentSessionId, item.adapterId, item.lifecycle);
289
+ }
243
290
  ```
244
291
 
245
- Prompts and handoffs on one `AgentSession` are serialized. The consumer does not need a
246
- separate mutex for them.
292
+ Inspect one session or its current continuation checkpoint:
247
293
 
248
- ## Observe state without polling
294
+ ```ts
295
+ const info = await sessions.getAgentSessionInfo(agentSessionId);
296
+ const resolved = await sessions.getAgentSessionCheckpoint(agentSessionId);
249
297
 
250
- Read the current snapshot first, then subscribe to future notifications:
298
+ if (!info || !resolved) throw new Error("Unknown session");
299
+
300
+ console.log(resolved.source); // "transcript" or "registry_projection"
301
+ console.log(resolved.authoritative);
302
+ console.log(resolved.checkpoint.internalSessionId);
303
+ ```
304
+
305
+ Maintenance inspection is also offline:
251
306
 
252
307
  ```ts
253
- function attachSession(session: AgentSession): () => void {
254
- publishState(session.state);
308
+ await sessions.getSessionMaintenance(agentSessionId);
309
+ await sessions.listSessionMaintenance({ limit: 100 });
310
+ ```
311
+
312
+ A prepared maintenance record means an interrupted create, restore, reconfiguration, or
313
+ deletion should be resumed or resolved before ordinary mutations continue.
255
314
 
256
- return session.subscribe((notification: AgentSessionNotification) => {
257
- publishNotification(notification);
315
+ ## Load an existing session
316
+
317
+ The manager requires the adapter at runtime but selects continuation from persisted state:
318
+
319
+ ```ts
320
+ async function loadSession(agentSessionId: string): Promise<AgentSession> {
321
+ const info = await sessions.getAgentSessionInfo(agentSessionId);
322
+ if (!info) throw new Error(`Unknown session: ${agentSessionId}`);
258
323
 
259
- switch (notification.event.kind) {
260
- case "state_changed":
261
- publishState(notification.event.state);
262
- break;
263
- case "turn_completed":
264
- case "turn_failed":
265
- case "handoff_completed":
266
- case "handoff_failed":
267
- scheduleDependentWork(session.agentSessionId);
268
- break;
269
- }
324
+ const opened = await sessions.loadAgentSession(agentSessionId, {
325
+ adapter: resolveAdapter(info.adapterId),
326
+ adapterId: info.adapterId,
327
+ defaultPermission: "cancel",
270
328
  });
329
+
330
+ console.log(opened.continuation);
331
+ console.log(opened.recovery);
332
+ console.log(opened.configuration);
333
+ console.log(opened.promptability);
334
+ console.log(opened.repairs);
335
+
336
+ liveSessions.set(agentSessionId, opened.session);
337
+ return opened.session;
271
338
  }
272
339
  ```
273
340
 
274
- Useful snapshots are:
341
+ Loading never silently creates a replacement provider thread. By default it attempts the
342
+ persisted `internalSessionId`. If that thread is unavailable, continuation reports the
343
+ failure and the returned session may be non-promptable.
344
+
345
+ For cross-adapter or missing-thread recovery, supply an explicit ordered continuation
346
+ strategy, such as a consumer-owned continuation:
275
347
 
276
348
  ```ts
277
- session.state;
278
- session.isBusy;
279
- session.queuedOperationCount;
349
+ const opened = await sessions.loadAgentSession(agentSessionId, {
350
+ adapter: resolveAdapter(targetAdapterId),
351
+ adapterId: targetAdapterId,
352
+ continuation: {
353
+ strategies: [
354
+ { kind: "load_internal_session" },
355
+ {
356
+ kind: "new_from_consumer_continuation",
357
+ continuationId: "summary-v3",
358
+ continuation: portableSummary,
359
+ },
360
+ ],
361
+ },
362
+ });
280
363
  ```
281
364
 
282
- Notifications carry a monotonically increasing `seq`, timestamp, and stable
283
- `agentSessionId`. A listener exception is isolated from the operation.
365
+ The consumer should always inspect `promptability`. Do not assume that successfully
366
+ opening files means the provider state is safe to mutate.
367
+
368
+ ## Resolve recovery and configuration blockers
284
369
 
285
- ## Interrupt and stop
370
+ An uncertain operation boundary is never guessed away. The consumer explicitly decides:
286
371
 
287
372
  ```ts
288
- session.interrupt(); // cancel the active operation
289
- session.interrupt({ clearQueue: true }); // also discard queued operations
373
+ await session.resolveRecovery({
374
+ strategy: "accept_harness_state",
375
+ });
290
376
 
291
- await session.stop();
292
- liveSessions.delete(session.agentSessionId);
377
+ // Or deliberately replace the provider thread:
378
+ await session.resolveRecovery({
379
+ strategy: "start_new_internal_session",
380
+ continuation: portableSummary,
381
+ });
382
+ ```
383
+
384
+ If persisted configuration no longer matches what the harness announces:
385
+
386
+ ```ts
387
+ await session.resolveConfigurationMismatch({
388
+ strategy: "accept_effective",
389
+ });
390
+
391
+ // Or apply an exact ordered replacement target list:
392
+ await session.resolveConfigurationMismatch({
393
+ strategy: "replace_restoration_targets",
394
+ selections: [
395
+ { configId: "model", value: "anthropic/claude-sonnet-4" },
396
+ ],
397
+ });
293
398
  ```
294
399
 
295
- `stop()` is terminal for that object. Reopen from the catalog to obtain a new live object
296
- with the same logical identity.
400
+ These are separate state machines. Resolving recovery does not implicitly accept a
401
+ configuration mismatch.
297
402
 
298
- ## Handoff within the current harness
403
+ ## Handoff without losing logical identity
299
404
 
300
405
  ```ts
301
- const result = await session.handoff();
406
+ const handoff = await session.handoff();
302
407
  ```
303
408
 
304
- Without options, the old provider thread generates a portable summary. The session then
305
- creates a new provider thread and introduces that summary through a user prompt.
409
+ The current thread generates portable continuation context, the library creates a new
410
+ thread on the same adapter, and the same `AgentSession` continues:
306
411
 
307
- The consumer may provide an already-generated summary:
412
+ ```ts
413
+ handoff.agentSessionId === session.agentSessionId;
414
+ handoff.toInternalSessionId === session.internalSessionId;
415
+ ```
416
+
417
+ If the consumer already has a summary, bypass summary generation:
308
418
 
309
419
  ```ts
310
- const result = await session.handoff({
420
+ await session.handoff({
311
421
  summary: "Objective, decisions, current state, and next steps...",
312
422
  });
313
423
  ```
314
424
 
315
- The following remains true:
425
+ V0 handoff uses the current adapter. The default summary-generation and new-thread
426
+ introduction prompts are library-defined, and introduction is an ordinary user prompt
427
+ because ACP has no portable system-prompt field.
428
+
429
+ ## Harness configuration and commands
430
+
431
+ ACP configuration is available through the stable session:
316
432
 
317
433
  ```ts
318
- result.agentSessionId === session.agentSessionId;
319
- result.toInternalSessionId === session.internalSessionId;
434
+ console.log(session.configOptions);
435
+ await session.setConfig("model", "some-model");
436
+ await session.authenticate(methodId, { onOutput: showAuthOutput });
320
437
  ```
321
438
 
322
- Current limitations are important:
439
+ Configuration selected through `AgentSession` is checkpointed according to the configured
440
+ `sessionConfiguration` persistence policy and reapplied during loading.
323
441
 
324
- - Handoff only creates a new thread on the current adapter/harness.
325
- - The summary-generation prompt is currently fixed unless generation is bypassed by
326
- supplying `summary`.
327
- - The new-thread introduction prompt is currently fixed.
328
- - The introduction is an ordinary user prompt, not a system prompt.
329
- - ACP `session/new` has no portable system-prompt field.
330
- - Handoff requires normal ACP mode.
442
+ Harness slash commands are discovered as metadata:
331
443
 
332
- Cross-adapter handoff and independently configurable summary/introduction policies should
333
- be treated as future API work, not emulated by mutating `internalSessionId` in consumer
334
- code.
444
+ ```ts
445
+ for (const command of session.internalSessionCommands) {
446
+ console.log(command.name, command.description, command.input?.hint);
447
+ }
335
448
 
336
- ## Discover and execute harness commands
449
+ await session.executeInternalSessionCommand("usage");
450
+ await session.executeInternalSessionCommand("status", "verbose");
451
+ ```
452
+
453
+ ACP sends a harness command as a prompt. `executeInternalSessionCommand()` makes the layer
454
+ explicit and routes it through the logical session's queue, lifecycle, transcript, and
455
+ metering machinery. Advertisement is discovery rather than an allow-list.
337
456
 
338
- Commands advertised by the active ACP harness are exposed as immutable metadata:
457
+ ## Discover commands for a UI
458
+
459
+ The library exposes command metadata separately for the two local operation layers. A UI
460
+ bound to one stable logical session can read the AgentSession command registry:
339
461
 
340
462
  ```ts
341
- for (const command of session.internalSessionCommands) {
342
- console.log(command.name, command.description, command.input?.hint);
463
+ const clientCommands = getAgentSessionCommands(session);
464
+
465
+ for (const command of clientCommands) {
466
+ renderCommand({
467
+ name: command.id,
468
+ description: command.description,
469
+ arguments: command.arguments,
470
+ disabled: !command.available,
471
+ disabledReason: command.unavailableReason,
472
+ });
343
473
  }
344
474
  ```
345
475
 
346
- Changes also arrive through the session listener as
347
- `internal_session_commands_changed`.
476
+ This registry contains `/handoff`, `/bridge`, and the introspection commands implemented
477
+ by `createAgentSessionCommands()`. Its availability is recomputed from current session
478
+ state. `/exit` is intentionally absent because it belongs to a particular REPL, not to an
479
+ `AgentSession`.
348
480
 
349
- Execute one explicitly without including the leading slash:
481
+ The lower-level controller exposes its own dynamically negotiated registry:
350
482
 
351
483
  ```ts
352
- await session.executeInternalSessionCommand("usage");
353
- await session.executeInternalSessionCommand("status", "verbose");
484
+ for (const command of controller.getCommands()) {
485
+ console.log(command.id, command.description, command.arguments);
486
+ if (!command.available) console.log(command.unavailableReason);
487
+ }
354
488
  ```
355
489
 
356
- ACP represents these commands as ordinary prompts. The named method makes consumer intent
357
- explicit and keeps the operation in the session queue, transcript, and lifecycle events.
358
- Advertisement is discovery, not an allow-list: a harness may accept a command before it
359
- advertises it.
490
+ These are provider-thread and transport controls such as `/load`, `/fork`, `/config`, and
491
+ `/degrade`; they are not aliases for logical-session operations. Harness-advertised
492
+ commands remain the third source in `session.internalSessionCommands` and are invoked
493
+ explicitly with `executeInternalSessionCommand()`. A consumer can merge all three sources
494
+ for display while retaining their origin so dispatch never crosses layers accidentally.
360
495
 
361
- ## Reuse the AgentSession local command set
496
+ ## Configure transcripts
362
497
 
363
- The same local handlers used by the opinionated one-session REPL are public:
498
+ Transcripts and audit logs are separate artifacts:
499
+
500
+ - A transcript supports conversation display, continuation, debugging, and restoration.
501
+ - An audit log supports a filtered operational history without copying conversation text.
502
+ - The registry is the managed inventory and current routing projection.
503
+
504
+ Configure them per session:
364
505
 
365
506
  ```ts
366
- const localCommands = createAgentSessionCommands({
367
- session,
368
- note: (message) => showNotice(message),
507
+ const session = await sessions.createAgentSession({
508
+ adapter: ADAPTERS.opencode,
509
+ adapterId: "opencode",
510
+ persistence: {
511
+ transcript: {
512
+ path: "/absolute/path/to/transcripts", // directory or exact file
513
+ preset: "detailed",
514
+ capture: {
515
+ permissions: "decision",
516
+ protocol: "none",
517
+ },
518
+ },
519
+ auditLog: {
520
+ path: "/absolute/path/to/audit",
521
+ capture: {
522
+ tools: "input",
523
+ usage: true,
524
+ },
525
+ },
526
+ sessionConfiguration: {
527
+ values: "typed",
528
+ exclude: ["secret-option"],
529
+ },
530
+ },
369
531
  });
532
+ ```
533
+
534
+ If a configured path is an existing directory, the library derives the filename from
535
+ `agentSessionId`. A file path is used exactly. Default managed locations are beneath the
536
+ manager root in separate transcript and audit directories.
537
+
538
+ Available transcript presets are:
539
+
540
+ | Preset | Intended use |
541
+ |---|---|
542
+ | `conversation` | User/assistant text with minimal transition metadata |
543
+ | `activity` | End-user operation history without reasoning or tool contents |
544
+ | `detailed` | Reasoning, tool input/output, and richer transition details |
545
+ | `diagnostic` | Full diagnostic capture, including raw protocol records |
546
+
547
+ Capture filtering happens before persistence. Selecting a more detailed preset is an
548
+ explicit decision to persist more sensitive content. Limits and truncation protect record
549
+ size; structural identity is never truncated merely to force an invalid record to fit.
550
+
551
+ The files are plaintext. The library does not provide encryption, tamper resistance, a
552
+ billing source of truth, or automatic retention policy. Apply filesystem permissions,
553
+ retention, backup, and deletion policy appropriate to the application.
554
+
555
+ ## Read a transcript with pagination
556
+
557
+ Resolve its authoritative path without starting the harness:
558
+
559
+ ```ts
560
+ const resolved = await sessions.getAgentSessionCheckpoint(agentSessionId);
561
+ const path = resolved?.checkpoint.transcript?.path;
562
+ if (!path) throw new Error("This session has no transcript");
370
563
 
371
- const handled = await localCommands.onSlashCommand("state", []);
564
+ const reader = new TranscriptReader(path);
372
565
  ```
373
566
 
374
- The built-in set currently handles:
567
+ The reader offers three projections:
375
568
 
376
- ```text
377
- /help
378
- /session
379
- /state
380
- /commands
381
- /handoff [SUMMARY]
382
- /bridge
569
+ ```ts
570
+ const conversation = await reader.readPage({
571
+ view: "conversation",
572
+ limit: 50,
573
+ });
574
+
575
+ const timeline = await reader.readPage({
576
+ view: "timeline",
577
+ types: ["message", "activity", "transition"],
578
+ limit: 50,
579
+ });
580
+
581
+ const records = await reader.readPage({
582
+ view: "records",
583
+ limit: 50,
584
+ });
585
+ ```
586
+
587
+ Each page is ordered oldest-first within that page, while the initial page selects the
588
+ newest matching records. Navigate using `olderCursor` and `newerCursor`:
589
+
590
+ ```ts
591
+ const older = timeline.olderCursor
592
+ ? await reader.readPage({
593
+ view: "timeline",
594
+ types: ["message", "activity", "transition"],
595
+ cursor: timeline.olderCursor,
596
+ limit: 50,
597
+ })
598
+ : null;
599
+ ```
600
+
601
+ Navigation cursors are bound to the snapshot, view, and filter. Reusing one with another
602
+ view or filter fails explicitly. Appends after the snapshot do not reorder the page being
603
+ read, while rewrites before its boundary invalidate the cursor.
604
+
605
+ Fold revisioned activities at the same snapshot:
606
+
607
+ ```ts
608
+ const activity = await reader.listActivityStates({
609
+ at: timeline.snapshot,
610
+ status: "open",
611
+ order: "updated_desc",
612
+ limit: 100,
613
+ });
383
614
  ```
384
615
 
385
- `/exit` is handled by the REPL loop rather than the command factory.
616
+ An activity that was open at the snapshot remains `historically_open`; the reader does not
617
+ claim that a tool is still executing in a process it cannot observe.
386
618
 
387
- The factory currently exposes the handler, not a declarative metadata array for local
388
- commands. A consumer can reuse the handler directly; a custom command palette must define
389
- its own local labels/descriptions for now. Harness commands do have declarative metadata
390
- through `session.internalSessionCommands`.
619
+ ## Read the independent audit log
391
620
 
392
- ## Run the opinionated single-session REPL
621
+ ```ts
622
+ const audit = new AuditLogReader(knownAuditLogPath);
623
+
624
+ const page = await audit.readPage({
625
+ types: ["operation", "activity", "permission", "metering_reference"],
626
+ limit: 100,
627
+ });
628
+ ```
629
+
630
+ Audit pagination has the same stable-snapshot behavior. V0 summaries expose whether an
631
+ audit log is available but do not expose its path. A consumer that enables an audit log
632
+ should retain the configured path or derive it as part of its own persistence policy.
633
+
634
+ ## Reconfigure persistence offline
635
+
636
+ Stop the live session before reconfiguration. Transcript and audit mutations are separate
637
+ fenced V0 operations.
638
+
639
+ ```ts
640
+ const info = await sessions.getAgentSessionInfo(agentSessionId);
641
+ const resolved = await sessions.getAgentSessionCheckpoint(agentSessionId);
642
+ if (!info || !resolved) throw new Error("Unknown session");
643
+
644
+ await sessions.reconfigureAgentSessionPersistence(agentSessionId, {
645
+ reconfigurationId: crypto.randomUUID(),
646
+ expectedIncarnationId: info.incarnationId,
647
+ expectedRecordRevision: info.recordRevision,
648
+ transcript: {
649
+ action: "replace",
650
+ config: {
651
+ path: resolved.checkpoint.transcript!.path,
652
+ preset: "conversation",
653
+ },
654
+ checkpoint: resolved.checkpoint,
655
+ acknowledgeContinuationLoss: true,
656
+ },
657
+ });
658
+ ```
659
+
660
+ V0 replacement changes the generation and policy while retaining the recorded path.
661
+ Disablement permanently removes that artifact and requires the corresponding explicit
662
+ acknowledgement. Use the managed CLI when an operator-facing confirmation flow is desired.
663
+
664
+ ## Delete and restore managed sessions
665
+
666
+ Deletion is tombstoning by default. The consumer supplies incarnation and revision CAS
667
+ tokens so a delayed request cannot delete a newly reused logical identity.
668
+
669
+ ```ts
670
+ const info = await sessions.getAgentSessionInfo(agentSessionId);
671
+ if (!info) throw new Error("Unknown session");
672
+
673
+ await sessions.deleteAgentSession(agentSessionId, {
674
+ deletionId: crypto.randomUUID(),
675
+ expectedIncarnationId: info.incarnationId,
676
+ expectedRecordRevision: info.recordRevision,
677
+ deleteTranscript: false,
678
+ deleteAuditLog: false,
679
+ removeRegistryEntry: false,
680
+ });
681
+ ```
682
+
683
+ Hard registry removal is allowed only when all retained artifacts are deleted in the same
684
+ operation. Prefer tombstones when restoration or identity history matters.
685
+
686
+ Restore a tombstone explicitly:
687
+
688
+ ```ts
689
+ const deleted = await sessions.getAgentSessionInfo(agentSessionId, {
690
+ includeDeleted: true,
691
+ });
692
+ if (!deleted) throw new Error("Unknown session");
693
+
694
+ const opened = await sessions.restoreAgentSession(agentSessionId, {
695
+ adapter: resolveAdapter(deleted.adapterId),
696
+ adapterId: deleted.adapterId,
697
+ restorationId: crypto.randomUUID(),
698
+ expectedIncarnationId: deleted.incarnationId,
699
+ expectedRecordRevision: deleted.recordRevision,
700
+ });
701
+ ```
702
+
703
+ Retained artifacts are reused. If an artifact was deleted, restoration requires an
704
+ explicit `false` or an absolute normalized replacement filename; directory shorthand is
705
+ not accepted because restoration IDs must remain stable if filesystem state changes. It
706
+ never silently recreates the previous file. The returned value has the same continuation, recovery, configuration,
707
+ promptability, and repairs report as ordinary managed loading.
708
+
709
+ ## Use the command layers in a UI
710
+
711
+ The one-session REPL uses unambiguous routing:
712
+
713
+ ```text
714
+ ordinary text -> session.prompt(...)
715
+ /command -> local AgentSession command
716
+ //command [input] -> session.executeInternalSessionCommand(...)
717
+ ```
393
718
 
394
719
  ```ts
395
720
  try {
396
721
  await runAgentSessionRepl(session, {
397
722
  activity: true,
398
- spinner: true,
399
- note: (message) => process.stderr.write(`${message}\n`),
400
723
  onSlashCommand: async (command, args) => {
401
- // Consumer-local extension, tried after the built-in AgentSession commands.
402
724
  if (command !== "tag") return false;
403
725
  await addTag(session.agentSessionId, args.join(" "));
404
726
  return true;
@@ -409,102 +731,107 @@ try {
409
731
  }
410
732
  ```
411
733
 
412
- Input routing is deliberately unambiguous:
734
+ Built-in local commands include `/session`, `/state`, `/commands`, `/handoff`, and
735
+ `/bridge`. Unknown `/...` commands never fall through as prompts. A graphical application
736
+ can skip slash parsing and bind the same methods directly to buttons, RPC methods, jobs,
737
+ or orchestration events.
413
738
 
414
- ```text
415
- ordinary text -> session.prompt(...)
416
- /command -> local AgentSession command
417
- //command [input] -> session.executeInternalSessionCommand(...)
418
- ```
739
+ The packaged managed CLI is a reference consumer:
419
740
 
420
- An unknown `/command` is rejected locally and never falls through to the harness.
741
+ ```bash
742
+ acp-client create [AGENT_SESSION_ID] --adapter opencode
743
+ acp-client open AGENT_SESSION_ID
744
+ acp-client sessions --json
745
+ acp-client info AGENT_SESSION_ID
746
+ acp-client checkpoint AGENT_SESSION_ID
747
+ acp-client maintenance [AGENT_SESSION_ID]
748
+ acp-client restore AGENT_SESSION_ID
749
+ acp-client reconfigure AGENT_SESSION_ID --replace-transcript --preset detailed --yes
750
+ acp-client delete AGENT_SESSION_ID --delete-transcript --yes
751
+ ```
421
752
 
422
- ## Reuse routing in a custom UI
753
+ ## Direct sessions
423
754
 
424
- Consumers do not need to use readline. `parseReplInput()` and `dispatchReplInput()` are
425
- terminal-independent:
755
+ Direct sessions are intentionally persistence-free unless configured:
426
756
 
427
757
  ```ts
428
- const local = createAgentSessionCommands({ session, note: showNotice });
429
- const promptHandlers: PromptHandlers = {
430
- onChunk: (text) => renderText(text),
431
- onActivity: (event) => renderActivity(event),
432
- };
433
-
434
- await dispatchReplInput(parseReplInput(input), {
435
- prompt: async (text) => {
436
- await session.prompt(text, promptHandlers);
437
- },
438
- localCommand: (command, args) => local.onSlashCommand(command, args),
439
- internalSessionCommand: async (command, value) => {
440
- await session.executeInternalSessionCommand(command, value, promptHandlers);
441
- },
442
- unknownLocalCommand: (command) => {
443
- showNotice(`Unknown local command: /${command}`);
444
- },
445
- missingInternalSessionCommand: () => {
446
- showNotice("A command name is required after //");
447
- },
758
+ const session = await AgentSession.create({
759
+ adapter: ADAPTERS.opencode,
760
+ adapterId: "opencode",
761
+ providerSession: { kind: "new" },
448
762
  });
449
763
  ```
450
764
 
451
- A graphical consumer may skip slash parsing entirely and bind these operations directly
452
- to buttons, menus, RPC methods, or orchestration events.
453
-
454
- ## Use the lower-level control plane when needed
455
-
456
- `session.connection` exposes the live `AgentController` for operations that do not belong
457
- to the stable session abstraction:
765
+ Direct V2 persistence requires stable logical and creation identities because there is no
766
+ manager catalog to discover generated ones after a crash:
458
767
 
459
768
  ```ts
460
- session.capabilities;
461
- session.configOptions;
462
- await session.setConfig("model", "some-model");
463
- await session.authenticate(methodId, { onOutput: showAuthOutput });
464
-
465
- const controller = session.connection;
466
- await controller.listSessions();
467
- await controller.loadSession(internalSessionId);
769
+ const session = await AgentSession.create({
770
+ adapter: ADAPTERS.opencode,
771
+ adapterId: "opencode",
772
+ agentSessionId,
773
+ creationId,
774
+ providerSession: { kind: "new" },
775
+ persistence: {
776
+ root: "/absolute/application-state",
777
+ transcript: { preset: "activity" },
778
+ },
779
+ });
468
780
  ```
469
781
 
470
- Use controller session-switching methods carefully: they operate directly on the provider
471
- thread. Prefer `AgentSession` methods when a stable logical-session equivalent exists, so
472
- the catalog, lifecycle notifications, and transcript remain coherent.
473
-
474
- ## Transcript policy
782
+ In V0 this direct transcript path is a preview convenience, not a crash-resumable creation
783
+ transaction. A failure after the transcript header is installed can leave an initialized
784
+ artifact which must be opened or cleaned up explicitly. Direct audit persistence is
785
+ rejected instead of creating an audit file which the live session cannot safely own.
475
786
 
476
- Choose exactly one history destination:
787
+ For durable persistent applications, use `SessionManager.createAgentSession()` and
788
+ `SessionManager.loadAgentSession()`. The manager owns prepared creation, registry fencing,
789
+ audit attachment, retry discovery, and completion receipts.
477
790
 
478
- ```ts
479
- transcriptPath: "/absolute/path/to/conversation.jsonl"
480
- // or
481
- transcriptDir: "/absolute/path/to/transcripts"
482
- ```
791
+ ## Legacy compatibility
483
792
 
484
- Omit both to disable transcript writes. This does not disable prompting, handoff, catalog
485
- management, or lifecycle notifications.
793
+ `FileSessionStore`, `sessions:`, `transcriptPath`, `transcriptDir`, and
794
+ `transcriptActivity` remain for compatibility with the earlier flat catalog/transcript
795
+ model. They should not be used for new managed implementations.
486
796
 
487
- Enable settled activity records when the consumer needs tool/thinking/plan history:
797
+ Legacy transcript conversion and registry import are explicit:
488
798
 
489
799
  ```ts
490
- transcriptActivity: {
491
- checkpointOnInput: true,
492
- rawOutput: false,
493
- maxBytes: 64_000,
494
- }
800
+ await migrateLegacyTranscript(options);
801
+ await sessions.importLegacySessions(legacyStore);
495
802
  ```
496
803
 
497
- Use `readTranscript()` for logical user/assistant messages and `readTranscriptLines()` for
498
- the complete typed stream, including activity and handoff boundaries.
804
+ Migration preserves the legacy prefix for presentation and establishes a new V2 authority
805
+ boundary. Strict V2 creation never claims an already initialized legacy file implicitly.
806
+
807
+ ## Current V0 boundaries
808
+
809
+ - Managed creation and loading support normal ACP mode only.
810
+ - Direct V2 creation supports transcript-only persistence and is not crash-resumable;
811
+ direct V2 audit persistence is rejected.
812
+ - Direct V2 opening currently requires an explicit `agentSessionId` and transcript;
813
+ checkpoint-only and exact-file identity inference are deferred.
814
+ - Handoff creates a new thread on the current adapter.
815
+ - Tombstone restoration currently loads only the recorded provider thread; reconstruction
816
+ strategies remain available to ordinary managed loading but are deferred for restoration.
817
+ - Transcript and audit reconfiguration are separate operations.
818
+ - Replacement reconfiguration retains the existing artifact path.
819
+ - Generic ACP load cannot prove what happened after a crash; uncertainty requires an
820
+ explicit consumer decision.
821
+ - Session logs are plaintext and do not provide encryption or tamper resistance.
822
+ - Metering records are application telemetry, not an invoice or trusted billing ledger.
823
+ - A transcript or audit generation has one active writer, enforced by a writer lock.
824
+ - Retention policy and automatic pruning belong to the consumer.
499
825
 
500
826
  ## Recommended ownership rules
501
827
 
502
- - Key orchestration state by `agentSessionId`, never `internalSessionId`.
503
- - Keep the map of live `AgentSession` objects in the consumer.
504
- - Treat `SessionManager` as routing metadata, not a process manager.
505
- - Read `session.state` before subscribing to notifications.
506
- - Use `executeInternalSessionCommand()` instead of constructing slash prompts manually.
507
- - Keep consumer/local commands separate from harness commands in the UI.
508
- - Resolve adapters in the consumer and fail explicitly on unknown adapter ids.
509
- - Stop every live session during consumer shutdown.
510
- - Do not infer provider loading from transcript filenames or contents.
828
+ - Key application state by `agentSessionId`, never `internalSessionId`.
829
+ - Keep live `AgentSession` objects in the consumer; use the manager for durable discovery.
830
+ - Resolve adapter IDs in the consumer and fail explicitly when one is unknown.
831
+ - Inspect `AgentSessionOpenResult.promptability` before dispatching work.
832
+ - Read state before subscribing so no initial snapshot is missed.
833
+ - Persist operation metering records separately when they matter financially.
834
+ - Use transcript presets deliberately; detailed and diagnostic capture can contain secrets.
835
+ - Keep local commands distinct from harness commands.
836
+ - Stop every live session during application shutdown.
837
+ - Do not infer provider loading from a transcript path or file contents.