@qlairoslabs/acp-client 0.12.1 → 0.13.0-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 (467) 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 +845 -6
  6. package/MIGRATION-0.10-to-0.12.md +4 -1
  7. package/MIGRATION-0.12-to-0.13.md +275 -0
  8. package/README.md +17 -16
  9. package/package.json +4 -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 +94 -158
  19. package/src/agent/manager-settings.ts +1 -0
  20. package/src/agent/native-channel-lifecycle.ts +111 -0
  21. package/src/agent/persisted-lifecycle.ts +44 -4
  22. package/src/agent/persistence-policy/context.ts +13 -0
  23. package/src/agent/persistence-policy/resolver.ts +7 -0
  24. package/src/agent/persistence-policy/types.ts +1 -0
  25. package/src/agent/record-capture.ts +1 -0
  26. package/src/agent-adapter-registry.ts +33 -7
  27. package/src/agent-conversation-contracts.ts +14 -1
  28. package/src/agent-conversation-errors.ts +8 -0
  29. package/src/agent-conversation-owner.ts +9 -4
  30. package/src/agent-session-config.ts +135 -0
  31. package/src/agent-session.ts +439 -934
  32. package/src/agent.ts +73 -0
  33. package/src/capabilities.ts +2 -0
  34. package/src/checkpointing/recovery.ts +3 -0
  35. package/src/cli/index.ts +3 -3
  36. package/src/cli/managed.ts +2 -2
  37. package/src/client.ts +52 -94
  38. package/src/connection-attempt.ts +95 -0
  39. package/src/controller-connection.ts +114 -0
  40. package/src/controller.ts +156 -148
  41. package/src/conversation-controller/capabilities.ts +88 -0
  42. package/src/conversation-controller/contracts.ts +208 -0
  43. package/src/conversation-controller/factory.ts +39 -0
  44. package/src/conversation-controller/guards.ts +98 -0
  45. package/src/conversation-controller/index.ts +20 -0
  46. package/src/conversation-startup.ts +35 -0
  47. package/src/conversation-turns/backend-turns.ts +373 -0
  48. package/src/conversation-turns/clear-operations.ts +37 -0
  49. package/src/conversation-turns/context.ts +135 -0
  50. package/src/conversation-turns/index.ts +4 -0
  51. package/src/conversation-turns/record-helpers.ts +75 -0
  52. package/src/conversation-turns/recording.ts +235 -0
  53. package/src/conversation-turns/run-turn.ts +367 -0
  54. package/src/conversation-turns/turn-run.ts +57 -0
  55. package/src/errors.ts +41 -0
  56. package/src/handoff-options.ts +81 -0
  57. package/src/identity/checkpoint-backed.ts +1 -1
  58. package/src/index.ts +58 -3
  59. package/src/internal-inference/coordination/manager.ts +11 -0
  60. package/src/internal-inference/runtime/harness-runtime.ts +4 -4
  61. package/src/launcher.ts +35 -2
  62. package/src/media/parts.ts +5 -0
  63. package/src/message-status.ts +83 -0
  64. package/src/metering/engine.ts +39 -64
  65. package/src/metering/measurement-provenance.ts +36 -0
  66. package/src/metering/native/durability.ts +115 -0
  67. package/src/metering/native/ledger.ts +104 -0
  68. package/src/metering/native/operation.ts +85 -0
  69. package/src/metering/native/projection.ts +114 -0
  70. package/src/metering/native/proof.ts +51 -0
  71. package/src/metering/native/requirements.ts +10 -0
  72. package/src/metering/native/retirement.ts +92 -0
  73. package/src/metering/native/source.ts +90 -0
  74. package/src/metering/record.ts +38 -1
  75. package/src/metering/state.ts +13 -3
  76. package/src/native/approvals.ts +169 -0
  77. package/src/native/capabilities.ts +17 -0
  78. package/src/native/channel-changes.ts +211 -0
  79. package/src/native/connection.ts +56 -0
  80. package/src/native/controller.ts +591 -0
  81. package/src/native/delegation-sender.ts +26 -0
  82. package/src/native/errors.ts +35 -0
  83. package/src/native/functions.ts +156 -0
  84. package/src/native/host-config.ts +59 -0
  85. package/src/native/host.ts +909 -0
  86. package/src/native/item-receipts.ts +15 -0
  87. package/src/native/metering.ts +12 -0
  88. package/src/native/records.ts +166 -0
  89. package/src/native/recovery.ts +186 -0
  90. package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
  91. package/src/native/reminders/idle.ts +70 -0
  92. package/src/native/reminders/limits.ts +19 -0
  93. package/src/native/reminders/notifications.ts +29 -0
  94. package/src/native/reminders/reminders.test.ts +553 -0
  95. package/src/native/reminders/routine-config.typecheck.ts +13 -0
  96. package/src/native/reminders/routine-guard.ts +66 -0
  97. package/src/native/reminders/routine-schedule.ts +25 -0
  98. package/src/native/reminders/routine-wire.ts +21 -0
  99. package/src/native/reminders/schedule.ts +97 -0
  100. package/src/native/reminders/service.ts +280 -0
  101. package/src/native/reminders/supervisor.ts +91 -0
  102. package/src/native/reminders/sync.ts +301 -0
  103. package/src/native/reminders/wire.ts +197 -0
  104. package/src/native/reminders/wire.typecheck.ts +13 -0
  105. package/src/native/submission-withdrawal.ts +65 -0
  106. package/src/native/usage.ts +15 -0
  107. package/src/native/worker-delivery.ts +61 -0
  108. package/src/native-harness/.res/README.md +1 -0
  109. package/src/native-harness/.res/architecture/README.md +21 -0
  110. package/src/native-harness/.res/architecture/context-and-data.md +31 -0
  111. package/src/native-harness/.res/architecture/execution.md +42 -0
  112. package/src/native-harness/.res/architecture/overview.md +44 -0
  113. package/src/native-harness/.res/architecture/persistence.md +56 -0
  114. package/src/native-harness/.res/architecture/suspend-and-resume.md +45 -0
  115. package/src/native-harness/.res/architecture/technical-architecture.md +50 -0
  116. package/src/native-harness/.res/decisions/0001-basic-loop.md +11 -0
  117. package/src/native-harness/.res/decisions/0002-channel-input.md +17 -0
  118. package/src/native-harness/.res/decisions/0003-inference-inspection.md +14 -0
  119. package/src/native-harness/.res/decisions/0004-shared-context.md +21 -0
  120. package/src/native-harness/.res/decisions/0005-notice-inbox.md +20 -0
  121. package/src/native-harness/.res/decisions/0006-explicit-notices.md +12 -0
  122. package/src/native-harness/.res/decisions/0007-channel-output.md +12 -0
  123. package/src/native-harness/.res/decisions/0008-browser-client.md +16 -0
  124. package/src/native-harness/.res/decisions/0009-scripted-model.md +18 -0
  125. package/src/native-harness/.res/decisions/0010-inprocess-protocol.md +19 -0
  126. package/src/native-harness/.res/decisions/0011-stdio-transport.md +21 -0
  127. package/src/native-harness/.res/decisions/0012-session-storage-contract.md +37 -0
  128. package/src/native-harness/.res/decisions/0013-durable-delivery-contract.md +64 -0
  129. package/src/native-harness/.res/decisions/0014-channel-controls-contract.md +73 -0
  130. package/src/native-harness/.res/decisions/0015-session-file-contract.md +72 -0
  131. package/src/native-harness/.res/decisions/0016-configuration-permissions.md +159 -0
  132. package/src/native-harness/.res/decisions/0017-openrouter-managed-config.md +69 -0
  133. package/src/native-harness/.res/decisions/0018-tool-dispatch-evidence.md +78 -0
  134. package/src/native-harness/.res/decisions/0019-model-execution.md +188 -0
  135. package/src/native-harness/.res/decisions/0020-startup-channel-changes.md +71 -0
  136. package/src/native-harness/.res/decisions/0021-tools-and-host-callbacks.md +100 -0
  137. package/src/native-harness/.res/decisions/0022-operator-controls.md +115 -0
  138. package/src/native-harness/.res/decisions/0023-long-running-mock.md +82 -0
  139. package/src/native-harness/.res/decisions/0024-callback-policy-names.md +46 -0
  140. package/src/native-harness/.res/decisions/0025-external-notices.md +364 -0
  141. package/src/native-harness/.res/decisions/0026-bounded-context.md +81 -0
  142. package/src/native-harness/.res/decisions/0027-development-instructions.md +22 -0
  143. package/src/native-harness/.res/decisions/0028-debug-tools.md +16 -0
  144. package/src/native-harness/.res/decisions/0029-bounded-model-call-pages.md +37 -0
  145. package/src/native-harness/.res/decisions/0030-timeline-retrieval.md +145 -0
  146. package/src/native-harness/.res/decisions/0031-one-off-reminders.md +173 -0
  147. package/src/native-harness/.res/docs/11-15.md +148 -0
  148. package/src/native-harness/.res/docs/BUSINESS_RULES.md +111 -0
  149. package/src/native-harness/.res/docs/WORK.md +65 -0
  150. package/src/native-harness/.res/docs/_/11-16-persistence/LOG.md +312 -0
  151. package/src/native-harness/.res/docs/_/11-16-persistence/PLAN.md +77 -0
  152. package/src/native-harness/.res/docs/_/11-16-persistence/SPEC.md +313 -0
  153. package/src/native-harness/.res/docs/_/11-19-channel-controls/LOG.md +160 -0
  154. package/src/native-harness/.res/docs/_/11-19-channel-controls/PLAN.md +89 -0
  155. package/src/native-harness/.res/docs/_/11-19-channel-controls/SPEC.md +135 -0
  156. package/src/native-harness/.res/docs/_/11-19-config-permissions/LOG.md +143 -0
  157. package/src/native-harness/.res/docs/_/11-19-config-permissions/PLAN.md +93 -0
  158. package/src/native-harness/.res/docs/_/11-19-config-permissions/SPEC.md +181 -0
  159. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/11-20-LOG.md +433 -0
  160. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PLAN.md +60 -0
  161. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PROTOCOL.md +141 -0
  162. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/SPEC.md +168 -0
  163. package/src/native-harness/.res/docs/attachments/0001-DESIGN/SPEC.md +111 -0
  164. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/PLAN.md +129 -0
  165. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/SPEC.md +135 -0
  166. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/LOG.md +437 -0
  167. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/PLAN.md +127 -0
  168. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/SPEC.md +203 -0
  169. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/LOG.md +292 -0
  170. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/PLAN.md +91 -0
  171. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/SPEC.md +187 -0
  172. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/LOG.md +148 -0
  173. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/PLAN.md +95 -0
  174. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/SPEC.md +200 -0
  175. package/src/native-harness/.res/docs/model-execution/0002-AMENDMENT-accounting/SPEC.md +80 -0
  176. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/LOG.md +206 -0
  177. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/PLAN.md +106 -0
  178. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/SPEC.md +297 -0
  179. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/LOG.md +41 -0
  180. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/PLAN.md +36 -0
  181. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/SPEC.md +84 -0
  182. package/src/native-harness/.res/docs/shell-execution/0001-DESIGN/SPEC.md +147 -0
  183. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/LOG.md +15 -0
  184. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/PLAN.md +107 -0
  185. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/SPEC.md +114 -0
  186. package/src/native-harness/.res/docs/todos/11-19-TODO-auto_review-approve.md +24 -0
  187. package/src/native-harness/.res/docs/todos/11-20-TODO-user-entered-tool-code.md +23 -0
  188. package/src/native-harness/.res/docs/todos/11-21-TODO-node-resource-coordination.md +103 -0
  189. package/src/native-harness/.res/docs/todos/11-22-TODO-harness-m1-sequence.md +50 -0
  190. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/LOG.md +337 -0
  191. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/PLAN.md +76 -0
  192. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/SPEC.md +204 -0
  193. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/LOG.md +73 -0
  194. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/SPEC.md +64 -0
  195. package/src/native-harness/.res/docs/tools-and-callbacks/0003-DESIGN-attachment-tools/SPEC.md +58 -0
  196. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/LOG.md +45 -0
  197. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/PLAN.md +108 -0
  198. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/SPEC.md +169 -0
  199. package/src/native-harness/.res/docs/web-tools/0001-DESIGN/SPEC.md +128 -0
  200. package/src/native-harness/.res/marketing-draft.md +22 -0
  201. package/src/native-harness/.res/sandbox/1-simple-harness/README.md +285 -0
  202. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-1.md +19 -0
  203. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-10.md +138 -0
  204. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-11.md +148 -0
  205. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-12.md +172 -0
  206. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-13.md +194 -0
  207. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-14.md +233 -0
  208. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-15.md +249 -0
  209. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-16.md +265 -0
  210. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-17.md +279 -0
  211. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-18.md +293 -0
  212. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-19.md +307 -0
  213. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-2.md +29 -0
  214. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-20.md +317 -0
  215. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-21.md +327 -0
  216. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-3.md +40 -0
  217. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-4.md +59 -0
  218. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-5.md +69 -0
  219. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-6.md +79 -0
  220. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-7.md +89 -0
  221. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-8.md +102 -0
  222. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-9.md +116 -0
  223. package/src/native-harness/.res/sandbox/1-simple-harness/conversation.jsonl +49 -0
  224. package/src/native-harness/.res/sandbox/1-simple-harness/doc.md +87 -0
  225. package/src/native-harness/.res/sandbox/1-simple-harness/harness.py +289 -0
  226. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 2.py +221 -0
  227. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 3.py +287 -0
  228. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy.py +165 -0
  229. package/src/native-harness/.res/sandbox/1-simple-harness/state.json +22 -0
  230. package/src/native-harness/.res/sandbox/1-simple-harness/system-prompt.md +2 -0
  231. package/src/native-harness/AGENTS.md +70 -0
  232. package/src/native-harness/ARCHITECTURE.md +249 -0
  233. package/src/native-harness/README.md +726 -0
  234. package/src/native-harness/bun.lock +26 -0
  235. package/src/native-harness/package.json +24 -0
  236. package/src/native-harness/src/capabilities/context/build.ts +59 -0
  237. package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
  238. package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
  239. package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
  240. package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
  241. package/src/native-harness/src/capabilities/context/session.ts +92 -0
  242. package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
  243. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
  244. package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
  245. package/src/native-harness/src/capabilities/model/runner.ts +116 -0
  246. package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
  247. package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
  248. package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
  249. package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
  250. package/src/native-harness/src/capabilities/model/usage.ts +15 -0
  251. package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
  252. package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
  253. package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
  254. package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
  255. package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
  256. package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
  257. package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
  258. package/src/native-harness/src/capabilities/tools/reminders/index.ts +75 -0
  259. package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
  260. package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
  261. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
  262. package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
  263. package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
  264. package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
  265. package/src/native-harness/src/client.ts +18 -0
  266. package/src/native-harness/src/contracts/agent.ts +105 -0
  267. package/src/native-harness/src/contracts/config-permissions.ts +47 -0
  268. package/src/native-harness/src/contracts/context.ts +112 -0
  269. package/src/native-harness/src/contracts/events.ts +47 -0
  270. package/src/native-harness/src/contracts/input-limits.ts +7 -0
  271. package/src/native-harness/src/contracts/inspection.ts +22 -0
  272. package/src/native-harness/src/contracts/loop.ts +31 -0
  273. package/src/native-harness/src/contracts/model-execution.ts +83 -0
  274. package/src/native-harness/src/contracts/operator-controls.ts +106 -0
  275. package/src/native-harness/src/contracts/output.ts +13 -0
  276. package/src/native-harness/src/contracts/protocol.ts +320 -0
  277. package/src/native-harness/src/contracts/reminders.ts +132 -0
  278. package/src/native-harness/src/contracts/scenario.ts +42 -0
  279. package/src/native-harness/src/contracts/session-file.ts +19 -0
  280. package/src/native-harness/src/contracts/session.ts +184 -0
  281. package/src/native-harness/src/contracts/storage.ts +596 -0
  282. package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
  283. package/src/native-harness/src/contracts/tools.ts +133 -0
  284. package/src/native-harness/src/governance/permissions/gate.ts +129 -0
  285. package/src/native-harness/src/governance/policy/resolve.ts +32 -0
  286. package/src/native-harness/src/index.ts +318 -0
  287. package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
  288. package/src/native-harness/src/interfaces/cli/development.ts +145 -0
  289. package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
  290. package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
  291. package/src/native-harness/src/interfaces/cli/main.ts +47 -0
  292. package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
  293. package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
  294. package/src/native-harness/src/interfaces/cli/start.ts +106 -0
  295. package/src/native-harness/src/interfaces/client.ts +225 -0
  296. package/src/native-harness/src/interfaces/inspector/index.html +283 -0
  297. package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
  298. package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
  299. package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
  300. package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
  301. package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
  302. package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
  303. package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
  304. package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
  305. package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
  306. package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
  307. package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
  308. package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
  309. package/src/native-harness/src/interfaces/protocol/server.ts +517 -0
  310. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +119 -0
  311. package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
  312. package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
  313. package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
  314. package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
  315. package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
  316. package/src/native-harness/src/kernel/channels.ts +405 -0
  317. package/src/native-harness/src/kernel/loop.ts +45 -0
  318. package/src/native-harness/src/runtime/config/development.ts +23 -0
  319. package/src/native-harness/src/runtime/config/managed.ts +2 -0
  320. package/src/native-harness/src/runtime/config/paths.ts +27 -0
  321. package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
  322. package/src/native-harness/src/runtime/reminder-validation.ts +104 -0
  323. package/src/native-harness/src/runtime/reminders.ts +66 -0
  324. package/src/native-harness/src/state/storage/archive.ts +239 -0
  325. package/src/native-harness/src/state/storage/engine.ts +1013 -0
  326. package/src/native-harness/src/state/storage/inference.ts +124 -0
  327. package/src/native-harness/src/state/storage/memory-reminders.ts +78 -0
  328. package/src/native-harness/src/state/storage/memory.ts +341 -0
  329. package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
  330. package/src/native-harness/src/state/storage/reminder-archive.ts +63 -0
  331. package/src/native-harness/src/state/storage/reminder-change.ts +92 -0
  332. package/src/native-harness/src/state/storage/reminder-tables.ts +27 -0
  333. package/src/native-harness/src/state/storage/retrieval.ts +122 -0
  334. package/src/native-harness/src/state/storage/script-identity.ts +7 -0
  335. package/src/native-harness/src/state/storage/session-file.ts +85 -0
  336. package/src/native-harness/src/state/storage/sqlite-reminders.ts +134 -0
  337. package/src/native-harness/src/state/storage/sqlite.ts +625 -0
  338. package/src/native-harness/src/testing.ts +190 -0
  339. package/src/native-harness/src/util/config.ts +58 -0
  340. package/src/native-harness/src/util/json.ts +41 -0
  341. package/src/native-harness/src/util/message-position.ts +3 -0
  342. package/src/native-harness/src/util/reminder-schedule.ts +44 -0
  343. package/src/native-harness/src/util/schema.ts +40 -0
  344. package/src/native-harness/src/util/timeline-text.ts +72 -0
  345. package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
  346. package/src/native-harness/test/agent.test.ts +130 -0
  347. package/src/native-harness/test/approval-gate.test.ts +255 -0
  348. package/src/native-harness/test/approval-protocol.test.ts +94 -0
  349. package/src/native-harness/test/boundaries.test.ts +18 -0
  350. package/src/native-harness/test/channel-controls.test.ts +322 -0
  351. package/src/native-harness/test/client-abort.test.ts +136 -0
  352. package/src/native-harness/test/config-policy.test.ts +301 -0
  353. package/src/native-harness/test/conformance/storage.ts +1141 -0
  354. package/src/native-harness/test/context.test.ts +177 -0
  355. package/src/native-harness/test/crash.test.ts +187 -0
  356. package/src/native-harness/test/debug-tools.test.ts +67 -0
  357. package/src/native-harness/test/development-cli.test.ts +67 -0
  358. package/src/native-harness/test/development.test.ts +171 -0
  359. package/src/native-harness/test/dispatch-evidence.test.ts +58 -0
  360. package/src/native-harness/test/e2e.test.ts +186 -0
  361. package/src/native-harness/test/external-notices.test.ts +101 -0
  362. package/src/native-harness/test/fixtures/approval-e2e.jsonl +4 -0
  363. package/src/native-harness/test/fixtures/crash-scenario.jsonl +5 -0
  364. package/src/native-harness/test/fixtures/development-lifecycle.jsonl +10 -0
  365. package/src/native-harness/test/fixtures/echo-scenario.jsonl +3 -0
  366. package/src/native-harness/test/fixtures/format2-schema.ts +27 -0
  367. package/src/native-harness/test/fixtures/format3-schema.ts +16 -0
  368. package/src/native-harness/test/fixtures/hold-scenario.jsonl +4 -0
  369. package/src/native-harness/test/fixtures/model-e2e.jsonl +3 -0
  370. package/src/native-harness/test/fixtures/storage-owner.ts +20 -0
  371. package/src/native-harness/test/format-reply.test.ts +10 -0
  372. package/src/native-harness/test/helpers/operator-view.ts +41 -0
  373. package/src/native-harness/test/helpers/scenario.ts +9 -0
  374. package/src/native-harness/test/helpers/session.ts +38 -0
  375. package/src/native-harness/test/helpers/stdio.ts +46 -0
  376. package/src/native-harness/test/inspector.test.ts +77 -0
  377. package/src/native-harness/test/listeners.test.ts +49 -0
  378. package/src/native-harness/test/loop.test.ts +88 -0
  379. package/src/native-harness/test/model-channel-double.test.ts +87 -0
  380. package/src/native-harness/test/model-crash.test.ts +62 -0
  381. package/src/native-harness/test/model-delivery-regressions.test.ts +55 -0
  382. package/src/native-harness/test/model-e2e.test.ts +71 -0
  383. package/src/native-harness/test/model-final-filter.test.ts +30 -0
  384. package/src/native-harness/test/model-large-reply.test.ts +28 -0
  385. package/src/native-harness/test/model-live-queue.test.ts +33 -0
  386. package/src/native-harness/test/model-runner.test.ts +117 -0
  387. package/src/native-harness/test/model-storage.test.ts +99 -0
  388. package/src/native-harness/test/model-stream-adapter.test.ts +26 -0
  389. package/src/native-harness/test/model-stream-public.test.ts +77 -0
  390. package/src/native-harness/test/notices.test.ts +64 -0
  391. package/src/native-harness/test/openrouter-config.test.ts +218 -0
  392. package/src/native-harness/test/operator-controls.test.ts +132 -0
  393. package/src/native-harness/test/output.test.ts +44 -0
  394. package/src/native-harness/test/owner-config.test.ts +64 -0
  395. package/src/native-harness/test/permissions-e2e.test.ts +68 -0
  396. package/src/native-harness/test/persistence.test.ts +236 -0
  397. package/src/native-harness/test/portability.test.ts +337 -0
  398. package/src/native-harness/test/protocol.test.ts +160 -0
  399. package/src/native-harness/test/reminder-clock.test.ts +61 -0
  400. package/src/native-harness/test/reminder-stdio.test.ts +140 -0
  401. package/src/native-harness/test/reminder-storage.test.ts +124 -0
  402. package/src/native-harness/test/scenario-jsonl.test.ts +112 -0
  403. package/src/native-harness/test/scripted.test.ts +92 -0
  404. package/src/native-harness/test/session-file.test.ts +51 -0
  405. package/src/native-harness/test/startup-channel-changes.test.ts +256 -0
  406. package/src/native-harness/test/stdio.test.ts +132 -0
  407. package/src/native-harness/test/storage-memory.test.ts +4 -0
  408. package/src/native-harness/test/storage-sqlite.test.ts +420 -0
  409. package/src/native-harness/test/suspension.test.ts +430 -0
  410. package/src/native-harness/test/timeline-retrieval.test.ts +211 -0
  411. package/src/native-harness/test/tools-catalog.test.ts +468 -0
  412. package/src/native-harness/test/tools-protocol.test.ts +418 -0
  413. package/src/native-harness/test/transfers.test.ts +94 -0
  414. package/src/native-harness/test/web-chat.test.ts +35 -0
  415. package/src/native-harness/tsconfig.json +20 -0
  416. package/src/observation/agent-event-bus.ts +44 -18
  417. package/src/observation/index.ts +1 -0
  418. package/src/operations/contracts.ts +11 -3
  419. package/src/operations/errors.ts +5 -0
  420. package/src/operations/stale-policy.ts +1 -1
  421. package/src/operations/supervisor.ts +34 -10
  422. package/src/orchestrator/acp-delivery.ts +68 -0
  423. package/src/orchestrator/assignments.ts +27 -0
  424. package/src/orchestrator/busy.ts +15 -0
  425. package/src/orchestrator/config.ts +41 -0
  426. package/src/orchestrator/consumer-api.ts +24 -0
  427. package/src/orchestrator/contracts.ts +71 -0
  428. package/src/orchestrator/durable-assignments.ts +111 -0
  429. package/src/orchestrator/native-delegation.ts +103 -0
  430. package/src/orchestrator/orchestrator.ts +318 -0
  431. package/src/orchestrator/permissions.ts +25 -0
  432. package/src/orchestrator/policy.ts +44 -0
  433. package/src/orchestrator/pool.ts +123 -0
  434. package/src/orchestrator/tool-descriptions.ts +11 -0
  435. package/src/permissions/acp.ts +18 -0
  436. package/src/permissions/arrival.ts +13 -0
  437. package/src/permissions/consumer-config.ts +19 -0
  438. package/src/permissions/conversation.ts +280 -0
  439. package/src/permissions/matcher.ts +85 -0
  440. package/src/permissions/outcome.ts +15 -0
  441. package/src/permissions/policy.ts +81 -0
  442. package/src/permissions/request.ts +26 -0
  443. package/src/persistence/activity-projection.ts +1 -0
  444. package/src/persistence/backend.ts +34 -1
  445. package/src/persistence/channels.ts +23 -0
  446. package/src/persistence/index.ts +4 -0
  447. package/src/persistence/protocol-method.ts +5 -0
  448. package/src/persistence/reminder-wake.ts +49 -0
  449. package/src/persistence/reminders.ts +385 -0
  450. package/src/persistence/sqlite-backend.ts +84 -6
  451. package/src/persistence/sqlite-channels.ts +65 -0
  452. package/src/persistence/sqlite-reminders.ts +85 -0
  453. package/src/persistence/sqlite-schema.ts +108 -3
  454. package/src/persistence/sqlite-worker-delivery.ts +374 -0
  455. package/src/persistence/sqlite-workers.ts +59 -0
  456. package/src/persistence/worker-delivery-contract.ts +104 -0
  457. package/src/persistence/worker-terminal-reason.ts +29 -0
  458. package/src/persistence/workers.ts +19 -0
  459. package/src/provider-notices.ts +137 -0
  460. package/src/repl/commands.ts +2 -2
  461. package/src/steering/combine.ts +3 -1
  462. package/src/steering/contracts.ts +11 -2
  463. package/src/steering/controller.ts +3 -2
  464. package/src/transport/acp-transport.ts +24 -14
  465. package/src/types.ts +15 -12
  466. package/src/updates.ts +14 -2
  467. package/src/wire-log.ts +1 -1
