@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,119 @@
1
+ import type { ClientTransport, StdioConnection, RpcCallbackCancel, RpcCallbackRequest, RpcResponse, RpcNotification, RpcSessionNotification } from "../../contracts/protocol.ts";
2
+ type Callback = RpcCallbackRequest | RpcCallbackCancel;
3
+ /** Decision 0021: a request or cancellation from the harness. */
4
+ function callback(value: any): value is Callback {
5
+ if (!value || value.jsonrpc !== "2.0" || !value.params || typeof value.params !== "object") return false;
6
+ if (value.method === "functions/cancel") return typeof value.params.invocationId === "string" && typeof value.params.reason === "string";
7
+ if (!Number.isSafeInteger(value.id)) return false;
8
+ if (value.method === "functions/call") return [value.params.invocationId, value.params.sessionId, value.params.channel, value.params.turnId, value.params.tool, value.params.handler].every(field => typeof field === "string")
9
+ && !!value.params.arguments && typeof value.params.arguments === "object";
10
+ return value.method === "results/read" && [value.params.resultId, value.params.invocationId, value.params.channel].every(field => typeof field === "string")
11
+ && Number.isSafeInteger(value.params.offset) && Number.isSafeInteger(value.params.length);
12
+ }
13
+ import { LineDecoder, LineWriter } from "./framing.ts";
14
+
15
+ const strings = (value: unknown) => Array.isArray(value) && value.every((id: unknown) => typeof id === "string");
16
+ function message(value: any): value is RpcResponse | RpcNotification | RpcSessionNotification {
17
+ if (!value || value.jsonrpc !== "2.0") return false;
18
+ if (value.method === "session/event" && value.params?.type === "reminders_due") return Number.isSafeInteger(value.params.revision)
19
+ && value.params.revision >= 0 && (value.params.nextDueAt === null || typeof value.params.nextDueAt === "string");
20
+ if (value.method === "session/event") return value.params?.type === "lifecycle" && Number.isSafeInteger(value.params.revision)
21
+ && ["running", "suspending", "suspended"].includes(value.params.lifecycle);
22
+ if (value.method === "channel/event") {
23
+ if (typeof value.params?.channel !== "string" || !value.params?.event) return false;
24
+ if (value.params.revision !== undefined && !Number.isSafeInteger(value.params.revision)) return false;
25
+ const event = value.params.event;
26
+ if (event.type === "channel_state") return ["open", "suspending", "suspended", "retired"].includes(event.lifecycle)
27
+ && (event.displayName === undefined || typeof event.displayName === "string") && (event.policy === undefined || typeof event.policy === "string");
28
+ if (event.type === "item_withdrawn") return typeof event.item === "string";
29
+ if (event.type === "reminder_changed") return typeof event.reminder?.id === "string" && event.reminder.channel === value.params.channel;
30
+ if (event.type === "reminder_cancelled") return typeof event.reminderId === "string" && ["host", "agent", "channel_retired"].includes(event.by);
31
+ if (event.type === "reminder_fired" || event.type === "reminder_expired") {
32
+ return typeof event.reminderId === "string" && typeof event.occurrenceId === "string" && typeof event.scheduledAt === "string"
33
+ && (event.type === "reminder_fired" ? typeof event.firedAt === "string" && typeof event.noticeId === "string" : typeof event.expiredAt === "string");
34
+ }
35
+ if (typeof event.turnId !== "string") return false;
36
+ switch (event.type) {
37
+ case "turn_started": case "turn_took": return strings(event.items);
38
+ case "items_receipt": return strings(event.items) && ["delivered", "seen"].includes(event.milestone);
39
+ case "turn_suspended": case "turn_resumed": return true;
40
+ case "approval_closed": return typeof event.requestId === "string" && typeof event.reason === "string";
41
+ case "approval_requested": return typeof event.requestId === "string" && typeof event.channel === "string"
42
+ && typeof event.toolCallId === "string" && typeof event.tool === "string" && typeof event.arguments === "string";
43
+ case "turn_ended": return ["completed", "failed", "interrupted"].includes(event.outcome)
44
+ && (event.error === undefined || typeof event.error === "string")
45
+ && (event.uncertainCalls === undefined || strings(event.uncertainCalls));
46
+ case "text_delta": return typeof event.messageId === "string" && typeof event.text === "string";
47
+ case "text_gap": return typeof event.messageId === "string";
48
+ case "text_incomplete": return typeof event.messageId === "string" && ["failed", "incomplete", "output_limit", "timeout", "interrupted"].includes(event.reason);
49
+ case "message_completed": return typeof event.messageId === "string" && (event.reference === true && event.parts === undefined || Array.isArray(event.parts)
50
+ && event.parts.every((part: any) => part?.type === "text" && typeof part.text === "string"));
51
+ case "tool_call": return typeof event.id === "string" && typeof event.name === "string"
52
+ && ["started", "completed", "failed", "skipped", "interrupted"].includes(event.status)
53
+ && (event.invocationId === undefined || typeof event.invocationId === "string")
54
+ && (event.input === undefined || typeof event.input === "string")
55
+ && (event.output === undefined || typeof event.output === "string");
56
+ default: return false;
57
+ }
58
+ }
59
+ if ("method" in value) return false;
60
+ if (value.id !== null && !Number.isSafeInteger(value.id)) return false;
61
+ if ("error" in value) return !("result" in value) && typeof value.error?.code === "number"
62
+ && typeof value.error?.message === "string" && typeof value.error?.data?.code === "string";
63
+ return value.id !== null && "result" in value;
64
+ }
65
+
66
+ export function createStdioTransport(connection: StdioConnection): ClientTransport {
67
+ let closed = false;
68
+ let failure: Error | undefined;
69
+ const listeners = new Set<(value: RpcResponse | RpcNotification) => void>();
70
+ const sessionListeners = new Set<(value: RpcSessionNotification) => void>();
71
+ const closeListeners = new Set<(error?: Error) => void>();
72
+ const callbackListeners = new Set<(value: Callback) => void>();
73
+ const reader = connection.readable.getReader();
74
+ const writer = new LineWriter(connection.write);
75
+ function stop(error?: Error) {
76
+ if (closed) return;
77
+ closed = true; failure = error;
78
+ void reader.cancel().catch(() => {});
79
+ for (const listener of closeListeners) { try { listener(error); } catch { /* Isolate consumers. */ } }
80
+ closeListeners.clear(); listeners.clear(); sessionListeners.clear(); callbackListeners.clear();
81
+ // Close stdin only after queued frames. Process ownership stays with host.
82
+ void writer.flush().catch(() => {}).then(() => connection.end()).catch(() => {});
83
+ }
84
+ const decoder = new LineDecoder();
85
+ void (async () => {
86
+ try {
87
+ while (!closed) {
88
+ const chunk = await reader.read();
89
+ if (chunk.done) { decoder.finish(); stop(new Error("Protocol output closed")); break; }
90
+ for (const line of decoder.push(chunk.value)) {
91
+ const value: unknown = JSON.parse(line);
92
+ // Handlers run in the listener's own tasks: reading never waits for one.
93
+ if (callback(value)) { for (const listener of callbackListeners) { try { listener(structuredClone(value)); } catch { /* Consumer isolation. */ } } continue; }
94
+ if (!message(value)) throw new Error("Invalid protocol message from server");
95
+ // Lifecycle notifications never reach channel/response listeners.
96
+ if ("method" in value && value.method === "session/event") {
97
+ for (const listener of sessionListeners) { try { listener(structuredClone(value)); } catch { /* Consumer isolation. */ } }
98
+ } else for (const listener of listeners) { try { listener(structuredClone(value as RpcResponse | RpcNotification)); } catch { /* Consumer isolation. */ } }
99
+ }
100
+ }
101
+ } catch (error) { stop(new Error(`Protocol connection failed: ${String(error)}`)); }
102
+ finally { reader.releaseLock(); }
103
+ })();
104
+ // Let buffered stdout drain before interpreting a normal exit as EOF.
105
+ void connection.exited?.then(code => { if (code !== 0) stop(new Error(`Harness process exited with code ${code}`)); }, error => stop(new Error(String(error))));
106
+ return {
107
+ send(request) {
108
+ if (closed) throw failure ?? new Error("Transport closed");
109
+ try { void writer.send(request).catch(error => stop(new Error(String(error)))); }
110
+ catch (error) { stop(new Error(String(error))); throw error; }
111
+ },
112
+ subscribe(listener) { if (closed) throw failure ?? new Error("Transport closed"); listeners.add(listener); return () => { listeners.delete(listener); }; },
113
+ subscribeSession(listener) { if (closed) throw failure ?? new Error("Transport closed"); sessionListeners.add(listener); return () => { sessionListeners.delete(listener); }; },
114
+ subscribeCallbacks(listener) { if (closed) throw failure ?? new Error("Transport closed"); callbackListeners.add(listener); return () => { callbackListeners.delete(listener); }; },
115
+ respond(response) { if (closed) return; try { void writer.send(response).catch(error => stop(new Error(String(error)))); } catch (error) { stop(new Error(String(error))); } },
116
+ onClose(listener) { if (closed) listener(failure); else closeListeners.add(listener); return () => { closeListeners.delete(listener); }; },
117
+ close() { stop(); },
118
+ };
119
+ }
@@ -0,0 +1,82 @@
1
+ import { DuplicateJsonField, parseUniqueJson } from "../../util/json.ts";
2
+ import type { ProtocolEndpoint, RpcRequest } from "../../contracts/protocol.ts";
3
+ import { LineDecoder, LineWriter } from "./framing.ts";
4
+ import { LiveQueue } from "./live-queue.ts";
5
+
6
+ /** Serve until EOF. EOF is stop (decision 0013): admission closes, inference
7
+ * and tools are cancelled, active turns are recorded interrupted and pending
8
+ * input stays pending. Nothing is drained; the grace period only bounds the
9
+ * settling of requests already read and the flush of protocol output. */
10
+ export async function serveProtocolStdio(endpoint: ProtocolEndpoint, input: ReadableStream<Uint8Array>, write: (bytes: Uint8Array) => Promise<void>, graceMs = 5000) {
11
+ if (!Number.isFinite(graceMs) || graceMs <= 0) throw new Error("Shutdown grace must be positive");
12
+ const reader = input.getReader();
13
+ const writer = new LineWriter(write);
14
+ const decoder = new LineDecoder();
15
+ const pending = new Set<Promise<void>>();
16
+ let failure: unknown;
17
+ const fail = (error: unknown) => { failure = error; void reader.cancel().catch(() => {}); };
18
+ const queue = new LiveQueue(value => writer.send(value), fail);
19
+ function send(value: unknown) { try { queue.send(value); } catch (error) { fail(error); } }
20
+ // One writer for responses and both notification kinds keeps wire order
21
+ // equal to publication order.
22
+ const unsubscribeChannel = endpoint.subscribe(send), unsubscribeSession = endpoint.subscribeSession?.(send), unsubscribeCallbacks = endpoint.subscribeCallbacks?.(send);
23
+ const unsubscribe = () => { unsubscribeChannel(); unsubscribeSession?.(); unsubscribeCallbacks?.(); };
24
+ let timer: ReturnType<typeof setTimeout> | undefined;
25
+ try {
26
+ while (true) {
27
+ const chunk = await reader.read();
28
+ if (failure) throw failure;
29
+ if (chunk.done) { decoder.finish(); break; }
30
+ for (const line of decoder.push(chunk.value)) {
31
+ if (failure) throw failure;
32
+ let request;
33
+ try { request = parseUniqueJson(line) as RpcRequest; }
34
+ catch (error) {
35
+ if (error instanceof DuplicateJsonField && error.field.startsWith("params.config.")) {
36
+ const envelope = JSON.parse(line) as { id?: unknown };
37
+ const id = Number.isSafeInteger(envelope.id) ? envelope.id as number : null;
38
+ send({ jsonrpc: "2.0", id, error: { code: -32602, message: error.message, data: { code: "invalid_config" } } });
39
+ continue;
40
+ }
41
+ send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Invalid JSON", data: { code: "parse_error" } } });
42
+ continue;
43
+ }
44
+ // Decision 0021: a line without a method that carries a result or an
45
+ // error answers one of our callback requests. It is matched by ID to an
46
+ // open wait; anything else is dropped there.
47
+ const answer = request as unknown as { method?: unknown; id?: unknown; result?: unknown; error?: unknown };
48
+ if (answer && typeof answer === "object" && answer.method === undefined && Number.isSafeInteger(answer.id) && ("result" in answer || "error" in answer)) {
49
+ endpoint.respond?.(answer as never);
50
+ continue;
51
+ }
52
+ // Dispatch concurrently: one slow request must not block other channels.
53
+ const task = endpoint.request(request).then(send, fail);
54
+ pending.add(task);
55
+ void task.finally(() => pending.delete(task));
56
+ }
57
+ }
58
+ const settle = async () => {
59
+ // Requests read before EOF are still dispatched (above), so a stop issued
60
+ // here follows them. Its interruption events go out with the final flush.
61
+ // A server with no session, or without stop, has nothing to interrupt.
62
+ endpoint.disconnect?.();
63
+ await endpoint.request({ jsonrpc: "2.0", id: -1, method: "session/stop", params: {} });
64
+ await Promise.all(pending);
65
+ if (failure) throw failure;
66
+ await queue.flush();
67
+ await writer.flush();
68
+ };
69
+ await Promise.race([settle(), new Promise<never>((_, reject) => {
70
+ timer = setTimeout(() => reject(new Error("Stdio shutdown grace expired before requests settled")), graceMs);
71
+ })]);
72
+ } finally {
73
+ // A failed writer or live queue closes this connection just like EOF: stop
74
+ // the session so in-flight work is fenced before releasing the endpoint.
75
+ if (failure) {
76
+ endpoint.disconnect?.();
77
+ await endpoint.request({ jsonrpc: "2.0", id: -1, method: "session/stop", params: {} }).catch(() => {});
78
+ }
79
+ clearTimeout(timer); endpoint.disconnect?.(); unsubscribe();
80
+ await reader.cancel().catch(() => {}); reader.releaseLock();
81
+ }
82
+ }
@@ -0,0 +1,41 @@
1
+ import type { ChannelOutput } from "../../contracts/output.ts";
2
+
3
+ /** Resolve only after SSE handshake; done rejects if delivery is interrupted. */
4
+ export async function subscribeLocal(socketPath: string, channelId: string, onOutput: (output: ChannelOutput) => void) {
5
+ const abort = new AbortController();
6
+ const response = await fetch(`http://localhost/events?channelId=${encodeURIComponent(channelId)}`, {
7
+ unix: socketPath, signal: abort.signal,
8
+ });
9
+ if (!response.ok || !response.body) throw new Error(`Channel subscription HTTP ${response.status}`);
10
+ const reader = response.body.getReader();
11
+ const decoder = new TextDecoder();
12
+ let buffer = "";
13
+ let ready!: () => void;
14
+ let fail!: (error: unknown) => void;
15
+ let connected = false;
16
+ const handshake = new Promise<void>((resolve, reject) => { ready = resolve; fail = reject; });
17
+ const done = (async () => {
18
+ try {
19
+ while (true) {
20
+ const { done, value } = await reader.read();
21
+ if (done) throw new Error("Channel subscription closed");
22
+ buffer += decoder.decode(value, { stream: true });
23
+ let boundary: number;
24
+ while ((boundary = buffer.indexOf("\n\n")) !== -1) {
25
+ const frame = buffer.slice(0, boundary);
26
+ buffer = buffer.slice(boundary + 2);
27
+ if (frame.startsWith("event: ready\n")) { connected = true; ready(); continue; }
28
+ const data = frame.split("\n").filter(line => line.startsWith("data: ")).map(line => line.slice(6)).join("\n");
29
+ if (data) onOutput(JSON.parse(data) as ChannelOutput);
30
+ }
31
+ }
32
+ } catch (error) {
33
+ if (!connected) fail(error);
34
+ if (!abort.signal.aborted) throw error;
35
+ } finally { reader.releaseLock(); }
36
+ })();
37
+ // Install a handler immediately; callers attach theirs after the handshake.
38
+ void done.catch(() => {});
39
+ try { await handshake; } catch (error) { abort.abort(); throw error; }
40
+ return { done, close() { abort.abort(); } };
41
+ }
@@ -0,0 +1,146 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { appendFileSync, closeSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import type { DurableErrorCode, TransferLimits } from "../../contracts/protocol.ts";
5
+ import { decodeSessionFile, encodeSessionFile } from "../../state/storage/session-file.ts";
6
+
7
+ export const TRANSFER_LIMITS: TransferLimits = { chunkBytes: 524288, maxBytes: 268435456, idleMs: 60000 };
8
+ export class TransferFault extends Error {
9
+ constructor(readonly code: DurableErrorCode, message: string) { super(message); }
10
+ }
11
+ const PREFIX = ".transfer-";
12
+ const sha256 = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
13
+
14
+ /** Hash the complete session-file envelope, including its header. */
15
+ export function encodeArchive(archive: unknown, maxBytes: number) {
16
+ const bytes = encodeSessionFile(archive, maxBytes);
17
+ return { bytes, sha256: sha256(bytes) };
18
+ }
19
+ export function decodeArchive(bytes: Uint8Array, maxBytes = TRANSFER_LIMITS.maxBytes): unknown {
20
+ return decodeSessionFile(bytes, maxBytes);
21
+ }
22
+
23
+ /** Write beside the destination, then publish with a hard link, which refuses
24
+ * an existing file. No partial or replaced archive is ever visible at `path`. */
25
+ export function writeArchiveFile(path: string, bytes: Uint8Array) {
26
+ if (existsSync(path)) throw new TransferFault("already_exists", `A file already exists at ${path}`);
27
+ const draft = `${path}.draft-${randomUUID()}`;
28
+ try {
29
+ writeFileSync(draft, bytes, { flag: "wx" });
30
+ try { linkSync(draft, path); }
31
+ catch (error) {
32
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new TransferFault("already_exists", `A file already exists at ${path}`);
33
+ throw error;
34
+ }
35
+ } finally { rmSync(draft, { force: true }); }
36
+ }
37
+ export function readArchiveFile(path: string, maxBytes: number): Uint8Array {
38
+ let size: number;
39
+ try { size = statSync(path).size; } catch { throw new TransferFault("not_found", `No archive at ${path}`); }
40
+ if (size > maxBytes) {
41
+ const header = Buffer.alloc(14), fd = openSync(path, "r"); let n: number;
42
+ try { n = readSync(fd, header, 0, 14, 0); } finally { closeSync(fd); }
43
+ if (n !== 14 || header.subarray(0, 8).toString() !== "HARNSESS" || header.readUInt16BE(8) !== 1 || size !== 14 + header.readUInt32BE(10))
44
+ throw new TransferFault("invalid_archive", "Invalid session file header or length");
45
+ throw new TransferFault("transfer_limit", `Archive is ${size} bytes; the limit is ${maxBytes}`);
46
+ }
47
+ return readFileSync(path);
48
+ }
49
+
50
+ /** One bounded transfer for one connection, backed by a temporary file so an
51
+ * archive never has to fit a frame or stay in memory between requests. The
52
+ * file is removed when the transfer is closed, consumed, idle too long, or the
53
+ * connection ends; files left by a killed process are removed at startup. */
54
+ export function createTransfers(directory: string, limits: TransferLimits = TRANSFER_LIMITS) {
55
+ mkdirSync(directory, { recursive: true });
56
+ // The directory may be shared with other live servers: remove only files
57
+ // whose owning process no longer exists.
58
+ for (const name of readdirSync(directory)) {
59
+ const pid = Number(/^\.transfer-(\d+)-/.exec(name)?.[1]);
60
+ if (!pid || pid === process.pid) continue;
61
+ // Only "no such process" proves the owner is gone. EPERM means it exists
62
+ // and merely cannot be signalled from here, so its file is left alone.
63
+ try { process.kill(pid, 0); }
64
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") rmSync(join(directory, name), { force: true }); }
65
+ }
66
+ let open: { id: string; path: string; upload: boolean; bytes: number; sha256: string; received: number; timer?: ReturnType<typeof setTimeout> } | undefined;
67
+ function close() {
68
+ if (!open) return;
69
+ // Free the slot first: a failing unlink must not leave the connection
70
+ // unable to open another transfer.
71
+ const { path, timer } = open;
72
+ open = undefined; clearTimeout(timer);
73
+ rmSync(path, { force: true });
74
+ }
75
+ function begin(upload: boolean, bytes: number, digest: string) {
76
+ if (open) throw new TransferFault("transfer_limit", "Only one transfer may be open per connection");
77
+ const id = randomUUID();
78
+ open = { id, path: join(directory, `${PREFIX}${process.pid}-${id}`), upload, bytes, sha256: digest, received: 0 };
79
+ return open;
80
+ }
81
+ function use(id: unknown, upload: boolean) {
82
+ if (!open || open.id !== id || open.upload !== upload) throw new TransferFault("not_found", "Unknown transfer");
83
+ clearTimeout(open.timer);
84
+ open.timer = setTimeout(close, limits.idleMs);
85
+ return open;
86
+ }
87
+ return {
88
+ limits,
89
+ /** Announce an upload of `bytes` bytes with the given SHA-256. */
90
+ openUpload(bytes: unknown, digest: unknown) {
91
+ if (!Number.isSafeInteger(bytes) || (bytes as number) < 1 || typeof digest !== "string" || !/^[0-9a-f]{64}$/.test(digest))
92
+ throw new TransferFault("invalid_archive", "Expected a positive byte length and a lowercase hex SHA-256");
93
+ if ((bytes as number) > limits.maxBytes) throw new TransferFault("transfer_limit", `Archive is ${bytes} bytes; the limit is ${limits.maxBytes}`);
94
+ const transfer = begin(true, bytes as number, digest);
95
+ // The slot is taken: if its file cannot be created, free it again.
96
+ try { writeFileSync(transfer.path, new Uint8Array(0), { flag: "wx" }); }
97
+ catch (error) { close(); throw error; }
98
+ return use(transfer.id, true).id;
99
+ },
100
+ write(id: unknown, offset: unknown, data: unknown) {
101
+ const transfer = use(id, true);
102
+ if (typeof data !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(data)) throw new TransferFault("transfer_limit", "Chunk must be base64");
103
+ const chunk = Buffer.from(data, "base64");
104
+ // Sequential, bounded and never past the announced length; a refused chunk writes nothing.
105
+ if (offset !== transfer.received || !chunk.length || chunk.length > limits.chunkBytes || transfer.received + chunk.length > transfer.bytes)
106
+ throw new TransferFault("transfer_limit", `Expected at most ${limits.chunkBytes} bytes at offset ${transfer.received} of ${transfer.bytes}`);
107
+ // A failed append may have written part of the chunk, so this offset can
108
+ // no longer be retried safely: the transfer ends and its file is removed.
109
+ try { appendFileSync(transfer.path, chunk); }
110
+ catch (error) { close(); throw error; }
111
+ transfer.received += chunk.length;
112
+ return transfer.received;
113
+ },
114
+ /** Take a finished upload. The transfer ends here whether or not the bytes are usable. */
115
+ consume(id: unknown): Uint8Array {
116
+ const transfer = use(id, true);
117
+ try {
118
+ if (transfer.received !== transfer.bytes) throw new TransferFault("invalid_archive", `Upload has ${transfer.received} of ${transfer.bytes} bytes`);
119
+ const bytes = readFileSync(transfer.path);
120
+ if (sha256(bytes) !== transfer.sha256) throw new TransferFault("invalid_archive", "Uploaded bytes do not match the announced SHA-256");
121
+ return bytes;
122
+ } finally { close(); }
123
+ },
124
+ /** Offer bytes for download; nothing is written if another transfer is open. */
125
+ offer(bytes: Uint8Array, digest: string) {
126
+ const transfer = begin(false, bytes.length, digest);
127
+ try { writeFileSync(transfer.path, bytes, { flag: "wx" }); }
128
+ catch (error) { close(); throw error; }
129
+ return use(transfer.id, false).id;
130
+ },
131
+ read(id: unknown, offset: unknown) {
132
+ const transfer = use(id, false);
133
+ if (!Number.isSafeInteger(offset) || (offset as number) < 0 || (offset as number) > transfer.bytes) throw new TransferFault("transfer_limit", "Offset is outside the transfer");
134
+ const chunk = Buffer.alloc(Math.min(limits.chunkBytes, transfer.bytes - (offset as number)));
135
+ let count: number;
136
+ try {
137
+ const file = openSync(transfer.path, "r");
138
+ try { count = readSync(file, chunk, 0, chunk.length, offset as number); } finally { closeSync(file); }
139
+ } catch (error) { close(); throw error; }
140
+ // Send only what was read; the end is the announced length, not a short read.
141
+ return { data: chunk.subarray(0, count).toString("base64"), eof: (offset as number) + count >= transfer.bytes };
142
+ },
143
+ close(id: unknown) { if (!open || open.id !== id) throw new TransferFault("not_found", "Unknown transfer"); close(); },
144
+ dispose: close,
145
+ };
146
+ }
@@ -0,0 +1,94 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <meta charset="utf-8">
4
+ <meta name="viewport" content="width=device-width,initial-scale=1,interactive-widget=resizes-content">
5
+ <title>Harness chat</title>
6
+ <style>
7
+ :root { color-scheme: dark; font: 16px system-ui; background: #11151d; color: #edf1fa; }
8
+ * { box-sizing: border-box; } body { margin: 0; }
9
+ .app { max-width: 800px; margin: auto; height: 100dvh; display: flex; flex-direction: column; }
10
+ header { padding: 20px; border-bottom: 1px solid #30394b; } h1 { font-size: 20px; margin: 0 0 6px; }
11
+ #status { font-size: 13px; color: #a3b4d1; } form { display: flex; gap: 8px; }
12
+ #connect { margin-top: 16px; flex-wrap: wrap; align-items: end; }
13
+ label { font-size: 12px; color: #a3b4d1; flex: 1; min-width: 120px; }
14
+ input, textarea, button { font: inherit; padding: 10px 12px; border: 1px solid #3a4962; border-radius: 9px; }
15
+ input, textarea { color: inherit; background: #1b2230; width: 100%; } input { margin-top: 5px; }
16
+ button { background: #365f9e; color: white; cursor: pointer; } button:disabled { opacity: .45; cursor: default; }
17
+ #messages { flex: 1; overflow-y: auto; padding: 20px; } .message { margin-bottom: 16px; padding: 14px; border-radius: 12px; background: #1d2737; }
18
+ .message.you { background: #253c5b; margin-left: 30px; } .message.error { border: 1px solid #c76464; }
19
+ .message small { display: block; color: #a3b4d1; margin-bottom: 7px; }
20
+ .message div { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.6; }
21
+ #compose { padding: 12px 16px calc(12px + env(safe-area-inset-bottom)); border-top: 1px solid #30394b; }
22
+ textarea { resize: none; min-height: 48px; max-height: 180px; flex: 1; }
23
+ #waiting { min-height: 20px; color: #a3b4d1; font-size: 13px; padding: 0 20px; }
24
+ .spin { display: inline-block; width: 11px; height: 11px; border: 2px solid #4c6384; border-top-color: #a4c5ff; border-radius: 50%; animation: spin .8s linear infinite; margin-right: 7px; }
25
+ @keyframes spin { to { transform: rotate(360deg); } }
26
+ @media(prefers-reduced-motion:reduce) { .spin { animation:none; } }
27
+ </style>
28
+ <div class="app">
29
+ <header><h1>Harness chat</h1><div id="status" role="status">Choose a channel and participant.</div>
30
+ <form id="connect">
31
+ <label>Channel<input id="channel" value="channel1" required autocomplete="off"></label>
32
+ <label>Your name<input id="participant" value="alice" required autocomplete="nickname"></label>
33
+ <button>Connect</button>
34
+ </form>
35
+ </header>
36
+ <main id="messages" role="log" aria-live="polite"></main>
37
+ <div id="waiting" role="status"></div>
38
+ <form id="compose"><textarea id="text" rows="2" placeholder="Message the agent…" aria-label="Message" disabled></textarea><button id="send" disabled>Send</button></form>
39
+ </div>
40
+ <script>
41
+ const $ = id => document.getElementById(id);
42
+ const token = new URL(location.href).searchParams.get('token') || sessionStorage.getItem('harness-token') || '';
43
+ if (token) sessionStorage.setItem('harness-token', token);
44
+ history.replaceState(null, '', location.pathname);
45
+ let source, channelId, participantId, connected = false, pending = 0, generation = 0;
46
+ function status(text) { $('status').textContent = text; }
47
+ function waiting() {
48
+ $('waiting').replaceChildren();
49
+ if (pending) { const spin = document.createElement('span'); spin.className = 'spin'; $('waiting').append(spin, 'Waiting for reply…'); }
50
+ }
51
+ function add(label, text, type = '') {
52
+ const card = document.createElement('article'); card.className = 'message ' + type;
53
+ const name = document.createElement('small'); name.textContent = label;
54
+ const content = document.createElement('div'); content.textContent = text;
55
+ card.append(name, content); $('messages').append(card); $('messages').scrollTop = $('messages').scrollHeight;
56
+ }
57
+ $('connect').onsubmit = event => {
58
+ event.preventDefault(); source?.close(); generation++; pending = 0; waiting();
59
+ channelId = $('channel').value.trim(); participantId = $('participant').value.trim();
60
+ if (!channelId || !participantId) return;
61
+ connected = false; $('send').disabled = $('text').disabled = true; $('messages').replaceChildren();
62
+ status('Connecting…');
63
+ source = new EventSource('/events?channelId=' + encodeURIComponent(channelId) + '&token=' + encodeURIComponent(token));
64
+ source.addEventListener('ready', () => {
65
+ connected = true; $('send').disabled = $('text').disabled = false;
66
+ status('Connected · ' + channelId + ' · ' + participantId);
67
+ });
68
+ source.onmessage = event => { const output = JSON.parse(event.data); add('Agent', output.text, output.type === 'error' ? 'error' : ''); };
69
+ source.onerror = () => {
70
+ connected = false; $('send').disabled = $('text').disabled = true;
71
+ source.close(); status('Connection lost. Use the startup pairing link and press Connect to reconnect.');
72
+ };
73
+ };
74
+ const inputMaxBytes = __SESSION_INPUT_MAX_BYTES__;
75
+ $('compose').onsubmit = async event => {
76
+ event.preventDefault(); const text = $('text').value.trim();
77
+ if (!connected || !text) return;
78
+ if (new TextEncoder().encode(text).length > inputMaxBytes) {
79
+ add('Error', 'Input exceeds the ' + inputMaxBytes + '-byte UTF-8 limit', 'error');
80
+ return;
81
+ }
82
+ const submittedGeneration = generation;
83
+ add(participantId, text, 'you'); $('text').value = ''; pending++; waiting();
84
+ try {
85
+ const response = await fetch('/messages', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token }, body: JSON.stringify({channelId, participantId, text}) });
86
+ if (!response.ok) throw new Error((await response.json().catch(() => null))?.error || 'Request failed (' + response.status + ')');
87
+ // The answer arrives on SSE; printing this HTTP response would duplicate it.
88
+ } catch (error) { if (generation === submittedGeneration) add('Error', String(error), 'error'); }
89
+ finally { if (generation === submittedGeneration) { pending--; waiting(); } }
90
+ };
91
+ $('text').onkeydown = event => { if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); $('compose').requestSubmit(); } };
92
+ if (!token) status('Open the pairing link printed by bun run start.');
93
+ </script>
94
+ </html>
@@ -0,0 +1,34 @@
1
+ import { SESSION_INPUT_MAX_BYTES } from "../../contracts/input-limits.ts";
2
+ import { networkInterfaces } from "node:os";
3
+
4
+ /** Separate LAN surface; the inspector remains bound to loopback. */
5
+ export function serveWebChat(handleChannel: (request: Request) => Promise<Response>, port = 3001, token: string = crypto.randomUUID()) {
6
+ const page = Bun.file(new URL("./index.html", import.meta.url)).text().then(
7
+ html => html.replace("__SESSION_INPUT_MAX_BYTES__", String(SESSION_INPUT_MAX_BYTES)),
8
+ );
9
+ const server = Bun.serve({
10
+ hostname: "0.0.0.0", port, development: false, idleTimeout: 0,
11
+ async fetch(request) {
12
+ const url = new URL(request.url);
13
+ if (url.pathname === "/" && request.method === "GET") {
14
+ return new Response(await page, { headers: {
15
+ "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Referrer-Policy": "no-referrer",
16
+ } });
17
+ }
18
+ if (url.pathname !== "/messages" && url.pathname !== "/events") return new Response("Not found", { status: 404 });
19
+ const supplied = request.headers.get("authorization")?.replace(/^Bearer /, "") ?? url.searchParams.get("token");
20
+ if (supplied !== token) return new Response("Open the pairing link printed by the agent", { status: 401 });
21
+ const origin = request.headers.get("origin");
22
+ if (origin && origin !== url.origin) return new Response("Invalid origin", { status: 403 });
23
+ return handleChannel(request);
24
+ },
25
+ });
26
+ const hosts = new Set(["127.0.0.1"]);
27
+ for (const addresses of Object.values(networkInterfaces())) {
28
+ for (const address of addresses ?? []) if (!address.internal && address.family === "IPv4") hosts.add(address.address);
29
+ }
30
+ return {
31
+ server,
32
+ urls: [...hosts].map(host => `http://${host}:${server.port}/?token=${encodeURIComponent(token)}`),
33
+ };
34
+ }