@qlairoslabs/acp-client 0.11.1 → 0.12.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 (80) hide show
  1. package/CHANGELOG-consumer-fixes.md +55 -0
  2. package/CHANGELOG-operation-lifecycle.md +64 -0
  3. package/CONSUMER_GUIDE.md +287 -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 +3 -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 +5 -0
  25. package/src/checkpointing/strategy.ts +2 -0
  26. package/src/client.ts +120 -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,55 @@
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
+ - **Message boundaries.** A new tool call now ends the assistant message before it, also when the
17
+ agent sends no message ids (before, message → tool → message was one message). Tool updates
18
+ do not split. Applies to the live `result.messages` and to stored messages.
19
+ - **Message completion is stored when it happens.** Agent-owned conversations record a message
20
+ `completed` when the next message or a tool call begins, with that time, instead of completing
21
+ every message of the turn at its end with one shared timestamp. Only the turn's last message
22
+ takes the turn's outcome; messages that ended before a failure or cancel stay `completed`.
23
+ - **Item times.** `ConversationTimelineItem` has `startedAt` (first revision) and `updatedAt`
24
+ (latest). Presentation items have `startedAt` and `updatedAt`; their `timestamp` is now a
25
+ deprecated alias of `updatedAt`.
26
+ - **No-op settings are not recorded.** `setConfig` with the value the option already has (and,
27
+ with a transcript, that is already the explicit restoration target) sends, records and emits
28
+ nothing.
29
+ - **Every record carries its operation.** Records have a typed `operationId`: the library
30
+ operation that wrote them (turn, internal inference or recap, setting change, mode change,
31
+ handoff). Appended out-of-band messages are standalone records without an operation id. Tool calls, permissions, thinking, activity, configuration, mode changes and protocol
32
+ lines now carry it as messages already did. A tool call still running when its turn ends is
33
+ recorded `failed` in that turn; an update for it in a later turn is recorded under the later
34
+ turn. Records outside an operation have none. `records.list(id, { operationId })` filters by it.
35
+ SQLite agent schema 15 recovers it on older records from their record ids.
36
+ - **Cancellations are recorded.** A new record kind, `cancellation` (SQLite and JSONL), with
37
+ `requested` (reason: `steer`, `interrupt`, `stalled`, `stop`, `abort`) and `resolved`
38
+ (outcome: `acknowledged`, `forced`, `too_late`, `failed`) revisions under the cancelled
39
+ operation's id. After a reload a turn can still be shown as stopped or redirected. Stopping a
40
+ conversation mid-turn records reason `stop`. SQLite schema 15
41
+ rebuilds `conversation_records` to admit the kind. Audit capture key `cancellation`
42
+ (default `metadata`); JSONL audit logs write it too (`t: "cancellation"`).
43
+ - **Timeline items are scoped by operation.** `reconcileConversationTimeline` keys tool call,
44
+ permission, thinking and activity items by the record's `operationId`, so two turns that reuse a
45
+ provider id stay two items. Items whose records carried `operationId` in their metadata keep their
46
+ ids; the others (tool calls, for example) get new ids, so a consumer that stored timeline item ids
47
+ sees them change once.
48
+ - **Transcript writes are serialized.** A JSONL transcript and its audit log run their writes one at
49
+ a time. Before, a cancellation record written while an internal prompt finished could claim the
50
+ same sequence as the prompt's reply and leave the transcript refusing every later write.
51
+ - **History pages by agent messages.** `records.listRecent(id, { agentMessages: N })` returns N
52
+ agent messages per page with the activity that led to each, cut right after an agent message,
53
+ with every record on the page where its item began. `fold: true` returns timeline items,
54
+ `detail: "summary"` leaves out tool calls' input and output (`records.get` returns them), and
55
+ `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,103 @@ 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 reach ACP session creation/load;
183
+ the harness applies its own permissions. The library does not restrict pointers. A harness on
184
+ another machine or in an isolated container needs a shared mount or a copy.
185
+
186
+ SQLite schema 16 stores kept blobs separately from message rows in the same database and
187
+ transaction. History and audit records contain refs/URIs and metadata. Ordinary text messages
188
+ remain strings; mixed messages use `PersistedContentBlock[]`, including `media` and `pasted`.
189
+ Old inline image/resource blocks can still be read; migration rebuilds structured message
190
+ search text and its FTS index without old inline bytes or refs. Raw canonical protocol capture and debug
191
+ prompt logs redact inline media; a consumer's explicitly requested `wire` callback is verbatim.
192
+
193
+ ```ts
194
+ const agent = await Agent.open({
195
+ // ...persistence, adapters, and other settings...
196
+ capture: { message: "content", media: "metadata" },
197
+ // media: { store: yourMediaStore }, // optional MediaStore override
198
+ });
199
+
200
+ const store = agent.media.store ?? agent.persistence.media;
201
+ const saved = await store?.get(ref); // { ref, info, data } or null when removed
202
+ await conversation.prompt({ parts: [{ kind: "image", ref }] });
203
+ await agent.deleteMedia(ref); // removes bytes; history retains the dangling ref
204
+ await agent.deleteMediaForConversation(conversation.id);
205
+
206
+ const files = await agent.persistence.files?.search({
207
+ text: "plot", agentConversationId: conversation.id, kind: "image", minSize: 1,
208
+ });
209
+ ```
210
+
211
+ `capture.media` is `none`, `metadata`, or `content` (default), independently of message text.
212
+ The conversation persistence resolver can override it, and a part's own `record`/`keep` wins.
213
+ Checkpointing still summarizes text. A backend without `media` and no override defaults to
214
+ metadata; explicit `keep: true` is refused. The older SessionManager/AgentSession JSONL
215
+ transcript records text and descriptive part lines, with no media store.
216
+
217
+ A `MediaStore` implements async `put(bytes, info) -> ref`, `get(ref)`, `delete(ref)` and
218
+ `list(owner)`. `get` returns `{ ref, info, data }` or null; `list` returns `{ ref, info }`
219
+ entries. Preserve all `MediaInfo` fields. Separate stores cannot share the record transaction: failed
220
+ writes stop dispatch, and `list(owner)` supports orphan cleanup. Reusing a kept ref within
221
+ its conversation reuses bytes; another conversation gets a new copy. Copies record SHA-256
222
+ but are not deduplicated. Clearing records deletes SQLite media; the Agent clear API also
223
+ cleans an overridden store. Soft deletion retains media.
224
+
225
+ `files.list` and `files.search` browse media metadata, including unkept/deleted copies and
226
+ links, with optional conversation, name, kind, MIME type and size filters. They accept `limit`
227
+ and `cursor`; response revisions are folded. Message search covers text and pasted text,
228
+ without indexing media names, refs or bytes. Offset file cursors can shift under concurrent
229
+ inserts. Custom backends can supply the optional `files` repository.
230
+
134
231
  SQLite keeps ordering and type-specific content separate. `conversation_records` is a
135
232
  narrow canonical envelope containing the conversation-local sequence, kind, timestamp,
136
233
  operation correlation, and optional metadata. Every envelope has exactly one typed detail
@@ -200,7 +297,64 @@ const older = first.olderCursor
200
297
  if (older) items = reconcileConversationTimeline(items, older.records);
201
298
  ```
