@qlairoslabs/acp-client 0.7.4 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG-audit.md +58 -0
  2. package/CONSUMER_GUIDE.md +571 -19
  3. package/package.json +6 -1
  4. package/src/agent-adapter-registry.ts +66 -0
  5. package/src/agent-conversation-continuation.ts +121 -0
  6. package/src/agent-conversation-contracts.ts +279 -0
  7. package/src/agent-conversation-errors.ts +31 -0
  8. package/src/agent-conversation-owner.ts +60 -0
  9. package/src/agent-conversation-presentation.ts +217 -0
  10. package/src/agent-conversation-queue.ts +44 -0
  11. package/src/agent-conversation.ts +41 -0
  12. package/src/agent-ids.ts +50 -0
  13. package/src/agent-session.ts +1032 -674
  14. package/src/agent.ts +1223 -0
  15. package/src/audit/config.ts +186 -0
  16. package/src/audit/contracts.ts +59 -0
  17. package/src/audit/index.ts +50 -0
  18. package/src/audit/projection.ts +127 -0
  19. package/src/audit/reader.ts +371 -0
  20. package/src/audit/runtime.ts +1060 -0
  21. package/src/checkpointing/config.ts +91 -0
  22. package/src/checkpointing/contracts.ts +45 -0
  23. package/src/checkpointing/coordinator.ts +100 -0
  24. package/src/checkpointing/ids.ts +5 -0
  25. package/src/checkpointing/index.ts +6 -0
  26. package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
  27. package/src/checkpointing/recovery.ts +114 -0
  28. package/src/checkpointing/strategy.ts +139 -0
  29. package/src/identity/checkpoint-backed.ts +248 -0
  30. package/src/identity.ts +76 -0
  31. package/src/index.ts +132 -0
  32. package/src/internal-inference/config.ts +68 -0
  33. package/src/internal-inference/contracts.ts +218 -0
  34. package/src/internal-inference/coordination/handles.ts +133 -0
  35. package/src/internal-inference/coordination/manager.ts +487 -0
  36. package/src/internal-inference/ids.ts +10 -0
  37. package/src/internal-inference/index.ts +10 -0
  38. package/src/internal-inference/persistence/records.ts +132 -0
  39. package/src/internal-inference/persistence/repository.ts +35 -0
  40. package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
  41. package/src/internal-inference/runtime/harness-runtime.ts +78 -0
  42. package/src/internal-inference/strategy/registry.ts +42 -0
  43. package/src/metering/engine.ts +47 -0
  44. package/src/metering/record.ts +4 -1
  45. package/src/observation/contracts.ts +10 -0
  46. package/src/observation/index.ts +8 -0
  47. package/src/observation/subscription-hub.ts +43 -0
  48. package/src/persistence/activity-projection.ts +26 -12
  49. package/src/persistence/backend.ts +839 -0
  50. package/src/persistence/index.ts +113 -0
  51. package/src/persistence/sqlite-backend.ts +2192 -0
  52. package/src/persistence/sqlite-conversation-records.ts +430 -0
  53. package/src/persistence/sqlite-owner-lock.ts +106 -0
  54. package/src/persistence/sqlite-schema.ts +589 -0
  55. package/src/persistence/timeline-reconcile.ts +72 -0
