@qlairoslabs/acp-client 0.12.0 → 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 -3
  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 +847 -7
  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 +30 -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 +10 -0
  35. package/src/cli/index.ts +3 -3
  36. package/src/cli/managed.ts +2 -2
  37. package/src/client.ts +68 -98
  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,405 @@
1
+ import type { ContextLimits } from "../contracts/context.ts";
2
+ import type { ActiveTurn, ChannelInput, ChannelNotice, SendResult, SessionAgent, TurnExecutor, TurnPort } from "../contracts/agent.ts";
3
+ import type { EventSink, SessionEventSink } from "../contracts/events.ts";
4
+ import type { ChannelControls, ChannelStatus, ControlResult, LifecycleResult, SessionStatus } from "../contracts/session.ts";
5
+ import type { AcceptItem, SessionLifecycle, SessionStorage, StorageError, StorageResult, StorageSnapshot, StoredTurn } from "../contracts/storage.ts";
6
+
7
+ export interface ChannelScheduler {
8
+ wakeCommittedChannel(channelId: string): void;
9
+ agent: SessionAgent;
10
+ channels: ChannelControls;
11
+ start(): void;
12
+ suspend(): Promise<LifecycleResult>;
13
+ resume(): LifecycleResult;
14
+ stop(reason: string): SessionStatus;
15
+ status(): SessionStatus;
16
+ }
17
+
18
+ /** Status is a pure reading of one snapshot plus this process's own state. */
19
+ export function sessionStatus(view: Pick<StorageSnapshot, "revision" | "session" | "channels" | "turns" | "items">, stopped: boolean, incompatible = false): SessionStatus {
20
+ const working = view.turns.some(turn => turn.state.status === "running");
21
+ // Input pending on a channel that cannot run (suspended, suspending) is waiting
22
+ // for a resume, not execution.
23
+ const open = new Set(view.channels.filter(channel => channel.lifecycle === "open").map(channel => channel.channelId));
24
+ const pending = view.items.some(item => item.milestone === "received" && open.has(item.channelId));
25
+ const sessionRuns = view.session.lifecycle === "running";
26
+ return {
27
+ sessionId: view.session.sessionId, revision: view.revision, lifecycle: view.session.lifecycle,
28
+ execution: stopped ? "stopped" : incompatible ? "incompatible" : view.session.lifecycle !== "running" ? view.session.lifecycle : working || pending ? "working" : "idle",
29
+ channels: view.channels.map(({ channelId, displayName, policy, lifecycle }) => {
30
+ const turns = view.turns.filter(turn => turn.channelId === channelId), last = turns.at(-1);
31
+ const live = turns.find(turn => turn.state.status === "running" || turn.state.status === "suspended");
32
+ const pendingItemIds = view.items.filter(item => item.channelId === channelId && item.milestone === "received").map(item => item.itemId);
33
+ return {
34
+ channelId, ...(displayName === undefined ? {} : { displayName }), ...(policy === undefined ? {} : { policy }), lifecycle,
35
+ ...(live ? { activeTurn: { turnId: live.turnId, status: live.state.status as "running" | "suspended" } } : {}),
36
+ pendingItemIds,
37
+ waitingForResume: (pendingItemIds.length > 0 || live?.state.status === "suspended")
38
+ && (lifecycle === "suspending" || lifecycle === "suspended" || !sessionRuns),
39
+ ...(last && (last.state.status === "failed" || last.state.status === "interrupted")
40
+ ? { unresolvedInterruption: { turnId: last.turnId, ...last.state } } : {}),
41
+ };
42
+ }),
43
+ };
44
+ }
45
+
46
+ /** One live turn per channel, any number of channels at once. Storage decides
47
+ * every admission, take and finish; this module only reacts to those commits,
48
+ * publishes each one after it happens, and keeps the per-process handles
49
+ * (promises and abort controllers) that storage cannot hold. */
50
+ export function createChannelScheduler(
51
+ storage: SessionStorage, execute: TurnExecutor, emit: EventSink = () => {}, emitSession: SessionEventSink = () => {}, limits?: ContextLimits,
52
+ ): ChannelScheduler {
53
+ const live = new Map<string, { turnId: number; abort: AbortController; suspension: AbortController }>();
54
+ // Channels that may have pending input. Only an optimization and an idle
55
+ // signal: beginTurn remains the authority on whether a turn starts.
56
+ const waiting = new Set<string>();
57
+ let started = false, stopped = false;
58
+ let lifecycle: SessionLifecycle = "running";
59
+ let suspension: { promise: Promise<LifecycleResult>; settle(result: LifecycleResult): void } | undefined;
60
+ // Individual channel suspensions begun by this process and not yet committed
61
+ // as `suspended`. Storage holds the truth; this holds the waiting callers.
62
+ const channelSuspensions = new Map<string, { promise: Promise<ControlResult<ChannelStatus>>; settle(result: ControlResult<ChannelStatus>): void }>();
63
+ const channelRecord = (channelId: string) => {
64
+ const read = storage.readChannel(channelId);
65
+ if (read.ok) return read.value.channel;
66
+ if (read.error.code !== "not_found") throw new Error(read.error.message);
67
+ return undefined;
68
+ };
69
+ const compatible = () => { const result = storage.executionCompatible(); if (!result.ok) throw new Error(result.error.message); return result.value; };
70
+ const status = () => {
71
+ const read = storage.readExecution();
72
+ if (!read.ok) throw new Error(read.error.message);
73
+ return sessionStatus(read.value, stopped, !compatible());
74
+ };
75
+ /** Channels whose pending input this process may start: open ones only. A
76
+ * suspended channel's backlog waits for its own resume and is not "waiting"
77
+ * here, so it never keeps the session from reporting idle. */
78
+ function rescan() {
79
+ const current = storage.readReadyChannels();
80
+ if (!current.ok) throw new Error(current.error.message);
81
+ lifecycle = current.value.lifecycle;
82
+ waiting.clear();
83
+ for (const channel of current.value.channels) waiting.add(channel);
84
+ }
85
+ rescan();
86
+ const channelStatus = (channelId: string): ChannelStatus => status().channels.find(channel => channel.channelId === channelId)!;
87
+ const emitState = (channelId: string, revision: number) => {
88
+ const channel = channelStatus(channelId);
89
+ // A channel that is not open has no input this process may start.
90
+ if (channel.lifecycle !== "open") waiting.delete(channelId);
91
+ emit({ channel: channelId, revision, event: { type: "channel_state", lifecycle: channel.lifecycle,
92
+ ...(channel.displayName === undefined ? {} : { displayName: channel.displayName }), ...(channel.policy === undefined ? {} : { policy: channel.policy }) } });
93
+ };
94
+ /** A commit just ended or checkpointed this channel's turn: if its individual
95
+ * suspension completed in that same transaction, announce it and answer the caller. */
96
+ function settleChannel(channelId: string, revision: number) {
97
+ const waiter = channelSuspensions.get(channelId);
98
+ if (!waiter || channelStatus(channelId).lifecycle === "suspending") return;
99
+ channelSuspensions.delete(channelId);
100
+ emitState(channelId, revision);
101
+ waiter.settle({ ok: true, value: channelStatus(channelId), revision });
102
+ }
103
+ const ended = (turn: StoredTurn, revision: number) => {
104
+ if (turn.state.status !== "failed" && turn.state.status !== "interrupted") return;
105
+ emit({ channel: turn.channelId, revision, event: { type: "turn_ended", turnId: String(turn.turnId), outcome: turn.state.status,
106
+ error: turn.state.reason, ...(turn.state.uncertainCallIds.length ? { uncertainCalls: turn.state.uncertainCallIds } : {}) } });
107
+ };
108
+
109
+ /** Start the channel's next turn if storage has one to start. */
110
+ function pump(channelId: string) {
111
+ if (!started || stopped || lifecycle !== "running" || live.has(channelId)) return;
112
+ const begun = storage.beginTurn(channelId, limits);
113
+ // A suspended or retired channel is not ours to start; its backlog stays
114
+ // pending until its own resume re-queues it.
115
+ if (!begun.ok && (begun.error.code === "channel_suspended" || begun.error.code === "channel_retired")) { waiting.delete(channelId); return; }
116
+ if (!begun.ok || !begun.value) { if (begun.ok) waiting.delete(channelId); return; }
117
+ waiting.delete(channelId);
118
+ emit({ channel: channelId, revision: begun.revision, event: { type: "turn_started", turnId: String(begun.value.turn.turnId),
119
+ items: begun.value.items.map(item => item.itemId), messages: begun.value.entries.flatMap(entry =>
120
+ entry.kind === "participant_message" && entry.itemId ? [{ itemId: entry.itemId, messageId: `item:${entry.itemId}`, position: String(entry.seq) }] : []) } });
121
+ run({ channelId, turnId: begun.value.turn.turnId, resumed: false });
122
+ }
123
+
124
+ function run(turn: ActiveTurn) {
125
+ const { channelId, turnId } = turn, abort = new AbortController(), suspensionSignal = new AbortController();
126
+ live.set(channelId, { turnId, abort, suspension: suspensionSignal });
127
+ // Called with the commit that ends or parks the turn, before its event, so
128
+ // an observer reacting to that event already sees the channel as free.
129
+ const release = () => { if (live.get(channelId)?.turnId === turnId) live.delete(channelId); };
130
+ // A refusal here means the turn is no longer running (stopped): unwind the loop.
131
+ const fenced = (message: string): never => { throw new Error(`Turn ${turnId} can no longer be advanced: ${message}`); };
132
+ const port: TurnPort = {
133
+ signal: abort.signal,
134
+ suspensionSignal: suspensionSignal.signal,
135
+ take() {
136
+ const taken = storage.takePending(turnId, limits);
137
+ if (!taken.ok) { if (taken.error.code !== "not_running" && taken.error.code !== "channel_suspended") fenced(taken.error.message); return; }
138
+ waiting.delete(channelId);
139
+ if (taken.value.items.length) emit({ channel: channelId, revision: taken.revision,
140
+ event: { type: "turn_took", turnId: String(turnId), items: taken.value.items.map(item => item.itemId), messages: taken.value.entries.flatMap(entry =>
141
+ entry.kind === "participant_message" && entry.itemId ? [{ itemId: entry.itemId, messageId: `item:${entry.itemId}`, position: String(entry.seq) }] : []) } });
142
+ },
143
+ confirm(milestone) {
144
+ const advanced = storage.confirmReceipts(turnId, milestone);
145
+ if (advanced.ok && advanced.value.length) emit({ channel: channelId, revision: advanced.revision,
146
+ event: { type: "items_receipt", turnId: String(turnId), items: advanced.value.map(item => item.itemId), milestone } });
147
+ },
148
+ finish() {
149
+ // The pending check and the completion are one storage transaction, so
150
+ // a concurrent send either keeps this turn open or starts the next one.
151
+ const finished = storage.finishTurn(turnId, { status: "completed" });
152
+ if (!finished.ok) return fenced(finished.error.message);
153
+ if (!finished.value.finished) return false;
154
+ release();
155
+ emit({ channel: channelId, revision: finished.revision, event: { type: "turn_ended", turnId: String(turnId), outcome: "completed" } });
156
+ settleChannel(channelId, finished.revision);
157
+ return true;
158
+ },
159
+ checkpoint() {
160
+ // Either suspension stops the turn at this boundary; storage completes the
161
+ // channel's own suspension in the same commit as the checkpoint.
162
+ if (lifecycle !== "suspending" && !channelSuspensions.has(channelId)) return false;
163
+ const saved = storage.checkpointTurn(turnId);
164
+ if (!saved.ok) return fenced(saved.error.message);
165
+ release();
166
+ emit({ channel: channelId, revision: saved.revision, event: { type: "turn_suspended", turnId: String(turnId) } });
167
+ settleChannel(channelId, saved.revision);
168
+ return true;
169
+ },
170
+ };
171
+ // Never run the executor inside the caller's stack: acceptance and resume
172
+ // return before any model or tool work begins.
173
+ void Promise.resolve().then(() => execute(turn, port)).then(() => {}, error => {
174
+ // Record the failure unless stop already ended the turn; either way the
175
+ // channel stays usable.
176
+ const outcome = error && typeof error === "object" && "outcome" in error && typeof error.outcome === "string" ? error.outcome : String(error);
177
+ const failed = storage.finishTurn(turnId, { status: "failed", reason: outcome });
178
+ release();
179
+ if (failed.ok && failed.value.finished) { ended(failed.value.turn, failed.revision); settleChannel(channelId, failed.revision); }
180
+ }).then(() => {
181
+ release();
182
+ settleSuspension();
183
+ pump(channelId);
184
+ });
185
+ }
186
+
187
+ function settleSuspension() {
188
+ if (!suspension || lifecycle !== "suspending" || live.size) return;
189
+ const done = storage.completeSuspend();
190
+ if (done.ok) { lifecycle = "suspended"; emitSession({ type: "lifecycle", lifecycle, revision: done.revision }); }
191
+ suspension.settle(done.ok ? { ok: true, status: status() } : { ok: false, error: done.error });
192
+ suspension = undefined;
193
+ }
194
+
195
+ function accept(item: AcceptItem): SendResult {
196
+ if (stopped && item.kind !== "external_notice") return { accepted: false, code: "stopped", error: "This process has stopped accepting work" };
197
+ if (stopped) {
198
+ const known = storage.snapshot();
199
+ if (!known.ok || !known.value.items.some(stored => stored.itemId === item.itemId))
200
+ return { accepted: false, code: "stopped", error: "This process has stopped accepting work" };
201
+ }
202
+ const result = storage.acceptItem(item, limits?.maxInputBytes);
203
+ if (!result.ok) {
204
+ const code = result.error.code;
205
+ return { accepted: false, error: result.error.message, code: code === "invalid_input" || code === "item_conflict"
206
+ || code === "invalid_policy" || code === "incompatible" || code === "not_running" || code === "not_found" || code === "channel_suspended" || code === "channel_retired" ? code : "storage_failure" };
207
+ }
208
+ const { item: stored, duplicate } = result.value;
209
+ if (!duplicate) {
210
+ waiting.add(stored.channelId);
211
+ // Acknowledge first; the channel takes the item on a later microtask.
212
+ queueMicrotask(() => pump(stored.channelId));
213
+ }
214
+ return { accepted: true, itemId: stored.itemId, duplicate, milestone: stored.milestone,
215
+ ...(stored.turnId === undefined ? {} : { turnId: stored.turnId }) };
216
+ }
217
+
218
+ const stoppedResult = { ok: false as const, error: { code: "stopped" as const, message: "Session is stopped" } };
219
+ const failedWith = (error: StorageError) => ({ ok: false as const, error });
220
+ /** Run one storage control; `after` publishes its effects once it committed. */
221
+ function control<T, R>(act: () => StorageResult<T>, after: (value: T, revision: number) => R): ControlResult<R> {
222
+ if (stopped) return stoppedResult;
223
+ const result = act();
224
+ if (!result.ok) return failedWith(result.error);
225
+ return { ok: true, value: after(result.value, result.revision), revision: result.revision };
226
+ }
227
+ const lifecycleOf = (channelId: string) => channelRecord(channelId)?.lifecycle;
228
+
229
+ const channels: ChannelControls = {
230
+ create: input => {
231
+ const result = control(() => storage.createChannel(input), ({ created }, revision) => {
232
+ if (created) emitState(input.channelId, revision);
233
+ return { channel: channelStatus(input.channelId), created };
234
+ });
235
+ return result;
236
+ },
237
+ edit: (channelId, displayName, policy) => {
238
+ const before = channelRecord(channelId);
239
+ return control(() => storage.editChannel(channelId, displayName, policy), (now, revision) => {
240
+ if (now.displayName !== before?.displayName || now.policy !== before?.policy) emitState(channelId, revision);
241
+ return channelStatus(channelId);
242
+ });
243
+ },
244
+ suspend(channelId) {
245
+ if (stopped) return Promise.resolve(stoppedResult);
246
+ const waiter = channelSuspensions.get(channelId);
247
+ if (waiter) return waiter.promise;
248
+ const before = lifecycleOf(channelId);
249
+ const begun = storage.beginChannelSuspend(channelId);
250
+ if (!begun.ok) return Promise.resolve(failedWith(begun.error));
251
+ if (begun.value.lifecycle === "suspended") {
252
+ if (before !== "suspended") emitState(channelId, begun.revision);
253
+ return Promise.resolve({ ok: true, value: channelStatus(channelId), revision: begun.revision });
254
+ }
255
+ let settle!: (result: ControlResult<ChannelStatus>) => void;
256
+ const promise = new Promise<ControlResult<ChannelStatus>>(resolve => { settle = resolve; });
257
+ channelSuspensions.set(channelId, { promise, settle });
258
+ // Install the waiter before aborting: a synchronous cancellation observer
259
+ // may call stop and must be able to settle this very suspension.
260
+ if (before === "open") live.get(channelId)?.suspension.abort();
261
+ if (channelSuspensions.has(channelId)) emitState(channelId, begun.revision);
262
+ // The channel's turn reaches its boundary on its own and settles this at
263
+ // the commit that checkpoints, completes or interrupts it.
264
+ return promise;
265
+ },
266
+ resume: channelId => {
267
+ const before = lifecycleOf(channelId);
268
+ if (stopped) return stoppedResult;
269
+ const resumed = storage.resumeChannel(channelId);
270
+ if (!resumed.ok) return failedWith(resumed.error);
271
+ // An explicit resume runs its checkpoint independently of session.start.
272
+ if (before !== "open") emitState(channelId, resumed.revision);
273
+ for (const reminder of resumed.value.unblockedReminders ?? [])
274
+ emit({ channel: reminder.channel, revision: resumed.revision, event: { type: "reminder_changed", reminder } });
275
+ if (resumed.value.turn) {
276
+ emit({ channel: channelId, revision: resumed.revision, event: { type: "turn_resumed", turnId: String(resumed.value.turn.turnId) } });
277
+ run({ channelId, turnId: resumed.value.turn.turnId, resumed: true });
278
+ } else if (before !== "open") {
279
+ rescan();
280
+ pump(channelId);
281
+ }
282
+ return { ok: true, value: channelStatus(channelId), revision: resumed.revision };
283
+ },
284
+ delete: channelId => {
285
+ const before = lifecycleOf(channelId);
286
+ return control(() => storage.deleteChannel(channelId), (channel, revision) => {
287
+ waiting.delete(channelId);
288
+ if (before !== "retired") emitState(channelId, revision);
289
+ for (const id of channel.cancelledReminderIds ?? [])
290
+ emit({ channel: channelId, revision, event: { type: "reminder_cancelled", reminderId: id, by: "channel_retired" } });
291
+ return channelStatus(channelId);
292
+ });
293
+ },
294
+ withdraw: (channelId, itemId) => control(() => storage.withdrawItem(channelId, itemId), (outcome, revision) => {
295
+ if (outcome.outcome === "withdrawn" && !outcome.repeated)
296
+ emit({ channel: channelId, revision, event: { type: "item_withdrawn", item: itemId } });
297
+ return outcome;
298
+ }),
299
+ interrupt: (channelId, turnId, reason = "interrupted by request") => control(
300
+ () => {
301
+ const handle = live.get(channelId);
302
+ // Close approval and record its paired result before terminal storage
303
+ // state. Reject invalid reasons without touching the live turn.
304
+ if (handle?.turnId === turnId && typeof reason === "string" && reason.trim()) handle.abort.abort(new Error(reason));
305
+ return storage.interruptTurn(channelId, turnId, reason);
306
+ }, (outcome, revision) => {
307
+ if (!outcome.interrupted) return outcome;
308
+ // Commit first, then cancel: whatever the aborted work returns is already fenced.
309
+ const handle = live.get(channelId);
310
+ if (handle?.turnId === turnId) { live.delete(channelId); handle.abort.abort(new Error(reason)); }
311
+ ended(outcome.turn, revision);
312
+ settleChannel(channelId, revision);
313
+ // Untaken input may start the next turn; the old turn's late result cannot reach it.
314
+ queueMicrotask(() => pump(channelId));
315
+ return outcome;
316
+ }),
317
+ };
318
+
319
+ return {
320
+ channels,
321
+ wakeCommittedChannel(channelId: string) {
322
+ if (stopped) return;
323
+ waiting.add(channelId);
324
+ if (started) queueMicrotask(() => pump(channelId));
325
+ },
326
+ agent: {
327
+ idle: () => live.size === 0 && (!compatible() || !started || stopped || lifecycle !== "running" || waiting.size === 0),
328
+ send: (input: ChannelInput) => accept({ kind: "participant_message", channelId: input?.channelId, senderId: input?.participantId,
329
+ text: input?.text, ...(input?.policy == null ? {} : { explicitPolicy: input.policy }), ...(input?.itemId === undefined ? {} : { itemId: input.itemId }) }),
330
+ notifyExternal: notice => accept({ kind: "external_notice", itemId: notice.itemId, channelId: notice.channelId,
331
+ senderId: notice.source ?? "host", externalSource: notice.source, inheritedPolicyNames: notice.policyNames, text: notice.text }),
332
+ notify: (notice: ChannelNotice) => accept({ kind: "channel_notice", channelId: notice?.channelId,
333
+ senderId: `channel:${notice?.fromChannelId}`, sourceChannelId: notice?.fromChannelId, sourceTurnId: notice?.sourceTurnId, text: notice?.text }),
334
+ },
335
+ start() {
336
+ if (started || stopped) return;
337
+ started = true;
338
+ for (const channelId of [...waiting]) pump(channelId);
339
+ },
340
+ suspend() {
341
+ if (stopped) return Promise.resolve({ ok: false, error: { code: "stopped", message: "Session is stopped" } });
342
+ if (suspension) return suspension.promise;
343
+ const begun = storage.beginSuspend();
344
+ if (!begun.ok) return Promise.resolve({ ok: false, error: begun.error });
345
+ if (begun.value.lifecycle === "suspended") { lifecycle = "suspended"; return Promise.resolve({ ok: true, status: status() }); }
346
+ const announce = lifecycle === "running";
347
+ lifecycle = "suspending";
348
+ let settle!: (result: LifecycleResult) => void;
349
+ const promise = new Promise<LifecycleResult>(resolve => { settle = resolve; });
350
+ suspension = { promise, settle };
351
+ // Observers can synchronously stop the session while an approval closes.
352
+ // Make the waiter visible before notifying any of them.
353
+ for (const handle of live.values()) handle.suspension.abort();
354
+ if (!suspension) return promise;
355
+ if (announce) emitSession({ type: "lifecycle", lifecycle: "suspending", revision: begun.revision });
356
+ if (!suspension) return promise;
357
+ // Active turns reach their boundary on their own; with none, finish now.
358
+ settleSuspension();
359
+ return promise;
360
+ },
361
+ resume() {
362
+ if (stopped) return { ok: false, error: { code: "stopped", message: "Session is stopped" } };
363
+ const resumed = storage.resume();
364
+ if (!resumed.ok) return { ok: false, error: resumed.error };
365
+ if (lifecycle !== "running") emitSession({ type: "lifecycle", lifecycle: "running", revision: resumed.revision });
366
+ started = true;
367
+ for (const reminder of resumed.value.unblockedReminders ?? [])
368
+ emit({ channel: reminder.channel, revision: resumed.revision, event: { type: "reminder_changed", reminder } });
369
+ // Storage returned only turns of channels that are not individually
370
+ // suspended; those channels keep their checkpoint and backlog.
371
+ rescan();
372
+ for (const turn of resumed.value.turns) {
373
+ emit({ channel: turn.channelId, revision: resumed.revision, event: { type: "turn_resumed", turnId: String(turn.turnId) } });
374
+ run({ channelId: turn.channelId, turnId: turn.turnId, resumed: true });
375
+ }
376
+ for (const channelId of [...waiting]) pump(channelId);
377
+ return { ok: true, status: status() };
378
+ },
379
+ stop(reason) {
380
+ if (stopped) return status();
381
+ stopped = true;
382
+ const suspending = [...channelSuspensions.keys()];
383
+ // Cancellation synchronously closes pending approvals and records their
384
+ // skip before the storage transaction ends each turn.
385
+ for (const { abort } of live.values()) abort.abort(Object.assign(new Error(reason), { approvalCloseCode: "approval_cancelled_by_stop" }));
386
+ const interrupted = storage.interruptActive(reason);
387
+ live.clear();
388
+ if (interrupted.ok) {
389
+ for (const turn of interrupted.value) ended(turn, interrupted.revision);
390
+ if (lifecycle === "suspending") { lifecycle = "running"; emitSession({ type: "lifecycle", lifecycle, revision: interrupted.revision }); }
391
+ }
392
+ suspension?.settle({ ok: false, error: { code: "stopped", message: "Session was stopped before suspension completed" } });
393
+ suspension = undefined;
394
+ // A channel suspension that had not committed returned to `open`; committed ones are untouched.
395
+ for (const channelId of suspending) {
396
+ const waiter = channelSuspensions.get(channelId);
397
+ channelSuspensions.delete(channelId);
398
+ if (interrupted.ok) emitState(channelId, interrupted.revision);
399
+ waiter?.settle({ ok: false, error: { code: "stopped", message: "Session was stopped before the channel suspension completed" } });
400
+ }
401
+ return status();
402
+ },
403
+ status,
404
+ };
405
+ }
@@ -0,0 +1,45 @@
1
+ import type { ExecuteTurnTool, Message } from "../contracts/loop.ts";
2
+ import type { TurnContext } from "../contracts/context.ts";
3
+
4
+ /** Run a live turn to its next durable resting point: completed, or
5
+ * checkpointed for suspension. Every pass starts at the iteration boundary. */
6
+ export async function runTurn(
7
+ context: TurnContext,
8
+ infer: (signal?: AbortSignal) => Promise<Extract<Message, { role: "assistant" }>>,
9
+ executeTool: ExecuteTurnTool,
10
+ ): Promise<"completed" | "suspended"> {
11
+ const signal = context.signal;
12
+ while (true) {
13
+ // Suspension wins the boundary: checkpoint without taking input or inferring.
14
+ if (context.checkpoint?.()) return "suspended";
15
+ context.drainNotices?.();
16
+ const answer = await infer(signal);
17
+ // A stopped turn is already interrupted; its late answer must not be recorded.
18
+ signal?.throwIfAborted();
19
+ // The injected inference boundary returns only a committed response.
20
+ if (answer.calls.length === 0) {
21
+ if (context.finish?.() ?? true) return "completed";
22
+ continue;
23
+ }
24
+
25
+ for (const call of answer.calls) {
26
+ try {
27
+ const result = await context.dispatchTool(call, executeTool);
28
+ signal?.throwIfAborted();
29
+ // A skip is already paired synchronously by the gate, so interruption
30
+ // cannot end a turn between its approval closure and its result commit.
31
+ if (result.dispatched) {
32
+ context.append({ role: "tool", callId: call.id, content: result.content, ...(result.outcome ? { outcome: result.outcome } : {}) });
33
+ // A dispatched call whose executor reported a typed failure, or whose
34
+ // wait ended at its deadline, still has a paired result: the turn goes on.
35
+ const status = result.outcome?.status === "interrupted" ? "interrupted" : result.outcome?.status === "failed" ? "failed" : "completed";
36
+ context.emit?.({ type: "tool_call", id: call.id, name: call.name, status, output: result.content });
37
+ }
38
+ } catch (error) {
39
+ // A stopped turn has already reported its interruption; stay silent after it.
40
+ if (!signal?.aborted) context.emit?.({ type: "tool_call", id: call.id, name: call.name, status: "failed", output: String(error) });
41
+ throw error;
42
+ }
43
+ }
44
+ }
45
+ }
@@ -0,0 +1,23 @@
1
+ import { tmpdir } from "node:os";
2
+ import { join } from "node:path";
3
+
4
+ export function localConnection() {
5
+ const directory = join(tmpdir(), `native-harness-${process.getuid?.() ?? "local"}`);
6
+ return {
7
+ socketPath: process.env.HARNESS_SOCKET ?? join(directory, "agent.sock"),
8
+ // Custom paths are caller-managed; only the default directory is created.
9
+ managedDirectory: process.env.HARNESS_SOCKET ? undefined : directory,
10
+ };
11
+ }
12
+
13
+ export function agentConfiguration() {
14
+ const apiKey = process.env.OPENROUTER_API_KEY;
15
+ if (!apiKey) throw new Error("Set OPENROUTER_API_KEY before starting the agent.");
16
+ return {
17
+ apiKey,
18
+ model: process.env.OPENROUTER_MODEL ?? "deepseek/deepseek-v4.1-flash",
19
+ inspectorPort: Number(process.env.HARNESS_INSPECTOR_PORT ?? 3000),
20
+ webChatPort: Number(process.env.HARNESS_CHAT_PORT ?? 3001),
21
+ ...localConnection(),
22
+ };
23
+ }
@@ -0,0 +1,2 @@
1
+ /** Runtime entry point for the shared, side-effect-free config validator. */
2
+ export { ConfigError, LEGACY_POLICY, resolveCredential, validateManagedConfig } from "../../util/config.ts";
@@ -0,0 +1,27 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { ConfigError, validateManagedConfig } from "./managed.ts";
5
+ import { parseUniqueJson } from "../../util/json.ts";
6
+ import type { ManagedConfig } from "../../contracts/config-permissions.ts";
7
+
8
+ /** Session IDs name exactly one child; paths supplied by consumers never
9
+ * become path traversal components. The development --db path is separate. */
10
+ export function managedSessionPaths(sessionId: string, home = join(homedir(), ".harness")) {
11
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(sessionId)) throw new ConfigError("sessionId", "expected a plain session ID");
12
+ const directory = join(home, sessionId);
13
+ return { directory, config: join(directory, "config.json"), database: join(directory, "session.sqlite") };
14
+ }
15
+ /** Read once for this open. A present sidecar wins over inline on reopen and
16
+ * an invalid sidecar is never silently replaced by a saved config. */
17
+ export function chooseManagedConfig(options: { mode: "create" | "open"; sidecar: string; inline?: unknown; saved?: unknown }): ManagedConfig {
18
+ const sidecar = () => {
19
+ try { return parseUniqueJson(readFileSync(options.sidecar, "utf8")); }
20
+ catch (error) { throw new ConfigError("config.json", String(error)); }
21
+ };
22
+ const present = existsSync(options.sidecar);
23
+ const raw = options.mode === "create" ? options.inline ?? (present ? sidecar() : undefined)
24
+ : present ? sidecar() : options.inline ?? options.saved;
25
+ if (raw === undefined) throw new ConfigError("config", "supply an inline configuration or config.json; no saved configuration exists");
26
+ return validateManagedConfig(raw, options.mode === "open" && raw === options.saved);
27
+ }
@@ -0,0 +1,42 @@
1
+ import type { ReminderClock } from "../contracts/reminders.ts";
2
+
3
+ export const wallReminderClock: ReminderClock = {
4
+ now: Date.now,
5
+ setTimer(callback, delayMs) {
6
+ const timer = setTimeout(callback, delayMs);
7
+ return () => clearTimeout(timer);
8
+ },
9
+ };
10
+
11
+ /** Keep one live wake. Timer callbacks only ask the owner to check current eligibility. */
12
+ export function createReminderTimer(clock: ReminderClock, wake: () => void) {
13
+ let cancel: (() => void) | undefined;
14
+ let generation = 0;
15
+ let stopped = false;
16
+
17
+ function clear() {
18
+ generation++;
19
+ cancel?.();
20
+ cancel = undefined;
21
+ }
22
+
23
+ return {
24
+ arm(nextDueAt: string | null) {
25
+ clear();
26
+ if (stopped || nextDueAt === null) return;
27
+ const current = generation;
28
+ const due = Date.parse(nextDueAt);
29
+ const rearm = () => {
30
+ const delay = Math.max(0, Math.min(60_000, due - clock.now()));
31
+ cancel = clock.setTimer(() => {
32
+ if (current !== generation) return;
33
+ cancel = undefined;
34
+ if (clock.now() < due) rearm();
35
+ else wake();
36
+ }, delay);
37
+ };
38
+ rearm();
39
+ },
40
+ stop() { stopped = true; clear(); },
41
+ };
42
+ }
@@ -0,0 +1,104 @@
1
+ import { reminderInstant } from "../util/reminder-schedule.ts";
2
+ import type { OneOffReminderChange, ReminderListParams } from "../contracts/reminders.ts";
3
+ import { SESSION_INPUT_MAX_BYTES } from "../contracts/input-limits.ts";
4
+
5
+ export class ReminderShapeError extends Error {}
6
+
7
+ const bad = (field: string): never => { throw new ReminderShapeError(`Invalid reminder ${field}`); };
8
+
9
+ const record = (value: unknown): Record<string, unknown> => {
10
+ if (!value || typeof value !== "object" || Array.isArray(value)) return bad("object");
11
+ return value as Record<string, unknown>;
12
+ };
13
+
14
+ function keys(value: Record<string, unknown>, allowed: readonly string[]) {
15
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) bad(key);
16
+ }
17
+
18
+ function text(value: unknown, field: string): string {
19
+ if (typeof value !== "string" || !value.trim() || Buffer.byteLength(value) > SESSION_INPUT_MAX_BYTES) return bad(field);
20
+ return value;
21
+ }
22
+
23
+ function positive(value: unknown, field: string): number {
24
+ if (!Number.isSafeInteger(value) || (value as number) < 1) return bad(field);
25
+ return value as number;
26
+ }
27
+
28
+ function instant(value: unknown, field: string) {
29
+ const raw = text(value, field), ms = reminderInstant(raw);
30
+ return ms === undefined ? raw : new Date(ms).toISOString();
31
+ }
32
+
33
+ function schedule(value: unknown) {
34
+ const input = record(value);
35
+ keys(input, ["at"]);
36
+ return { at: instant(input.at, "schedule.at") };
37
+ }
38
+
39
+ function grace(value: unknown) {
40
+ if (value === undefined || value === null) return value;
41
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) return bad("expiresAfter");
42
+ return value;
43
+ }
44
+
45
+ function policyNames(value: unknown): string[] {
46
+ if (value === undefined) return [];
47
+ if (!Array.isArray(value) || value.length > 100) return bad("policyNames");
48
+ return [...new Set(value.map(name => text(name, "policyNames")))].sort();
49
+ }
50
+
51
+ /** Validate both batch shape and individual live requests before any mutation. */
52
+ export function parseReminderChange(value: unknown): OneOffReminderChange {
53
+ const input = record(value);
54
+ keys(input, ["reminderId", "changeId", "op", "payload"]);
55
+ const id = { reminderId: text(input.reminderId, "reminderId"), changeId: positive(input.changeId, "changeId") };
56
+ const payload = record(input.payload);
57
+ switch (input.op) {
58
+ case "create": {
59
+ keys(payload, ["channel", "schedule", "text", "acceptedAt", "policyNames", "expiresAfter"]);
60
+ const expiresAfter = grace(payload.expiresAfter);
61
+ return { ...id, op: "create", payload: {
62
+ channel: text(payload.channel, "channel"), schedule: schedule(payload.schedule),
63
+ text: text(payload.text, "text"), acceptedAt: instant(payload.acceptedAt, "acceptedAt"),
64
+ policyNames: policyNames(payload.policyNames), ...(expiresAfter === undefined ? {} : { expiresAfter }),
65
+ } };
66
+ }
67
+ case "update": {
68
+ keys(payload, ["schedule", "acceptedAt", "text", "state", "expiresAfter"]);
69
+ if (!Object.keys(payload).length || (payload.schedule === undefined) !== (payload.acceptedAt === undefined)) return bad("edit");
70
+ const state = payload.state;
71
+ if (state !== undefined && state !== "active" && state !== "paused") return bad("state");
72
+ const expiresAfter = grace(payload.expiresAfter);
73
+ const edit: { text?: string; state?: "active" | "paused"; expiresAfter?: number | null } = {
74
+ ...(payload.text === undefined ? {} : { text: text(payload.text, "text") }),
75
+ ...(state === undefined ? {} : { state }),
76
+ ...(expiresAfter === undefined ? {} : { expiresAfter }),
77
+ };
78
+ return { ...id, op: "update", payload: payload.schedule === undefined ? edit
79
+ : { ...edit, schedule: schedule(payload.schedule), acceptedAt: instant(payload.acceptedAt, "acceptedAt") } };
80
+ }
81
+ case "cancel":
82
+ keys(payload, []);
83
+ return { ...id, op: "cancel", payload: {} };
84
+ default: return bad("operation");
85
+ }
86
+ }
87
+
88
+ export function parseReminderBatch(value: unknown): OneOffReminderChange[] {
89
+ if (value === undefined) return [];
90
+ if (!Array.isArray(value) || value.length > 100) return bad("batch");
91
+ return value.map(parseReminderChange);
92
+ }
93
+
94
+ export function parseReminderList(value: unknown): ReminderListParams {
95
+ const input = record(value);
96
+ keys(input, ["channel", "after", "limit"]);
97
+ const limit = input.limit === undefined ? 50 : positive(input.limit, "limit");
98
+ if (limit > 100) return bad("limit");
99
+ return {
100
+ limit,
101
+ ...(input.channel === undefined ? {} : { channel: text(input.channel, "channel") }),
102
+ ...(input.after === undefined ? {} : { after: text(input.after, "after") }),
103
+ };
104
+ }