@qlairoslabs/acp-client 0.12.1 → 0.13.1-alpha.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 (288) hide show
  1. package/CHANGELOG-consumer-fixes.md +17 -10
  2. package/CHANGELOG-controller-interface.md +258 -0
  3. package/CHANGELOG-metering.md +29 -0
  4. package/CHANGELOG-operation-lifecycle.md +15 -1
  5. package/CONSUMER_GUIDE.md +984 -6
  6. package/MIGRATION-0.10-to-0.12.md +4 -1
  7. package/MIGRATION-0.12-to-0.13.md +288 -0
  8. package/README.md +17 -16
  9. package/package.json +11 -2
  10. package/src/acp-client-handlers.ts +48 -0
  11. package/src/activity.ts +3 -0
  12. package/src/adapters.ts +25 -0
  13. package/src/agent/adoption/provider-attachment.ts +33 -0
  14. package/src/agent/adoption/provider-session-delete.ts +1 -1
  15. package/src/agent/adoption/provider-sessions.ts +3 -2
  16. package/src/agent/append-assistant-message.ts +91 -0
  17. package/src/agent/config.ts +54 -6
  18. package/src/agent/conversation-manager.ts +95 -158
  19. package/src/agent/manager-settings.ts +1 -0
  20. package/src/agent/native-channel-lifecycle.ts +111 -0
  21. package/src/agent/native-operations.ts +39 -0
  22. package/src/agent/persisted-lifecycle.ts +44 -4
  23. package/src/agent/persistence-policy/context.ts +13 -0
  24. package/src/agent/persistence-policy/resolver.ts +7 -0
  25. package/src/agent/persistence-policy/types.ts +1 -0
  26. package/src/agent/record-capture.ts +1 -0
  27. package/src/agent-adapter-registry.ts +33 -7
  28. package/src/agent-conversation-contracts.ts +14 -1
  29. package/src/agent-conversation-errors.ts +8 -0
  30. package/src/agent-conversation-owner.ts +9 -4
  31. package/src/agent-session-config.ts +137 -0
  32. package/src/agent-session.ts +440 -934
  33. package/src/agent.ts +168 -0
  34. package/src/capabilities.ts +2 -0
  35. package/src/checkpointing/recovery.ts +3 -0
  36. package/src/cli/index.ts +3 -3
  37. package/src/cli/managed.ts +2 -2
  38. package/src/client.ts +56 -96
  39. package/src/connection-attempt.ts +95 -0
  40. package/src/controller-connection.ts +115 -0
  41. package/src/controller.ts +158 -148
  42. package/src/conversation-controller/capabilities.ts +88 -0
  43. package/src/conversation-controller/contracts.ts +208 -0
  44. package/src/conversation-controller/factory.ts +39 -0
  45. package/src/conversation-controller/guards.ts +98 -0
  46. package/src/conversation-controller/index.ts +20 -0
  47. package/src/conversation-startup.ts +35 -0
  48. package/src/conversation-turns/backend-turns.ts +373 -0
  49. package/src/conversation-turns/clear-operations.ts +37 -0
  50. package/src/conversation-turns/context.ts +135 -0
  51. package/src/conversation-turns/index.ts +4 -0
  52. package/src/conversation-turns/record-helpers.ts +75 -0
  53. package/src/conversation-turns/recording.ts +235 -0
  54. package/src/conversation-turns/run-turn.ts +367 -0
  55. package/src/conversation-turns/turn-run.ts +57 -0
  56. package/src/errors.ts +41 -0
  57. package/src/handoff-options.ts +81 -0
  58. package/src/identity/checkpoint-backed.ts +1 -1
  59. package/src/index.ts +59 -3
  60. package/src/internal-inference/coordination/manager.ts +11 -0
  61. package/src/internal-inference/runtime/harness-runtime.ts +4 -4
  62. package/src/launcher.ts +37 -2
  63. package/src/media/parts.ts +5 -0
  64. package/src/message-status.ts +83 -0
  65. package/src/metering/engine.ts +39 -64
  66. package/src/metering/measurement-provenance.ts +36 -0
  67. package/src/metering/native/durability.ts +115 -0
  68. package/src/metering/native/ledger.ts +104 -0
  69. package/src/metering/native/operation.ts +85 -0
  70. package/src/metering/native/projection.ts +114 -0
  71. package/src/metering/native/proof.ts +51 -0
  72. package/src/metering/native/requirements.ts +10 -0
  73. package/src/metering/native/retirement.ts +92 -0
  74. package/src/metering/native/source.ts +90 -0
  75. package/src/metering/record.ts +38 -1
  76. package/src/metering/state.ts +13 -3
  77. package/src/native/approvals.ts +186 -0
  78. package/src/native/capabilities.ts +17 -0
  79. package/src/native/channel-changes.ts +211 -0
  80. package/src/native/connection.ts +56 -0
  81. package/src/native/controller.ts +592 -0
  82. package/src/native/delegation-sender.ts +26 -0
  83. package/src/native/errors.ts +35 -0
  84. package/src/native/functions.ts +156 -0
  85. package/src/native/host-config.ts +59 -0
  86. package/src/native/host.ts +978 -0
  87. package/src/native/item-receipts.ts +15 -0
  88. package/src/native/metering.ts +12 -0
  89. package/src/native/records.ts +166 -0
  90. package/src/native/recovery.ts +186 -0
  91. package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
  92. package/src/native/reminders/idle.ts +70 -0
  93. package/src/native/reminders/limits.ts +19 -0
  94. package/src/native/reminders/notifications.ts +29 -0
  95. package/src/native/reminders/routine-guard.ts +66 -0
  96. package/src/native/reminders/routine-schedule.ts +25 -0
  97. package/src/native/reminders/routine-wire.ts +21 -0
  98. package/src/native/reminders/schedule.ts +97 -0
  99. package/src/native/reminders/service.ts +280 -0
  100. package/src/native/reminders/supervisor.ts +91 -0
  101. package/src/native/reminders/sync.ts +301 -0
  102. package/src/native/reminders/wire.ts +197 -0
  103. package/src/native/submission-withdrawal.ts +65 -0
  104. package/src/native/usage.ts +15 -0
  105. package/src/native/worker-delivery.ts +61 -0
  106. package/src/native-harness/README.md +726 -0
  107. package/src/native-harness/package.json +24 -0
  108. package/src/native-harness/scripts/build-routine-zones.py +47 -0
  109. package/src/native-harness/src/capabilities/context/build.ts +59 -0
  110. package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
  111. package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
  112. package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
  113. package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
  114. package/src/native-harness/src/capabilities/context/session.ts +93 -0
  115. package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
  116. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
  117. package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
  118. package/src/native-harness/src/capabilities/model/runner.ts +116 -0
  119. package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
  120. package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
  121. package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
  122. package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
  123. package/src/native-harness/src/capabilities/model/usage.ts +15 -0
  124. package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
  125. package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
  126. package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
  127. package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
  128. package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
  129. package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
  130. package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
  131. package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
  132. package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
  133. package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
  134. package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
  135. package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
  136. package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
  137. package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
  138. package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
  139. package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
  140. package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
  141. package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
  142. package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
  143. package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
  144. package/src/native-harness/src/capabilities/tools/reminders/index.ts +97 -0
  145. package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
  146. package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
  147. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
  148. package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
  149. package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
  150. package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
  151. package/src/native-harness/src/client.ts +18 -0
  152. package/src/native-harness/src/contracts/agent.ts +105 -0
  153. package/src/native-harness/src/contracts/config-permissions.ts +49 -0
  154. package/src/native-harness/src/contracts/context.ts +112 -0
  155. package/src/native-harness/src/contracts/events.ts +47 -0
  156. package/src/native-harness/src/contracts/input-limits.ts +7 -0
  157. package/src/native-harness/src/contracts/inspection.ts +22 -0
  158. package/src/native-harness/src/contracts/loop.ts +31 -0
  159. package/src/native-harness/src/contracts/model-execution.ts +83 -0
  160. package/src/native-harness/src/contracts/operator-controls.ts +106 -0
  161. package/src/native-harness/src/contracts/output.ts +13 -0
  162. package/src/native-harness/src/contracts/protocol.ts +320 -0
  163. package/src/native-harness/src/contracts/reminders.ts +134 -0
  164. package/src/native-harness/src/contracts/routines.ts +20 -0
  165. package/src/native-harness/src/contracts/scenario.ts +42 -0
  166. package/src/native-harness/src/contracts/session-file.ts +20 -0
  167. package/src/native-harness/src/contracts/session.ts +184 -0
  168. package/src/native-harness/src/contracts/storage.ts +597 -0
  169. package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
  170. package/src/native-harness/src/contracts/tools.ts +133 -0
  171. package/src/native-harness/src/governance/permissions/gate.ts +129 -0
  172. package/src/native-harness/src/governance/policy/resolve.ts +32 -0
  173. package/src/native-harness/src/index.ts +322 -0
  174. package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
  175. package/src/native-harness/src/interfaces/cli/development.ts +145 -0
  176. package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
  177. package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
  178. package/src/native-harness/src/interfaces/cli/main.ts +47 -0
  179. package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
  180. package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
  181. package/src/native-harness/src/interfaces/cli/start.ts +106 -0
  182. package/src/native-harness/src/interfaces/client.ts +225 -0
  183. package/src/native-harness/src/interfaces/inspector/index.html +283 -0
  184. package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
  185. package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
  186. package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
  187. package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
  188. package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
  189. package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
  190. package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
  191. package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
  192. package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
  193. package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
  194. package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
  195. package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
  196. package/src/native-harness/src/interfaces/protocol/server.ts +519 -0
  197. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +126 -0
  198. package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
  199. package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
  200. package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
  201. package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
  202. package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
  203. package/src/native-harness/src/kernel/channels.ts +409 -0
  204. package/src/native-harness/src/kernel/loop.ts +45 -0
  205. package/src/native-harness/src/runtime/config/development.ts +23 -0
  206. package/src/native-harness/src/runtime/config/managed.ts +2 -0
  207. package/src/native-harness/src/runtime/config/paths.ts +33 -0
  208. package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
  209. package/src/native-harness/src/runtime/reminder-validation.ts +125 -0
  210. package/src/native-harness/src/runtime/reminders.ts +66 -0
  211. package/src/native-harness/src/state/storage/archive.ts +257 -0
  212. package/src/native-harness/src/state/storage/engine.ts +1204 -0
  213. package/src/native-harness/src/state/storage/inference.ts +124 -0
  214. package/src/native-harness/src/state/storage/memory-reminders.ts +103 -0
  215. package/src/native-harness/src/state/storage/memory.ts +354 -0
  216. package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
  217. package/src/native-harness/src/state/storage/reminder-archive.ts +104 -0
  218. package/src/native-harness/src/state/storage/reminder-change.ts +138 -0
  219. package/src/native-harness/src/state/storage/reminder-tables.ts +35 -0
  220. package/src/native-harness/src/state/storage/retrieval.ts +122 -0
  221. package/src/native-harness/src/state/storage/routine-row.ts +25 -0
  222. package/src/native-harness/src/state/storage/script-identity.ts +7 -0
  223. package/src/native-harness/src/state/storage/session-file.ts +85 -0
  224. package/src/native-harness/src/state/storage/sqlite-reminders.ts +174 -0
  225. package/src/native-harness/src/state/storage/sqlite.ts +632 -0
  226. package/src/native-harness/src/testing.ts +190 -0
  227. package/src/native-harness/src/util/config.ts +66 -0
  228. package/src/native-harness/src/util/intake.ts +7 -0
  229. package/src/native-harness/src/util/json.ts +41 -0
  230. package/src/native-harness/src/util/message-position.ts +3 -0
  231. package/src/native-harness/src/util/reminder-schedule.ts +44 -0
  232. package/src/native-harness/src/util/schema.ts +40 -0
  233. package/src/native-harness/src/util/timeline-text.ts +72 -0
  234. package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
  235. package/src/native-harness/tsconfig.json +20 -0
  236. package/src/observation/agent-event-bus.ts +44 -18
  237. package/src/observation/index.ts +1 -0
  238. package/src/operations/contracts.ts +11 -3
  239. package/src/operations/errors.ts +5 -0
  240. package/src/operations/stale-policy.ts +1 -1
  241. package/src/operations/supervisor.ts +34 -10
  242. package/src/orchestrator/acp-delivery.ts +68 -0
  243. package/src/orchestrator/assignments.ts +27 -0
  244. package/src/orchestrator/busy.ts +15 -0
  245. package/src/orchestrator/config.ts +41 -0
  246. package/src/orchestrator/consumer-api.ts +24 -0
  247. package/src/orchestrator/contracts.ts +71 -0
  248. package/src/orchestrator/durable-assignments.ts +111 -0
  249. package/src/orchestrator/native-delegation.ts +103 -0
  250. package/src/orchestrator/orchestrator.ts +318 -0
  251. package/src/orchestrator/permissions.ts +28 -0
  252. package/src/orchestrator/policy.ts +44 -0
  253. package/src/orchestrator/pool.ts +123 -0
  254. package/src/orchestrator/tool-descriptions.ts +11 -0
  255. package/src/permissions/acp.ts +18 -0
  256. package/src/permissions/arrival.ts +13 -0
  257. package/src/permissions/consumer-config.ts +19 -0
  258. package/src/permissions/conversation.ts +288 -0
  259. package/src/permissions/matcher.ts +87 -0
  260. package/src/permissions/outcome.ts +26 -0
  261. package/src/permissions/policy.ts +86 -0
  262. package/src/permissions/request.ts +26 -0
  263. package/src/persistence/activity-projection.ts +1 -0
  264. package/src/persistence/backend.ts +34 -1
  265. package/src/persistence/channels.ts +23 -0
  266. package/src/persistence/index.ts +4 -0
  267. package/src/persistence/protocol-method.ts +5 -0
  268. package/src/persistence/reminder-wake.ts +49 -0
  269. package/src/persistence/reminders.ts +385 -0
  270. package/src/persistence/sqlite-backend.ts +84 -6
  271. package/src/persistence/sqlite-channels.ts +65 -0
  272. package/src/persistence/sqlite-reminders.ts +85 -0
  273. package/src/persistence/sqlite-schema.ts +108 -3
  274. package/src/persistence/sqlite-worker-delivery.ts +374 -0
  275. package/src/persistence/sqlite-workers.ts +59 -0
  276. package/src/persistence/worker-delivery-contract.ts +104 -0
  277. package/src/persistence/worker-terminal-reason.ts +29 -0
  278. package/src/persistence/workers.ts +19 -0
  279. package/src/provider-notices.ts +137 -0
  280. package/src/repl/commands.ts +2 -2
  281. package/src/steering/combine.ts +3 -1
  282. package/src/steering/contracts.ts +11 -2
  283. package/src/steering/controller.ts +3 -2
  284. package/src/terminals.ts +9 -6
  285. package/src/transport/acp-transport.ts +24 -14
  286. package/src/types.ts +15 -12
  287. package/src/updates.ts +14 -2
  288. package/src/wire-log.ts +1 -1
