@qlairoslabs/acp-client 0.11.1 → 0.12.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 (80) hide show
  1. package/CHANGELOG-consumer-fixes.md +62 -0
  2. package/CHANGELOG-operation-lifecycle.md +64 -0
  3. package/CONSUMER_GUIDE.md +288 -12
  4. package/MIGRATION-0.10-to-0.12.md +189 -0
  5. package/README.md +6 -3
  6. package/package.json +5 -2
  7. package/src/adapters.ts +8 -1
  8. package/src/agent/adoption/replay.ts +1 -0
  9. package/src/agent/config.ts +4 -0
  10. package/src/agent/conversation-manager.ts +178 -150
  11. package/src/agent/error-record-writer.ts +77 -0
  12. package/src/agent/persisted-lifecycle.ts +152 -35
  13. package/src/agent/record-capture.ts +18 -18
  14. package/src/agent-adapter-registry.ts +2 -0
  15. package/src/agent-client.ts +9 -3
  16. package/src/agent-conversation-contracts.ts +6 -0
  17. package/src/agent-conversation-owner.ts +31 -6
  18. package/src/agent-conversation-presentation.ts +12 -1
  19. package/src/agent-conversation-queue.ts +3 -2
  20. package/src/agent-session.ts +535 -94
  21. package/src/agent.ts +46 -23
  22. package/src/audit/config.ts +4 -0
  23. package/src/audit/projection.ts +3 -0
  24. package/src/checkpointing/recovery.ts +12 -0
  25. package/src/checkpointing/strategy.ts +2 -0
  26. package/src/client.ts +132 -30
  27. package/src/controller.ts +116 -7
  28. package/src/degraded/pty-client.ts +25 -1
  29. package/src/index.ts +17 -0
  30. package/src/internal-inference/config.ts +7 -0
  31. package/src/internal-inference/contracts.ts +3 -0
  32. package/src/internal-inference/coordination/handles.ts +11 -2
  33. package/src/internal-inference/coordination/manager.ts +20 -3
  34. package/src/internal-inference/index.ts +2 -0
  35. package/src/internal-inference/persistence/records.ts +3 -1
  36. package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
  37. package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
  38. package/src/internal-inference/runtime/harness-runtime.ts +19 -2
  39. package/src/media/acp.ts +118 -0
  40. package/src/media/capture.ts +15 -0
  41. package/src/media/content.ts +142 -0
  42. package/src/media/files.ts +28 -0
  43. package/src/media/parts.ts +145 -0
  44. package/src/media/pending.ts +51 -0
  45. package/src/media/redact.ts +14 -0
  46. package/src/media/store.ts +127 -0
  47. package/src/metering/provider.ts +8 -1
  48. package/src/operations/activity-tracker.ts +31 -0
  49. package/src/operations/contracts.ts +63 -0
  50. package/src/operations/errors.ts +31 -0
  51. package/src/operations/index.ts +6 -0
  52. package/src/operations/stale-policy.ts +51 -0
  53. package/src/operations/supervisor.ts +209 -0
  54. package/src/operations/timers.ts +12 -0
  55. package/src/out-of-band-messages.ts +49 -32
  56. package/src/persistence/audit-runtime.ts +14 -2
  57. package/src/persistence/backend.ts +108 -12
  58. package/src/persistence/error-records.ts +27 -0
  59. package/src/persistence/index.ts +8 -0
  60. package/src/persistence/presentation.ts +9 -1
  61. package/src/persistence/projection.ts +20 -0
  62. package/src/persistence/records.ts +45 -6
  63. package/src/persistence/sqlite-backend.ts +207 -16
  64. package/src/persistence/sqlite-conversation-records.ts +31 -4
  65. package/src/persistence/sqlite-files.ts +95 -0
  66. package/src/persistence/sqlite-media-store.ts +67 -0
  67. package/src/persistence/sqlite-schema.ts +86 -10
  68. package/src/persistence/state-runtime.ts +2 -0
  69. package/src/persistence/timeline-reconcile.ts +21 -4
  70. package/src/persistence/transcript-reader.ts +11 -4
  71. package/src/persistence/transcript-runtime.ts +105 -12
  72. package/src/repl/repl.ts +1 -1
  73. package/src/response.ts +40 -8
  74. package/src/steering/combine.ts +11 -4
  75. package/src/steering/contracts.ts +14 -4
  76. package/src/steering/controller.ts +96 -21
  77. package/src/steering/index.ts +1 -0
  78. package/src/transport/acp-transport.ts +18 -7
  79. package/src/types.ts +7 -0
  80. package/src/updates.ts +4 -4