@@ -0,0 +1,909 @@
1
+ import type { NativeConnection, NativeHarnessHostConfig } from "./host-config.ts";
2
+ export type { NativeConnection, NativeHarnessHostConfig, NativeApprovalRequest, NativeApprovalResponder } from "./host-config.ts";
3
+ import { idleMilliseconds, ReminderIdleSupervisor } from "./reminders/idle.ts";
4
+ import { reminderNotification, type WireChange, type ReminderNotification, type WireReminderEvent } from "./reminders/wire.ts";
5
+ import type { ReminderWakeSupervisor } from "./reminders/supervisor.ts";
6
+ import type { ReminderSync } from "./reminders/sync.ts";
7
+ import { deferred, launchNativeConnection, type Deferred } from "./connection.ts";
8
+ import { NativeUsageLedger } from "../metering/native/ledger.ts";
9
+ import { summarizeModelUsage } from "./usage.ts";
10
+ import { NativeWorkerDelivery } from "./worker-delivery.ts";
11
+ import type { WorkerDeliveryRepository } from "../persistence/worker-delivery-contract.ts";
12
+ import { NativeApprovals } from "./approvals.ts";
13
+ import { SubmissionWithdrawal } from "./submission-withdrawal.ts";
14
+ import { takenSender } from "./delegation-sender.ts";
15
+ /**
16
+ * The shared native harness host: one per Agent (acp-client integration spec, Ownership).
17
+ *
18
+ * It owns what belongs to the process and the session rather than to one conversation:
19
+ * - launching the harness (`serve --stdio`) through the host launcher, lazily and once: concurrent
20
+ * first uses share one start;
21
+ * - the open sequence: handlers attached, `initialize`, then `session/open` (or `session/create` on a
22
+ * confirmed `not_found`) carrying the channel changes made while the harness was stopped;
23
+ * - reconciliation after every open, and reopening after a lost process or connection;
24
+ * - the durable-acceptance rule for inputs: an id and exact payload are saved before `channel/push`,
25
+ * and an unresolved submission is retried with the same id and payload;
26
+ * - process shutdown. A conversation never stops the process.
27
+ *
28
+ * It uses only the harness's public client entry point. Conversations attach as `ChannelPort`s keyed
29
+ * by channel id (the conversation id) and receive that channel's events and reconciled view.
30
+ */
31
+ import {
32
+ type HarnessClient, type ConditionalStopResult,
33
+ type ChannelEvent,
34
+ type ChannelStatusResult,
35
+ type ItemStatus,
36
+ type LoadResult,
37
+ type StatusResult,
38
+ type StoredMessage,
39
+ type TurnStatus,
40
+ type ToolAvailability,
41
+ type ToolInvocation,
42
+ } from "../native-harness/src/client.ts";
43
+ import { commitChannelCatchUp, openOrCreate, readCompleteMessage, recoverChannel, recoverStoppedReplies } from "./recovery.ts";
44
+ import { createNativeFunctionHost, type NativeFunctionHost } from "./functions.ts";
45
+ import { noopLogger, type Logger } from "../logger.ts";
46
+ import type { ChannelDesire, ChannelPersistence, PendingChange } from "../persistence/channels.ts";
47
+ import { createMemoryHostRecords, fileHasPendingChannelChanges, submissionRecords, type NativeHostRecords, type Submission } from "./records.ts";
48
+ import { channelStore, NativeChannelChanges, type ChannelChangeOutcome } from "./channel-changes.ts";
49
+ import { ambiguous, codeOf, HarnessIncompatibleError, HarnessUnavailableError, terminalStartupError } from "./errors.ts";
50
+
51
+ export { HarnessIncompatibleError, HarnessUnavailableError } from "./errors.ts";
52
+ export type { ChannelChangeOutcome } from "./channel-changes.ts";
53
+
54
+ export type NativeHostState = "stopped" | "starting" | "running" | "failed";
55
+
56
+ /** One channel's part of a load view, as reconciled after an open. */
57
+ export interface ChannelView {
58
+ /** The storage revision of the view. Events at or below it are already reflected. */
59
+ readonly revision: number;
60
+ readonly status: ChannelStatusResult | undefined;
61
+ readonly turns: readonly TurnStatus[];
62
+ readonly items: readonly ItemStatus[];
63
+ /** Committed assistant messages of this channel, in timeline order. Oversized text is a reference: read it with `readMessage`. */
64
+ readonly messages: readonly StoredMessage[];
65
+ }
66
+
67
+ /** What a conversation's controller implements to receive its channel. */
68
+ export interface ChannelPort {
69
+ event(event: ChannelEvent): void;
70
+ reminderEvent?(event: WireReminderEvent): void;
71
+ readonly idleStopWindowMs?: number;
72
+ /** After every open, before any live event of that connection is delivered. */
73
+ reconcile(view: ChannelView): void;
74
+ /** The connection was lost. Work stays pending: the next open reconciles it. */
75
+ disconnected(): void;
76
+ /** The host gave up (restarts ran out) or was stopped: nothing pending will be reconciled. */
77
+ failed(error: Error): void;
78
+ /** Whether this channel has a turn the host should reopen for after a lost connection. */
79
+ busy(): boolean;
80
+ trackedTurns?(): string[];
81
+ }
82
+
83
+ const REQUIRED_METHODS = ["session/open", "channel/observe", "channel/reconcile", "channel/push", "channel/create", "channel/edit", "channel/suspend", "channel/resume", "channel/delete", "channel/withdraw", "channel/interrupt", "approval/respond", "session/message/read"];
84
+
85
+ export class NativeHarnessHost {
86
+ readonly sessionId: string;
87
+ readonly records: NativeHostRecords;
88
+ readonly #config: NativeHarnessHostConfig;
89
+ readonly #log: Logger;
90
+ reminderSync?: ReminderSync;
91
+ reminderWake?: ReminderWakeSupervisor;
92
+ #stoppingExplicitly = false;
93
+ // Keep receiving deadlines from the detached connection until explicit stop drains them.
94
+ #stoppingConnection: NativeConnection | null = null;
95
+ #wakeFailure: Error | null = null;
96
+ get reminderWakeState(): NativeHostState { return this.#wakeFailure ? "failed" : this.#stoppingExplicitly ? "running" : this.#state; }
97
+ get reminderTimer() { return this.#config.reminderTimer; }
98
+ startForReminder(now: number): Promise<void> {
99
+ if (this.#starting || this.#state === "running") return this.ensureStarted();
100
+ if (!this.#claimRestart(now)) {
101
+ if (this.#localBusy()) return Promise.reject(this.#failReopen());
102
+ this.#wakeFailure = new HarnessUnavailableError("the reminder wake exhausted its restart budget", { code: "reopen_failed" });
103
+ return Promise.reject(this.#wakeFailure);
104
+ }
105
+ return this.ensureStarted().catch(error => { if (terminalStartupError(error)) { this.#restarts.pop(); this.#wakeFailure = error; } throw error; });
106
+ }
107
+ async changeReminder(change: WireChange) {
108
+ await this.ensureStarted();
109
+ return this.reminderSync?.dispatch(this.#client(), change);
110
+ }
111
+ async refreshReminders(channel?: string, id?: string) {
112
+ await this.#idling;
113
+ if (this.#state === "running") return this.reminderSync?.refresh(this.#client(), channel, id);
114
+ }
115
+ reminderIdle?: ReminderIdleSupervisor;
116
+ closeReminderSupervisors(): void { this.reminderIdle?.close(); this.reminderWake?.close(); }
117
+ #idling?: Promise<ConditionalStopResult>;
118
+
119
+ #localBusy(): boolean {
120
+ return this.#waiters.size > 0 || this.records.submissions().length > 0 || this.#approvals.busy
121
+ || this.#changes.busy || [...this.#ports.values()].some(port => port.busy());
122
+ }
123
+
124
+ #idleStop(window: number, stillIdle: () => boolean): Promise<ConditionalStopResult> {
125
+ if (this.#idling) return this.#idling;
126
+ const connection = this.#connection;
127
+ if (this.#stoppingExplicitly || !connection || !stillIdle() || this.#localBusy()) return Promise.resolve({ stopped: false, reason: "busy" });
128
+ const attempt = connection.client.stopIfIdle({ ifIdle: true, unlessDueWithinMs: window });
129
+ this.#idling = attempt.then(async result => {
130
+ await this.reminderSync?.settled();
131
+ if (result.stopped && this.#connection === connection) {
132
+ this.#connection = null;
133
+ this.#approvals.stop();
134
+ for (const port of this.#ports.values()) port.disconnected();
135
+ try { await connection.kill(); } finally { this.#setState("stopped"); }
136
+ }
137
+ return result;
138
+ }).finally(() => { this.#idling = undefined; });
139
+ return this.#idling;
140
+ }
141
+
142
+ armIdleStop(pending: () => Promise<{ held: boolean; channels: string[] }>): void {
143
+ const interval = idleMilliseconds(this.#config.idleStopMs, "idleStopMs");
144
+ const fallback = idleMilliseconds(this.#config.idleStopWindowMs, "idleStopWindowMs") ?? 0;
145
+ if (!interval) return;
146
+ this.reminderIdle = new ReminderIdleSupervisor({
147
+ state: () => this.#state,
148
+ window: async () => {
149
+ if (!this.reminderSync?.supported || this.#localBusy() || (await this.#changes.pendingChanges()).length) return;
150
+ const { held, channels } = await pending();
151
+ if (!held) return channels.reduce((max, channel) => Math.max(max, this.#ports.get(channel)?.idleStopWindowMs ?? fallback), 0);
152
+ },
153
+ stop: (window, stillIdle) => this.#idleStop(window, stillIdle),
154
+ error: error => this.#log.warn("native_idle_stop_failed", { error: String(error) }),
155
+ }, interval, this.#config.reminderTimer);
156
+ this.subscribeState(() => this.reminderIdle?.activity());
157
+ }
158
+ #state: NativeHostState = "stopped";
159
+ #connection: NativeConnection | null = null;
160
+ #starting: Promise<void> | null = null;
161
+ /** Set by `stop()`: an explicit stop is never followed by an automatic reopen. */
162
+ #stopped = false;
163
+ #failure: Error | null = null;
164
+ readonly #ports = new Map<string, ChannelPort>();
165
+ /** Events for a channel no conversation is attached to yet; delivered on attach. */
166
+ readonly #backlog = new Map<string, ChannelEvent[]>();
167
+ /** While an open is in progress: events received before the view was applied. */
168
+ #early: ChannelEvent[] | null = null;
169
+ /** The harness's channels as last seen (load view, control responses, `channel_state`). */
170
+ readonly #channels = new Map<string, ChannelStatusResult>();
171
+ readonly #changes: NativeChannelChanges;
172
+ readonly #approvals: NativeApprovals;
173
+ readonly #workerDelivery?: NativeWorkerDelivery;
174
+ /** Callers waiting for a submission's acceptance, across reopens. */
175
+ readonly #waiters = new Map<string, Deferred<ItemStatus>>();
176
+ readonly #withdrawals: SubmissionWithdrawal;
177
+ readonly #stateListeners = new Set<() => void>();
178
+ readonly #restarts: number[] = [];
179
+ /** How many processes this host has started (observability and tests). */
180
+ launches = 0;
181
+ /** @internal Pins reads of one turn to the same connection across pages. */
182
+ readonly usageLedger = new NativeUsageLedger(() => {
183
+ const client = this.#client();
184
+ return (query, signal) => client.modelCalls(query, signal);
185
+ });
186
+
187
+ constructor(config: NativeHarnessHostConfig, channels?: ChannelPersistence, workerDelivery?: WorkerDeliveryRepository) {
188
+ this.#config = config;
189
+ this.sessionId = config.sessionId;
190
+ this.#log = config.logger ?? noopLogger;
191
+ this.#approvals = new NativeApprovals(config.approvalResponder, this.#log);
192
+ const records = config.records ?? createMemoryHostRecords();
193
+ this.records = channels ? submissionRecords(records) : records;
194
+ this.#withdrawals = new SubmissionWithdrawal(this.records, config.requestTimeoutMs ?? 30_000,
195
+ (channel, item) => this.withdraw(channel, item),
196
+ async (channel, item) => (await this.#client().reconcileChannel({ channel, itemIds: [item] })).items[0],
197
+ (channel, item) => this.#deliver({ channel, event: { type: "item_withdrawn", item } }));
198
+ this.#changes = new NativeChannelChanges(channels ?? channelStore(records), this.#channels, () => this.#client(),
199
+ this.#log, config.onChannelChangeBlocked);
200
+ if (workerDelivery) this.#workerDelivery = new NativeWorkerDelivery(
201
+ workerDelivery, () => this.#state === "running",
202
+ ({ id, destination, source, text, policyNames }) => this.#changes.enqueue(destination.id, async () => {
203
+ if (this.#state !== "running" || await this.#changes.pendingChange(destination.id)) return false;
204
+ const client = this.#client();
205
+ const params = { channel: destination.id, notice: { id, source, text, policyNames: [...policyNames] } };
206
+ try {
207
+ await client.notify(params);
208
+ } catch (error) {
209
+ if (codeOf(error) !== "timeout" || client !== this.#connection?.client) throw error;
210
+ await client.notify(params);
211
+ }
212
+ return true;
213
+ }),
214
+ );
215
+ if (channels && fileHasPendingChannelChanges(records)) {
216
+ this.#log.warn("native_file_channel_changes_ignored", { sessionId: this.sessionId });
217
+ }
218
+ }
219
+
220
+ get state(): NativeHostState { return this.#state; }
221
+ /** Why the host is `failed`. */
222
+ get failure(): Error | null { return this.#failure ?? this.#wakeFailure; }
223
+ get explicitlyStopped(): boolean { return this.#stopped; }
224
+ subscribeState(listener: () => void): () => void {
225
+ this.#stateListeners.add(listener);
226
+ return () => this.#stateListeners.delete(listener);
227
+ }
228
+ #setState(state: NativeHostState): void {
229
+ if (this.#state === state) return;
230
+ this.#state = state;
231
+ this.#notifyState();
232
+ }
233
+ #notifyState(): void {
234
+ for (const listener of [...this.#stateListeners]) { try { listener(); } catch { /* an observer never breaks the host */ } }
235
+ }
236
+
237
+ approvalFor(event: Extract<ChannelEvent["event"], { type: "approval_requested" }>) {
238
+ return this.#approvals.ticket(event);
239
+ }
240
+
241
+ #observeApproval(connection: NativeConnection, { channel, event }: ChannelEvent): void {
242
+ if (event.type === "approval_requested") {
243
+ this.#approvals.observe(channel, event, async decision =>
244
+ this.#connection === connection && this.#answerApproval(event.requestId, decision));
245
+ } else if (event.type === "approval_closed") {
246
+ this.#approvals.closed(event);
247
+ }
248
+ }
249
+
250
+ /** The channel as the harness last reported it; undefined before the first open or for a channel it has not seen. */
251
+ channel(channel: string): ChannelStatusResult | undefined { return this.#channels.get(channel); }
252
+
253
+ // --- conversations ----------------------------------------------------------------------------
254
+
255
+ /** Attaches a conversation to its channel. Starts nothing. Events held for the channel are delivered now. */
256
+ attach(channel: string, port: ChannelPort, observe = false): () => void {
257
+ this.#ports.set(channel, port);
258
+ const held = this.#backlog.get(channel);
259
+ if (held && (!observe || !this.#connection)) {
260
+ this.#backlog.delete(channel);
261
+ for (const event of held) port.event(event);
262
+ }
263
+ return () => { if (this.#ports.get(channel) === port) this.#ports.delete(channel); };
264
+ }
265
+
266
+ readonly #attaching = new Map<string, ChannelEvent[]>();
267
+
268
+ async observeAttachment(channel: string, port: ChannelPort): Promise<void> {
269
+ const connection = this.#connection;
270
+ if (!connection || this.#ports.get(channel) !== port) return;
271
+ const buffered = this.#backlog.get(channel) ?? [];
272
+ this.#backlog.delete(channel);
273
+ this.#attaching.set(channel, buffered);
274
+ let boundary = 0;
275
+ try {
276
+ const saved = this.records.submissions(channel).map(item => item.id);
277
+ const recovered = await recoverChannel(connection.client, channel, saved, port.trackedTurns?.() ?? [], { atObservation: () => { boundary = buffered.length; } });
278
+ if (this.#connection !== connection || this.#ports.get(channel) !== port) return;
279
+ const { observation } = recovered;
280
+ const { pendingCount: _pendingCount, ...state } = observation.channel;
281
+ const status = { pending: this.#channels.get(channel)?.pending ?? [], ...state };
282
+ this.#channels.set(channel, status);
283
+ port.reconcile({ ...recovered, status, revision: observation.revision });
284
+ for (const request of observation.approvals) {
285
+ if (buffered.slice(boundary).some(({ event }) => event.type === "approval_closed" && event.requestId === request.requestId)) continue;
286
+ const event = { channel, event: { type: "approval_requested" as const, ...request } };
287
+ this.#observeApproval(connection, event);
288
+ this.#approvals.start(event.event);
289
+ port.event(event);
290
+ }
291
+ for (const [index, event] of buffered.entries()) {
292
+ if (event.revision === undefined ? index >= boundary : event.revision > observation.revision) port.event(event);
293
+ }
294
+ } catch (error) {
295
+ if (this.#connection === connection) {
296
+ if (codeOf(error) !== "not_found") throw error;
297
+ for (const event of buffered) port.event(event);
298
+ }
299
+ } finally {
300
+ if (this.#attaching.get(channel) === buffered) this.#attaching.delete(channel);
301
+ }
302
+ }
303
+
304
+ /** Starts the harness if it is not running. Concurrent callers share one start. */
305
+ ensureStarted(): Promise<void> {
306
+ if (this.#idling) return this.#idling.catch(() => {}).then(() => this.ensureStarted());
307
+ if (this.#wakeFailure) { this.#wakeFailure = null; this.#restarts.length = 0; }
308
+ this.reminderIdle?.activity();
309
+ if (this.#state === "running") return Promise.resolve();
310
+ if (this.#state === "failed") return Promise.reject(new HarnessUnavailableError("the native harness is unavailable; call restart()", { cause: this.#failure, code: "failed" }));
311
+ this.#stopped = false;
312
+ this.#starting ??= this.#start().finally(() => { this.#starting = null; });
313
+ return this.#starting;
314
+ }
315
+
316
+ /** Clears a failed state and starts again. */
317
+ restart(): Promise<void> {
318
+ if (this.#state === "failed") { this.#failure = null; this.#restarts.length = 0; this.#setState("stopped"); }
319
+ return this.ensureStarted();
320
+ }
321
+
322
+ /** Stops the process. Pending work is not reconciled until the next start; waiting pushes fail. */
323
+ async stop(): Promise<void> {
324
+ this.#stopped = this.#stoppingExplicitly = true;
325
+ this.reminderWake?.refresh();
326
+ await this.#idling?.catch(() => {});
327
+ const connection = this.#stoppingConnection = this.#connection;
328
+ this.#connection = null;
329
+ await this.#starting?.catch(() => undefined);
330
+ this.#setState("stopped");
331
+ const error = new HarnessUnavailableError("the native harness was stopped", { code: "stopped" });
332
+ this.#rejectWaiters(error);
333
+ for (const port of [...this.#ports.values()]) port.failed(error);
334
+ this.#approvals.stop();
335
+ const live = this.#stoppingConnection = connection ?? this.#connection;
336
+ this.#connection = null;
337
+ try {
338
+ if (live) {
339
+ try { await live.client.stop(); }
340
+ finally { await this.reminderSync?.settled(); await live.kill(); }
341
+ }
342
+ } finally {
343
+ this.#functions?.dispose();
344
+ this.#functions = null;
345
+ this.#stoppingConnection = null;
346
+ this.#stoppingExplicitly = false;
347
+ this.reminderWake?.refresh();
348
+ }
349
+ }
350
+
351
+ async #start(): Promise<void> {
352
+ this.#setState("starting");
353
+ let connection: NativeConnection | undefined;
354
+ const limit = this.#config.startupTimeoutMs ?? 30_000;
355
+ const deadline = new AbortController();
356
+ let timer: ReturnType<typeof setTimeout> | undefined;
357
+ try {
358
+ const opening = (async () => {
359
+ connection = await (this.#config.connect ?? (() => launchNativeConnection(this.#config, this.#log)))();
360
+ this.launches += 1;
361
+ if (deadline.signal.aborted) {
362
+ await connection.kill();
363
+ return;
364
+ }
365
+ const live = connection;
366
+ await this.#open(live, deadline.signal);
367
+ await this.#changes.afterOpen(deadline.signal, () => {
368
+ this.#connection = live;
369
+ this.#replaySubmissions();
370
+ this.#setState("running");
371
+ void this.flushWorkerDelivery();
372
+ void this.reminderSync?.dispatch(live.client).catch(error => this.#log.warn("reminder_dispatch_failed", { error: String(error) }));
373
+ void live.closed.then(async () => {
374
+ // A loss at the open boundary must reopen after the old start has retired.
375
+ await this.#starting?.catch(() => undefined);
376
+ await this.#idling?.catch(() => undefined);
377
+ this.#lost(live);
378
+ });
379
+ });
380
+ })();
381
+ opening.catch(() => undefined);
382
+ await Promise.race([opening, new Promise<never>((_, reject) => {
383
+ timer = setTimeout(() => {
384
+ const error = new HarnessUnavailableError(`the native harness did not open within ${limit} ms`, { code: "open_timeout" });
385
+ deadline.abort(error);
386
+ reject(error);
387
+ }, limit);
388
+ })]);
389
+ } catch (error) {
390
+ this.#early = null;
391
+ this.#connection = null;
392
+ await connection?.kill().catch(() => undefined);
393
+ // A failed start is reported to whoever needed the harness. It is not retried automatically:
394
+ // the next use tries again. Only a loss with work outstanding is reopened by the host itself.
395
+ this.#setState("stopped");
396
+ throw error;
397
+ } finally {
398
+ clearTimeout(timer);
399
+ }
400
+ }
401
+
402
+ /** Handlers first, then initialize, then load (or create) with the pending channel changes; then reconcile. */
403
+ async #open(connection: NativeConnection, signal: AbortSignal): Promise<void> {
404
+ const { client } = connection;
405
+ let reminderOpen = false;
406
+ const earlyReminders: ReminderNotification[] = [];
407
+ const reminderEvent = (event: ReminderNotification) =>
408
+ this.reminderSync?.notification(event, (channel, payload) => this.#ports.get(channel)?.reminderEvent?.(payload), client);
409
+ const notifyReminder = (event: ReminderNotification) => {
410
+ if (!reminderOpen) earlyReminders.push(event);
411
+ else if (this.#connection === connection || ("deadline" in event && this.#stoppingConnection === connection)) reminderEvent(event);
412
+ };
413
+ connection.onReminderNotification?.(notifyReminder);
414
+ client.onReminderWake?.(event => notifyReminder({ deadline: event }));
415
+ this.#early = [];
416
+ client.onChannelEvent(event => {
417
+ const reminder = reminderNotification({ jsonrpc: "2.0", method: "channel/event", params: event });
418
+ if (reminder) notifyReminder(reminder); else this.#route(connection, event);
419
+ });
420
+ client.onSessionEvent(event => {
421
+ const status = this.#lastStatus;
422
+ if (this.#connection !== connection || !status || status.revision > event.revision) return;
423
+ this.#lastStatus = { ...status, lifecycle: event.lifecycle, revision: event.revision };
424
+ this.#notifyState();
425
+ });
426
+ // Handlers are in place before `initialize` names them: a recovered call can arrive right after the open.
427
+ const functions = this.#functionHost();
428
+ if (functions) client.serveFunctions((call, signal) => functions.call(call, signal,
429
+ () => takenSender(client, call.channel, call.turnId, signal)), (read) => functions.read(read));
430
+ const initialized = await client.initialize({
431
+ protocolVersion: 1,
432
+ host: { name: "acp-client", version: "1" },
433
+ callbacks: functions ? ["functions/call"] : [],
434
+ ...(functions ? { functions: functions.handlers() } : {}),
435
+ approval: true,
436
+ subscription: { text: this.#config.text ?? "final", tools: "full" },
437
+ });
438
+ signal.throwIfAborted();
439
+ const capabilities = initialized.description.capabilities;
440
+ const missing = REQUIRED_METHODS.filter((method) => !capabilities.methods.includes(method));
441
+ if (!capabilities.persistence || capabilities.acceptance !== "durable") throw new HarnessIncompatibleError("the native harness does not offer durable sessions");
442
+ if (missing.length) throw new HarnessIncompatibleError(`the native harness lacks ${missing.join(", ")}`);
443
+ if (!capabilities.startupChannelChanges) throw new HarnessIncompatibleError("the native harness cannot apply channel changes at open");
444
+ if (functions && !capabilities.functions) throw new HarnessIncompatibleError("the native harness cannot call host functions");
445
+
446
+ // The startup cutoff: what is pending now goes inside the open and is applied before any work
447
+ // can run. An edit made after this line is sent through the live channel methods once open.
448
+ const batch = await this.#changes.startupBatch(signal);
449
+ await this.reminderSync?.initialize(initialized.description);
450
+ const opened = await openOrCreate(client, this.#config, batch, functions?.catalog(), signal, this.reminderSync);
451
+ for (const event of earlyReminders.splice(0)) reminderEvent(event);
452
+ await this.reminderSync?.settled();
453
+ signal.throwIfAborted();
454
+ await this.#changes.acknowledgeOpen(opened.channelChanges ?? [], signal);
455
+ signal.throwIfAborted();
456
+
457
+ const status = await client.status();
458
+ signal.throwIfAborted();
459
+ const view: LoadResult = { status, items: [], turns: [], messages: [] };
460
+ const submissions = this.records.submissions();
461
+ const observed = new Map<string, number>();
462
+ const boundaries = new Map<string, number>();
463
+ for (const channel of new Set([...this.#ports.keys(), ...submissions.map(item => item.channel)])) {
464
+ const saved = submissions.filter(item => item.channel === channel).map(item => item.id);
465
+ try {
466
+ const recovered = await recoverChannel(client, channel, saved, this.#ports.get(channel)?.trackedTurns?.() ?? [], { signal, atObservation: () => { boundaries.set(channel, this.#early?.length ?? 0); } });
467
+ const { observation } = recovered;
468
+ observed.set(channel, observation.revision);
469
+ const known = status.channels.find(value => value.channel === channel);
470
+ const { pendingCount: _pendingCount, ...state } = observation.channel;
471
+ if (known) Object.assign(known, state);
472
+ else status.channels.push({ ...state, pending: [] });
473
+ view.items.push(...recovered.items);
474
+ view.turns.push(...recovered.turns);
475
+ view.messages.push(...recovered.messages);
476
+ for (const request of observation.approvals) {
477
+ const boundary = boundaries.get(channel)!;
478
+ const event = { channel, event: { type: "approval_requested" as const, ...request } };
479
+ this.#observeApproval(connection, event);
480
+ this.#early?.splice(boundary, 0, event);
481
+ }
482
+ } catch (error) {
483
+ if (codeOf(error) !== "not_found") throw error;
484
+ }
485
+ }
486
+
487
+ this.#lastStatus = status;
488
+ this.#capabilities = capabilities;
489
+ this.#channels.clear();
490
+ for (const channel of view.status.channels) this.#channels.set(channel.channel, channel);
491
+ this.#connection = connection;
492
+ reminderOpen = true;
493
+ for (const event of earlyReminders.splice(0)) reminderEvent(event);
494
+ this.#reconcile(view, observed);
495
+ for (const turn of view.turns) {
496
+ if (turn.state !== "running" && turn.state !== "suspended") this.#approvals.end(turn.channel, turn.turnId);
497
+ }
498
+
499
+ // Events received while the view was being read and applied: the ones it already includes are
500
+ // dropped; the rest follow in delivery order. Several events can share a revision, so the
501
+ // comparison is with the view's revision, never with the previous event's.
502
+ const early = this.#early ?? [];
503
+ this.#early = null;
504
+ for (const [index, event] of early.entries()) {
505
+ if (event.revision === undefined ? index < (boundaries.get(event.channel) ?? 0)
506
+ : event.revision <= (observed.get(event.channel) ?? status.revision)) continue;
507
+ this.#deliver(event);
508
+ }
509
+ }
510
+
511
+ #functions: NativeFunctionHost | null = null;
512
+
513
+ /** The function host, created on first use so a host without functions makes no result directory. */
514
+ #functionHost(): NativeFunctionHost | null {
515
+ if (!this.#config.functions) return null;
516
+ return this.#functions ??= createNativeFunctionHost(this.#config.functions);
517
+ }
518
+
519
+ /** Every registered tool with its availability and, when unavailable, the reason. Policy is separate. */
520
+ async tools(): Promise<ToolAvailability[]> { return (await this.#client().tools()).tools; }
521
+ /** Revoke a `revocable` tool's grant. The harness keeps it with the session, across reopen. */
522
+ async revokeTool(name: string): Promise<ToolAvailability> { return (await this.#client().revokeTool(name)).tool; }
523
+ async restoreTool(name: string): Promise<ToolAvailability> { return (await this.#client().restoreTool(name)).tool; }
524
+ /** Enable a `runtime` tool by name. Remembered here and supplied again on the next open. */
525
+ async enableTool(name: string): Promise<ToolAvailability> {
526
+ const tool = (await this.#client().enableTool(name)).tool;
527
+ this.#functionHost()?.select(name, true);
528
+ return tool;
529
+ }
530
+ async removeTool(name: string): Promise<ToolAvailability> {
531
+ const tool = (await this.#client().removeTool(name)).tool;
532
+ this.#functionHost()?.select(name, false);
533
+ return tool;
534
+ }
535
+ /** One tool call by its invocation ID, from the harness's records. Undefined when unknown. */
536
+ async toolInvocation(invocationId: string): Promise<ToolInvocation | undefined> {
537
+ try { return (await this.#client().toolInvocation(invocationId)).invocation; }
538
+ catch (error) { if (codeOf(error) === "not_found") return undefined; throw error; }
539
+ }
540
+ async toolInvocations(turn: string): Promise<ToolInvocation[]> { return (await this.#client().toolInvocations(turn)).invocations; }
541
+
542
+ /** Settles what the view answers: submissions first (they decide which turn causes are ours), then each channel. */
543
+ #reconcile(view: LoadResult, observed: ReadonlyMap<string, number>): void {
544
+ const items = new Map(view.items.map((item) => [item.id, item]));
545
+ for (const submission of this.records.submissions()) {
546
+ const item = items.get(submission.id);
547
+ if (!item) continue; // unknown to the harness: retried after the open, with the same id and payload
548
+ if (item.milestone === "withdrawn") this.records.settleSubmission(submission.id);
549
+ else this.records.markAccepted(submission.id, item.turnId !== undefined);
550
+ this.#waiters.get(submission.id)?.resolve(item);
551
+ this.#waiters.delete(submission.id);
552
+ }
553
+ for (const [channel, port] of [...this.#ports]) {
554
+ port.reconcile({
555
+ revision: observed.get(channel) ?? view.status.revision,
556
+ status: this.#channels.get(channel),
557
+ turns: view.turns.filter((turn) => turn.channel === channel),
558
+ items: view.items.filter((item) => item.channel === channel),
559
+ messages: view.messages.filter((message) => message.channel === channel),
560
+ });
561
+ }
562
+ }
563
+
564
+ /** Queue unresolved submissions behind the post-cutoff edits. */
565
+ #replaySubmissions(): void {
566
+ for (const submission of this.records.submissions()) {
567
+ if (submission.withdrawing) { this.#retryWithdrawal(submission, true); continue; }
568
+ if (submission.state === "accepted") continue;
569
+ // Saved and never written, with nobody waiting (its caller was told it failed, or is gone):
570
+ // it is not sent now.
571
+ if (submission.state === "saved" && !this.#waiters.has(submission.id)) { this.records.settleSubmission(submission.id); continue; }
572
+ void this.#changes.enqueue(submission.channel, () => this.#submit(submission.id)).catch(() => undefined);
573
+ }
574
+ }
575
+ /** The connection is gone. Reopen if work is outstanding; otherwise wait for the next use. */
576
+ #lost(connection: NativeConnection): void {
577
+ if (this.#connection !== connection) return;
578
+ this.#connection = null;
579
+ this.#approvals.disconnected();
580
+ if (this.#stopped) return;
581
+ this.#setState("stopped");
582
+ this.#log.warn("native_harness_connection_lost", { sessionId: this.sessionId });
583
+ for (const port of [...this.#ports.values()]) port.disconnected();
584
+ // An input the harness accepted is outstanding until its turn settles, even when the process died
585
+ // before this host saw that turn start: its `turn_started` may never have been written.
586
+ const outstanding = this.#waiters.size > 0 || [...this.#ports.values()].some((port) => port.busy()) || this.records.submissions().length > 0;
587
+ if (outstanding) void this.#reopen();
588
+ else if (this.#workerDelivery) void this.#workerDelivery.hasWork().then(hasWork => {
589
+ if (hasWork && this.#state === "stopped" && !this.#stopped) void this.#reopen();
590
+ }).catch(error => this.#log.warn("native_worker_delivery_discovery_failed", { error: String(error) }));
591
+ }
592
+
593
+ async #reopen(): Promise<void> {
594
+ while (!this.#stopped && this.#claimRestart(Date.now())) {
595
+ try {
596
+ await this.ensureStarted();
597
+ return;
598
+ } catch (error) {
599
+ if (terminalStartupError(error)) { this.#restarts.pop(); this.#failReopen(error); return; }
600
+ this.#log.warn("native_harness_reopen_failed", { error: String(error) });
601
+ await new Promise((resolve) => setTimeout(resolve, 100 * this.#restarts.length));
602
+ }
603
+ }
604
+ if (!this.#stopped) this.#failReopen();
605
+ }
606
+
607
+ #claimRestart(now: number): boolean {
608
+ const { limit, windowMs } = this.#config.restart ?? { limit: 3, windowMs: 60_000 };
609
+ while (this.#restarts.length && now - this.#restarts[0]! > windowMs) this.#restarts.shift();
610
+ if (this.#restarts.length >= limit) return false;
611
+ this.#restarts.push(now);
612
+ return true;
613
+ }
614
+
615
+ #failReopen(error?: Error): Error {
616
+ this.#failure = error ?? new HarnessUnavailableError("the native harness could not be reopened", { code: "reopen_failed" });
617
+ this.#setState("failed");
618
+ this.#rejectWaiters(this.#failure);
619
+ for (const port of [...this.#ports.values()]) port.failed(this.#failure);
620
+ return this.#failure;
621
+ }
622
+
623
+ #rejectWaiters(error: Error): void {
624
+ for (const waiter of this.#waiters.values()) waiter.reject(error);
625
+ this.#waiters.clear();
626
+ }
627
+
628
+ #route(connection: NativeConnection, event: ChannelEvent): void {
629
+ // A late event of a connection that was replaced is not this session's present.
630
+ if (this.#stopped || (this.#connection !== null && this.#connection !== connection)) return;
631
+ this.#observeApproval(connection, event);
632
+ if (this.#early) { this.#early.push(event); return; }
633
+ this.#deliver(event);
634
+ }
635
+
636
+ #deliver(event: ChannelEvent): void {
637
+ this.reminderIdle?.activity();
638
+ if (event.event.type === "item_withdrawn") {
639
+ const id = event.event.item;
640
+ const sender = this.records.submission(id)?.sender ?? "";
641
+ this.records.settleSubmission(id);
642
+ this.#waiters.get(id)?.resolve({ id, channel: event.channel, sender, kind: "participant_message", milestone: "withdrawn" });
643
+ this.#waiters.delete(id);
644
+ }
645
+ if (event.event.type === "turn_started" || event.event.type === "turn_took") for (const id of event.event.items) if (this.records.submission(id)?.withdrawing) this.records.markAccepted(id, true);
646
+ if (event.event.type === "approval_requested") this.#approvals.start(event.event);
647
+ if (event.event.type === "approval_closed") this.#approvals.closed(event.event);
648
+ if (event.event.type === "turn_ended") this.#approvals.end(event.channel, event.event.turnId);
649
+ if (event.event.type === "channel_state") {
650
+ const known = this.#channels.get(event.channel);
651
+ const { displayName, policy, lifecycle } = event.event;
652
+ const { displayName: _name, policy: _policy, ...rest } = known ?? { channel: event.channel, pending: [], waitingForResume: false, lifecycle };
653
+ this.#channels.set(event.channel, { ...rest, lifecycle, ...(displayName === undefined ? {} : { displayName }), ...(policy === undefined ? {} : { policy }) });
654
+ }
655
+ const buffered = this.#attaching.get(event.channel);
656
+ if (buffered) { buffered.push(event); return; }
657
+ const port = this.#ports.get(event.channel);
658
+ if (port) { port.event(event); return; }
659
+ // No conversation attached: keep the channel's events until one is. Bounded so an unattended
660
+ // channel cannot grow without limit; state events are not kept (the status is tracked above).
661
+ if (event.event.type === "channel_state") return;
662
+ const held = this.#backlog.get(event.channel) ?? [];
663
+ held.push(event);
664
+ if (held.length > 2000) held.shift();
665
+ this.#backlog.set(event.channel, held);
666
+ }
667
+
668
+ #client(): HarnessClient {
669
+ // Also during an open, once the view is in: reconciliation may read a message by reference.
670
+ const client = this.#connection?.client;
671
+ if (!client) throw new HarnessUnavailableError("the native harness is not running", { code: "not_running" });
672
+ return client;
673
+ }
674
+
675
+ /**
676
+ * Hands one input to the harness. The id and exact payload are saved first; the promise resolves on a
677
+ * receipt or when reconciliation finds the item, whichever comes first, possibly after a reopen. A
678
+ * definite refusal (suspended or retired channel, unknown policy, a conflicting id) rejects it.
679
+ */
680
+ async push(input: Omit<Submission, "state">): Promise<ItemStatus> {
681
+ this.records.saveSubmission({ ...input, state: "saved" });
682
+ const waiter = this.#waiters.get(input.id) ?? deferred<ItemStatus>();
683
+ this.#waiters.set(input.id, waiter);
684
+ try {
685
+ await this.ensureStarted();
686
+ } catch (error) {
687
+ if (this.#waiters.get(input.id) === waiter) this.#waiters.delete(input.id);
688
+ // Nothing was written for it, so the harness cannot have it: the caller is told it failed and
689
+ // it must never run later. One that was written before (`unknown`) stays for the next open.
690
+ if (this.records.submission(input.id)?.state === "saved") this.records.settleSubmission(input.id);
691
+ throw error;
692
+ }
693
+ // Behind the channel's queued live edits: an edit made before this input reaches the harness first.
694
+ void this.#changes.enqueue(input.channel, () => this.#submit(input.id)).catch(() => undefined);
695
+ return waiter.promise;
696
+ }
697
+
698
+ async #submit(id: string): Promise<void> {
699
+ const submission = this.records.submission(id);
700
+ if (!submission || submission.withdrawing) return;
701
+ if (submission.state === "accepted" && !this.#waiters.has(id)) return;
702
+ // Read when the outcome is known, not now: a caller may start waiting for this id while the
703
+ // request is in flight (a retry after a reopen, then the conversation's own send).
704
+ const settle = (act: (waiter: Deferred<ItemStatus>) => void) => {
705
+ const waiter = this.#waiters.get(id);
706
+ this.#waiters.delete(id);
707
+ if (waiter) act(waiter);
708
+ };
709
+ const request = () => {
710
+ const client = this.#client();
711
+ // Recorded before the bytes leave: from here the outcome is unknown until a receipt or a view.
712
+ this.records.markSent(id);
713
+ return client.push({
714
+ channel: submission.channel,
715
+ item: {
716
+ id: submission.id, kind: "user_message", sender: submission.sender,
717
+ content: [{ type: "text", text: submission.text }],
718
+ ...(submission.policy === undefined ? {} : { policy: submission.policy }),
719
+ },
720
+ });
721
+ };
722
+ try {
723
+ let receipt;
724
+ try { receipt = await request(); }
725
+ catch (error) {
726
+ // No answer on a live connection: the same id and payload again. The harness answers a
727
+ // repeat with the original item, so this never creates a second input.
728
+ const pending = this.records.submission(id);
729
+ if (codeOf(error) !== "timeout" || this.#state !== "running" || !pending || pending.withdrawing) throw error;
730
+ receipt = await request();
731
+ }
732
+ const item: ItemStatus = receipt.item ?? { id, channel: submission.channel, kind: "participant_message", sender: submission.sender, milestone: "received" };
733
+ if (item.milestone === "withdrawn") { this.#deliver({ channel: submission.channel, event: { type: "item_withdrawn", item: id } }); return; }
734
+ this.records.markAccepted(id, item.turnId !== undefined);
735
+ settle((waiter) => waiter.resolve(item));
736
+ if (this.records.submission(id)?.withdrawing) this.#retryWithdrawal(submission);
737
+ } catch (error) {
738
+ // Unknown outcome: the saved submission stays `unknown`. The next open finds it in the view
739
+ // (accepted) or retries it with this id and payload.
740
+ if (ambiguous(error)) {
741
+ if (codeOf(error) === "timeout" && this.records.submission(id)?.withdrawing) this.#retryWithdrawal(submission, true);
742
+ return;
743
+ }
744
+ // Not running, so nothing was written this time. Whoever waits is reopened for by `#lost`, or
745
+ // was already told the host stopped or failed.
746
+ if (error instanceof HarnessUnavailableError) return;
747
+ this.records.settleSubmission(id);
748
+ settle((waiter) => waiter.reject(error));
749
+ }
750
+ }
751
+
752
+ /** The input reached its end (its turn ended, or it was withdrawn): nothing is left to retry. */
753
+ settle(ids: Iterable<string>): void {
754
+ for (const id of ids) this.records.settleSubmission(id);
755
+ }
756
+
757
+ /**
758
+ * Records the newest desired state of a channel. Running: applied through the live channel methods,
759
+ * in order with that channel's inputs. Stopped: stored, and sent with the next open; it never starts
760
+ * the harness.
761
+ */
762
+ async changeChannel(channel: string, desire: ChannelDesire): Promise<ChannelChangeOutcome> {
763
+ if (this.#idling) await this.ensureStarted();
764
+ this.reminderIdle?.activity();
765
+ const result = await this.#changes.change(channel, desire, this.#state === "running");
766
+ if (result.state === "applied") void this.flushWorkerDelivery();
767
+ return result;
768
+ }
769
+
770
+ /** The pending channel intents from the host's active store. */
771
+ async pendingChannelChanges(): Promise<PendingChange[]> { return this.#changes.pendingChanges(); }
772
+
773
+ /** Reserve delivery now, then read the intent only after its transaction commits. */
774
+ async deliverCommittedChannelChange<T>(channel: string, commit: Promise<T>, deliver: (result: T) => boolean = () => true): Promise<T> {
775
+ this.reminderIdle?.activity();
776
+ const result = await this.#changes.deliverCommitted(channel, commit, () => this.#state === "running", deliver);
777
+ void this.flushWorkerDelivery();
778
+ return result;
779
+ }
780
+
781
+ /** The session's status as the running harness reports it now. */
782
+ #lastStatus?: StatusResult;
783
+ #capabilities?: Awaited<ReturnType<HarnessClient["initialize"]>>["description"]["capabilities"];
784
+
785
+ get capabilities() { return this.#capabilities; }
786
+ get sessionLifecycle() { return this.#lastStatus?.lifecycle; }
787
+ async status(): Promise<StatusResult> {
788
+ const live = await this.#client().status();
789
+ this.#lastStatus = live;
790
+ return live;
791
+ }
792
+
793
+ async operatorStatus() {
794
+ const connection = this.#connection;
795
+ let confirmed = false;
796
+ if (connection) {
797
+ try { await this.status(); confirmed = true; }
798
+ catch (error) { if (!ambiguous(error)) throw error; }
799
+ }
800
+ const session = this.#lastStatus;
801
+ const workingChannels = session?.channels.filter(channel => channel.activeTurn?.state === "running").length ?? 0;
802
+ return { process: this.#state, stale: !confirmed || this.#connection !== connection, session, workingChannels };
803
+ }
804
+
805
+ async usage(channel?: string) { return summarizeModelUsage(this.#client(), channel); }
806
+
807
+ start(): Promise<void> { return this.ensureStarted(); }
808
+ async suspend(): Promise<StatusResult> {
809
+ const status = await this.#client().suspend();
810
+ this.#lastStatus = status;
811
+ return status;
812
+ }
813
+ async resume(): Promise<StatusResult> {
814
+ const status = await this.#client().resume();
815
+ this.#lastStatus = status;
816
+ void this.flushWorkerDelivery();
817
+ return status;
818
+ }
819
+ validateConfig(config: unknown) { return this.#client().validateConfig(config); }
820
+ async suspendChannel(channel: string) { return this.#client().suspendChannel({ channel }); }
821
+ async resumeChannel(channel: string) {
822
+ const status = await this.#changes.resume(channel);
823
+ void this.flushWorkerDelivery();
824
+ return status;
825
+ }
826
+
827
+ async flushWorkerDelivery(): Promise<void> {
828
+ if (this.#state !== "running") return;
829
+ try { await this.#workerDelivery?.flush(); }
830
+ catch (error) { this.#log.warn("native_worker_delivery_failed", { error: String(error) }); }
831
+ }
832
+ reconcileChannel(params: Parameters<HarnessClient["reconcileChannel"]>[0]) { return this.#client().reconcileChannel(params); }
833
+ modelCalls(params: Parameters<HarnessClient["modelCalls"]>[0] = {}, signal?: AbortSignal) { return this.#client().modelCalls(params, signal); }
834
+ conversationMessages(params: Parameters<HarnessClient["channelMessages"]>[0]) { return this.#client().channelMessages(params); }
835
+ /** Commit each page atomically with its position. On failure the caller's
836
+ * last committed position is the retry boundary. */
837
+ async catchUp(channel: string, after: string,
838
+ commit: (messages: Awaited<ReturnType<HarnessClient["channelMessages"]>>["messages"], position: string) => Promise<void>,
839
+ signal?: AbortSignal,
840
+ ): Promise<string> {
841
+ const client = this.#client();
842
+ const connection = this.#connection;
843
+ if (this.#attaching.has(channel)) throw new Error("Channel observation is already in progress");
844
+ const buffered: ChannelEvent[] = [];
845
+ this.#attaching.set(channel, buffered);
846
+ const committed = new Set<string>();
847
+ try { return await commitChannelCatchUp(client, channel, after, committed, commit, signal);
848
+ } finally {
849
+ this.#attaching.delete(channel);
850
+ const port = this.#connection === connection ? this.#ports.get(channel) : undefined;
851
+ for (const event of this.#connection === connection ? buffered : []) {
852
+ if (event.event.type === "message_completed" && event.event.messageId && committed.has(event.event.messageId)) continue;
853
+ if (port) port.event(event);
854
+ else this.#deliver(event);
855
+ }
856
+ }
857
+ }
858
+
859
+ timeline(params: Parameters<HarnessClient["timeline"]>[0] = {}) { return this.#client().timeline(params); }
860
+
861
+ /** Interrupts exactly this turn. False when it had already ended or was checkpointed. */
862
+ async interrupt(channel: string, turn: string, reason?: string): Promise<boolean> {
863
+ const result = await this.#client().interruptTurn({ channel, turn, ...(reason === undefined ? {} : { reason }) });
864
+ return result.interrupted;
865
+ }
866
+
867
+ async respondApproval(requestId: string, decision: "allow_once" | "deny"): Promise<boolean> {
868
+ if (this.#config.approvalResponder) return false;
869
+ return this.#answerApproval(requestId, decision);
870
+ }
871
+
872
+ async #answerApproval(requestId: string, decision: "allow_once" | "deny"): Promise<boolean> {
873
+ try {
874
+ await this.#client().respondApproval(requestId, decision);
875
+ return true;
876
+ } catch (error) {
877
+ if (codeOf(error) === "not_found" || ambiguous(error) || error instanceof HarnessUnavailableError) return false;
878
+ throw error;
879
+ }
880
+ }
881
+
882
+ async withdraw(channel: string, item: string): Promise<{ outcome: "withdrawn" } | { outcome: "taken"; turnId: string | undefined }> {
883
+ const result = await this.#client().withdrawItem({ channel, item });
884
+ if (result.outcome === "withdrawn") this.#deliver({ channel, event: { type: "item_withdrawn", item } });
885
+ else { this.records.markAccepted(item, true); this.#waiters.get(item)?.resolve(result.item); this.#waiters.delete(item); }
886
+ return result.outcome === "withdrawn" ? { outcome: "withdrawn" } : { outcome: "taken", turnId: result.item.turnId };
887
+ }
888
+
889
+ async withdrawSubmission(channel: string, id: string, onTaken?: (turnId?: string) => void): Promise<boolean> {
890
+ const result = await this.#withdrawals.withdraw(channel, id, this.#waiters.get(id)?.promise);
891
+ if (result?.outcome === "taken") onTaken?.(result.turnId);
892
+ return result?.outcome === "withdrawn";
893
+ }
894
+
895
+ #retryWithdrawal(submission: Submission, reopened = false): void {
896
+ const connection = this.#connection;
897
+ void this.#withdrawals.retry(submission.channel, submission.id, undefined, reopened).catch(error => {
898
+ this.#log.warn("native_withdrawal_unresolved", { item: submission.id, error: String(error) });
899
+ // Once reconciliation is exhausted, unblock an unacknowledged push with uncertainty.
900
+ if (reopened && this.#connection === connection && this.records.submission(submission.id)?.withdrawing) {
901
+ this.#waiters.get(submission.id)?.reject(error);
902
+ this.#waiters.delete(submission.id);
903
+ }
904
+ });
905
+ }
906
+
907
+ recoverStoppedReplies(channel: string, turnId: string, seen: Parameters<typeof recoverStoppedReplies>[3]) { return recoverStoppedReplies(this.#client(), channel, turnId, seen); }
908
+ readMessage(messageId: string): Promise<string> { return readCompleteMessage(this.#client(), messageId); }
909
+ }