202
299
 
300
+ Paging by records cuts turns anywhere: a tool call is several records, so a page can start
301
+ mid-turn. To page by what the conversation shows, count agent messages instead:
302
+
303
+ ```ts
304
+ const page = await agent.persistence.records.listRecent!(conversation.id, {
305
+ agentMessages: 50, // each page: 50 agent messages and the activity that led to each
306
+ fold: true, // timeline items instead of records
307
+ detail: "summary", // tool calls without input and output
308
+ });
309
+ let items = page.items;
310
+ // Expanding a step: its full record merges into the summary item.
311
+ const full = await agent.persistence.records.get(step.current.recordId);
312
+ items = reconcileConversationTimeline(items, [full!]);
313
+ ```
314
+
315
+ - The cut goes right after an agent message (out-of-band appends count), so a page usually
316
+ begins with a turn's user message, and activity after the newest message (a running turn)
317
+ stays on the newest page.
318
+ - A record goes to the page where its item's first revision falls. A page holds every revision
319
+ of its items, including later ones up to the snapshot, and none of another page's: a message
320
+ that completed after the next tool started is not split across pages.
321
+ - `limit` caps the page (records, or items when folded; default 2000). A page that reaches it
322
+ ends at a whole item with `truncated: true`, and `olderCursor` continues from there.
323
+ - `fold: true` returns `ConversationTimelineItem`s; live records still merge with
324
+ `reconcileConversationTimeline(items, records)`. With `detail: "summary"` an item keeps two
325
+ revisions, its first (its start) and its merged current (under its latest revision's id),
326
+ so it reconciles like any other item.
327
+ - `detail: "summary"` also works on records. The step title is the harness's `name`, which
328
+ varies by harness; `records.get` returns the input and output.
329
+ - Without `agentMessages`, `fold` or `detail`, `listRecent` is unchanged. A cursor is bound to
330
+ its unit: a record-paging cursor is refused when paging by agent messages, and the reverse.
331
+
203
332
  Every physical record has a stable `recordId` and a conversation-local `sequence`.
333
+ `operationId` says which library operation wrote it: a turn (`result.operationId`), an
334
+ internal inference or recap, a setting change, a mode change, or a handoff. Appended out-of-band messages are standalone records
335
+ without an operation id. Every record of one
336
+ operation shares it, so a turn's messages, tool calls, permissions and thinking can be grouped
337
+ without inferring turns from their position; `sequence` gives the order. A tool call still
338
+ running when its turn ends is recorded `failed` in that turn; if the harness reports it later, that
339
+ update is recorded under the turn it arrived in, as a separate timeline item. Protocol lines
340
+ carry the operation that sent them: a handoff's own lines its id, the lines of its summary, seed
341
+ or target prompt that prompt's id (`<handoffId>:summary`, `:seed`, `:target`); a recap's or a
342
+ recovery seed's lines theirs. Records written outside any operation (protocol lines while
343
+ connecting) have none. Operations can interleave:
344
+ a message appended during a turn sits inside the turn's sequence range, so group by
345
+ `operationId`, not by range. Timeline items for tool calls, permissions, thinking and activity are
346
+ keyed within their operation, so a provider id reused by a later turn is a new item.
347
+ A cancelled operation records why and how in a `cancellation` record (two revisions under one
348
+ `cancellationId`, carrying the cancelled operation's `operationId`): `requested` with its
349
+ `reason` (`steer`: a message sent mid-turn; `interrupt`: Stop; `stalled`: the stale policy;
350
+ `stop`: the conversation was stopped), then `resolved` with its `outcome` (`acknowledged`,
351
+ `forced` when the process had to be killed, `too_late` when the turn finished first, or
352
+ `failed`). So after a reload a client can still show a turn as "Stopped" or "Redirected"; for
353
+ a steer, the redirecting message is the next turn's. It describes the cancellation, not the
354
+ mechanism (ACP `session/cancel`). JSONL transcripts and audit logs write the same record
355
+ (`t: "cancellation"`).
356
+ Databases from before schema 15 recover it for tool call, thinking, activity, permission,
357
+ configuration and mode-change records; `records.list(id, { operationId })` filters by it.
204
358
  The reconciliation helper keeps distinct messages separate and groups revisions of an
205
359
  assistant message, tool call, permission, thinking block, activity, or transition by its
206
360
  logical ID. Assistant snapshots take their position from the first streamed text; the
@@ -208,8 +362,17 @@ completed revision supplies their final content and status. Providers that expos
208
362
  message only in the final prompt result cannot supply an earlier position. Records
209
363
  written before schema version 11 have no such boundaries to reconstruct. The helper's
210
364
  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
365
+ the earliest loaded sequence. `startedAt` is when the item's first revision was written
366
+ (when a message began) and `updatedAt` when its latest was (also `current.timestamp`).
367
+ Loading an older page may move an item to its true
368
+ earlier position when its first revision arrives.
369
+
370
+ ACP has no "message finished" signal, so an assistant message ends when the next one begins:
371
+ a chunk with a different message id, or a new tool call (with or without ids; tool *updates*
372
+ do not split a message). That message is recorded `completed` at that moment, so a client
373
+ sees it finish as soon as the next text or tool appears. The turn's last message ends with
374
+ the turn and takes its outcome (`completed`, `cancelled` or `failed`); messages that ended
375
+ before a failure stay `completed`. The live `result.messages` uses the same boundaries. Configuration, protocol, agent
213
376
  actions, and metering references remain individual records unless they have an
214
377
  explicit logical identity; metering details are read from `persistence.metering`.
215
378
 
@@ -239,7 +402,8 @@ Preview paging follows conversation `updatedAt` order; that list may
239
402
  reorder as conversations advance, so consumers should refresh it rather than treat
240
403
  offset cursors as a frozen snapshot. `messages.list()` returns the latest visible
241
404
  revision per logical message; `records.list()` and `records.listRecent()` retain all
242
- physical revisions for timeline reconstruction and audit. `listRecent` and `listPreviews` are SQLite
405
+ physical revisions for timeline reconstruction and audit (except `listRecent` with `fold: true`
406
+ and `detail: "summary"`, which keeps two per item). `listRecent` and `listPreviews` are SQLite
243
407
  capabilities; custom persistence backends may not implement them.
244
408
 
245
409
  ### Live committed-record events
@@ -367,16 +531,27 @@ turn, in a `<messages-you-sent>` block between any identity preamble and
367
531
  - A recovery seed covers messages through `recoveredThroughSequence`, so they are not
368
532
  repeated after recovery. A loaded provider session is treated like one that never
369
533
  closed.
370
- - A turn that completes without an assistant message does not advance delivery, so its
371
- pending messages are repeated once more.
534
+ - SQLite commits a delivery cursor with a successful turn, including turns whose message
535
+ text is not captured.
372
536
  - The block is capped at `OUT_OF_BAND_PROMPT_MAX_CHARS`; the oldest messages are dropped
373
537
  first with an omission note. The transcript always keeps all of them.
374
538
 
375
539
  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.
540
+ canonical message. Text-only appends require `capture.message` of `"content"` or `"raw"`;
541
+ media-only appends are supported under the independent media capture policy. An append rejects
542
+ empty input and unknown or deleted conversations. `appendAssistantMessage(id, { parts })` uses
543
+ the same part/store rules. Parts are accepted whatever the next turn's agent supports.
544
+
545
+ A message waits for the next successful turn. When its record can restore it (text captured,
546
+ every copy kept, no `record: false` part), it is delivered from the record. Otherwise its parts
547
+ wait in memory: unkept bytes are never written anywhere, and a failed turn keeps them for the
548
+ retry. After a restart such a message is delivered from its record, and a copy whose bytes were
549
+ not kept (or were deleted) is named instead, as `[image plot.png: not available]`; an unrecorded
550
+ part is gone. A copy the agent cannot take is named too (`[image plot.png: not supported by this
551
+ agent]`), so an out-of-band message never makes a turn fail. A PTY agent receives every media
552
+ part as such a line.
553
+ Custom backends can supply `outOfBandDelivery` to track completion independently of captured
554
+ text; otherwise delivery uses visible completed messages, scanning forward without `listRecent`.
380
555
 
381
556
  ### Agent audit log
382
557
 
@@ -564,6 +739,22 @@ into the visible transcript. Attempts are queued in SQLite, leased to one worker
564
739
  with a new `aii-…` attempt ID, observable, cancellable, and resumed when the database is
565
740
  reopened.
566
741
 
742
+ Each attempt runs in a fresh, disposable harness session that is stopped as soon as its prompt is answered. A harness
743
+ 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
744
+ it: OpenCode names a session with a second request on a small model, started at the first prompt, and stopping the process
745
+ right after the answer can cut it off mid-stream (behind a gateway that is a cancelled, half-accounted request). So for
746
+ OpenCode the default runtime starts the disposable process with `OPENCODE_CONFIG_CONTENT` set to turn the title agent off,
747
+ for internal inference only: conversations are not touched, and an `OPENCODE_CONFIG_CONTENT` you already set (in
748
+ `conversationDefaults.env` or the process environment) is kept, with the title agent switched off inside it. With a
749
+ `launcher`, the variable is added to its `spawnEnv`; a launcher that starts the harness elsewhere (a container, a remote
750
+ host) must forward it. Set `internalInference: { suppressHarnessBackgroundWork: false }` to leave the harness as configured.
751
+ It has no effect with a custom `runtime`; see `withoutHarnessBackgroundWork` to apply it there.
752
+
753
+ A failed attempt keeps the original error for whoever awaits it, and records on the attempt (`failureDetails`) the
754
+ JSON-RPC code and the labels harnesses send in `data` (`service`, `errorName`, `providerCode`), nothing else of `data`. A
755
+ harness decides what its errors carry: OpenCode's ACP adapter, for example, sends the upstream message text but not the HTTP
756
+ status, gateway error code or request id, so those cannot be recovered here.
757
+
567
758
  Consumers register versioned strategies. A strategy derives a prompt from durable input,
568
759
  then validates and publishes the result inside the transaction that completes the attempt.
569
760
  The generic runtime deliberately does not define checkpoint or identity artifact schemas.
@@ -1008,7 +1199,9 @@ const answer = await note; // the turn that carried the message
1008
1199
  `withdraw()`. A prompt that does not have to wait runs immediately and `delivery` has no effect.
1009
1200
 
1010
1201
  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):