@@ -0,0 +1,62 @@
1
+ # Consumer fixes (from the 2026-10-13 agents-core requirements)
2
+
3
+ Released in 0.12.0. Upgrading from 0.10.x: see `MIGRATION-0.10-to-0.12.md`.
4
+
5
+ - **Messages made of parts.** Ordered text, named paste, image, audio and file inputs; copy/link
6
+ modes, capability checks and configurable automatic thresholds. Structured media output,
7
+ out-of-band media, independent `capture.media`, SQLite schema 16 blob storage, reusable refs,
8
+ byte deletion, and separate shared-file metadata listing/search. Canonical protocol/debug
9
+ capture redacts inline bytes. Legacy positional attachments remain no-keep copies, mapped
10
+ by MIME type; legacy JSONL stores descriptive media lines. Shared directories reach ACP
11
+ session creation/loading. Out-of-band media waits in memory until delivered (unkept bytes are
12
+ never written), and media an agent cannot take, or whose bytes are gone, is named instead of
13
+ failing the turn. See the consumer guide for store and out-of-band delivery contracts.
14
+
15
+
16
+ - **Grok Build preset.** `ADAPTERS.grok` launches xAI's Grok Build over ACP
17
+ (`grok --no-auto-update agent stdio`). A Grok session that no longer exists is recognised as
18
+ missing, so checkpoint recovery applies to it.
19
+ - **Additional directories only when advertised.** The client sends `additionalDirectories` only to an
20
+ agent that advertises `sessionCapabilities.additionalDirectories`, as ACP requires; otherwise they
21
+ are left out with a warning (`additional_directories_unsupported`). Grok refused session requests
22
+ that carried them.
23
+ - **Message boundaries.** A new tool call now ends the assistant message before it, also when the
24
+ agent sends no message ids (before, message → tool → message was one message). Tool updates
25
+ do not split. Applies to the live `result.messages` and to stored messages.
26
+ - **Message completion is stored when it happens.** Agent-owned conversations record a message
27
+ `completed` when the next message or a tool call begins, with that time, instead of completing
28
+ every message of the turn at its end with one shared timestamp. Only the turn's last message
29
+ takes the turn's outcome; messages that ended before a failure or cancel stay `completed`.
30
+ - **Item times.** `ConversationTimelineItem` has `startedAt` (first revision) and `updatedAt`
31
+ (latest). Presentation items have `startedAt` and `updatedAt`; their `timestamp` is now a
32
+ deprecated alias of `updatedAt`.
33
+ - **No-op settings are not recorded.** `setConfig` with the value the option already has (and,
34
+ with a transcript, that is already the explicit restoration target) sends, records and emits
35
+ nothing.
36
+ - **Every record carries its operation.** Records have a typed `operationId`: the library
37
+ operation that wrote them (turn, internal inference or recap, setting change, mode change,
38
+ handoff). Appended out-of-band messages are standalone records without an operation id. Tool calls, permissions, thinking, activity, configuration, mode changes and protocol
39
+ lines now carry it as messages already did. A tool call still running when its turn ends is
40
+ recorded `failed` in that turn; an update for it in a later turn is recorded under the later
41
+ turn. Records outside an operation have none. `records.list(id, { operationId })` filters by it.
42
+ SQLite agent schema 15 recovers it on older records from their record ids.
43
+ - **Cancellations are recorded.** A new record kind, `cancellation` (SQLite and JSONL), with
44
+ `requested` (reason: `steer`, `interrupt`, `stalled`, `stop`, `abort`) and `resolved`
45
+ (outcome: `acknowledged`, `forced`, `too_late`, `failed`) revisions under the cancelled
46
+ operation's id. After a reload a turn can still be shown as stopped or redirected. Stopping a
47
+ conversation mid-turn records reason `stop`. SQLite schema 15
48
+ rebuilds `conversation_records` to admit the kind. Audit capture key `cancellation`
49
+ (default `metadata`); JSONL audit logs write it too (`t: "cancellation"`).
50
+ - **Timeline items are scoped by operation.** `reconcileConversationTimeline` keys tool call,
51
+ permission, thinking and activity items by the record's `operationId`, so two turns that reuse a
52
+ provider id stay two items. Items whose records carried `operationId` in their metadata keep their
53
+ ids; the others (tool calls, for example) get new ids, so a consumer that stored timeline item ids
54
+ sees them change once.
55
+ - **Transcript writes are serialized.** A JSONL transcript and its audit log run their writes one at
56
+ a time. Before, a cancellation record written while an internal prompt finished could claim the
57
+ same sequence as the prompt's reply and leave the transcript refusing every later write.
58
+ - **History pages by agent messages.** `records.listRecent(id, { agentMessages: N })` returns N
59
+ agent messages per page with the activity that led to each, cut right after an agent message,
60
+ with every record on the page where its item began. `fold: true` returns timeline items,
61
+ `detail: "summary"` leaves out tool calls' input and output (`records.get` returns them), and
62
+ `limit` caps the page (`truncated`). Without these options `listRecent` is unchanged.
@@ -0,0 +1,64 @@
1
+ # Operation lifecycle
2
+
3
+ Released in 0.12.0 (it landed on `beta` while the package version still read 0.11.2).
4
+
5
+ Provider turns, internal inference and adoption recaps now expose their current operation stage and
6
+ last output time. Silent inference requests fail with `OperationStalledError` (`code: stalled`), carrying
7
+ the silence phase, captured messages, operation ID and metering record. Agent-owned conversations
8
+ persist an error record and mark any partial assistant reply failed.
9
+
10
+ Cancellation answers pending permissions as cancelled, aborts the handler's optional second
11
+ `AbortSignal` argument, resends the notification halfway through the adapter's grace period, and
12
+ force-stops an unresponsive process. Cancelled prompt results expose `cancel: acknowledged | forced`.
13
+ Interrupt and steer results keep their normal cancelled behavior after a forced stop.
14
+
15
+ The next provider operation reconnects automatically after an exit or forced stop. It first loads the
16
+ same session; Agent-owned conversations can recover from a checkpoint under their existing recovery
17
+ policy, preserving the conversation object. Observe `state.providerConnection` and
18
+ `provider_reconnected` (`via: loaded | recovered`). Consumers that previously retired a disconnected
19
+ conversation can now keep it and send the next prompt normally. A failed reconnect is retryable on the
20
+ next operation. When the provider no longer has the session, the conversation applies the rule it
21
+ applies at open: Agent-owned checkpoint recovery, SessionManager continuation strategies, or
22
+ `providerSession.onFailure` without transcript persistence (`"new"` reports `via: fresh`). With nothing
23
+ left, the conversation reports `continuation_unavailable` instead of failing every prompt.
24
+ SessionManager's manual recovery after the library process itself dies is unchanged.
25
+
26
+ After a turn the provider received ends in a stall or error, explicit queue messages are held (a prompt
27
+ that fails before reaching the provider holds nothing). Pending steers up to the next queued message run
28
+ after recovery as one prompt with `via: stall`; the next consumer turn that completes releases the held
29
+ queue (internal prompts such as a recap do not). Inspect `state.pendingHold`,
30
+ `pendingMessages[].heldBy`, and `message_held` / `message_released` events. With `busyDelivery: queue`,
31
+ every prompt sent after a failure joins the hold, so the conversation stays held until you send one prompt
32
+ with `delivery: steer` (or withdraw). Withdrawal still works.
33
+
34
+ Configure `AgentConfig.operationLifecycle` (or the same field on a detached conversation) with
35
+ `turns`, `internalInference`, and `recap`. First/next-output limits default to 120/180 seconds;
36
+ `false` disables an individual inference limit. Tools and permissions explain silence and suspend
37
+ those limits; optional `toolMs` bounds a tool. Adapter `cancelGraceMs` defaults to 30 seconds.
38
+ Control requests (initialize, new, load, list, delete, config, authenticate) have no deadline: they end when the
39
+ harness answers or the process exits.
40
+
41
+ Codex measurements on 2026-10-18 (three throwaway sessions, default model): first protocol output
42
+ 8–12ms, longest observed tool-free silence 3260–4128ms, acknowledged cancel 32–72ms, and session load
43
+ 514–621ms. Claude (three sessions): first output 3–15ms, silence 1989–4296ms, cancel 4–5ms, and load 828–848ms. These are short-history measurements and do not cover automatic compaction; conservative
44
+ defaults are retained. See `smoke-tests/test13-operationLifecycle/` for reproducible scenarios and results.
45
+
46
+ Known measurement gaps: OpenCode's default upstream refused ACP model calls under its free-tier
47
+ policy. Codex's permission smoke prompt did not generate a native permission request; the mock
48
+ permission scenario verifies cancellation and handler aborts. Initialization excludes launcher
49
+ preparation; downloads inside a spawned installer command still count unless moved into launcher
50
+ preparation. Turn-ending persistence beyond the existing message status remains the separate
51
+ requirement 3 referenced by the lifecycle spec.
52
+
53
+ Degraded PTY mode observes raw terminal output for visibility and keeps output silence deadlines
54
+ disabled by default because it has no ACP tool/permission signals. Explicit limits still apply there,
55
+ and cancellation remains bounded. Handoff operations use the target adapter's cancellation grace.
56
+
57
+ A separate Codex run with 24 additional short turns replayed 53 updates in 554ms (maximum replay gap
58
+ 535ms, including initial wait). No automatic-compaction stress run was performed.
59
+
60
+ `AgentConversation.listSessions()` is deprecated. It merges the library's catalog with the harness's
61
+ session list into one `MergedSession` shape, and when the harness listing fails it returns the catalog
62
+ half without saying so. Use `agent.conversations` for conversations and
63
+ `agent.conversations.listProviderSessions()` for harness sessions; that one reports listing failures.
64
+ A failed harness listing in `listSessions()` now throws instead of returning the catalog half silently.
package/CONSUMER_GUIDE.md CHANGED
@@ -131,6 +131,104 @@ not interpret its fields. The separate envelope `metadata` field still carries o
131
131
  library-owned operation correlation. A raw audit capture includes consumer metadata;