package/CONSUMER_GUIDE.md CHANGED
@@ -31,7 +31,7 @@ provider or harness thread behind that conversation.
31
31
  consumer
32
32
  └── Agent ags-… stable agent identity + SQLite database
33
33
  └── AgentConversation agc-… stable conversation identity
34
- └── AgentController
34
+ └── ConversationController (ACP or native)
35
35
  └── internal thread abc replaceable harness identity
36
36
  ```
37
37
 
@@ -503,6 +503,76 @@ kept as evidence and is not deleted; recovery or a future fresh-session operatio
503
503
  supersedes it. A `session/load` failure that is recoverable and has a usable checkpoint
504
504
  still recovers, with the error recorded before the recovery action.
505
505
 
506
+ ### Message status
507
+
508
+ Every prompt handle has a `status`, and each change is a `message_status { id, status, turnId? }`
509
+ event on the conversation. One sequence for every backend:
510
+
511
+ `queued` → `received` → `taken` → `delivered` → `seen`, or the end states `withdrawn` and `failed`.
512
+
513
+ ```ts
514
+ import type { AgentConversation, MessageStatus } from "@qlairoslabs/acp-client";
515
+
516
+ async function promptWithStatus(
517
+ conversation: AgentConversation,
518
+ text: string,
519
+ showTicks: (status: MessageStatus) => void,
520
+ ) {
521
+ const handle = conversation.prompt(text);
522
+ showTicks(handle.status);
523
+ const unsubscribe = conversation.subscribe(({ event }) => {
524
+ if (event.kind === "message_status" && event.id === handle.id) showTicks(event.status);
525
+ });
526
+ try {
527
+ return await handle;
528
+ } finally {
529
+ unsubscribe();
530
+ }
531
+ }
532
+ ```
533
+
534
+ - **Native conversations** use the harness's milestones: `received` when its inbox accepted the
535
+ message, `taken` when a turn took it, `delivered` and `seen` from its `items_receipt` evidence.
536
+ - **ACP conversations** approximate: `received`, `taken` and `delivered` together when the prompt is
537
+ sent, `seen` at the provider's first output (it started answering, not proof it read the message).
538
+ - A status only moves forward; skipped steps are still reported in order.
539
+ - `failed` means it never reached `seen`; a seen message whose turn fails stays `seen`, and the
540
+ prompt's result says how the turn ended. `withdrawn` is only possible before a take.
541
+ - Live only: statuses aren't restored after a restart. The other message events are unchanged.
542
+
543
+ ### Provider notices: retries, warnings and failures
544
+
545
+ Harnesses report retries, warnings and failures in an update's `_meta`, not as ACP errors.
546
+ acp-client reads two shapes and turns them into one `provider_notice` activity:
547
+
548
+ - the JetBrains AIR session-failure extension, which acp-client now advertises in
549
+ `clientCapabilities._meta` (`jetbrains.air`, version 1, `sessionFailure`): codex-acp and
550
+ claude-agent-acp then send typed notices with an id, a revision, a category, a severity,
551
+ a title and suggested actions;
552
+ - codex-acp's own fallback, `_meta.codex.error`, for a Codex that doesn't use AIR.
553
+
554
+ ```ts
555
+ handlers.onActivity = (activity) => {
556
+ if (activity.kind !== "provider_notice") return;
557
+ // activity.severity: "info" | "warning" | "error"
558
+ // activity.category: "limit" | "service" | "connection" | "access" | "request" | …
559
+ // activity.code (when known: "rate_limited", "auth_required", …), activity.title,
560
+ // activity.actions: "retry" | "login" | "new_session"
561
+ // activity.noticeId + activity.revision: later revisions of one notice replace it
562
+ };
563
+ ```
564
+
565
+ A `warning` or `info` notice ends nothing: a retry in progress ("Rate limited, retrying"),
566
+ a reconnect, an advisory. Show it as a passing status, keyed by `noticeId`. An `error`
567
+ notice is a failure the provider reported. Notices are stored as activity records, so they
568
+ appear in the conversation's timeline. When a turn is judged stalled while the provider was
569
+ retrying, its `stalled` error record says so in its `message` and carries the cause in
570
+ `details.providerCode` (for example `rate_limited`). Adapters that send neither
571
+ recognized shape produce no `provider_notice`.
572
+ Unmodeled `session_info_update` metadata and `usage_update` metadata are kept
573
+ as `meta` on their respective activities. Extend exhaustive `ActivityEvent`
574
+ switches to cover `provider_notice`.
575
+
506
576
  ### Append an assistant message without a turn
507
577
 
508
578
  `conversations.appendAssistantMessage()` adds a completed assistant message the provider
@@ -947,6 +1017,913 @@ All non-deleted conversations are shared in v1, including conversations with dif
947
1017
  users, so consumers should enable this only where such cross-conversation visibility is
948
1018
  appropriate. A custom `AgentIdentityRuntime` remains available for other policies.
949
1019
 
1020
+ ## Permissions and approval UI
1021
+
1022
+ Use `permissions: { default, rules? }` for Agent, conversation, direct session,
1023
+ or raw ACP client configuration. Omission means `ask`. Agent defaults are
1024
+ overridden by `conversationDefaults`, then conversation settings, then its
1025
+ `runtime`. Each supplied `permissions` object replaces the previous one.
1026
+
1027
+ An explicit `permissionRule(request)` result wins. On ACP, the next step matches
1028
+ `kind:<tool-kind>` and `command:<exact command>`. Command rules apply to execute
1029
+ requests whose arguments the library can normalize to one command. Supported
1030
+ input includes a single command string, a simple argument array, and the
1031
+ recognized `bash -lc` wrappers. Rules match exactly and do not use glob or
1032
+ substring matching. The stricter matching level wins
1033
+ (`deny`, then `ask`, then `allow`). An unmatched request uses the default.
1034
+ Deny selects `reject_once` where offered and otherwise cancels the request.
1035
+
1036
+ ```ts
1037
+ import { Agent, type AgentAdapter } from "@qlairoslabs/acp-client";
1038
+
1039
+ export async function openApprovalDemo(adapter: AgentAdapter, path: string) {
1040
+ const agent = await Agent.open({
1041
+ persistence: { kind: "sqlite", path },
1042
+ adapters: { main: adapter },
1043
+ defaultAdapterId: "main",
1044
+ permissions: {
1045
+ default: "ask",
1046
+ rules: { "kind:read": "allow", "command:git status": "allow", "kind:delete": "deny" },
1047
+ },
1048
+ permissionRule: request => request.tool?.name === "publish" ? "deny" : undefined,
1049
+ conversationDefaults: { answersPermissions: true, permissionTimeoutMs: 60_000 },
1050
+ });
1051
+ const conversation = await agent.conversations.create();
1052
+ const unsubscribe = conversation.subscribe(({ event }) => {
1053
+ if (event.kind === "permission_requested") {
1054
+ console.log(event.id, event.title, event.options, event.expiresAt);
1055
+ } else if (event.kind === "permission_resolved") {
1056
+ console.log(event.id, event.outcome, event.by);
1057
+ }
1058
+ });
1059
+ // Call with the request ID and the option ID selected by your UI.
1060
+ const answer = (id: string, optionId: string) => conversation.answerPermission(id, optionId);
1061
+ return { agent, conversation, answer, unsubscribe };
1062
+ }
1063
+ ```
1064
+
1065
+ Allow and deny resolve immediately. Ask first uses a per-prompt
1066
+ `onPermissionRequest` handler. Without one, it waits for a consumer only if
1067
+ `answersPermissions` is true. An ask with neither responder uses `permissions.unanswered`. The default,
1068
+ `"reject"`, refuses the tool and lets the turn continue. ACP selects
1069
+ `reject_once` when offered and sends cancellation otherwise. Native responds
1070
+ with `deny`. Use `permissions: { default: "ask", unanswered: "cancel" }`
1071
+ to send ACP's cancelled permission response or interrupt the requesting
1072
+ native turn. The setting applies only to an unanswered ask. It leaves
1073
+ explicit deny, handler responses and consumer timeout behavior unchanged.
1074
+ A forwarded ask uses the giving conversation's setting when it is
1075
+ available. Without a giving conversation, an applicable worker policy with
1076
+ `unanswered: "cancel"` cancels an otherwise unanswered ask. The consumer wait defaults to five minutes, starts at request ingress, and expires
1077
+ to a refusal. Supply a positive integer below 600,000 to override it.
1078
+ `expiresAt` is epoch milliseconds and is present only for a consumer wait.
1079
+ Check `answerPermission()`'s `{ accepted }` result. Unknown, expired,
1080
+ invalid-option, handler-owned and already resolved requests return false.
1081
+ Each request has one resolution event in a microtask after it closes.
1082
+ `by` is `handler`, `consumer`, `default`, `timeout` or `turn_ended`.
1083
+ Forwarded worker requests include a worker `source` and can omit `turnId`.
1084
+
1085
+ A harness policy first decides whether a native tool needs approval. For
1086
+ native asks the library uses `permissionRule` and the configured default.
1087
+ Native requests supply the tool name and raw argument string. ACP kind and
1088
+ command rules apply only to ACP. Native approval options are `allow_once`
1089
+ and `deny`. The harness also has a ten-minute approval limit. A configured
1090
+ `harness.approvalResponder(request, answer, signal)` can answer centrally,
1091
+ including while detached. Await `answer("allow_once")` or `answer("deny")`
1092
+ to learn whether the harness accepted the decision.
1093
+
1094
+ ## Built-in ACP terminal environments
1095
+
1096
+ Set `terminalEnv` on the client, controller or conversation runtime, or
1097
+ return it from `launcher.prepare()`. The prepared value takes precedence.
1098
+ For example, `terminalEnv: { PATH: "/usr/bin:/bin", LANG: "C.UTF-8" }`
1099
+ passes exactly those environment variables to built-in terminals. Use an
1100
+ empty object to pass none. In this mode ACP terminal request environment
1101
+ entries cannot add to or override the host's environment.
1102
+
1103
+ When no exact environment is configured, the built-in ACP terminal uses the
1104
+ variables supplied in the terminal request. The hub's process environment,
1105
+ client spawn settings and the launcher's `spawnEnv` are separate.
1106
+ `TerminalRegistry` also accepts `terminalEnv` in its options and in a direct
1107
+ `create()` call. A direct per-terminal setting wins. Custom terminal
1108
+ handlers are responsible for their own environment isolation.
1109
+
1110
+ ## Cancellable ACP startup and deferred connections
1111
+
1112
+ Agent-owned normal ACP conversations connect on open by default. Use
1113
+ `providerStart: "on_first_use"` in `conversationDefaults` or override it in
1114
+ `runtime` on create or reopen. The first provider-bound operation starts the
1115
+ connection. A deferred reopen returns `providerSession: "deferred"`. Provider
1116
+ settings and commands can be empty until then. Watch reopen progress and
1117
+ `provider_reconnected` for first-use recovery.
1118
+
1119
+ ```ts
1120
+ import { AgentSession, ConnectionCancelledError, type Agent, type Adapter,
1121
+ type AgentConversationId } from "@qlairoslabs/acp-client";
1122
+
1123
+ export async function reopenLazily(agent: Agent, id: AgentConversationId) {
1124
+ const opened = await agent.conversations.open(id, {
1125
+ runtime: { providerStart: "on_first_use" },
1126
+ onRecoveryProgress: event => console.log(event),
1127
+ });
1128
+ if (opened.providerSession === "deferred") console.log("Connects on first use");
1129
+ return opened.conversation;
1130
+ }
1131
+
1132
+ export async function startDirect(adapter: Adapter, adapterId: string, signal: AbortSignal) {
1133
+ try {
1134
+ return await AgentSession.create({ adapter, adapterId, signal });
1135
+ } catch (error) {
1136
+ if (error instanceof ConnectionCancelledError) return null;
1137
+ throw error;
1138
+ }
1139
+ }
1140
+ ```
1141
+
1142
+ An explicit stop or a superseding ACP connection attempt rejects the pending
1143
+ connection with `ConnectionCancelledError` and code `connection_cancelled`.
1144
+ Direct session startup accepts an `AbortSignal`, as above. Use eager startup
1145
+ when a failed session creation must leave the connection available for
1146
+ authentication.
1147
+
1148
+ ## Native harness conversations (experimental)
1149
+
1150
+ An Agent can run native conversations on its own harness alongside external ACP
1151
+ adapters. Configure a real OpenRouter model with a key supplied through the
1152
+ environment, or use a scripted model with a local JSONL scenario for offline
1153
+ development. Keep the harness home on durable storage. Backend kind stays fixed
1154
+ across a conversation's mode changes and handoffs.
1155
+
1156
+ ```ts
1157
+ import { Agent, ADAPTERS, type AgentHarnessConfig } from "@qlairoslabs/acp-client";
1158
+
1159
+ export async function openNative(
1160
+ directory: string,
1161
+ model: AgentHarnessConfig["config"]["model"] = {
1162
+ protocol: "openrouter", model: "openai/gpt-4.1-mini", apiKeyEnv: "OPENROUTER_API_KEY",
1163
+ },
1164
+ ) {
1165
+ return Agent.open({
1166
+ persistence: { kind: "sqlite", path: `${directory}/agent.sqlite` },
1167
+ adapters: { main: { kind: "native" }, codex: ADAPTERS.codex },
1168
+ defaultAdapterId: "main",
1169
+ harness: {
1170
+ home: `${directory}/harness-home`,
1171
+ config: {
1172
+ version: 1, system: "Be concise.", model,
1173
+ defaultPolicy: "open",
1174
+ policies: { open: { fallback: "deny", tools: { lookup: "ask" } } },
1175
+ },
1176
+ approvalResponder: async (request, answer) => {
1177
+ await answer(request.tool === "lookup" ? "allow_once" : "deny");
1178
+ },
1179
+ functions: {
1180
+ tools: {
1181
+ lookup: {
1182
+ description: "Read the configured status.",
1183
+ parameters: { type: "object", properties: {}, additionalProperties: false },
1184
+ handler: (_args, context) => ({ status: "ready", channel: context.channel }),
1185
+ },
1186
+ },
1187
+ },
1188
+ },
1189
+ });
1190
+ }
1191
+ ```
1192
+
1193
+ Use a supported OpenRouter model ID configured for your account. `harness.config.model` is typed from the harness SDK
1194
+ and passed through unchanged on every open. Besides `scripted` and `openrouter`, the SDK defines an inference-source arm,
1195
+ `{ protocol: "openai-compatible", providerId, model, baseUrl, apiKeyEnv? }` (decision 0034): an OpenAI-compatible Chat
1196
+ Completions endpoint chosen by the consumer. `baseUrl` is HTTPS or a literal loopback address over HTTP (`127.x` or `::1`,
1197
+ not `localhost`) with no credentials, query or fragment; the harness appends the Chat Completions path and follows no
1198
+ redirects; `apiKeyEnv` names a variable in the harness's environment, is optional for keyless endpoints and is read only
1199
+ when the session opens. The library accepts and forwards this arm today (compile-time and open-request tests); the harness
1200
+ runtime that executes it is still being implemented, so an open with this arm is not yet usable end to end. For an offline
1201
+ equivalent, pass `{ protocol: "scripted", script: "/path/to/scenario.jsonl" }`
1202
+ as the second argument. Function parameters are JSON Schema. Functions return
1203
+ JSON values and receive a context with invocation identity and an abort signal.
1204
+ Harness policies grant `allow`, `ask` or `deny` by tool name and define a
1205
+ fallback. This host responder grants one call to the read-only lookup.
1206
+ Subscribe to `items_receipt` when you need delivery evidence.
1207
+
1208
+ ```ts
1209
+ import { NativeInputStoppedError, type Agent, type ItemsReceipt } from "@qlairoslabs/acp-client";
1210
+
1211
+ export async function nativePrompt(agent: Agent) {
1212
+ const conversation = await agent.conversations.create({ title: "Native example" });
1213
+ const receipts: ItemsReceipt[] = [];
1214
+ const unsubscribe = conversation.subscribe(({ event }) => {
1215
+ if (event.kind === "items_receipt") receipts.push(event);
1216
+ });
1217
+ try {
1218
+ const prompt = conversation.prompt("Report the status.");
1219
+ // Use await prompt.withdrawAsync() if the user asks to take it back.
1220
+ return { result: await prompt, receipts };
1221
+ } catch (error) {
1222
+ if (error instanceof NativeInputStoppedError) return { stoppedInput: error.messageId, receipts };
1223
+ throw error;
1224
+ } finally {
1225
+ unsubscribe();
1226
+ await conversation.stop();
1227
+ }
1228
+ }
1229
+ ```
1230
+
1231
+ - **One Agent is one harness session; one conversation is one channel.** All
1232
+ native conversations of an Agent talk to the same agent and share one process.
1233
+ `conversation.internalSessionId` is the Agent's id for each of them.
1234
+ - **The process starts on first use,** not when the Agent or a conversation
1235
+ opens. Concurrent first prompts share one start. It stops with `agent.close()`.
1236
+ Use `agent.nativeHarness.start()`, `suspend()`, `resume()`, and `stop()`
1237
+ for agent-wide controls. `operatorStatus()` reports process health and the
1238
+ last confirmed session view. `workingChannels` counts running turns.
1239
+ - **Attachment** is independent of the channel and agent. Call
1240
+ `conversation.attachObservation()` and dispose the returned handle to
1241
+ detach without interrupting. Read `conversation.connection.attachmentConnected`
1242
+ for attachment state and the host's `status()` for channel and session
1243
+ lifecycle. `restartConversation(conversation.connection)` starts only after
1244
+ confirmed stop.
1245
+ - **The harness schedules turns.** A prompt resolves with the turn that took its
1246
+ message. A `delivery: "steer"` message sent while a turn runs is accepted at
1247
+ once and taken by that turn at its next model call; both prompts then resolve
1248
+ with the same `operationId`.
1249
+ - **Item receipts** are live conversation events with
1250
+ `{ kind: "items_receipt", turnId, itemIds, milestone }`. They carry the
1251
+ harness's committed `delivered` and `seen` advances for a turn. The IDs can
1252
+ include external notices as well as prompts. Receipts can arrive for a held
1253
+ turn and are not replayed as history after reconnect. The existing
1254
+ `message_delivered` event and prompt settlement keep their own meanings.
1255
+ - **Approvals** use the [permission configuration and events](#permissions-and-approval-ui) above.
1256
+ - **Interrupting** (`conversation.interrupt()`, or `connection.forceStop()`)
1257
+ ends that conversation's turn only. Other conversations and the shared
1258
+ process keep running, and the interrupted conversation accepts new input.
1259
+ - **Withdrawing input.** `promptHandle.withdraw()` and `conversation.withdraw(id)`
1260
+ remove local input synchronously. Use `await promptHandle.withdrawAsync()` or
1261
+ `await conversation.withdrawAsync(id)` once a native input has been submitted.
1262
+ A confirmed withdrawal cancels its prompt. If take wins, the call returns
1263
+ false and the prompt follows its turn. Push and withdraw can be dispatched
1264
+ concurrently. A `not_found` reply can leave the withdrawal unresolved and
1265
+ the async call can reject. The host retains its intent and suppresses push
1266
+ replay while checking the original channel and item ID on reconnect. If those
1267
+ checks still leave a push unacknowledged, its prompt can reject with the
1268
+ unresolved error. The intent remains available for later reconciliation.
1269
+ Default submission records are in memory even with SQLite persistence.
1270
+ Configure file-backed host records to retain the intent across Agent reopen.
1271
+ A custom submission store needs `markWithdrawing` to track async withdrawal
1272
+ and clears that flag on `markAccepted(id, true)` when take is confirmed.
1273
+ `interrupt({ clearQueue: true })` still clears locally queued input. Already
1274
+ submitted native input remains with the harness on interrupt. Stop and Agent
1275
+ close give withdrawal of submitted, unclaimed inputs a shared one-second
1276
+ grace period before interrupting the active turn. A prompt whose input was
1277
+ taken resolves as cancelled. It returns completed messages from the turn
1278
+ and its cancelled metering record. If the first message was still
1279
+ streaming without a completion, the returned text is empty. Before stop
1280
+ finishes, the Agent tries to recover missed committed replies from that
1281
+ prepared turn for persistence. Recovered replies are stored once and do not
1282
+ change the caller's result. If the controller never saw the turn and learned
1283
+ of the take only from withdrawal, a committed reply can remain missing
1284
+ after reopening the conversation in the same Agent. A new Agent can recover
1285
+ it from the persisted harness session.
1286
+ A silent host can add about six seconds for withdrawal and reply recovery.
1287
+ Submitted
1288
+ inputs that were never taken reject with `NativeInputStoppedError` (includes
1289
+ `messageId`). If take wins or the host is unavailable or silent, the input
1290
+ may still run and incur model charges.
1291
+ - **Channel changes** go through `agent.nativeHarness.changeChannel(conversationId,
1292
+ { displayName, policy, lifecycle })`. While the harness is stopped they are
1293
+ stored (they never start it) and applied by the next start before any pending
1294
+ work can run. Creating a conversation with a title, and deleting one, record
1295
+ the channel's name and retirement the same way.
1296
+ - **After a harness crash** the host reopens the session, restores committed
1297
+ replies it missed, settles interrupted turns as failed, and keeps accepted
1298
+ input pending. Interrupted tool calls are never replayed.
1299
+
1300
+ Use `conversationMessages({ channel })` for a page from the harness.
1301
+ `catchUp(channel, savedPosition, commitPage)` requests missed messages.
1302
+ Persist each page and its position together, using message IDs to deduplicate.
1303
+ The default acp-client transcript remains available independently. Use
1304
+ `timeline()` for harness activity and `usage(channel?)` for reported token
1305
+ totals, missing field counts, and completeness. Usage is an explicit scan
1306
+ of the model-call pages. For per-turn records, see [Native turn metering](#native-turn-metering).
1307
+
1308
+ ### One-off reminders (experimental)
1309
+
1310
+ Use `conversation.reminders` on an Agent-owned native conversation. Check
1311
+ `conversation.conversationCapabilities.reminders` before offering controls.
1312
+ Native support is provisional before the harness connects. On initialize,
1313
+ the host checks the harness description for `capabilities.reminders` and
1314
+ reads its `reminderLimits`. ACP conversations and harnesses that lack support
1315
+ reject reminder operations with `ReminderError` code `reminders_unsupported`.
1316
+
1317
+ ```ts
1318
+ import type { Agent, AgentConversation } from "@qlairoslabs/acp-client";
1319
+
1320
+ export async function scheduleFollowUp(conversation: AgentConversation) {
1321
+ if (!conversation.conversationCapabilities.reminders) return;
1322
+ const reminder = await conversation.reminders.create({
1323
+ text: "Check whether the build has finished and report the result.",
1324
+ schedule: { in: 5 * 60_000 },
1325
+ });
1326
+ if (reminder.state === "blocked") {
1327
+ console.warn("Reminder blocked", reminder.id, reminder.reason);
1328
+ }
1329
+ return reminder;
1330
+ }
1331
+
1332
+ export async function listReminderPages(agent: Agent) {
1333
+ let after: string | undefined;
1334
+ do {
1335
+ const { items, nextCursor } = await agent.reminders.list({ after, limit: 50 });
1336
+ for (const reminder of items) console.log(reminder.id, reminder.status, reminder.state);
1337
+ after = nextCursor ?? undefined;
1338
+ } while (after !== undefined);
1339
+ }
1340
+ ```
1341
+
1342
+ - **Schedule.** Use `{ at: epochMilliseconds }` or `{ in: delayMilliseconds }`.
1343
+ The library converts relative time to an absolute time at acceptance and
1344
+ keeps it across retries and restarts. The bundled harness requires at least
1345
+ two minutes of lead time. See [Reminder routines](#reminder-routines) for
1346
+ interval and cron schedules on compatible harnesses.
1347
+ - **Expiry.** Grace starts at the scheduled instant. Omit `expiresAfter`
1348
+ for twice the lead time, clamped to five minutes through 24 hours with the
1349
+ bundled limits. Supply an integer millisecond duration within those bounds
1350
+ or `null` to allow late delivery without expiry. At the expiry instant
1351
+ the reminder expires without queuing a notice. A schedule edit resolves
1352
+ a new default grace from the new lead and preserves an earlier explicit
1353
+ duration or `null` unless you supply a replacement. An expiry-only edit
1354
+ uses the saved schedule anchor. Pause and resume do not extend the expiry
1355
+ or move the scheduled time.
1356
+ - **Read or edit.** Use `get(id)` (returns `undefined` for a missing view)
1357
+ or `list()` for the conversation. Use `update(id, patch)` for text, a new
1358
+ schedule or expiry, and `pause(id)`, `resume(id)` or `cancel(id)` for
1359
+ lifecycle changes. Cancelling a reminder cannot retract a notice already
1360
+ queued. The Agent-wide list returns `{ items, nextCursor }`, defaulting to
1361
+ 50 items with a maximum of 100. Pass the cursor as `after` for the next page.
1362
+ - **Offline writes.** With a durable reminders repository, stopped writes are
1363
+ journaled and applied on the next executable open before due work runs.
1364
+ A stopped write does not directly start the harness. Eligible pending work
1365
+ can arm a wake. Without a durable repository, mutations that need to write
1366
+ offline reject with `reminders_unavailable`. In-flight changes retain their
1367
+ identity and payload on retry. A blocked journal entry stays visible with
1368
+ its reason. Use `discardBlocked(id)` to clear the local refusal. To correct
1369
+ a blocked create, call `create()` again for a new ID.
1370
+ - **Read freshness.** `state` describes the local view (`pending`,
1371
+ `maybe_sent`, `blocked` or `confirmed`), while `status` describes the
1372
+ reminder lifecycle. Offline reads combine the last-confirmed cache and
1373
+ local intents. The harness rows are authoritative. The host reconciles at
1374
+ open and refreshes reads while connected, so re-read after reconnect for
1375
+ current state.
1376
+
1377
+ `AgentConfig.reminders.authorize(conversationId, operation)` can veto host
1378
+ changes. Operations are `create`, `update` and `cancel`. The `limits`
1379
+ option supplies local validation defaults before negotiation. Harness
1380
+ limits take precedence when available. A host create can include additional
1381
+ `policyNames`. The library does not copy the destination channel's policy
1382
+ onto that request, and updates cannot replace the original names.
1383
+
1384
+ Local validation and availability errors reject with a `ReminderError`.
1385
+ A blocked harness change stays in the journal and appears on a
1386
+ `ReminderView` with `state: "blocked"` and a `reason`. Some code names
1387
+ are shared, so check whether the operation rejected or returned a blocked
1388
+ view.
1389
+
1390
+ | Where | Code | Meaning |
1391
+ | --- | --- | --- |
1392
+ | Local | `invalid_schedule` | The time is invalid or does not meet the minimum lead. |
1393
+ | Local | `invalid_input` | Invalid text, expiry, update patch or page size. |
1394
+ | Local | `conflict` | The edit conflicts with a terminal reminder or a cancellation already in progress. |
1395
+ | Local | `not_found` | The mutation has no matching editable reminder in this conversation. |
1396
+ | Local | `unauthorized` | The configured authorization callback refused the change. |
1397
+ | Local | `reminders_unavailable` | The mutation needs a live reminder service or durable storage. Agent-owned storage and service setup are required for this API. |
1398
+ | Local | `reminders_unsupported` | The conversation or connected harness lacks reminder support. |
1399
+ | Local | `routines_unavailable` | The peer lacks routine or unattended guard support, or executable open has yet to confirm an effective guard. |
1400
+ | Local or harness startup | `invalid_config` | The unattended-turn limit is invalid or differs from the saved limit. |
1401
+ | Harness request | `storage_failure` | A retryable storage or proof-budget failure returned no receipt. A live routine mutation that still has no receipt after retry returns a pending view. Retrying the same input reuses the saved ID and change. |
1402
+ | Startup | `reminder_batch_retry_exhausted` | Three startup attempts returned a storage failure. The session stays stopped and the frozen batch remains unacknowledged. See the recovery steps below. |
1403
+ | Harness | `unattended_guard_required` | Routine activation was blocked because the session lacks an enabled guard. |
1404
+ | Harness | `invalid_policy` | The reminder names a policy the harness does not accept. |
1405
+ | Harness | `channel_missing`, `channel_retired` | The destination channel is missing or retired. |
1406
+ | Harness | `invalid_schedule` | The harness refused the scheduled time, acceptance anchor or expiry. |
1407
+ | Harness | `limit_exceeded` | A harness reminder limit was exceeded. |
1408
+ | Harness | `conflict` | The change would reuse an identity with different content or collide with an existing reminder. |
1409
+ | Harness | `not_found` | The target reminder is missing. |
1410
+ | Harness | `stale` | An unseen change ID is at or below the recorded high-water mark for the reminder. |
1411
+ | Harness | `invalid_state` | The requested change is incompatible with the reminder's current state. |
1412
+
1413
+ Subscribe on the conversation for live updates. Extend exhaustive
1414
+ `AgentSessionEvent` and `AgentConversationEvent` switches for these events.
1415
+
1416
+ | Event | When it appears |
1417
+ | --- | --- |
1418
+ | `reminder_intent_recorded` | A local change was journaled. |
1419
+ | `reminder_intent_confirmed`, `reminder_intent_blocked` | A live mutation returned its outcome. Read the cache after startup to get outcomes of changes submitted offline. |
1420
+ | `reminder_intent_discarded` | A local blocked entry was discarded or cancellation removed an unsent create. |
1421
+ | `reminder_changed` | The harness reported a row change, including an agent-created reminder. |
1422
+ | `reminder_fired` | A notice was queued. Use its `noticeId` to relate it to inbox activity. This event does not indicate a completed turn. |
1423
+ | `reminder_cancelled`, `reminder_expired` | The harness cancelled or expired the reminder. |
1424
+ | `routine_disposition` | A routine processed a range of occurrences. Includes `reminderId`, `firstScheduledAt`, `lastScheduledAt`, `count` and `reason` (`missed`, `catch_up_limit`, `overlap`, `expired` or `coalesced`). |
1425
+ | `routine_migration_blocked` | A timezone data update held a cron routine. Includes `reminderId`, `fromVersion`, `targetVersion` and `cause` (`invalid_schedule` or `proof_budget`). |
1426
+
1427
+ The harness tools `schedule_reminder`, `list_reminders` and
1428
+ `cancel_reminder` are scoped to the calling channel and subject to its
1429
+ tool policy. Historical events are not replayed. Read reminder rows and
1430
+ normal inbox or turn history after reconnect.
1431
+
1432
+ #### Reminder routines
1433
+
1434
+ A 0032-compatible native harness advertises both `routines` and
1435
+ `unattendedTurnGuard`. The Agent enables authoring when an executable open
1436
+ also confirms a non-null guard. Check `conversationCapabilities.routines`
1437
+ after that open. Routine authoring requires an executable open in this Agent
1438
+ process, including for offline writes after a restart. Guard evidence stays
1439
+ in memory and each connection obtains it from its own executable open.
1440
+ The bundled one-off harness reports a zero routine cap.
1441
+
1442
+ Set `AgentConfig.harness.config.limits.unattendedTurns` to a positive safe
1443
+ integer or `"unlimited"` to enable the guard on session creation or on the first executable
1444
+ open that enables it for an existing session. There is no default. The
1445
+ harness persists the bound value and later opens can omit it. Setting a
1446
+ different value fails with `invalid_config`. Explicit configuration on a
1447
+ peer lacking support fails as incompatible. Inspection cannot enable the
1448
+ guard.
1449
+
1450
+ `"unlimited"` sends `9007199254740991` (`Number.MAX_SAFE_INTEGER`). The
1451
+ guard stays on and keeps counting, with a limit high enough that it
1452
+ effectively leaves unattended paid turns uncapped. A spending cap is
1453
+ still a TODO. Both spellings bind the same numeric value.
1454
+
1455
+ The guard counts consecutive turns per channel that begin without
1456
+ owning-host participant input. A taken participant item resets the count.
1457
+ Automated work should use notices. When the limit is exhausted, the
1458
+ channel's routines wait for eligible participant input and contribute no
1459
+ routine wake. No disposition is emitted when the guard holds work.
1460
+
1461
+ Use the existing reminder API to author a routine after startup.
1462
+
1463
+ ```ts
1464
+ import type { ReminderCreate } from "@qlairoslabs/acp-client";
1465
+
1466
+ export const checkQueue = {
1467
+ text: "Check the queue and summarize new items.",
1468
+ schedule: { every: 600_000, count: 6 },
1469
+ missedRuns: "coalesce",
1470
+ overlap: "skip",
1471
+ } satisfies ReminderCreate;
1472
+
1473
+ export const reviewCalendar = {
1474
+ text: "Review today's calendar.",
1475
+ schedule: { cron: "0 9 * * 1-5", timezone: "Europe/Paris" },
1476
+ expiresAfter: null,
1477
+ } satisfies ReminderCreate;
1478
+ ```
1479
+
1480
+ Pass either input to `conversation.reminders.create(input)`.
1481
+
1482
+ - Intervals take milliseconds and an optional epoch-millisecond `startAt`.
1483
+ The first occurrence defaults to acceptance plus one interval. Cron accepts
1484
+ five numeric fields with wildcards, lists, ranges and steps. Both day
1485
+ fields must match. Supply a timezone. The harness validates the zone and
1486
+ proves the spacing between occurrences.
1487
+ - Use a positive safe integer `count` or an inclusive epoch-millisecond
1488
+ `until`. Omitting both allows the routine to continue indefinitely.
1489
+ Each processed occurrence consumes count, including skipped ones. A
1490
+ routine can remain active after `reminder_fired`.
1491
+ - A schedule edit replaces the remaining recurrence and resets its anchor
1492
+ and bound. The schedule kind stays the same. Text, grace, policy and
1493
+ lifecycle edits preserve the anchor. Default grace is twice the time to
1494
+ the next calendar match, clamped to five minutes through 24 hours. Explicit
1495
+ durations and `null` are preserved unless replaced. Read a confirmed row
1496
+ for the next occurrence's expiry and any remaining count.
1497
+ - `missedRuns` defaults to `coalesce`, which produces one notice for the
1498
+ live backlog. `skip` consumes it without a notice. `each` queues a
1499
+ bounded backlog. `overlap` defaults to `skip` and also accepts `queue`.
1500
+ The harness advertises a 600,000 ms minimum interval, 20 active routines
1501
+ per channel and 10 catch-up notices per routine per eligibility episode.
1502
+ The harness enforces its active cap.
1503
+ - Offline mutations require durable storage and guard confirmation in this process.
1504
+ At startup, cancellations, pauses and other non-activating changes go
1505
+ before due work. Creates, resumes and schedule replacements wait for
1506
+ the connection's executable open and retain their original acceptance time.
1507
+ A held entry also holds any later changes to its ID. An entirely unsent
1508
+ create can be cancelled locally. A create followed by pause is sent live
1509
+ in order, and a due occurrence may commit between those requests. An
1510
+ offline schedule replacement can take effect after overdue work from the
1511
+ old calendar. Held changes alone do not launch the harness. If open
1512
+ confirms no effective guard, the harness can record
1513
+ `unattended_guard_required` when the queued activation is sent live.
1514
+
1515
+ If startup exhausts its reminder batch retries, correct the storage cause
1516
+ and start again to replay the exact frozen batch. The harness does not
1517
+ identify the failing entry. To recover by elimination, stop the harness,
1518
+ call `conversation.reminders.discardExhausted(reminderId)` for one
1519
+ reminder, then start the harness again. Repeat if the remaining batch still
1520
+ fails. The call returns `true` when it removes that reminder's frozen
1521
+ entries. Later pending entries for the same reminder stay queued. If they
1522
+ target a discarded create that never committed, they can come back blocked
1523
+ with `not_found`. Use `discardBlocked(reminderId)` to clear them.
1524
+
1525
+ Discard removes local intent only. If the harness already committed a
1526
+ discarded create, the reminder can still fire and the next startup sweep
1527
+ will show it as a confirmed row. Check that row before creating a new
1528
+ reminder. A new ID creates a duplicate if the original is still alive.
1529
+
1530
+ Routine events are live, and identical frames are all delivered. An
1531
+ `expired` disposition counts occurrences. The client refreshes the row to
1532
+ learn the remaining count, next run and terminal state. Within one commit a disposition precedes the fire
1533
+ it describes. A migration hold precedes the updated row, whose state is
1534
+ `blocked` with `blockedReason: "invalid_schedule"` and `timezoneMigration`.
1535
+ The row remains visible and contributes no wake while held. Use confirmed
1536
+ rows after reconnect.
1537
+
1538
+ #### Cold wake and idle stop
1539
+
1540
+ Only an Agent holding the file-backed SQLite owner lock arms a cold wake.
1541
+ While running, the harness owns reminder scheduling. While stopped, the
1542
+ host uses the earliest eligible deadline, including any earlier validation
1543
+ wake from a pending change. Validation can launch the host early without
1544
+ moving the reminder's schedule. Paused or suspended work contributes no
1545
+ eligible deadline from the harness. Executable opens and deadline events
1546
+ share a revision fence for the same session. Older revisions and conflicting
1547
+ values at the same revision are ignored, and conflicts are logged. Only a
1548
+ replacement session starts a new fence.
1549
+
1550
+ During `agent.nativeHarness.stop()`, the host drains deadline updates from
1551
+ the stopping connection and rearms the cold wake from the stored index when
1552
+ stop finishes. `agent.close()` clears the timer and retains the stored wake
1553
+ for the next Agent open. Each cold timer
1554
+ wait is capped at 60 seconds and the wall clock is checked again before
1555
+ launching. Wakes only run while acp-client is running. Starting the process
1556
+ and reopening its session adds delay. If acp-client dies after the harness
1557
+ commits a new deadline but before acp-client saves it, the next eligible
1558
+ open recovers it. The reminder can then run late or expire.
1559
+
1560
+ Configure optional idle stop under `AgentConfig.harness`. A positive
1561
+ `idleStopMs` enables it. Omit it or set it to zero to leave it off.
1562
+ `idleStopWindowMs` defaults to zero, and an attached conversation can
1563
+ override it through its runtime settings. The host uses the largest window
1564
+ for channels with active confirmed reminders. The optional `reminderTimer`
1565
+ injects a clock and cancellable timer for wake and idle checks. Its
1566
+ `ReminderTimer` shape is structural. Supply `now(): number` for the current
1567
+ epoch time in milliseconds and `set(delayMs, task)` to schedule `task` after
1568
+ that many milliseconds. Return a `() => void` cancellation function from
1569
+ `set`. Without an override, the host uses the wall clock and unref'ed timers.
1570
+
1571
+ Idle stop waits until local work is clear, then asks the harness to stop
1572
+ atomically with `session/stop { ifIdle: true, unlessDueWithinMs }`.
1573
+ The harness can refuse with `busy` or `next_due_soon`. A refusal leaves
1574
+ the session running. Work that arrives after a successful idle stop can
1575
+ start it again.
1576
+
1577
+ ### Restart the native agent and apply live settings
1578
+
1579
+ Use `await agent.previewNativeRestart()` to get `conversationCount` and
1580
+ `conversationIds` for a confirmation dialog. The preview includes active
1581
+ native conversation records, including ones whose harness channel is created
1582
+ on first use. ACP conversations are outside its scope.
1583
+
1584
+ ```ts
1585
+ const preview = await agent.previewNativeRestart();
1586
+ const result = await agent.restartNative({ when: "idle", config: nextHarnessConfig });
1587
+ ```
1588
+
1589
+ `when: "idle"` waits for active turns, approvals and queued native input
1590
+ across the agent, then uses the harness's atomic idle stop. Use
1591
+ `waitForNativeIdle({ signal })` to wait without restarting. An idle wait is
1592
+ a snapshot and new input can arrive after it resolves. Suspended work
1593
+ with queued input can keep the wait pending. Supply an abort signal when
1594
+ the user can cancel the wait. `when: "now"` requests interruption of
1595
+ running turns and restarts the shared native process. The harness retains
1596
+ its durable queue and reminder wake. Closing the Agent cancels idle waits.
1597
+
1598
+ The executable open takes the replacement `config` and optional
1599
+ `functions` catalog. Omit either to keep the Agent's current setting.
1600
+ Pass `functions: null` to clear application-supplied functions.
1601
+ The harness applies its normal configuration precedence and compatibility
1602
+ checks, including a managed configuration sidecar when present. The
1603
+ Agent uses the new settings for subsequent opens in the same process.
1604
+ Persist application configuration separately if future Agent instances
1605
+ need to supply it.
1606
+
1607
+ `subscribeNativeRestart(listener)` returns an unsubscribe function.
1608
+ The listener receives the same `restarted` or `restart_failed` result
1609
+ as the caller, with interrupted harness turn IDs and per-conversation
1610
+ outcomes. A `reconnected` channel was reconciled by the replacement
1611
+ open. A `deferred` conversation has no channel in that open and can
1612
+ materialize on use. On failure the result includes the error. Native
1613
+ conversation handles retain their identity and subscriptions.
1614
+
1615
+ Read `agent.channelSettingsLive` for channel-scoped edits, session-wide
1616
+ tool controls and settings to defer to an executable open.
1617
+
1618
+ - `applyNativeChannelSettings(id, { displayName, policy, lifecycle })`
1619
+ uses the ordered channel change path. A running harness applies it
1620
+ live. A stopped harness stores it for its next open. `policy` selects
1621
+ an existing named policy. A policy-only change keeps the channel
1622
+ name. Pass `null` to clear a name or policy. The lifecycle values
1623
+ `"suspended"`, `"open"` and `"retired"` map to suspend, resume and
1624
+ delete. To delete the local conversation and its records as well,
1625
+ use `agent.conversations.delete(id)`.
1626
+ - `applyNativeToolSetting(name, operation)` enables or removes runtime
1627
+ tools, or revokes or restores revocable tools. It requires a running
1628
+ harness. The operations affect the whole session. Per-channel access
1629
+ can be restricted by the channel's named policy.
1630
+ - Named policy definitions, the default policy, model, system prompt and
1631
+ tool catalog take effect on executable open. The native wire has no
1632
+ participant-roster edit for an existing channel. An open alone cannot
1633
+ replace that roster, so hold or refuse that edit. Unsupported
1634
+ channel fields return `channel_settings_not_live` with the field
1635
+ names, without applying any part of the patch.
1636
+
1637
+ ### Native turn metering
1638
+
1639
+ Agent-owned native conversations meter turns by default (`best_effort`). The
1640
+ native path ignores a consumer-supplied `inferenceSource` and pricing policy.
1641
+ The source is scoped to `<Agent id>/<channel id>` and reads bounded pages from
1642
+ the harness's model-call ledger for the exact channel and wire turn ID. Read
1643
+ `result.metering` or the persisted metering operation. Native per-call usage
1644
+ events and native values in `TurnResult.usage` are deferred.
1645
+
1646
+ `nativeUsage` carries observed call and attempt IDs, outcomes, and usage fields,
1647
+ or an unavailable reason. Missing or still-running attempts stay unmeasured.
1648
+ A partially measured turn includes a reason. For measured native usage,
1649
+ provenance is always `native_ledger` with unknown routing, partial attribution,
1650
+ and no certification ID, even when every attempt was measured. An empty scan,
1651
+ an unavailable host, or an undispatched turn gives unavailable usage. A prompt
1652
+ cancelled while still queued may have no metering record. The current wire
1653
+ leaves provider and model identity unknown, so measured native usage has
1654
+ `pricing_unavailable`.
1655
+
1656
+ SQLite upgrades schema 20 to 21 on open. The upgrade is one-way. Older code
1657
+ refuses a schema 21 database. The per-channel cursor lives in the metering
1658
+ state. The bounded proof lives on the operation index row and survives when
1659
+ operation detail is pruned.
1660
+
1661
+ A failed final save can replay under the same operation ID when the write-ahead
1662
+ record was staged. If staging and final save both fail, a later close can
1663
+ recover the sealed calls as unaccounted usage of an earlier turn.
1664
+ `nativeUsage.earlierEvidencePending` means an earlier turn is still awaiting confirmation
1665
+ that it ended.
1666
+
1667
+ The turn's usage and `state.totals` carry attributed usage. Read totals from the
1668
+ record's `nextState.totals` or from `(await persistence.metering.state(id))?.state.totals`
1669
+ for conversation `id`. A later close can record earlier-turn evidence in
1670
+ `nativeUsage.unaccountedEarlierCalls` and accrue measured tokens once in
1671
+ `state.unallocatedUsage`. These additions represent unaccounted usage of an
1672
+ earlier turn. Between-turn usage remains unsupported. Attributed and
1673
+ unallocated tokens together cover known spend and may still be a lower bound.
1674
+ If only truncated proof survives, later-sealed attempts outside the retained
1675
+ proof appear as unmeasured. Earlier evidence can also list an already-counted
1676
+ attempt as unmeasured when its ID was omitted from proof. The unmeasured count
1677
+ is an evidence count and cannot be summed as lost spend.
1678
+
1679
+ Native `billing_required` throws `MeteringPreflightError` until the harness can
1680
+ attest `native-harness@1` sealed per-turn accounting. Certification still needs
1681
+ provider and model identity, normalized cache categories, reported cost and
1682
+ currency when available, attempt purpose, and a sealed turn manifest that can
1683
+ attest zero usage. Between-turn billing needs a harness producer for calls
1684
+ without turn ownership and a bounded collection path while idle.
1685
+
1686
+ ### Offline native rehearsal
1687
+
1688
+ From the repository root, run the checked-in multi-minute fixture:
1689
+
1690
+ ```sh
1691
+ bun run test/native/rehearsal-cli.ts test/native/fixtures/rehearsal-two-minutes.jsonl 150000
1692
+ ```
1693
+
1694
+ The driver creates a fresh local harness home and uses a scripted stdio child.
1695
+ The fixture schedules two bursts and a final notice after idle gaps. Its
1696
+ policy allows only `notify_channel` and the test callback `quiet`, which
1697
+ waits up to two seconds and has a five-second tool deadline. The command
1698
+ requires no provider credentials or manual answers. It checks exact
1699
+ consumption, reports input outcomes and callback effects, compares reply IDs
1700
+ against bounded history reads at a settled revision, and reports the child
1701
+ exit code. Full inference-request capture is off. Longer JSONL fixtures use
1702
+ the same command with a deadline in milliseconds. Deterministic tests handle
1703
+ manual barriers and process replacement in code.
1704
+
1705
+ ### Functions the model can call
1706
+
1707
+ Register functions in `harness.functions.tools` before the Agent starts.
1708
+ The host declares the handler names during initialize and sends the tool
1709
+ catalog on every executable session open or create. Set `defaultPolicy` and
1710
+ `policies` under `harness.config`. The harness uses those policies to decide
1711
+ which tools to offer and whether a call needs approval. It validates the
1712
+ arguments against `parameters` before calling the handler in this process.
1713
+
1714
+ `harness.config.system` supplies the complete consumer system text. At the
1715
+ next executable open, changing it replaces that text for subsequent model
1716
+ requests in the same saved session. The harness still appends its own
1717
+ instructions and retains the conversation history. To apply a different
1718
+ configuration, close the Agent and open it with the new configuration and
1719
+ the same persisted Agent and harness home.
1720
+
1721
+ ```ts
1722
+ harness: {
1723
+ home, config,
1724
+ functions: {
1725
+ defaultDeadlineMs: 60_000, // optional; without it a call has no deadline
1726
+ tools: {
1727
+ lookup: {
1728
+ description: "Look up an order",
1729
+ parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"], additionalProperties: false },
1730
+ handler: async ({ id }, { signal, channel }) => findOrder(id, signal),
1731
+ },
1732
+ refund: { group: "revocable", description: "...", parameters: {...}, handler: refund },
1733
+ export: { group: "runtime", enabled: false, description: "...", parameters: {...}, handler: exportData },
1734
+ },
1735
+ },
1736
+ },
1737
+ ```
1738
+
1739
+ - **Groups.** `fixed` (default) cannot be removed while running. `revocable`:
1740
+ `agent.nativeHarness.revokeTool(name)` and `restoreTool(name)`; the harness
1741
+ stores this with the session, so it survives restarts. `runtime`:
1742
+ `enableTool(name)` and `removeTool(name)`; the selection lives in this
1743
+ process and is sent again when the harness reopens.
1744
+ - **Why a tool cannot run.** `agent.nativeHarness.tools()` lists each tool
1745
+ with `available` and a reason (`revoked`, `not_enabled`, `handler_missing`).
1746
+ Policy is separate: a tool the conversation's policy denies is not offered.
1747
+ - **Handlers.** The second argument contains `invocationId`, `channel`,
1748
+ `turnId`, `tool`, `policyNames` and `signal`. `policyNames` comes from
1749
+ the harness authorization snapshot. The names have no precedence by order.
1750
+ Return a JSON value as the tool result. Throw `FunctionError(code, message)` for
1751
+ a failure the model should see. `signal` aborts when the harness stops
1752
+ waiting: the tool's deadline passed, the turn was interrupted, or the harness
1753
+ stopped. A value returned after that is ignored.
1754
+ - **Quiet handlers are fine.** A native turn is not cancelled by
1755
+ `operationLifecycle` silence limits. The harness enforces the model,
1756
+ approval and tool deadlines. `agent.nativeHarness.status()` shows each
1757
+ running turn's `activeTurn.phase` (`model`, `approval` or `tool`, since when,
1758
+ and the ID it concerns).
1759
+ - **Deadlines.** `deadlineMs` on a tool overrides `defaultDeadlineMs`. When it
1760
+ passes, the model receives a timeout result that says the effect is unknown,
1761
+ and the turn continues.
1762
+ - **Large results.** A result over 16 384 bytes is written to a private
1763
+ directory (`resultDirectory`, or a temporary one removed on stop) and the
1764
+ model receives a preview and an ID. It reads parts with the built-in
1765
+ `read_tool_result` tool. Only the conversation that produced a result can
1766
+ read it. Results expire after `resultTtlMs` (24 hours by default).
1767
+ - **Records.** `agent.nativeHarness.toolInvocation(id)` and
1768
+ `toolInvocations(turn)` return each call's state. A call that was dispatched
1769
+ but has no recorded result (crash, lost connection, interrupt) is
1770
+ `interrupted` with `effect: "unknown"`. It is never run again automatically.
1771
+
1772
+ Native conversations do not support attaching ACP `mcpServers`. To use an
1773
+ MCP tool, connect the MCP client in your host application and register a
1774
+ native function that calls it. Supply the tool description and input schema
1775
+ and allow the wrapper by its registered name in `harness.config.policies`.
1776
+
1777
+ ```ts
1778
+ import { FunctionError, type NativeFunctionsConfig } from "@qlairoslabs/acp-client";
1779
+
1780
+ export function orderTools(
1781
+ callMcpTool: (name: string, args: Record<string, unknown>, signal: AbortSignal) =>
1782
+ Promise<{ content: unknown[]; isError?: boolean }>,
1783
+ ): NativeFunctionsConfig {
1784
+ return {
1785
+ tools: {
1786
+ lookup: {
1787
+ description: "Look up an order",
1788
+ parameters: {
1789
+ type: "object",
1790
+ properties: { id: { type: "string" } },
1791
+ required: ["id"],
1792
+ additionalProperties: false,
1793
+ },
1794
+ async handler(args, { signal }) {
1795
+ const result = await callMcpTool("lookup_order", args, signal);
1796
+ if (result.isError) throw new FunctionError("mcp_tool_error", "Order lookup failed");
1797
+ return result.content;
1798
+ },
1799
+ },
1800
+ },
1801
+ };
1802
+ }
1803
+ ```
1804
+
1805
+ Pass the returned object as `harness.functions`. The host owns the MCP
1806
+ connection lifecycle and forwards cancellation through its client library.
1807
+
1808
+ Tool changes need a running harness: `revokeTool` and the others fail with
1809
+ `HarnessUnavailableError` while it is stopped.
1810
+
1811
+ Not available on a native conversation yet: `startFresh` and anything that
1812
+ needs a fresh context (`conversationCapabilities.freshContext` is `false`),
1813
+ handoff, modes, config options, provider session listing, adoption, and a
1814
+ local user-message record for native prompts. See [native turn metering](#native-turn-metering)
1815
+ for available usage evidence and its limits.
1816
+
1817
+ ## Orchestrator and worker delivery (experimental)
1818
+
1819
+ Enable the orchestrator on the same Agent as the native harness. It requires
1820
+ `capture.message: "content"` and persistence capabilities for workers and worker
1821
+ delivery. SQLite provides both. Use an ACP adapter for the worker pool. The
1822
+ example adds a native `owner` policy that can call the delegation tools and a
1823
+ separate policy for approvals requested by workers.
1824
+
1825
+ ```ts
1826
+ import { Agent, type AgentAdapter, type AgentHarnessConfig } from "@qlairoslabs/acp-client";
1827
+
1828
+ export async function openWorkerPool(
1829
+ directory: string,
1830
+ worker: AgentAdapter,
1831
+ model: AgentHarnessConfig["config"]["model"],
1832
+ ) {
1833
+ const delegation = { use: true, scope: "all", redirect: true, maxOpen: 2 } as const;
1834
+ return Agent.open({
1835
+ persistence: { kind: "sqlite", path: `${directory}/agent.sqlite` },
1836
+ adapters: { main: { kind: "native" }, worker },
1837
+ defaultAdapterId: "main",
1838
+ capture: { message: "content" },
1839
+ harness: {
1840
+ home: `${directory}/harness-home`,
1841
+ config: {
1842
+ version: 1, system: "Delegate bounded tasks and report the results.", model,
1843
+ defaultPolicy: "owner",
1844
+ policies: { owner: { fallback: "deny", tools: {
1845
+ delegate: "allow", check: "allow", list: "allow", stop: "allow",
1846
+ } } },
1847
+ },
1848
+ },
1849
+ orchestrator: {
1850
+ workers: { adapterId: "worker", cwd: directory, limit: 2, idleStopMs: 60_000 },
1851
+ ownerPolicies: ["owner"],
1852
+ defaults: { delegation, workerPermissions: { default: "ask" } },
1853
+ policies: { owner: { delegation, workerPermissions: { default: "ask" } } },
1854
+ },
1855
+ });
1856
+ }
1857
+
1858
+ export async function workerControls(agent: Agent, handle: string) {
1859
+ const workers = agent.workers;
1860
+ if (!workers) throw new Error("Enable the orchestrator first");
1861
+ const summary = await workers.check(handle);
1862
+ return {
1863
+ summary,
1864
+ list: () => workers.list(),
1865
+ retryBlockedDelivery: () => workers.retryDelivery(handle),
1866
+ stop: () => workers.stop(handle),
1867
+ delete: () => workers.delete(handle),
1868
+ };
1869
+ }
1870
+ ```
1871
+
1872
+ The harness exposes `delegate`, `check`, `list` and `stop` as native tools.
1873
+ Grant them in the harness policy as well as configuring the corresponding
1874
+ orchestrator policy. For `delegate`, send `{ text, about? }` to create a
1875
+ worker, or include `worker` to send to a known handle. `check` and `stop`
1876
+ take `{ worker }`; `list` takes an empty object. These names are reserved
1877
+ while native delegation is enabled. The trusted host can also use
1878
+ `agent.orchestrator` with a consumer actor. Use
1879
+ `agent.events.subscribeWorkers` for worker lifecycle events. Event kinds are
1880
+ `worker_opened`, `worker_busy`, `worker_idle`, `worker_replied`,
1881
+ `worker_reloaded`, `worker_dropped`, `worker_redirected`, `worker_failed`
1882
+ and `worker_stopped`.
1883
+
1884
+ A busy worker follows its current assignment. Its current giver can steer
1885
+ with another message for the same handle. A different giver needs redirect
1886
+ authority and `redirect: true` to take over the destination. Without a redirect,
1887
+ a send from another giver reports `busy` and queues nothing. Use
1888
+ `assignment: "new"` to replace the assignment. Outstanding forwarded
1889
+ approvals stay with their original giving conversation. The giving
1890
+ conversation answers forwarded requests with `answerPermission`. Non-owner
1891
+ requests omit persistent approval options. Without an eligible answerer,
1892
+ an ask is refused.
1893
+
1894
+ `workers.limit` bounds the active pool. Policy can further narrow scope,
1895
+ redirection and the maximum number opened by a giver. An idle worker may be
1896
+ evicted to make room. If no slot can be freed, sending reports
1897
+ `no_worker_free`. Idle stop defaults to ten minutes and accepts `false`
1898
+ to keep idle connections open. The next send reloads a stopped worker.
1899
+ `workers.delete` returns the provider cleanup outcome. Consumer defaults
1900
+ apply to consumer work or when no native policy contributes. When several
1901
+ named policies contribute, their restrictions compose and all must be in
1902
+ `ownerPolicies` to grant owner authority.
1903
+
1904
+ The Agent records the assignment before dispatch. A finished worker leaves
1905
+ one saved outcome, tied to that assignment and destination. An ACP
1906
+ destination receives an out-of-band message for the next prompt. A native
1907
+ destination receives a harness notice. Restart recovery looks for the saved
1908
+ result by assignment ID, and retries eligible notices without running the
1909
+ worker again. A lost result can be reported as uncertain. `check` and
1910
+ `list` show the latest outcome and delivery state when available. Native
1911
+ results may be absent until the harness opens. Delivery states are `pending`
1912
+ (awaiting delivery), `delivered`, `blocked_policy` (policy rejection), and
1913
+ `failed_destination` (the destination is missing or retired). `retryDelivery` explicitly
1914
+ retries only the newest policy-blocked delivery. A retired or missing
1915
+ destination remains a failed delivery.
1916
+
1917
+ From the source checkout, run the offline smoke test with
1918
+ `bun smoke-tests/orchestrator/run.ts`. Live mode requires explicit approval
1919
+ for spend, `ACP_ORCH_LIVE=1`, `OPENROUTER_API_KEY`, local Codex binaries
1920
+ and a separately authenticated disposable `ACP_ORCH_CODEX_HOME`. Use
1921
+ throwaway work, supervise with the documented external wall-clock cap, and
1922
+ never set the flag for an offline run. The runner caps native requests and
1923
+ worker submissions. The Codex CLI's internal calls are uncapped.
1924
+ [Smoke-test instructions](smoke-tests/orchestrator/README.md)
1925
+
1926
+
950
1927
  ## Legacy direct and managed sessions
951
1928
 
952
1929
  The remaining sections describe the compatibility `AgentSession` and
@@ -1037,7 +2014,7 @@ async function createSession(adapterId: string): Promise<AgentSession> {
1037
2014
  adapterId,
1038
2015
  cwd: process.cwd(),
1039
2016
  title: "Repository agent",
1040
- defaultPermission: "cancel",
2017
+ permissions: { default: "ask" },
1041
2018
  persistence: {
1042
2019
  transcript: { preset: "activity" },
1043
2020
  },
@@ -1251,6 +2228,7 @@ Messages that had to wait emit events on the conversation event stream:
1251
2228
  | Event | Meaning |
1252
2229
  |---|---|
1253
2230
  | `message_pending { id, delivery }` | Accepted and waiting. `delivery` is the mode in effect: `"queue"` while the running operation is not a consumer prompt turn (a handoff, a configuration change). |
2231
+ | `message_status { id, status, turnId? }` | Live delivery progress for an individual prompt. See [Message status](#message-status). |
1254
2232
  | `message_delivered { ids, via, turnId }` | Sent to the agent. `ids` lists every message in the prompt; `via` is `"tool_boundary"`, `"interrupt"` or `"turn_end"`. |
1255
2233
  | `message_withdrawn { id }` | Removed before delivery. |
1256
2234
 
@@ -1524,7 +2502,7 @@ async function loadSession(agentSessionId: string): Promise<AgentSession> {
1524
2502
  const opened = await sessions.loadAgentSession(agentSessionId, {
1525
2503
  adapter: resolveAdapter(info.adapterId),
1526
2504
  adapterId: info.adapterId,
1527
- defaultPermission: "cancel",
2505
+ permissions: { default: "ask" },
1528
2506
  onOpenProgress: projectOpenProgress,
1529
2507
  });
1530
2508
 
@@ -2116,9 +3094,9 @@ Set `operationLifecycle` on `Agent.open()` or a detached conversation:
2116
3094
 
2117
3095
  ```ts
2118
3096
  operationLifecycle: {
2119
- turns: { firstOutputMs: 120_000, nextOutputMs: 180_000 },
2120
- internalInference: { firstOutputMs: 120_000 },
2121
- recap: { nextOutputMs: 180_000 },
3097
+ turns: { firstOutputMs: 600_000, nextOutputMs: 900_000 },
3098
+ internalInference: { firstOutputMs: 600_000 },
3099
+ recap: { nextOutputMs: 900_000 },
2122
3100
  }
2123
3101
  ```
2124
3102