@@ -0,0 +1,58 @@
1
+ # Agent audit log — breaking changes and release notes
2
+
3
+ Pre-1.0 changes introduced by the SQLite-backed Agent audit stream
4
+ (`.res/somelogs.md/9-16+/9-18-SPEC-agent-audit-log.md`). Fold this into the release notes.
5
+
6
+ ## 1. SQLite schema version 8
7
+
8
+ Schema version 8 adds the durable Agent audit state and pending outbox. Pre-release
9
+ version-7 databases are intentionally not migrated; recreate development and smoke-test
10
+ databases before opening them with this release.
11
+
12
+ The SQLite database remains the conversation-recovery source. Audit JSONL files are an
13
+ independent operational history, not a second recovery backend.
14
+
15
+ ## 2. One optional audit stream per Agent
16
+
17
+ `Agent.open()` accepts `auditLog`. Its caller-selected directory contains one logical
18
+ stream across all conversations owned by that agent, split into numbered JSONL segments.
19
+ Capture policy is evaluated from the normalized observation independently of canonical
20
+ SQLite capture, so either side may retain more detail than the other.
21
+
22
+ Canonical persistence and outbox enqueue share a transaction. Delivery happens in the
23
+ background, is ordered, durable, and at least once. Entries carry stable audit sequence,
24
+ outbox, source-observation, agent, and optional conversation identifiers.
25
+
26
+ ## 3. Rotation, recovery, and observability
27
+
28
+ Size and age triggers rotate the stream without changing its identity. Startup validates
29
+ the contiguous segment set, repairs only an incomplete highest tail, and reconciles the
30
+ bounded physically written but unacknowledged suffix against SQLite. Missing delivered
31
+ history and identity conflicts fail closed.
32
+
33
+ `agent.audit` exposes `status()`, `subscribe()`, `flush()`, and `retry()`. `Agent.close()`
34
+ attempts a bounded flush and preserves undelivered rows for the next open.
35
+
36
+ `AgentAuditLogReader` provides paginated `logical` and `physical` views. Logical mode
37
+ deduplicates the bounded crash-replay window; physical mode preserves it for diagnostics.
38
+
39
+ ## 4. Explicit single-owner rule
40
+
41
+ One live process owns an agent SQLite database, and one live writer owns an audit
42
+ destination. A second open fails with `AgentDatabaseInUseError` or
43
+ `AuditLogDestinationInUseError`. Any number of conversations may still execute
44
+ concurrently through that owning `Agent` instance.
45
+
46
+ ## 5. Accepted initial limitations
47
+
48
+ - Audit configuration cannot change while an Agent is open.
49
+ - All numbered segments are required; automatic retention is not included.
50
+ - Enabling audit later does not backfill canonical history.
51
+ - Age rotation is evaluated on delivery, not by an idle timer.
52
+ - Files are plaintext and unsigned.
53
+ - Entry-level syncing prioritizes crash recovery over maximum raw-protocol throughput.
54
+ - Custom persistence backends cannot enable Agent audit until they implement the durable
55
+ audit outbox contract.
56
+
57
+ The older `SessionManager` transcript/audit system remains supported and is not silently
58
+ redirected to this Agent-level stream.
package/CONSUMER_GUIDE.md CHANGED
@@ -1,38 +1,38 @@
1
1
  # Consumer guide
2
2
 
3
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.
4
+ orchestrators that own several agents and conversations. The recommended durable API is
5
+ `Agent`, backed by a caller-located SQLite database. The library owns ACP communication,
6
+ conversation queues, typed records, search, identity lifecycle hooks, and persistence.
7
+ The consumer owns database placement, adapter definitions, user interface, and application
8
+ policy.
9
+
10
+ `AgentSession` remains the compatibility name for one live `AgentConversation`. The
11
+ older `SessionManager`/JSONL workflow is still supported and documented later in this
12
+ guide, but new durable applications should normally begin with `Agent`.
7
13
 
8
14
  The package requires Bun 1.3.5 or newer.
9
15
 
10
16
  ## Mental model
11
17
 
12
- There are three different operation layers:
18
+ There are three primary runtime layers:
13
19
 
14
20
  | Layer | Main API | Examples |
15
21
  |---|---|---|
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 |
22
+ | Agent identity and persistence | `Agent` | Own SQLite persistence, adapter registry, identity runtime, and conversations |
23
+ | One stable conversation | `AgentConversation` (`AgentSession` compatibility alias) | Prompt, interrupt, handoff, switch adapters, reset, observe state, and configure the harness |
18
24
  | Active harness thread | ACP and `internalSessionCommands` | Harness-specific commands such as `/usage` and `/model` |
19
25
 
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.
26
+ An `agentSessionId` (`ags-*`) identifies the agent. An `agentConversationId` (`agc-*`)
27
+ identifies one of its conversations. An `internalSessionId` identifies the replaceable
28
+ provider or harness thread behind that conversation.
23
29
 
24
30
  ```text
25
31
  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>();
32
+ └── Agent ags-… stable agent identity + SQLite database
33
+ └── AgentConversation agc-… stable conversation identity
34
+ └── AgentController
35
+ └── internal thread abc replaceable harness identity
36
36
  ```
37
37
 
38
38
  ## Install and import
@@ -44,6 +44,8 @@ bun add @qlairoslabs/acp-client
44
44
  ```ts
45
45
  import {
46
46
  ADAPTERS,
47
+ Agent,
48
+ AgentAuditLogReader,
47
49
  AgentSession,
48
50
  AuditLogReader,
49
51
  SessionManager,
@@ -56,6 +58,556 @@ import {
56
58
  } from "@qlairoslabs/acp-client";
57
59
  ```