132
132
  content/metadata audit capture omits it.
133
133
 
134
+ ### Messages made of parts
135
+
136
+ `prompt({ parts })` accepts ordered `MessagePart` values. An optional `text` is a leading text
137
+ part; `pasted` retains its optional name and is sent as text. The text-only `result.text` view
138
+ and positional calls remain available. A response containing media also has ordered
139
+ `result.messages[i].parts`; streaming `onResponseChunk` exposes each non-text `part`.
140
+
141
+ ```ts
142
+ await conversation.prompt({
143
+ parts: [
144
+ { kind: "text", text: "Review this plot and these notes." },
145
+ { kind: "image", path: "plot.png" },
146
+ { kind: "pasted", name: "notes", text: "The red line is the baseline." },
147
+ { kind: "file", path: "/shared/report.pdf", mode: "link" },
148
+ ],
149
+ });
150
+ ```
151
+
152
+ Media kinds are `image`, `audio`, and `file`. Each input has exactly one source: `data:
153
+ Uint8Array`, `path` (relative to the conversation's working directory, absolute, or a `file://`
154
+ URI), or `ref` (a previously kept copy). MIME types are inferred from file paths; supply the
155
+ MIME type for byte-array inputs when known. SVG is a `file` and is embedded as markup, retaining
156
+ its MIME type. Text files are ACP embedded text resources; other files use blob resources.
157
+ An embedded copy's uri is `attachment:///<name>`: it names the copy, not a file the agent could
158
+ open. A UI rendering SVG must sanitize it.
159
+
160
+ Some adapters drop kinds they advertise. Claude's (`claude-agent-acp`, checked at 0.85.0) keeps
161
+ embedded text files but silently drops binary ones (PDFs, any blob), although it advertises
162
+ `embeddedContext`, so the model never sees them and nothing fails. Send binary files to Claude as
163
+ links (`mode: "link"`, a file it can reach): its Read tool opens PDFs. Whether a model reads a
164
+ kind also depends on the model: OpenCode on DeepSeek V4.1 Flash has no PDF input.
165
+
166
+ `mode: "copy"` sends the actual content. `keep: false` records name, MIME type, size and SHA-256
167
+ without retaining bytes; the default keeps bytes when a store is available. `mode: "link"`
168
+ requires a path and sends an absolute `file://` resource link. It records a pointer, so later
169
+ edits/deletion of the original affect what history can display. The library does not open a
170
+ link: one whose file cannot be read is still sent, with no size. `keep` is invalid on links.
171
+ A link the agent sends without a size is recorded without one.
172
+ `record: false` sends a part without recording it and cannot be combined with `keep`.
173
+
174
+ With no mode, path sources use copies up to 100,000 bytes for files, 3,750,000 for images and
175
+ 5,000,000 for audio; larger paths use links. Configure these byte thresholds on the Agent with
176
+ `media: { thresholds: { file, image, audio } }`. Byte-array and ref sources remain copies.
177
+ There is no library size ceiling. Provider errors surface to the caller. Unsupported explicit
178
+ copies are refused using the agent's prompt capabilities; an automatic path source falls back
179
+ to a link. PTY mode refuses media parts.
180
+
181
+ Declare shared directories with `conversationDefaults: { additionalDirectories: ["/shared"] }`
182
+ or a conversation's `runtime.additionalDirectories`. They are sent only to an agent that advertises
183
+ `sessionCapabilities.additionalDirectories` (otherwise left out, with a warning). They reach ACP session creation/load;
184
+ the harness applies its own permissions. The library does not restrict pointers. A harness on
185
+ another machine or in an isolated container needs a shared mount or a copy.
186
+
187
+ SQLite schema 16 stores kept blobs separately from message rows in the same database and
188
+ transaction. History and audit records contain refs/URIs and metadata. Ordinary text messages
189
+ remain strings; mixed messages use `PersistedContentBlock[]`, including `media` and `pasted`.
190
+ Old inline image/resource blocks can still be read; migration rebuilds structured message
191
+ search text and its FTS index without old inline bytes or refs. Raw canonical protocol capture and debug
192
+ prompt logs redact inline media; a consumer's explicitly requested `wire` callback is verbatim.
193
+
194
+ ```ts
195
+ const agent = await Agent.open({
196
+ // ...persistence, adapters, and other settings...
197
+ capture: { message: "content", media: "metadata" },
198
+ // media: { store: yourMediaStore }, // optional MediaStore override
199
+ });
200
+
201
+ const store = agent.media.store ?? agent.persistence.media;
202
+ const saved = await store?.get(ref); // { ref, info, data } or null when removed
203
+ await conversation.prompt({ parts: [{ kind: "image", ref }] });
204
+ await agent.deleteMedia(ref); // removes bytes; history retains the dangling ref
205
+ await agent.deleteMediaForConversation(conversation.id);
206
+
207
+ const files = await agent.persistence.files?.search({
208
+ text: "plot", agentConversationId: conversation.id, kind: "image", minSize: 1,
209
+ });
210
+ ```
211
+
212
+ `capture.media` is `none`, `metadata`, or `content` (default), independently of message text.
213
+ The conversation persistence resolver can override it, and a part's own `record`/`keep` wins.
214
+ Checkpointing still summarizes text. A backend without `media` and no override defaults to
215
+ metadata; explicit `keep: true` is refused. The older SessionManager/AgentSession JSONL
216
+ transcript records text and descriptive part lines, with no media store.
217
+
218
+ A `MediaStore` implements async `put(bytes, info) -> ref`, `get(ref)`, `delete(ref)` and
219
+ `list(owner)`. `get` returns `{ ref, info, data }` or null; `list` returns `{ ref, info }`
220
+ entries. Preserve all `MediaInfo` fields. Separate stores cannot share the record transaction: failed
221
+ writes stop dispatch, and `list(owner)` supports orphan cleanup. Reusing a kept ref within
222
+ its conversation reuses bytes; another conversation gets a new copy. Copies record SHA-256
223
+ but are not deduplicated. Clearing records deletes SQLite media; the Agent clear API also
224
+ cleans an overridden store. Soft deletion retains media.
225
+
226
+ `files.list` and `files.search` browse media metadata, including unkept/deleted copies and
227
+ links, with optional conversation, name, kind, MIME type and size filters. They accept `limit`
228
+ and `cursor`; response revisions are folded. Message search covers text and pasted text,
229
+ without indexing media names, refs or bytes. Offset file cursors can shift under concurrent
230
+ inserts. Custom backends can supply the optional `files` repository.
231
+
134
232
  SQLite keeps ordering and type-specific content separate. `conversation_records` is a