1202
+ change it (before this was `"queue"`; set `busyDelivery: "queue"` to keep the old behaviour). With `"queue"`
1203
+ as the default, a failed turn holds every later prompt until one is sent with `delivery: "steer"`; see
1204
+ [Operation lifecycle](#operation-lifecycle-and-automatic-provider-recovery).
1012
1205
 
1013
1206
  ```ts
1014
1207
  const agent = await Agent.open({
@@ -1219,7 +1412,9 @@ const unsubscribe = session.subscribe((notification: AgentSessionNotification) =
1219
1412
  `presentation_recorded` notification means the displayed item revision has been appended
1220
1413
  to the V2 transcript. Its ID, first position, revision, record sequence, and operation ID
1221
1414
  are exactly the values the presentation reader returns after a restart. Upsert by `id`
1222
- and ignore revisions older than the one already rendered.
1415
+ and ignore revisions older than the one already rendered. `startedAt` is when the item's
1416
+ first revision was written and `updatedAt` when this one was; `timestamp` is a deprecated
1417
+ alias of `updatedAt`.
1223
1418
 
1224
1419
  Useful live properties include:
1225
1420
 
@@ -1483,7 +1678,12 @@ await session.authenticate(methodId, { onOutput: showAuthOutput });
1483
1678
  ```
1484
1679
 
1485
1680
  Configuration selected through `AgentSession` is checkpointed according to the configured
1486
- `sessionConfiguration` persistence policy and reapplied during loading.
1681
+ `sessionConfiguration` persistence policy and reapplied during loading. Selecting the value an
1682
+ option already has (the harness reports it, and with a transcript it is already the explicit
1683
+ restoration target) is a no-op: nothing is sent, recorded or emitted, so re-applying
1684
+ settings on every start does not fill the history with repeated changes. Agent-owned
1685
+ conversations do not restore their settings when reopened; a consumer that wants them pinned
1686
+ re-applies them, and only real changes are recorded.
1487
1687
 
1488
1688
  Harness slash commands are discovered as metadata:
1489
1689
 
@@ -1903,3 +2103,78 @@ boundary. Strict V2 creation never claims an already initialized legacy file imp
1903
2103
  - Keep local commands distinct from harness commands.
1904
2104
  - Stop every live session during application shutdown.
1905
2105
  - Do not infer provider loading from a transcript path or file contents.
2106
+
2107
+ ## Operation lifecycle and automatic provider recovery
2108
+
2109
+ `conversation.state.operation` is null when no model request is running. While running it exposes
2110
+ `operationId`, `kind`, `stage`, `startedAt`, `lastOutputAt`, `toolsInFlight` and optional cancellation
2111
+ reason/time. `operation_stage_changed` fires on stage changes; read the snapshot for current output
2112
+ timestamps. Internal-inference attempt handles expose the same information at `handle.snapshot.operation`.
2113
+
2114
+ Set `operationLifecycle` on `Agent.open()` or a detached conversation:
2115
+
2116
+ ```ts
2117
+ operationLifecycle: {
2118
+ turns: { firstOutputMs: 120_000, nextOutputMs: 180_000 },
2119
+ internalInference: { firstOutputMs: 120_000 },
2120
+ recap: { nextOutputMs: 180_000 },
2121
+ }
2122
+ ```
2123
+
2124
+ Individual inference limits accept `false`; tools and pending permissions suspend output deadlines.
2125
+ `toolMs` is optional and disabled by default. Each adapter may set `cancelGraceMs` (default 30 seconds).
2126
+ Permission handlers may accept a second optional AbortSignal; discard UI and stop asynchronous work
2127
+ when it aborts. A late permission answer cannot change the cancelled outcome.
2128
+
2129
+ A stalled turn rejects with `OperationStalledError`, including `phase` (`no_response` or
2130
+ `incomplete_response`), `messages`, `operationId`, `metering` and optional `followedBy` steer IDs.
2131
+ Its partial response is failed, and its metering outcome is cancelled. Forced interrupts and steers
2132
+ resolve cancelled and expose `cancel: forced`; acknowledged cancellation reports `acknowledged`.
2133
+
2134
+ After a provider exit or forced stop, keep the conversation and send the next prompt. The library
2135
+ loads its provider session automatically and emits `provider_reconnected` with `via: loaded` or
2136
+ `recovered` (Agent-owned checkpoint recovery under the configured policy). The snapshot connection
2137
+ moves through `disconnected`, `reconnecting`, and `connected`. A transient reconnect failure fails
2138
+ that prompt, and the next prompt tries again.
2139
+
2140
+ When the harness no longer has the session, the conversation applies the same rule it applies when
2141
+ opened: checkpoint recovery for Agent-owned conversations (`onLoadFailure: "recover"`), the
2142
+ `continuation.strategies` list for SessionManager conversations (only `new_from_transcript` or a
2143
+ consumer continuation can replace the session; the default list is load only), and
2144
+ `providerSession.onFailure` otherwise (`"new"` starts a fresh session without the earlier context and
2145
+ reports `via: fresh`). When the rule has nothing left, the prompt rejects with the reason, `promptability`
2146
+ reports `continuation_unavailable`, and later prompts are refused until the conversation is reopened
2147
+ with a different policy. SessionManager's existing library-crash uncertainty recovery remains separate.
2148
+
2149
+ Harness behaviours seen after a crash (test13, 2026-10-19):
2150
+
2151
+ - **OpenCode finishes the interrupted turn first.** When a reloaded session has a turn that was cut
2152
+ off (the process was killed or frozen mid-turn), OpenCode completes that interrupted request before
2153
+ answering the next prompt. The reply to the next prompt can therefore start with the old turn's
2154
+ output, and it can be silent for longer than usual while the old request runs. The failed turn was
2155
+ already reported as an error; treat the start of the next reply accordingly, and keep the silence
2156
+ limits generous on OpenCode (the defaults are).
2157
+ - **Codex archives a deleted session.** Loading it fails until it is unarchived with
2158
+ `codex unarchive <id>`; the library treats it as missing, so the conversation's continuation rule
2159
+ applies (a replacement session, when the rule provides one).
2160
+
2161
+ After a turn the provider received fails (stalled, crashed, or errored), queued messages remain held.
2162
+ A prompt that fails before reaching the provider holds nothing. Read `state.pendingHold`,
2163
+ `pendingMessages[].heldBy` and the `message_held` / `message_released` events. Steers waiting after a
2164
+ stall are sent as the recovery prompt, up to the next queued message (not including it); steers after
2165
+ that message run after it. Send a message with `delivery: steer` to continue; its successful
2166
+ completion releases queued messages in order (internal prompts such as a recap do not release). Explicit queue delivery while held
2167
+ adds to the hold, including when idle. `withdraw()` remains available.
2168
+
2169
+ **If your default is `busyDelivery: "queue"`**, every prompt sent after a failure joins the hold, so
2170
+ nothing runs until you send a prompt with `delivery: "steer"` explicitly (or withdraw). Give the user
2171
+ a way to send that steer, for example when `state.pendingHold` is set. These message events are live
2172
+ observations; consumers may store them if needed.
2173
+
2174
+ Control requests (initialize, new, load, list, delete, config, authenticate) have no deadline. They
2175
+ end when the harness answers or when the process exits. A large session can take a minute or more to
2176
+ load; that is not treated as a failure.
2177
+
2178
+ Degraded PTY mode observes raw terminal output but cannot identify ACP tools or permissions. Its
2179
+ output silence limits are disabled by default to preserve long-running tools; explicit configured
2180
+ limits still apply, and cancellation is bounded.