58
60
 
61
+ ## Start with one SQLite-backed agent
62
+
63
+ The database path is explicit and belongs to the consumer. One database contains one
64
+ agent identity and any number of independently addressable conversations.
65
+
66
+ ```ts
67
+ import { Agent, ADAPTERS } from "@qlairoslabs/acp-client";
68
+
69
+ const agent = await Agent.open({
70
+ persistence: {
71
+ kind: "sqlite",
72
+ path: "/absolute/path/to/state/atlas.sqlite",
73
+ },
74
+ adapters: {
75
+ codex: ADAPTERS.codex,
76
+ },
77
+ defaultAdapterId: "codex",
78
+ });
79
+
80
+ try {
81
+ const conversation = await agent.conversations.create();
82
+ const result = await conversation.prompt("hi");
83
+
84
+ for (const message of result.messages) {
85
+ console.log(message.text);
86
+ }
87
+ } finally {
88
+ await agent.close();
89
+ }
90
+ ```
91
+
92
+ The user message and each assistant-message boundary are stored as separate typed rows.
93
+ Reopen the same database with `Agent.open()` and call
94
+ `agent.conversations.open(agentConversationId)` to continue its active provider thread.
95
+
96
+ ### Attach consumer data to a prompt message
97
+
98
+ The object-form prompt APIs attach opaque JSON to the submitted **user message**:
99
+
100
+ ```ts
101
+ await conversation.prompt({
102
+ text: "hello",
103
+ consumerMetadata: { deliveryId: "delivery-42", submittedBy: "relay" },
104
+ });
105
+ await conversation.promptFrom({
106
+ participantId: "agent-bob",
107
+ text: "Can you review this?",
108
+ consumerMetadata: { deliveryId: "delivery-43" },
109
+ });
110
+
111
+ const messages = await agent.persistence.messages.list(conversation.id);
112
+ console.log(messages.messages[0]?.consumerMetadata);
113
+ ```
114
+
115
+ The older positional `prompt(text, handlers?, attachments?)` and
116
+ `promptFrom(participantId, text, handlers?, attachments?)` calls remain valid.
117
+ `consumerMetadata` is stored in `conversation_messages.consumer_metadata_json` and
118
+ returned as `MessageRecord.consumerMetadata`; it is not copied onto assistant messages,
119
+ sent to the provider, added to identity context, or indexed for search. The library does
120
+ not interpret its fields. The separate envelope `metadata` field still carries older
121
+ library-owned operation correlation. A raw audit capture includes consumer metadata;
122
+ content/metadata audit capture omits it.
123
+
124
+ SQLite keeps ordering and type-specific content separate. `conversation_records` is a
125
+ narrow canonical envelope containing the conversation-local sequence, kind, timestamp,
126
+ operation correlation, and optional metadata. Every envelope has exactly one typed detail
127
+ row in tables such as `conversation_messages`, `conversation_tool_call_events`, or
128
+ `conversation_activity_events`. A mixed timeline is read as one envelope page followed by
129
+ bounded, batched subtype hydration; it never performs one query per record.
130
+
131
+ Messages store ordinary text directly in `content_text`; structured or multimodal content
132
+ uses `content_json`. Tool calls, permissions, configuration, actions, thinking, and
133
+ activities retain meaningful lifecycle transitions as independently sequenced records.
134
+ Raw ACP protocol bodies remain JSON because their external shape is intentionally open.
135
+ Each completed metered operation adds an ordered `metering` reference whose complete
136
+ financial record remains in `metering_records`; the timeline does not duplicate billing
137
+ payloads.
138
+
139
+ `activity` is reserved for model activity such as plans. Complete session observations
140
+ such as usage, available commands, mode/config announcements, session metadata, echoed
141
+ user messages, and unknown protocol updates are not reclassified as model activity.
142
+ Their semantic state is retained by the relevant configuration, metering, or checkpoint
143
+ storage, while consumers that need exact diagnostic traffic can enable protocol capture.
144
+
145
+ SQLite protocol capture supports `"none"`, `"metadata"`, and `"raw"`; protocol
146
+ `"content"` is rejected because coalesced content already belongs to the typed semantic
147
+ records. Exact method filters provide a compact protocol skeleton without persisting the
148
+ high-volume update stream:
149
+
150
+ ```ts
151
+ capture: {
152
+ protocol: {
153
+ level: "metadata",
154
+ excludeMethods: ["session/update"],
155
+ },
156
+ }
157
+ ```
158
+
159
+ `includeMethods` is also available and cannot be combined with `excludeMethods`. Both use
160
+ exact ACP method names. Methodless JSON-RPC responses remain captured because their method
161
+ cannot be determined without correlating request IDs. Filtering happens before canonical
162
+ sequence allocation, so omitted frames create neither rows nor sequence gaps.
163
+
164
+ FTS5 indexes deliberately extracted searchable text rather than serialized record JSON.
165
+ The initial indexes cover messages, tool calls, and activities. Consumer metadata and raw
166
+ protocol bodies are not searched implicitly.
167
+
168
+ Schema version 10 adds message consumer metadata and migrates version-8 and version-9
169
+ agent databases in place. Pre-release version-7 SQLite files are not migrated because
170
+ they were used only by development smoke tests; opening one gives a recreate instruction.
171
+
172
+ ### Read SQLite conversation history and previews
173
+
174
+ `records.listRecent()` returns the newest matching records at a fixed conversation
175
+ sequence snapshot. Each page is oldest-first for rendering; its `olderCursor` stays
176
+ bound to that snapshot and kind filter even if new records arrive:
177
+
178
+ ```ts
179
+ import { reconcileConversationTimeline } from "@qlairoslabs/acp-client";
180
+
181
+ const first = await agent.persistence.records.listRecent!(conversation.id, { limit: 50 });
182
+ let items = reconcileConversationTimeline([], first.records);
183
+ const older = first.olderCursor
184
+ ? await agent.persistence.records.listRecent!(conversation.id, {
185
+ limit: 50,
186
+ olderCursor: first.olderCursor,
187
+ })
188
+ : null;
189
+ if (older) items = reconcileConversationTimeline(items, older.records);
190
+ ```
191
+
192
+ Every physical record has a stable `recordId` and a conversation-local `sequence`.
193
+ The reconciliation helper keeps distinct messages separate and groups revisions of a
194
+ tool call, permission, thinking block, activity, or transition by its logical ID. Its
195
+ items retain every revision, carry the latest merged fields in `current`, and sort by
196
+ the earliest loaded sequence. Loading an older page may move an item to its true
197
+ earlier position when its first revision arrives. Configuration, protocol, agent
198
+ actions, and metering references remain individual records unless they have an
199
+ explicit logical identity; metering details are read from `persistence.metering`.
200
+
201
+ For live reconciliation, subscribe before the initial read if immediate UI feedback
202
+ matters, but treat subscription notifications as hints. The authoritative catch-up is
203
+ `records.list(conversation.id, { afterSequence: lastSeenSequence, limit: 100 })`.
204
+ Advance `lastSeenSequence` to the last returned record and repeat until the page is
205
+ short. Upsert by `recordId` through `reconcileConversationTimeline`; after a process
206
+ restart, catch up from the last sequence the consumer retained. Subscription sequence
207
+ numbers are **not** SQLite conversation sequences.
208
+
209
+ Use one batched preview read for a conversation list:
210
+
211
+ ```ts
212
+ const page = await agent.conversations.listPreviews({ limit: 50 });
213
+ for (const { conversation, latestMessage, lastHumanMessageAt } of page.previews) {
214
+ renderConversationRow(conversation.id, latestMessage?.text, lastHumanMessageAt);
215
+ }
216
+ ```
217
+
218
+ `latestMessage` has its stable record ID, role, participant ID, timestamp, sequence,
219
+ and up to 240 characters of preview text. `lastHumanMessageAt` includes only messages
220
+ whose participant kind is `user`, not agent-to-agent prompts whose message role is
221
+ also `user`. SQLite maintains that timestamp on conversation writes and backfills it
222
+ once for pre-version-10 databases; preview reads do not rescan long message histories.
223
+ Preview paging follows conversation `updatedAt` order; that list may
224
+ reorder as conversations advance, so consumers should refresh it rather than treat
225
+ offset cursors as a frozen snapshot. `listRecent` and `listPreviews` are SQLite
226
+ capabilities; custom persistence backends may not implement them.
227
+
228
+ ### Agent audit log
229
+
230
+ An SQLite-backed `Agent` can copy selected observations into an independently located,
231
+ rotating JSONL audit stream. The stream belongs to the whole agent, so observations from
232
+ all of its conversations share one ordered audit sequence. Audit capture is independent
233
+ of canonical conversation capture: for example, an application may omit message content
234
+ from SQLite while retaining it in the audit destination, or do the reverse.
235
+
236
+ ```ts
237
+ const agent = await Agent.open({
238
+ persistence: { kind: "sqlite", path: "/state/atlas.sqlite" },
239
+ adapters: { codex: ADAPTERS.codex },
240
+ auditLog: {
241
+ directory: "/audit/atlas",
242
+ filePrefix: "audit",
243
+ capture: {
244
+ message: "content",
245
+ protocol: {
246
+ level: "metadata",
247
+ excludeMethods: ["session/update"],
248
+ },
249
+ },
250
+ rotation: {
251
+ maxBytes: 64 * 1024 * 1024,
252
+ maxAgeMs: 24 * 60 * 60 * 1_000,
253
+ },
254
+ },
255
+ });
256
+ ```
257
+
258
+ The default prefix is `audit`. Segments are named `audit.000001.jsonl`,
259
+ `audit.000002.jsonl`, and so on. A durable pending outbox in the agent database makes
260
+ canonical persistence and audit intent one transaction. A background writer then appends
261
+ and syncs those entries without delaying `prompt()`. Delivery is at least once: after a
262
+ crash, a physically written entry may be encountered again during reconciliation, and
263
+ its stable audit sequence and outbox ID identify the replay.
264
+
265
+ Observe delivery or explicitly wait for it when an application boundary requires that:
266
+
267
+ ```ts
268
+ const unsubscribe = agent.audit?.subscribe((event) => {
269
+ console.log(event.kind, event.snapshot.pendingCount);
270
+ });
271
+
272
+ const snapshot = await agent.audit?.status();
273
+ const flushed = await agent.audit?.flush({ timeoutMs: 10_000 });
274
+ if (flushed?.status === "blocked") {
275
+ // Repair or restore the destination before reopening the agent.
276
+ }
277
+
278
+ await agent.audit?.retry(); // manually end retry backoff after a transient failure
279
+ unsubscribe?.();
280
+ ```
281
+
282
+ `Agent.close()` makes a bounded flush attempt using `shutdownGraceMs` (two seconds by
283
+ default), then releases the audit destination and agent database. Pending rows remain in
284
+ SQLite if the destination was unavailable and resume on the next open.
285
+
286
+ Read the stream without opening its agent database:
287
+
288
+ ```ts
289
+ const reader = await AgentAuditLogReader.open({
290
+ directory: "/audit/atlas",
291
+ filePrefix: "audit",
292
+ });
293
+
294
+ const logical = await reader.readPage({ mode: "logical", limit: 100 });
295
+ const next = logical.nextCursor
296
+ ? await reader.readPage({ mode: "logical", limit: 100, cursor: logical.nextCursor })
297
+ : null;
298
+
299
+ // Diagnostic view: preserves physical replay entries instead of deduplicating them.
300
+ const physical = await reader.readPage({ mode: "physical", limit: 100 });
301
+ ```
302
+
303
+ Logical mode is the normal consumer view and deduplicates the bounded crash-replay
304
+ window. Physical mode exposes what is actually present in the segment files. Reader
305
+ cursors describe a stable snapshot and fail if required segments have disappeared or
306
+ been truncated.
307
+
308
+ There is one active owner per agent database and one active writer per audit destination.
309
+ Opening either concurrently from another process fails with `AgentDatabaseInUseError` or
310
+ `AuditLogDestinationInUseError`; this does not restrict concurrent conversations within
311
+ the owning `Agent`. A stream whose identity, ordering, or synced history conflicts with
312
+ SQLite fails closed with `AuditLogIdentityConflictError` or
313
+ `AuditLogHistoryMissingError` instead of silently starting a new history.
314
+
315
+ The initial Agent audit design deliberately accepts these constraints:
316
+
317
+ - Configuration is fixed while the agent is open. Close and reopen to change it.
318
+ - Every numbered segment remains part of the logical stream; automatic audit retention
319
+ and deletion are not provided.
320
+ - Time-based rotation is checked when an entry is delivered, so an idle segment is not
321
+ rotated merely because time passed.
322
+ - Disabling audit and later enabling it creates a new stream from that point; canonical
323
+ history is not backfilled.
324
+ - JSONL is plaintext and not cryptographically signed. Protect, archive, and retain the
325
+ destination according to application policy.
326
+ - Durability currently favors an entry-level sync boundary. Raw protocol capture can
327
+ therefore create backlog under sustained high-volume streaming; exclude
328
+ `session/update` or use metadata/semantic capture unless exact raw traffic is required.
329
+
330
+ SQLite remains the source used for conversation recovery. Audit segments are an
331
+ independent operational history and are not imported to reconstruct provider sessions.
332
+ This API is distinct from the legacy `AuditLogReader` documented under
333
+ “Configure transcripts” below, which reads per-`AgentSession` v1 audit files.
334
+
335
+ The minimal end-to-end executable example is
336
+ [`smoke-tests/end-to-end/index.ts`](./smoke-tests/end-to-end/index.ts). It sends `"hi"`
337
+ through an ACP harness and independently queries SQLite to assert that the canonical
338
+ user-message row contains `"hi"`:
339
+
340
+ ```bash
341
+ bun smoke-tests/end-to-end/index.ts
342
+ ```
343
+
344
+ By default it owns and removes a temporary directory. Set `ACP_TEST8_DATA_DIR` to retain
345
+ the database at a caller-selected location for inspection:
346
+
347
+ ```bash
348
+ ACP_TEST8_DATA_DIR=./smoke-tests/test8-test/data \
349
+ bun smoke-tests/end-to-end/index.ts
350
+ ```
351
+
352
+ The smoke scenario uses a 64 MiB audit segment limit by default, so a short run may
353
+ produce only one segment. To assert rotation with a deliberately small test threshold,
354
+ set `ACP_TEST8_AUDIT_MAX_BYTES=1024`. This is a test override, not a suggested
355
+ production setting.
356
+
357
+ The current smoke scenario defaults to Codex because its second process opening verifies
358
+ that the provider thread remembers prior conversation context. It may use credentials and
359
+ consume model tokens.
360
+
361
+ Provider-session identity and persisted history are always hard assertions. Exact semantic
362
+ recall is also required by default for Codex, while other adapters report a warning because
363
+ their selected model may ignore correctly loaded context. Set
364
+ `ACP_TEST8_REQUIRE_SEMANTIC_RECALL=1` to require the exact recall assertion for any adapter,
365
+ or `0` to make it observational.
366
+
367
+ ### SQLite metering persistence
368
+
369
+ SQLite-backed agents always persist the bounded metering state needed to restore lifetime
370
+ totals and the active provider-counter baseline. By default they also retain every complete
371
+ `OperationMeteringRecord` locally:
372
+
373
+ ```ts
374
+ const agent = await Agent.open({
375
+ persistence: { kind: "sqlite", path: "/state/atlas.sqlite" },
376
+ adapters: { codex: ADAPTERS.codex },
377
+ defaultAdapterId: "codex",
378
+ meteringPersistence: {
379
+ meteringRecords: "all", // default
380
+ },
381
+ });
382
+
383
+ const page = await agent.persistence.metering.list(conversationId);
384
+ const records = page.records;
385
+ const state = await agent.persistence.metering.state(conversationId);
386
+
387
+ // Internal work not caused by a conversation has a separate agent-level scope.
388
+ const internalState = await agent.persistence.metering.agentState(agent.id);
389
+ const internalRecords = await agent.persistence.metering.listAgent(agent.id);
390
+ ```
391
+
392
+ Consumers with a separate authoritative billing store can omit the detailed local history:
393
+
394
+ ```ts
395
+ meteringPersistence: {
396
+ meteringRecords: "none",
397
+ }
398
+ ```
399
+
400
+ `"none"` still writes a minimal operation marker for idempotency, adds the independently
401
+ configured conversation-timeline reference, and always advances the bounded restoration
402
+ state. It only omits the full serialized metering record. Continue to
403
+ consume `result.metering` or `metering_recorded` notifications when delivering records to
404
+ an external billing repository.
405
+
406
+ ### Run durable internal inference
407
+
408
+ `internalInference` is agent-scoped background model work for checkpoint, recovery, and
409
+ identity features. It is not a participant turn and does not write its prompt or output
410
+ into the visible transcript. Attempts are queued in SQLite, leased to one worker, retried
411
+ with a new `aii-…` attempt ID, observable, cancellable, and resumed when the database is
412
+ reopened.
413
+
414
+ Consumers register versioned strategies. A strategy derives a prompt from durable input,
415
+ then validates and publishes the result inside the transaction that completes the attempt.
416
+ The generic runtime deliberately does not define checkpoint or identity artifact schemas.
417
+
418
+ ```ts
419
+ import {
420
+ ADAPTERS,
421
+ Agent,
422
+ HarnessInternalInferenceRuntime,
423
+ type InternalInferenceStrategy,
424
+ } from "@qlairoslabs/acp-client";
425
+
426
+ const strategy: InternalInferenceStrategy<{ throughSequence: number }> = {
427
+ strategyId: "checkpoint-v1",
428
+ purpose: "conversation_checkpoint",
429
+ version: 1,
430
+ validatePayload(value) {
431
+ const sequence = (value as { throughSequence?: unknown }).throughSequence;
432
+ if (!Number.isSafeInteger(sequence)) throw new Error("invalid sequence");
433
+ return { throughSequence: sequence as number };
434
+ },
435
+ async prepare(context, input) {
436
+ const page = await context.persistence.messages.list(context.attempt.agentConversationId!, {
437
+ throughSequence: input.throughSequence,
438
+ });
439
+ return {
440
+ prompt: `Summarize this conversation. Do not use tools.\n${JSON.stringify(page.messages)}`,
441
+ };
442
+ },
443
+ async complete(context, result) {
444
+ // Validate and write the artifact through context.persistence here.
445
+ return {
446
+ internalInferenceId: result.internalInferenceId,
447
+ rootInternalInferenceId: context.attempt.rootId,
448
+ internalSessionId: result.internalSessionId,
449
+ purpose: context.attempt.purpose,
450
+ completedAt: new Date().toISOString(),
451
+ };
452
+ },
453
+ classifyError() {
454
+ return { kind: "retryable", code: "provider_failure" };
455
+ },
456
+ };
457
+
458
+ const runtime = new HarnessInternalInferenceRuntime({
459
+ controllerConfig: (request) => ({
460
+ adapter: ADAPTERS.codex,
461
+ adapterId: request.adapterId,
462
+ cwd: process.cwd(),
463
+ }),
464
+ });
465
+
466
+ const agent = await Agent.open({
467
+ persistence: { kind: "sqlite", path: "/state/atlas.sqlite" },
468
+ adapters: { codex: ADAPTERS.codex },
469
+ defaultAdapterId: "codex",
470
+ internalInference: {
471
+ runtime, // optional; omit to use the agent's harness adapter and runtime defaults
472
+ strategies: [strategy],
473
+ adapter: "same",
474
+ maxConcurrency: 1,
475
+ retry: { maxAttempts: 3, backoffMs: [1_000, 10_000, 60_000] },
476
+ retention: { retain: 100 },
477
+ },
478
+ });
479
+
480
+ const run = await agent.internalInferences!.enqueue({
481
+ purpose: "conversation_checkpoint",
482
+ agentConversationId: conversation.agentConversationId,
483
+ input: {
484
+ strategyId: "checkpoint-v1",
485
+ version: 1,
486
+ payload: { throughSequence: 42 },
487
+ },
488
+ requestedThroughSequence: 42,
489
+ });
490
+
491
+ const unsubscribe = run.subscribe(({ snapshot }) => {
492
+ console.log(snapshot.stage, snapshot.status);
493
+ });
494
+ const completion = await run.result;
495
+ unsubscribe();
496
+ ```
497
+
498
+ The harness runtime starts a fresh disposable provider session and inherits the supplied
499
+ launcher, environment, working directory, and container boundary. Empty MCP/client
500
+ handlers and cancelled permission requests do not disable filesystem or terminal tools
501
+ built into the harness; enforce that boundary with the launcher or container when needed.
502
+ Custom runtimes should call `lifecycle.sessionStarted(...)` before prompting so strict
503
+ metering preflight can run. Completed custom results are metered as a fallback.
504
+
505
+ ### Generate recovery checkpoints and recover missing provider sessions
506
+
507
+ Enable `checkpointing` on an SQLite-backed `Agent` to generate rolling continuation
508
+ summaries outside the visible provider thread:
509
+
510
+ ```ts
511
+ const agent = await Agent.open({
512
+ persistence: { kind: "sqlite", path: "/state/atlas.sqlite" },
513
+ adapters: { codex: ADAPTERS.codex },
514
+ defaultAdapterId: "codex",
515
+ checkpointing: {
516
+ schedule: {
517
+ milestones: [1, 5, 10, 15, 30, 50],
518
+ everyAfterMilestones: 50,
519
+ },
520
+ recovery: {
521
+ onLoadFailure: "recover", // default
522
+ maxTailMessages: 100,
523
+ },
524
+ },
525
+ });
526
+ ```
527
+
528
+ Checkpoint generation is durably enqueued after the configured successful response counts;
529
+ the visible prompt does not wait for the summary model call. Each new checkpoint combines
530
+ the previous summary with canonical records added since its covered message boundary.
531
+ Checkpoint artifacts and their `conversation_checkpoint` timeline actions are committed in
532
+ the same transaction as the generating internal inference.
533
+
534
+ ```ts
535
+ const checkpoint = await agent.checkpointing!.latest(conversationId);
536
+
537
+ // Explicitly request a checkpoint outside the configured milestones.
538
+ await agent.checkpointing!.request(conversationId);
539
+ ```
540
+
541
+ When `conversations.open()` cannot load the recorded provider session and the error is
542
+ classified as a missing session, the agent creates a fresh provider thread and privately
543
+ seeds it from the latest checkpoint plus canonical messages written after that checkpoint.
544
+ The seed is metered as `conversation_recovery` and recorded as a native action; it is not a
545
+ user or assistant transcript message.
546
+
547
+ ```ts
548
+ const opened = await agent.conversations.open(conversationId, {
549
+ onRecoveryProgress(event) {
550
+ console.log(event.stage, event.checkpointId);
551
+ },
552
+ });
553
+
554
+ if (opened.providerSession === "recovered") {
555
+ console.log(opened.recovery);
556
+ }
557
+ ```
558
+
559
+ ACP does not standardize missing-session errors. The default classifier recognizes common
560
+ “session not found,” “does not exist,” and missing Codex rollout-path failures. A harness
561
+ with different errors can provide `recovery.isMissingProviderSession(error)`. Authentication,
562
+ network, and arbitrary internal failures remain fatal by default. Set `onLoadFailure:
563
+ "error"` to disable automatic recovery.
564
+
565
+ Checkpointing requires message capture at `"content"` or `"raw"`. The checkpoint is a
566
+ continuation aid, not the authoritative transcript: complete messages and other records
567
+ remain independently queryable from SQLite.
568
+
569
+ ### Share a basic identity across conversations
570
+
571
+ Checkpoint-backed identity is opt-in. It privately delivers knowledge from an agent's
572
+ other conversations to each provider thread, using the existing per-conversation
573
+ checkpoint summaries and messages after those checkpoints:
574
+
575
+ ```ts
576
+ const agent = await Agent.open({
577
+ persistence: { kind: "sqlite", path: "/state/atlas.sqlite" },
578
+ adapters: { codex: ADAPTERS.codex },
579
+ defaultAdapterId: "codex",
580
+ checkpointing: {},
581
+ identity: {
582
+ kind: "checkpoint-backed",
583
+ maxContextChars: 32_000,
584
+ maxSourceChars: 8_000,
585
+ },
586
+ });
587
+ ```
588
+
589
+ The first prompt to a provider thread receives each other conversation's latest
590
+ checkpoint summary plus its uncovered messages. Later prompts receive only messages
591
+ not yet delivered to that thread. Successful prompts advance sparse, durable cursors;
592
+ failed prompts do not. A new provider thread gets a fresh identity view, while loading
593
+ the same provider thread reuses its cursors. The current conversation never receives
594
+ its own history through identity; normal provider continuity and recovery handle that.
595
+
596
+ The character budgets are hard limits, not claims that all agent knowledge fits. When
597
+ the backlog is too large, the runtime delivers an ordered prefix and leaves the rest
598
+ pending. It may request a checkpoint in the background to compress an oversized gap.
599
+ `identityConsistency: "through-current"` rejects a prompt whose available cross-
600
+ conversation messages cannot all fit; the default `"eventual"` permits partial delivery.
601
+ All non-deleted conversations are shared in v1, including conversations with different
602
+ users, so consumers should enable this only where such cross-conversation visibility is
603
+ appropriate. A custom `AgentIdentityRuntime` remains available for other policies.
604
+
605
+ ## Legacy direct and managed sessions
606
+
607
+ The remaining sections describe the compatibility `AgentSession` and
608
+ `SessionManager`/JSONL APIs. They remain useful when an application needs a transient
609
+ connection or the existing file-oriented persistence model.
610
+
59
611
  Interactive helpers are a separate entry point:
60
612
 
61
613
  ```ts