135
233
  narrow canonical envelope containing the conversation-local sequence, kind, timestamp,
136
234
  operation correlation, and optional metadata. Every envelope has exactly one typed detail
@@ -200,7 +298,64 @@ const older = first.olderCursor
200
298
  if (older) items = reconcileConversationTimeline(items, older.records);
201
299
  ```
202
300
 
301
+ Paging by records cuts turns anywhere: a tool call is several records, so a page can start
302
+ mid-turn. To page by what the conversation shows, count agent messages instead:
303
+
304
+ ```ts
305
+ const page = await agent.persistence.records.listRecent!(conversation.id, {
306
+ agentMessages: 50, // each page: 50 agent messages and the activity that led to each
307
+ fold: true, // timeline items instead of records
308
+ detail: "summary", // tool calls without input and output
309
+ });
310
+ let items = page.items;
311
+ // Expanding a step: its full record merges into the summary item.
312
+ const full = await agent.persistence.records.get(step.current.recordId);
313
+ items = reconcileConversationTimeline(items, [full!]);
314
+ ```
315
+
316
+ - The cut goes right after an agent message (out-of-band appends count), so a page usually
317
+ begins with a turn's user message, and activity after the newest message (a running turn)
318
+ stays on the newest page.
319
+ - A record goes to the page where its item's first revision falls. A page holds every revision
320
+ of its items, including later ones up to the snapshot, and none of another page's: a message
321
+ that completed after the next tool started is not split across pages.
322
+ - `limit` caps the page (records, or items when folded; default 2000). A page that reaches it
323
+ ends at a whole item with `truncated: true`, and `olderCursor` continues from there.
324
+ - `fold: true` returns `ConversationTimelineItem`s; live records still merge with
325
+ `reconcileConversationTimeline(items, records)`. With `detail: "summary"` an item keeps two
326
+ revisions, its first (its start) and its merged current (under its latest revision's id),
327
+ so it reconciles like any other item.
328
+ - `detail: "summary"` also works on records. The step title is the harness's `name`, which
329
+ varies by harness; `records.get` returns the input and output.
330
+ - Without `agentMessages`, `fold` or `detail`, `listRecent` is unchanged. A cursor is bound to
331
+ its unit: a record-paging cursor is refused when paging by agent messages, and the reverse.
332
+
203
333
  Every physical record has a stable `recordId` and a conversation-local `sequence`.
334
+ `operationId` says which library operation wrote it: a turn (`result.operationId`), an
335
+ internal inference or recap, a setting change, a mode change, or a handoff. Appended out-of-band messages are standalone records
336
+ without an operation id. Every record of one
337
+ operation shares it, so a turn's messages, tool calls, permissions and thinking can be grouped
338
+ without inferring turns from their position; `sequence` gives the order. A tool call still
339
+ running when its turn ends is recorded `failed` in that turn; if the harness reports it later, that
340
+ update is recorded under the turn it arrived in, as a separate timeline item. Protocol lines
341
+ carry the operation that sent them: a handoff's own lines its id, the lines of its summary, seed
342
+ or target prompt that prompt's id (`<handoffId>:summary`, `:seed`, `:target`); a recap's or a
343
+ recovery seed's lines theirs. Records written outside any operation (protocol lines while
344
+ connecting) have none. Operations can interleave:
345
+ a message appended during a turn sits inside the turn's sequence range, so group by
346
+ `operationId`, not by range. Timeline items for tool calls, permissions, thinking and activity are
347
+ keyed within their operation, so a provider id reused by a later turn is a new item.
348
+ A cancelled operation records why and how in a `cancellation` record (two revisions under one
349
+ `cancellationId`, carrying the cancelled operation's `operationId`): `requested` with its
350
+ `reason` (`steer`: a message sent mid-turn; `interrupt`: Stop; `stalled`: the stale policy;
351
+ `stop`: the conversation was stopped), then `resolved` with its `outcome` (`acknowledged`,
352
+ `forced` when the process had to be killed, `too_late` when the turn finished first, or
353
+ `failed`). So after a reload a client can still show a turn as "Stopped" or "Redirected"; for
354
+ a steer, the redirecting message is the next turn's. It describes the cancellation, not the
355
+ mechanism (ACP `session/cancel`). JSONL transcripts and audit logs write the same record
356
+ (`t: "cancellation"`).
357
+ Databases from before schema 15 recover it for tool call, thinking, activity, permission,
358
+ configuration and mode-change records; `records.list(id, { operationId })` filters by it.
204
359
  The reconciliation helper keeps distinct messages separate and groups revisions of an
205
360
  assistant message, tool call, permission, thinking block, activity, or transition by its
206
361
  logical ID. Assistant snapshots take their position from the first streamed text; the
@@ -208,8 +363,17 @@ completed revision supplies their final content and status. Providers that expos
208
363
  message only in the final prompt result cannot supply an earlier position. Records
209
364
  written before schema version 11 have no such boundaries to reconstruct. The helper's
210
365
  items retain every revision, carry the latest merged fields in `current`, and sort by
211
- the earliest loaded sequence. Loading an older page may move an item to its true
212
- earlier position when its first revision arrives. Configuration, protocol, agent
366
+ the earliest loaded sequence. `startedAt` is when the item's first revision was written
367
+ (when a message began) and `updatedAt` when its latest was (also `current.timestamp`).
368
+ Loading an older page may move an item to its true
369
+ earlier position when its first revision arrives.
370
+
371
+ ACP has no "message finished" signal, so an assistant message ends when the next one begins:
372
+ a chunk with a different message id, or a new tool call (with or without ids; tool *updates*
373
+ do not split a message). That message is recorded `completed` at that moment, so a client
374
+ sees it finish as soon as the next text or tool appears. The turn's last message ends with
375
+ the turn and takes its outcome (`completed`, `cancelled` or `failed`); messages that ended
376
+ before a failure stay `completed`. The live `result.messages` uses the same boundaries. Configuration, protocol, agent
213
377
  actions, and metering references remain individual records unless they have an
214
378
  explicit logical identity; metering details are read from `persistence.metering`.
215
379
 
@@ -239,7 +403,8 @@ Preview paging follows conversation `updatedAt` order; that list may
239
403
  reorder as conversations advance, so consumers should refresh it rather than treat
240
404
  offset cursors as a frozen snapshot. `messages.list()` returns the latest visible
241
405
  revision per logical message; `records.list()` and `records.listRecent()` retain all
242
- physical revisions for timeline reconstruction and audit. `listRecent` and `listPreviews` are SQLite
406
+ physical revisions for timeline reconstruction and audit (except `listRecent` with `fold: true`
407
+ and `detail: "summary"`, which keeps two per item). `listRecent` and `listPreviews` are SQLite
243
408
  capabilities; custom persistence backends may not implement them.
244
409
 
245
410
  ### Live committed-record events
@@ -367,16 +532,27 @@ turn, in a `<messages-you-sent>` block between any identity preamble and
367
532
  - A recovery seed covers messages through `recoveredThroughSequence`, so they are not
368
533
  repeated after recovery. A loaded provider session is treated like one that never
369
534
  closed.
370
- - A turn that completes without an assistant message does not advance delivery, so its
371
- pending messages are repeated once more.
535
+ - SQLite commits a delivery cursor with a successful turn, including turns whose message
536
+ text is not captured.
372
537
  - The block is capped at `OUT_OF_BAND_PROMPT_MAX_CHARS`; the oldest messages are dropped
373
538
  first with an omission note. The transcript always keeps all of them.
374
539
 
375
540
  Other conversations of the same agent see the message through identity like any other
376
- canonical message. Appending requires `capture.message` of `"content"` or `"raw"`, since
377
- the provider could not be told otherwise; it rejects blank text and unknown or deleted
378
- conversations. Backends without `records.listRecent` scan the conversation's messages
379
- forward to find the last completed turn.
541
+ canonical message. Text-only appends require `capture.message` of `"content"` or `"raw"`;
542
+ media-only appends are supported under the independent media capture policy. An append rejects
543
+ empty input and unknown or deleted conversations. `appendAssistantMessage(id, { parts })` uses
544
+ the same part/store rules. Parts are accepted whatever the next turn's agent supports.
545
+
546
+ A message waits for the next successful turn. When its record can restore it (text captured,
547
+ every copy kept, no `record: false` part), it is delivered from the record. Otherwise its parts
548
+ wait in memory: unkept bytes are never written anywhere, and a failed turn keeps them for the
549
+ retry. After a restart such a message is delivered from its record, and a copy whose bytes were
550
+ not kept (or were deleted) is named instead, as `[image plot.png: not available]`; an unrecorded
551
+ part is gone. A copy the agent cannot take is named too (`[image plot.png: not supported by this
552
+ agent]`), so an out-of-band message never makes a turn fail. A PTY agent receives every media
553
+ part as such a line.
554
+ Custom backends can supply `outOfBandDelivery` to track completion independently of captured
555
+ text; otherwise delivery uses visible completed messages, scanning forward without `listRecent`.
380
556
 
381
557
  ### Agent audit log
382
558
 
@@ -564,6 +740,22 @@ into the visible transcript. Attempts are queued in SQLite, leased to one worker
564
740
  with a new `aii-…` attempt ID, observable, cancellable, and resumed when the database is
565
741
  reopened.
566
742
 
743
+ Each attempt runs in a fresh, disposable harness session that is stopped as soon as its prompt is answered. A harness
744
+ may start work of its own in that session which the answer does not wait for, and ACP gives the client no way to wait for
745
+ it: OpenCode names a session with a second request on a small model, started at the first prompt, and stopping the process
746
+ right after the answer can cut it off mid-stream (behind a gateway that is a cancelled, half-accounted request). So for
747
+ OpenCode the default runtime starts the disposable process with `OPENCODE_CONFIG_CONTENT` set to turn the title agent off,
748
+ for internal inference only: conversations are not touched, and an `OPENCODE_CONFIG_CONTENT` you already set (in
749
+ `conversationDefaults.env` or the process environment) is kept, with the title agent switched off inside it. With a
750
+ `launcher`, the variable is added to its `spawnEnv`; a launcher that starts the harness elsewhere (a container, a remote
751
+ host) must forward it. Set `internalInference: { suppressHarnessBackgroundWork: false }` to leave the harness as configured.
752
+ It has no effect with a custom `runtime`; see `withoutHarnessBackgroundWork` to apply it there.
753
+
754
+ A failed attempt keeps the original error for whoever awaits it, and records on the attempt (`failureDetails`) the
755
+ JSON-RPC code and the labels harnesses send in `data` (`service`, `errorName`, `providerCode`), nothing else of `data`. A
756
+ harness decides what its errors carry: OpenCode's ACP adapter, for example, sends the upstream message text but not the HTTP
757
+ status, gateway error code or request id, so those cannot be recovered here.
758
+
567
759
  Consumers register versioned strategies. A strategy derives a prompt from durable input,
568
760
  then validates and publishes the result inside the transaction that completes the attempt.
569
761
  The generic runtime deliberately does not define checkpoint or identity artifact schemas.
@@ -1008,7 +1200,9 @@ const answer = await note; // the turn that carried the message
1008
1200
  `withdraw()`. A prompt that does not have to wait runs immediately and `delivery` has no effect.
1009
1201
 
1010
1202
  Set the default for prompts that do not say, per Agent or per conversation. It is `"steer"` unless you
1011
- change it (before this was `"queue"`; set `busyDelivery: "queue"` to keep the old behaviour):
1203
+ change it (before this was `"queue"`; set `busyDelivery: "queue"` to keep the old behaviour). With `"queue"`
1204
+ as the default, a failed turn holds every later prompt until one is sent with `delivery: "steer"`; see
1205
+ [Operation lifecycle](#operation-lifecycle-and-automatic-provider-recovery).
1012
1206
 
1013
1207
  ```ts
