@qlairoslabs/acp-client 0.6.0 → 0.7.0

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