1014
1208
  const agent = await Agent.open({
@@ -1219,7 +1413,9 @@ const unsubscribe = session.subscribe((notification: AgentSessionNotification) =
1219
1413
  `presentation_recorded` notification means the displayed item revision has been appended
1220
1414
  to the V2 transcript. Its ID, first position, revision, record sequence, and operation ID
1221
1415
  are exactly the values the presentation reader returns after a restart. Upsert by `id`
1222
- and ignore revisions older than the one already rendered.
1416
+ and ignore revisions older than the one already rendered. `startedAt` is when the item's
1417
+ first revision was written and `updatedAt` when this one was; `timestamp` is a deprecated
1418
+ alias of `updatedAt`.
1223
1419
 
1224
1420
  Useful live properties include:
1225
1421
 
@@ -1483,7 +1679,12 @@ await session.authenticate(methodId, { onOutput: showAuthOutput });
1483
1679
  ```
1484
1680
 
1485
1681
  Configuration selected through `AgentSession` is checkpointed according to the configured
1486
- `sessionConfiguration` persistence policy and reapplied during loading.
1682
+ `sessionConfiguration` persistence policy and reapplied during loading. Selecting the value an
1683
+ option already has (the harness reports it, and with a transcript it is already the explicit
1684
+ restoration target) is a no-op: nothing is sent, recorded or emitted, so re-applying
1685
+ settings on every start does not fill the history with repeated changes. Agent-owned
1686
+ conversations do not restore their settings when reopened; a consumer that wants them pinned
1687
+ re-applies them, and only real changes are recorded.
1487
1688
 
1488
1689
  Harness slash commands are discovered as metadata:
1489
1690
 
@@ -1903,3 +2104,78 @@ boundary. Strict V2 creation never claims an already initialized legacy file imp
1903
2104
  - Keep local commands distinct from harness commands.
1904
2105
  - Stop every live session during application shutdown.
1905
2106
  - Do not infer provider loading from a transcript path or file contents.
2107
+
2108
+ ## Operation lifecycle and automatic provider recovery
2109
+
2110
+ `conversation.state.operation` is null when no model request is running. While running it exposes
2111
+ `operationId`, `kind`, `stage`, `startedAt`, `lastOutputAt`, `toolsInFlight` and optional cancellation
2112
+ reason/time. `operation_stage_changed` fires on stage changes; read the snapshot for current output
2113
+ timestamps. Internal-inference attempt handles expose the same information at `handle.snapshot.operation`.
2114
+
2115
+ Set `operationLifecycle` on `Agent.open()` or a detached conversation:
2116
+
2117
+ ```ts
2118
+ operationLifecycle: {
2119
+ turns: { firstOutputMs: 120_000, nextOutputMs: 180_000 },
2120
+ internalInference: { firstOutputMs: 120_000 },
2121
+ recap: { nextOutputMs: 180_000 },
2122
+ }
2123
+ ```
2124
+
2125
+ Individual inference limits accept `false`; tools and pending permissions suspend output deadlines.
2126
+ `toolMs` is optional and disabled by default. Each adapter may set `cancelGraceMs` (default 30 seconds).
2127
+ Permission handlers may accept a second optional AbortSignal; discard UI and stop asynchronous work
2128
+ when it aborts. A late permission answer cannot change the cancelled outcome.
2129
+
2130
+ A stalled turn rejects with `OperationStalledError`, including `phase` (`no_response` or
2131
+ `incomplete_response`), `messages`, `operationId`, `metering` and optional `followedBy` steer IDs.
2132
+ Its partial response is failed, and its metering outcome is cancelled. Forced interrupts and steers
2133
+ resolve cancelled and expose `cancel: forced`; acknowledged cancellation reports `acknowledged`.
2134
+
2135
+ After a provider exit or forced stop, keep the conversation and send the next prompt. The library
2136
+ loads its provider session automatically and emits `provider_reconnected` with `via: loaded` or
2137
+ `recovered` (Agent-owned checkpoint recovery under the configured policy). The snapshot connection
2138
+ moves through `disconnected`, `reconnecting`, and `connected`. A transient reconnect failure fails
2139
+ that prompt, and the next prompt tries again.
2140
+
2141
+ When the harness no longer has the session, the conversation applies the same rule it applies when
2142
+ opened: checkpoint recovery for Agent-owned conversations (`onLoadFailure: "recover"`), the
2143
+ `continuation.strategies` list for SessionManager conversations (only `new_from_transcript` or a
2144
+ consumer continuation can replace the session; the default list is load only), and
2145
+ `providerSession.onFailure` otherwise (`"new"` starts a fresh session without the earlier context and
2146
+ reports `via: fresh`). When the rule has nothing left, the prompt rejects with the reason, `promptability`
2147
+ reports `continuation_unavailable`, and later prompts are refused until the conversation is reopened
2148
+ with a different policy. SessionManager's existing library-crash uncertainty recovery remains separate.
2149
+
2150
+ Harness behaviours seen after a crash (test13, 2026-10-19):
2151
+
2152
+ - **OpenCode finishes the interrupted turn first.** When a reloaded session has a turn that was cut
2153
+ off (the process was killed or frozen mid-turn), OpenCode completes that interrupted request before
2154
+ answering the next prompt. The reply to the next prompt can therefore start with the old turn's
2155
+ output, and it can be silent for longer than usual while the old request runs. The failed turn was
2156
+ already reported as an error; treat the start of the next reply accordingly, and keep the silence
2157
+ limits generous on OpenCode (the defaults are).
2158
+ - **Codex archives a deleted session.** Loading it fails until it is unarchived with
2159
+ `codex unarchive <id>`; the library treats it as missing, so the conversation's continuation rule
2160
+ applies (a replacement session, when the rule provides one).
2161
+
2162
+ After a turn the provider received fails (stalled, crashed, or errored), queued messages remain held.
2163
+ A prompt that fails before reaching the provider holds nothing. Read `state.pendingHold`,
2164
+ `pendingMessages[].heldBy` and the `message_held` / `message_released` events. Steers waiting after a
2165
+ stall are sent as the recovery prompt, up to the next queued message (not including it); steers after
2166
+ that message run after it. Send a message with `delivery: steer` to continue; its successful
2167
+ completion releases queued messages in order (internal prompts such as a recap do not release). Explicit queue delivery while held
2168
+ adds to the hold, including when idle. `withdraw()` remains available.
2169
+
2170
+ **If your default is `busyDelivery: "queue"`**, every prompt sent after a failure joins the hold, so
2171
+ nothing runs until you send a prompt with `delivery: "steer"` explicitly (or withdraw). Give the user
2172
+ a way to send that steer, for example when `state.pendingHold` is set. These message events are live
2173
+ observations; consumers may store them if needed.
2174
+
2175
+ Control requests (initialize, new, load, list, delete, config, authenticate) have no deadline. They
2176
+ end when the harness answers or when the process exits. A large session can take a minute or more to
2177
+ load; that is not treated as a failure.
2178
+
2179
+ Degraded PTY mode observes raw terminal output but cannot identify ACP tools or permissions. Its
2180
+ output silence limits are disabled by default to preserve long-running tools; explicit configured
2181
+ limits still apply, and cancellation is bounded.