@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,225 @@
1
+ import type { ConditionalStopParams, ConditionalStopResult, ReminderSessionEvent } from "../contracts/reminders.ts";
2
+ import type { ClientTransport, Methods, DurableMethods, InitializeParams, CreateParams, PushParams } from "../contracts/protocol.ts";
3
+ import type { EventSink, SessionEventSink } from "../contracts/events.ts";
4
+ import { createHash } from "node:crypto";
5
+ import type { FunctionCall, FunctionResult, ResultPage, ResultRead } from "../contracts/tools.ts";
6
+ import { MAX_FRAME_BYTES } from "./protocol/framing.ts";
7
+
8
+ /** A typed failure a function handler reports to the model (decision 0021). */
9
+ export class FunctionError extends Error {
10
+ constructor(public readonly code: string, message: string) { super(message); this.name = "FunctionError"; }
11
+ }
12
+ /** Runs one authorized call. `signal` aborts when the harness stops waiting
13
+ * (deadline, interrupt, stop): the answer is then ignored. Throw
14
+ * `FunctionError` for a typed failure. Return `{ preview, reference }` for a
15
+ * result the handler stored itself. */
16
+ export type FunctionHandler = (call: FunctionCall, signal: AbortSignal) => Promise<FunctionResult> | FunctionResult;
17
+ export type ResultReader = (read: ResultRead) => Promise<ResultPage> | ResultPage;
18
+
19
+ type Calls = Methods & DurableMethods;
20
+
21
+ export class HarnessClientError extends Error {
22
+ constructor(public readonly code: string, message: string) { super(message); this.name = "HarnessClientError"; }
23
+ }
24
+
25
+ /**
26
+ * Typed host API. A `cancelled` error from `request()` or `modelCalls()` means
27
+ * the caller stopped waiting. The harness may already have applied the request.
28
+ * Aborting sends no cancellation frame.
29
+ */
30
+ export class HarnessClient {
31
+ private nextId = 0;
32
+ private closed = false;
33
+ private terminalError = new HarnessClientError("closed", "Client closed");
34
+ private unsubscribeClose = () => {};
35
+ private readonly listeners = new Set<EventSink>();
36
+ private readonly sessionListeners = new Set<SessionEventSink>();
37
+ private readonly wakeListeners = new Set<(event: ReminderSessionEvent) => void>();
38
+ private unsubscribeSession = () => {};
39
+ private readonly waiting = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
40
+ private readonly unsubscribe: () => void;
41
+ private unsubscribeCallbacks = () => {};
42
+ private functionHandler: FunctionHandler | undefined;
43
+ private resultReader: ResultReader | undefined;
44
+ /** Calls being handled, by invocation ID, so a cancellation reaches the right one. */
45
+ private readonly running = new Map<string, AbortController>();
46
+ constructor(private readonly transport: ClientTransport, private readonly timeoutMs = 30000) {
47
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Request timeout must be positive");
48
+ this.unsubscribe = transport.subscribe(message => {
49
+ if ("method" in message) {
50
+ for (const listener of this.listeners) { try { listener(structuredClone(message.params)); } catch { /* Consumer isolation. */ } }
51
+ } else {
52
+ if (message.id === null) return;
53
+ const waiting = this.waiting.get(message.id);
54
+ if (!waiting) return;
55
+ if ("error" in message) waiting.reject(new HarnessClientError(message.error.data.code, message.error.message));
56
+ else waiting.resolve(message.result);
57
+ }
58
+ });
59
+ this.unsubscribeSession = transport.subscribeSession?.(message => {
60
+ const event = message.params;
61
+ if (event.type === "reminders_due") {
62
+ for (const listener of this.wakeListeners) { try { listener(structuredClone(event)); } catch { /* Consumer isolation. */ } }
63
+ return;
64
+ }
65
+ for (const listener of this.sessionListeners) { try { listener(structuredClone(event)); } catch { /* Consumer isolation. */ } }
66
+ }) ?? (() => {});
67
+ this.unsubscribeCallbacks = transport.subscribeCallbacks?.(message => {
68
+ if (message.method === "functions/cancel") { this.running.get(message.params.invocationId)?.abort(new Error(message.params.reason)); return; }
69
+ const answer = (work: () => Promise<unknown>, signal?: AbortSignal) => {
70
+ // Each handler runs in its own task. The answer carries the request's
71
+ // ID, so concurrent calls cannot be mixed up. Nothing is sent for a
72
+ // call the harness already cancelled.
73
+ void (async () => work())().then(result => {
74
+ if (signal?.aborted) return;
75
+ if (new TextEncoder().encode(JSON.stringify(result ?? null)).length > MAX_FRAME_BYTES - 1024) throw new FunctionError("result_too_large", "The result does not fit one protocol frame; store it and return a reference");
76
+ transport.respond?.({ jsonrpc: "2.0", id: message.id, result });
77
+ }).catch(error => {
78
+ if (signal?.aborted) return;
79
+ const code = typeof (error as { code?: unknown })?.code === "string" && (error as { code: string }).code ? (error as { code: string }).code : "handler_failed";
80
+ try { transport.respond?.({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: error instanceof Error ? error.message : String(error), data: { code } } }); } catch { /* Connection closed. */ }
81
+ });
82
+ };
83
+ if (message.method === "results/read") {
84
+ const reader = this.resultReader;
85
+ answer(async () => { if (!reader) throw new FunctionError("result_unavailable", "This host stores no results"); return reader(message.params); });
86
+ return;
87
+ }
88
+ const names = message.params.policyNames;
89
+ if (!Array.isArray(names) || names.some(name => typeof name !== "string" || !name.trim() || name === "__legacy_allow")
90
+ || new Set(names).size !== names.length) {
91
+ answer(async () => { throw new FunctionError("invalid_params", "Expected unique configured policy names"); });
92
+ return;
93
+ }
94
+ const handler = this.functionHandler, control = new AbortController(), id = message.params.invocationId;
95
+ this.running.set(id, control);
96
+ answer(async () => {
97
+ try { if (!handler) throw new FunctionError("handler_missing", "This host serves no functions"); return await handler(message.params, control.signal); }
98
+ finally { if (this.running.get(id) === control) this.running.delete(id); }
99
+ }, control.signal);
100
+ }) ?? (() => {});
101
+ this.unsubscribeClose = transport.onClose(error => {
102
+ if (this.closed) return;
103
+ this.terminalError = new HarnessClientError("transport_closed", error?.message ?? "Transport closed");
104
+ this.close();
105
+ });
106
+ }
107
+ request<K extends keyof Calls>(method: K, params: Calls[K]["params"], signal?: AbortSignal): Promise<Calls[K]["result"]> {
108
+ if (this.closed) return Promise.reject(this.terminalError);
109
+ const cancelled = () => new HarnessClientError("cancelled", `Request cancelled: ${method}`);
110
+ if (signal?.aborted) return Promise.reject(cancelled());
111
+ const id = ++this.nextId;
112
+ return new Promise((resolve, reject) => {
113
+ const finish = () => {
114
+ if (!this.waiting.delete(id)) return false;
115
+ clearTimeout(timer);
116
+ signal?.removeEventListener("abort", abort);
117
+ return true;
118
+ };
119
+ const fail = (error: unknown) => { if (finish()) reject(error); };
120
+ const abort = () => fail(cancelled());
121
+ const timer = setTimeout(() => fail(new HarnessClientError("timeout", `Request timed out: ${method}`)), this.timeoutMs);
122
+ this.waiting.set(id, { reject: fail, resolve: value => { if (finish()) resolve(value as Calls[K]["result"]); } });
123
+ signal?.addEventListener("abort", abort, { once: true });
124
+ try { this.transport.send({ jsonrpc: "2.0", id, method, params }); }
125
+ catch (error) { fail(error); }
126
+ });
127
+ }
128
+ initialize(params: InitializeParams = { protocolVersion: 1, host: { name: "harness-client", version: "0" }, callbacks: [], subscription: { text: "final", tools: "full" } }) {
129
+ return this.request("initialize", params);
130
+ }
131
+ createSession(params: CreateParams) { return this.request("session/create", params); }
132
+ /** Decision 0021. Serve `functions/call` requests. Set before `initialize`
133
+ * advertises handler names. One handler routes by `call.handler`. */
134
+ serveFunctions(handler: FunctionHandler, reader?: ResultReader) { this.functionHandler = handler; this.resultReader = reader; }
135
+ tools() { return this.request("session/tools", {}); }
136
+ revokeTool(name: string) { return this.request("tool/revoke", { name }); }
137
+ restoreTool(name: string) { return this.request("tool/restore", { name }); }
138
+ enableTool(name: string) { return this.request("tool/enable", { name }); }
139
+ removeTool(name: string) { return this.request("tool/remove", { name }); }
140
+ toolInvocation(invocationId: string) { return this.request("session/tool-invocation", { invocationId }); }
141
+ toolInvocations(turn: string) { return this.request("session/tool-invocations", { turn }); }
142
+ validateConfig(config: unknown) { return this.request("config/validate", { config }); }
143
+ respondApproval(requestId: string, decision: "allow_once" | "deny") { return this.request("approval/respond", { requestId, decision }); }
144
+ /** Open an existing session. The returned view precedes every live event
145
+ * for work the session recovers; callers reconcile their own records with it. */
146
+ openSession(params: Calls["session/open"]["params"]) { return this.request("session/open", params); }
147
+ observeChannel(params: Calls["channel/observe"]["params"]) { return this.request("channel/observe", params); }
148
+ reconcileChannel(params: Calls["channel/reconcile"]["params"]) { return this.request("channel/reconcile", params); }
149
+ channelMessages(params: Calls["channel/messages"]["params"]) { return this.request("channel/messages", params); }
150
+ timeline(params: Calls["session/timeline"]["params"] = {}) { return this.request("session/timeline", params); }
151
+ notify(params: Calls["channel/notify"]["params"]) { return this.request("channel/notify", params); }
152
+ status() { return this.request("session/status", {}); }
153
+ modelCalls(params: Calls["session/model-calls"]["params"] = {}, signal?: AbortSignal) { return this.request("session/model-calls", params, signal); }
154
+ readMessage(params: Calls["session/message/read"]["params"]) { return this.request("session/message/read", params); }
155
+ /** Resolves once the session is cleanly suspended: active iterations have
156
+ * finished and every unfinished turn is checkpointed. May take as long as a
157
+ * running tool; pass a longer client timeout for long tools. */
158
+ suspend() { return this.request("session/suspend", {}); }
159
+ /** Explicit: a loaded suspended session runs nothing until this is called. */
160
+ resume() { return this.request("session/resume", {}); }
161
+ /** Immediate: cancels inference and tools and reports active turns interrupted. */
162
+ changeReminder(params: Calls["reminder/change"]["params"]) { return this.request("reminder/change", params); }
163
+ getReminder(params: Calls["reminder/get"]["params"]) { return this.request("reminder/get", params); }
164
+ listReminders(params: Calls["reminder/list"]["params"] = {}) { return this.request("reminder/list", params); }
165
+ stopIfIdle(params: ConditionalStopParams = { ifIdle: true }): Promise<ConditionalStopResult> {
166
+ return this.request("session/stop", params as unknown as Calls["session/stop"]["params"]) as unknown as Promise<ConditionalStopResult>;
167
+ }
168
+ onReminderWake(listener: (event: ReminderSessionEvent) => void) {
169
+ this.wakeListeners.add(listener);
170
+ return () => { this.wakeListeners.delete(listener); };
171
+ }
172
+ stop() { return this.request("session/stop", {}); }
173
+ /** Write the session's archive to a path the harness can reach. */
174
+ exportTo(path: string) { return this.request("session/export", { to: { type: "path", path } }); }
175
+ /** Import an archive file the harness can reach, as a new session. */
176
+ importFrom(path: string, sessionId?: string) { return this.request("session/import", { from: { type: "path", path }, ...(sessionId === undefined ? {} : { sessionId }) }); }
177
+ /** Fetch the archive bytes over the connection in bounded chunks. The bytes
178
+ * are checked against the length and SHA-256 the harness reported. */
179
+ async exportArchive(): Promise<Uint8Array> {
180
+ const { bytes, sha256, transferId } = await this.request("session/export", { to: { type: "transfer" } });
181
+ const archive = new Uint8Array(bytes);
182
+ try {
183
+ for (let offset = 0, eof = bytes === 0; !eof;) {
184
+ const chunk = await this.request("transfer/read", { transferId: transferId!, offset });
185
+ const part = Buffer.from(chunk.data, "base64");
186
+ // No progress and no end means the bytes are not there: fail rather
187
+ // than ask for the same offset forever.
188
+ if ((!part.length && !chunk.eof) || offset + part.length > bytes) throw new HarnessClientError("invalid_archive", `Archive transfer ended at ${offset} of ${bytes} bytes`);
189
+ archive.set(part, offset); offset += part.length; eof = chunk.eof;
190
+ }
191
+ } finally { await this.request("transfer/close", { transferId: transferId! }).catch(() => {}); }
192
+ if (createHash("sha256").update(archive).digest("hex") !== sha256) throw new HarnessClientError("invalid_archive", "Received archive does not match its SHA-256");
193
+ return archive;
194
+ }
195
+ /** Send archive bytes over the connection in bounded chunks, then import them as a new session. */
196
+ async importArchive(archive: Uint8Array, sessionId?: string) {
197
+ const { transferId, limits } = await this.request("transfer/open", { bytes: archive.length, sha256: createHash("sha256").update(archive).digest("hex") });
198
+ try {
199
+ for (let offset = 0; offset < archive.length; offset += limits.chunkBytes)
200
+ await this.request("transfer/write", { transferId, offset, data: Buffer.from(archive.subarray(offset, offset + limits.chunkBytes)).toString("base64") });
201
+ } catch (error) { await this.request("transfer/close", { transferId }).catch(() => {}); throw error; }
202
+ return this.request("session/import", { from: { type: "transfer", transferId }, ...(sessionId === undefined ? {} : { sessionId }) });
203
+ }
204
+ /** Resolves when the input is accepted (Received), never with a reply. Follow
205
+ * `turn_started`/`turn_took` for the item ID to find the turn that took it. */
206
+ push(params: PushParams) { return this.request("channel/push", params); }
207
+ createChannel(params: Calls["channel/create"]["params"]) { return this.request("channel/create", params); }
208
+ editChannel(params: Calls["channel/edit"]["params"]) { return this.request("channel/edit", params); }
209
+ suspendChannel(params: Calls["channel/suspend"]["params"]) { return this.request("channel/suspend", params); }
210
+ resumeChannel(params: Calls["channel/resume"]["params"]) { return this.request("channel/resume", params); }
211
+ deleteChannel(params: Calls["channel/delete"]["params"]) { return this.request("channel/delete", params); }
212
+ withdrawItem(params: Calls["channel/withdraw"]["params"]) { return this.request("channel/withdraw", params); }
213
+ interruptTurn(params: Calls["channel/interrupt"]["params"]) { return this.request("channel/interrupt", params); }
214
+ idle() { return this.request("session/idle", {}); }
215
+ onChannelEvent(listener: EventSink) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
216
+ onSessionEvent(listener: SessionEventSink) { this.sessionListeners.add(listener); return () => { this.sessionListeners.delete(listener); }; }
217
+ close() {
218
+ if (this.closed) return;
219
+ this.closed = true; this.unsubscribe(); this.unsubscribeSession(); this.unsubscribeCallbacks(); this.unsubscribeClose(); this.transport.close();
220
+ // The harness no longer waits for anything this connection was handling.
221
+ for (const control of this.running.values()) control.abort(this.terminalError);
222
+ this.running.clear(); this.listeners.clear(); this.sessionListeners.clear(); this.wakeListeners.clear();
223
+ for (const pending of this.waiting.values()) pending.reject(this.terminalError);
224
+ }
225
+ }
@@ -0,0 +1,283 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <meta charset="utf-8">
4
+ <meta name="viewport" content="width=device-width,initial-scale=1">
5
+ <title>Harness context inspector</title>
6
+ <style>
7
+ :root { color-scheme: light dark; font: 15px system-ui; }
8
+ body { margin: 0; background: light-dark(#f7f8fa,#15171b); }
9
+ header { padding: 18px 24px; border-bottom: 1px solid #8885; display: flex; gap: 24px; align-items: baseline; }
10
+ h1 { font-size: 19px; margin: 0; } h2 { font-size: 18px; }
11
+ #connection, .muted { color: light-dark(#586174,#aab3c3); }
12
+ .layout { display: grid; grid-template-columns: 230px minmax(0,1fr); min-height: 85vh; }
13
+ nav { padding: 16px; border-right: 1px solid #8885; }
14
+ button { display: block; width: 100%; text-align: left; padding: 12px; margin-bottom: 8px; border: 1px solid #8885; border-radius: 7px; cursor: pointer; overflow-wrap: anywhere; }
15
+ button[aria-current=true] { border-color: #888a; font-weight: 600; background: light-dark(#e5edff,#253352); }
16
+ #channels button.working { border-color: #548deb; box-shadow: 0 0 5px #548deb33; animation: working-glow 2s ease-in-out infinite alternate; }
17
+ #channels button.working::before { content: ''; display: inline-block; width: 7px; height: 7px; margin-right: 8px; border-radius: 50%; background: #548deb; box-shadow: 0 0 6px #548deb; }
18
+ @keyframes working-glow { to { box-shadow: 0 0 9px #548deb55; } }
19
+ @media(prefers-reduced-motion: reduce) { #channels button.working { animation: none; } }
20
+ .tabs { display: flex; gap: 8px; padding: 12px 24px; border-bottom: 1px solid #8885; }
21
+ .tabs button { width: auto; margin: 0; }
22
+ .tabs button[aria-selected=true] { border-color: #688def; background: light-dark(#e5edff,#253352); }
23
+ .layout.single { grid-template-columns: minmax(0,1fr); }
24
+ .layout.single nav { display: none; }
25
+ main { padding: 12px 24px 40px; min-width: 0; }
26
+ article, details.request { border: 1px solid #8885; border-radius: 8px; margin: 12px 0; padding: 14px; background: light-dark(white,#1d2026); }
27
+ article.context-card { border: 2px solid #df8a27; }
28
+ article.result-card { border: 2px solid #548deb; }
29
+ .prompt-highlight { color: light-dark(#934100,#ffc078); background: light-dark(#fff0dc,#593615); border-radius: 3px; }
30
+ .notice-highlight { color: light-dark(#6d28a1,#ddb4ff); background: light-dark(#f2e6ff,#43205e); border-radius: 3px; }
31
+ .turn-divider { display: flex; gap: 16px; align-items: center; margin: 32px 0 16px; }
32
+ .turn-divider::before, .turn-divider::after { content: ''; flex: 1; border-top: 1px solid #8888; }
33
+ .iteration { margin-bottom: 28px; }
34
+ pre { white-space: pre-wrap; overflow-wrap: anywhere; font: 13px/1.6 ui-monospace,monospace; }
35
+ summary { cursor: pointer; } .error { color: light-dark(#ac2525,#ff9999); }
36
+ .context-text { border: 1px solid #8885; border-radius: 8px; padding: 20px; min-height: 60vh; background: light-dark(white,#1d2026); }
37
+ @media(max-width:650px) { .layout { grid-template-columns: 1fr; } nav { border-right: 0; } }
38
+ </style>
39
+ <header><h1>Harness context inspector</h1><span id="connection">Connecting…</span></header>
40
+ <div class="tabs" role="tablist" aria-label="Inspector views">
41
+ <button id="tab-live" role="tab" aria-controls="content" aria-selected="true" data-tab="live">Live context</button>
42
+ <button id="tab-timeline" role="tab" aria-controls="content" aria-selected="false" data-tab="timeline">Timeline</button>
43
+ <button id="tab-channels" role="tab" aria-controls="content" aria-selected="false" data-tab="channels">Channels</button>
44
+ </div>
45
+ <div class="layout single"><nav id="channels"></nav><main id="content" role="tabpanel" aria-labelledby="tab-live">Connecting to the agent…</main></div>
46
+ <script>
47
+ let channels = [], selected = null, tab = "live";
48
+ let liveContext = { systemPrompt: "", tools: [], entries: [] };
49
+ let connectionStatus = 'connecting';
50
+ let session = null, channelDetails = null, callDetails = null, timeline = [], nextPosition, paging = false;
51
+ let refreshTimer, refreshing = false, dirty = false, viewVersion = 0, olderLoaded = false, fetchError = '';
52
+ const endpoint = async path => {
53
+ const response = await fetch(path, {cache: 'no-store'});
54
+ if (!response.ok) throw new Error(await response.text());
55
+ return response.json();
56
+ };
57
+ function mergeTimeline(entries) {
58
+ const rows = new Map(timeline.map(entry => [entry.seq, entry]));
59
+ for (const entry of entries) rows.set(entry.seq, entry);
60
+ timeline = [...rows.values()].sort((a, b) => b.seq - a.seq);
61
+ }
62
+ function invalidate() {
63
+ dirty = true;
64
+ if (!document.hidden && !refreshing && !refreshTimer)
65
+ refreshTimer = setTimeout(() => { refreshTimer = undefined; void refresh(); }, 60);
66
+ }
67
+ async function refresh() {
68
+ if (document.hidden || refreshing || !dirty) return;
69
+ dirty = false; refreshing = true;
70
+ const version = viewVersion, currentTab = tab;
71
+ try {
72
+ const status = await endpoint('/state');
73
+ if (version !== viewVersion) return;
74
+ channels = status.channels; session = status.session;
75
+ if (currentTab === 'channels' && !channels.some(channel => channel.id === selected)) selected = channels[0]?.id ?? null;
76
+ const view = currentTab === 'live' ? await endpoint('/context')
77
+ : currentTab === 'timeline' ? await endpoint('/timeline')
78
+ : selected ? await endpoint('/channel?id=' + encodeURIComponent(selected)) : null;
79
+ if (version !== viewVersion) return;
80
+ if (currentTab === 'live') liveContext = view;
81
+ if (currentTab === 'channels') channelDetails = view;
82
+ if (currentTab === 'timeline') {
83
+ if (!olderLoaded || (timeline.length && view.entries.at(-1)?.seq > timeline[0].seq)) {
84
+ timeline = view.entries; nextPosition = view.next; olderLoaded = false;
85
+ }
86
+ else mergeTimeline(view.entries);
87
+ }
88
+ fetchError = '';
89
+ } catch (error) { if (version === viewVersion) fetchError = String(error); }
90
+ finally {
91
+ refreshing = false;
92
+ if (version === viewVersion) render();
93
+ if (dirty) invalidate();
94
+ }
95
+ }
96
+ async function loadOlder() {
97
+ if (!nextPosition || paging) return;
98
+ paging = true; render();
99
+ try {
100
+ const page = await endpoint('/timeline?before=' + nextPosition);
101
+ mergeTimeline(page.entries); nextPosition = page.next; olderLoaded = true; fetchError = '';
102
+ } catch (error) { fetchError = String(error); }
103
+ finally { paging = false; render(); }
104
+ }
105
+ const nav = document.querySelector('#channels'), main = document.querySelector('#content');
106
+ function node(tag, text, className) {
107
+ const element = document.createElement(tag);
108
+ if (text !== undefined) element.textContent = text;
109
+ if (className) element.className = className;
110
+ return element;
111
+ }
112
+ function json(value) { return node('pre', JSON.stringify(value, null, 2)); }
113
+ function messageCard(message, label, key, expanded) {
114
+ const card = node('article');
115
+ card.append(node('strong', label), node('pre', message.content ?? ''));
116
+ if (message.calls?.length) card.append(node('p', 'Tool calls'), json(message.calls));
117
+ if (message.callId) card.append(node('p', 'Call ID: ' + message.callId, 'muted'));
118
+ if (message.providerState) {
119
+ const raw = node('details'); raw.dataset.key = key;
120
+ raw.open = expanded.has(key);
121
+ raw.append(node('summary', 'Provider response'), json(message.providerState)); card.append(raw);
122
+ }
123
+ return card;
124
+ }
125
+ function render() {
126
+ const working = channels.filter(channel => channel.running).length;
127
+ document.querySelector('#connection').textContent = connectionStatus === 'live'
128
+ ? 'Live · working in ' + working + ' ' + (working === 1 ? 'channel' : 'channels') + ' · read only'
129
+ + (session ? ' · session ' + session.lifecycle + (session.execution === session.lifecycle ? '' : ' (' + session.execution + ')') + ' · ' + session.storage : '')
130
+ : connectionStatus === 'connecting' ? 'Connecting…' : 'Disconnected · reconnecting…';
131
+ const expanded = new Set([...main.querySelectorAll('details[data-key][open]')].map(e => e.dataset.key));
132
+ document.querySelector('.layout').classList.toggle('single', tab !== 'channels');
133
+ main.setAttribute('aria-labelledby', 'tab-' + tab);
134
+ document.querySelectorAll('[data-tab]').forEach(button => button.setAttribute('aria-selected', String(button.dataset.tab === tab)));
135
+ nav.replaceChildren();
136
+ main.replaceChildren();
137
+ if (fetchError) main.append(node('p', fetchError, 'error'));
138
+ if (tab === 'timeline') {
139
+ for (const entry of timeline) {
140
+ if (entry.omitted) { main.append(node('p', 'Position ' + entry.seq + ' · Payload omitted', 'muted')); continue; }
141
+ const role = entry.kind ?? entry.message.role;
142
+ main.append(messageCard(entry.message, '#' + entry.seq + ' · ' + entry.channelId + ' · ' + entry.from + ' · ' + role,
143
+ 'timeline:' + entry.seq, expanded));
144
+ }
145
+ if (!timeline.length) main.append(node('p', 'No timeline entries.', 'muted'));
146
+ if (nextPosition) {
147
+ const more = node('button', 'Load older events'); more.disabled = paging; more.onclick = () => void loadOlder();
148
+ main.append(more);
149
+ }
150
+ return;
151
+ }
152
+ if (tab === 'live') {
153
+ main.append(node('p', 'Shared base context · ' + liveContext.entries.length + ' events', 'muted'));
154
+ // Use the same rendered base as inference construction, without inventing
155
+ // an active channel or prompt. Exact requests remain in Channels.
156
+ const text = (liveContext.base ?? []).map(message => message.content ?? '').join('\n\n');
157
+ const container = node('div', undefined, 'context-text');
158
+ container.append(node('pre', text));
159
+ const tools = node('details');
160
+ tools.dataset.key = 'live:tools';
161
+ tools.open = expanded.has(tools.dataset.key);
162
+ tools.append(node('summary', 'Tools'), json(liveContext.tools));
163
+ container.append(tools);
164
+ main.append(container);
165
+ return;
166
+ }
167
+ if (!selected && channels.length) selected = channels[0].id;
168
+ for (const channel of channels) {
169
+ const status = channel.turn === 'suspended' ? 'suspended' : channel.running ? 'running' : channel.pending ? 'pending'
170
+ : channel.unresolved ? channel.unresolved.status : channel.error ? 'failed' : 'idle';
171
+ const button = node('button', channel.id + ' · ' + status);
172
+ button.classList.toggle('working', channel.running && connectionStatus === 'live');
173
+ button.setAttribute('aria-current', String(channel.id === selected));
174
+ button.onclick = () => { selected = channel.id; channelDetails = null; callDetails = null; fetchError = ''; viewVersion++; render(); invalidate(); };
175
+ nav.append(button);
176
+ }
177
+ const channel = channels.find(c => c.id === selected);
178
+ if (!channel) { main.append(node('p', 'No channels yet.', 'muted')); return; }
179
+ main.append(node('h2', 'Channel ' + channel.id));
180
+ main.append(node('p', 'Pending input: ' + channel.pending
181
+ + (channel.turn === 'suspended' ? ' · A checkpointed turn waits for resume' : ''), 'muted'));
182
+ if (channel.unresolved?.uncertainCallIds.length) main.append(node('p', 'Tool calls with no recorded result (not retried): ' + channel.unresolved.uncertainCallIds.join(', '), 'error'));
183
+ if (channel.error) main.append(node('p', channel.error, 'error'));
184
+ const loadCalls = node('button', callDetails?.id === selected ? 'Refresh recent model calls' : 'Load recent model calls');
185
+ loadCalls.onclick = async () => {
186
+ const id = selected, version = viewVersion;
187
+ loadCalls.disabled = true;
188
+ try {
189
+ const data = await endpoint('/calls?id=' + encodeURIComponent(id));
190
+ if (version === viewVersion) { callDetails = { id, modelCalls: data.modelCalls }; fetchError = ''; }
191
+ } catch (error) { if (version === viewVersion) fetchError = String(error); }
192
+ finally { if (version === viewVersion) render(); }
193
+ };
194
+ main.append(loadCalls);
195
+ const modelCalls = callDetails?.id === selected ? callDetails.modelCalls : [];
196
+ const turns = new Map();
197
+ for (const request of channelDetails?.requests ?? []) {
198
+ const id = request.turnId ?? 'unknown';
199
+ if (!turns.has(id)) turns.set(id, []);
200
+ turns.get(id).push(request);
201
+ }
202
+ for (const call of modelCalls) {
203
+ const id = Number(call.turnId);
204
+ if (!turns.has(id)) turns.set(id, []);
205
+ }
206
+ for (const [turnId, requests] of turns) {
207
+ main.append(node('h2', turnId === 'unknown' ? 'New turn' : 'Turn ' + turnId, 'turn-divider'));
208
+ const calls = modelCalls.filter(call => call.turnId === String(turnId));
209
+ for (const call of calls) {
210
+ const details = node('details');
211
+ details.dataset.key = channel.id + ':model-call:' + call.callId;
212
+ details.open = expanded.has(details.dataset.key);
213
+ details.append(node('summary', 'Model call ' + call.callId + ' · ' + call.outcome), json(call));
214
+ main.append(details);
215
+ }
216
+ if (!requests.length && !calls.length) main.append(node('p', channel.error ? 'Turn stopped before inference.' : 'Waiting for inference…', 'muted'));
217
+ for (const [index, request] of requests.entries()) {
218
+ const iteration = node('section', undefined, 'iteration');
219
+ iteration.append(node('p', 'Iteration ' + (index + 1) + ' · ' + request.at, 'muted'));
220
+ if (request.context) {
221
+ const { revision, estimatedInputBytes, omitted, records, offeredTools, modelCallId } = request.context;
222
+ iteration.append(node('p', 'Timeline revision ' + revision + ' · ' + estimatedInputBytes + ' estimated input bytes'
223
+ + ' · Trimmed records ' + omitted.active + ' active, ' + omitted.local + ' local, ' + omitted.shared + ' shared', 'muted'));
224
+ const inspection = node('details'); inspection.dataset.key = channel.id + ':selection:' + request.number;
225
+ inspection.open = expanded.has(inspection.dataset.key);
226
+ const call = modelCalls.find(call => call.callId === modelCallId);
227
+ inspection.append(node('summary', 'Request evidence'), json({
228
+ includedTimelinePositions: records.included, trimmedCandidatePositions: records.trimmed, offeredTools,
229
+ modelCallId, ...(call ? { outcome: call.outcome, attempts: call.attempts } : {}),
230
+ }));
231
+ iteration.append(inspection);
232
+ }
233
+ const context = node('article', undefined, 'context-card');
234
+ const text = node('pre');
235
+ // Preserve content as literal text, highlighting the active prompt only.
236
+ for (const message of request.body.messages ?? []) {
237
+ if (message.content != null) {
238
+ const content = node('span', typeof message.content === 'string' ? message.content : JSON.stringify(message.content, null, 2));
239
+ text.append(content, document.createTextNode('\n\n'));
240
+ }
241
+ const { role, content, ...fields } = message;
242
+ if (Object.keys(fields).length) text.append(document.createTextNode(JSON.stringify(fields, null, 2) + '\n\n'));
243
+ }
244
+ context.append(node('strong', 'Context'), text);
245
+ if (request.body.tools?.length) {
246
+ const tools = node('details');
247
+ tools.dataset.key = channel.id + ':tools:' + request.number;
248
+ tools.open = expanded.has(tools.dataset.key);
249
+ tools.append(node('summary', 'Tools'), json(request.body.tools));
250
+ context.append(tools);
251
+ }
252
+ const raw = node('details');
253
+ raw.dataset.key = channel.id + ':request:' + request.number;
254
+ raw.open = expanded.has(raw.dataset.key);
255
+ raw.append(node('summary', 'Inference request'), json(request.body));
256
+ context.append(raw);
257
+ iteration.append(context);
258
+ if (request.response) {
259
+ if (request.response.omitted) iteration.append(node('p', 'Large response omitted from capture.', 'muted'));
260
+ else {
261
+ const result = messageCard(request.response, 'Result', channel.id + ':response:' + request.number, expanded);
262
+ result.classList.add('result-card');
263
+ iteration.append(result);
264
+ }
265
+ } else {
266
+ const result = node('article', undefined, 'result-card');
267
+ result.append(node('strong', 'Result'), node('p', channel.error ? 'Inference failed: ' + channel.error : 'Waiting for response…', 'muted'));
268
+ iteration.append(result);
269
+ }
270
+ main.append(iteration);
271
+ }
272
+ }
273
+ }
274
+ document.querySelectorAll('[data-tab]').forEach(button => {
275
+ button.onclick = () => { tab = button.dataset.tab; fetchError = ''; viewVersion++; render(); invalidate(); };
276
+ });
277
+ document.addEventListener('visibilitychange', () => { if (!document.hidden) invalidate(); });
278
+ const events = new EventSource('/events');
279
+ events.onopen = () => { connectionStatus = 'live'; render(); invalidate(); };
280
+ events.onerror = () => { connectionStatus = 'disconnected'; render(); };
281
+ events.onmessage = invalidate;
282
+ </script>
283
+ </html>
@@ -0,0 +1,35 @@
1
+ import type { SessionAgent } from "../../contracts/agent.ts";
2
+ import type { Model } from "../../contracts/loop.ts";
3
+ import type { PersistentSession } from "../../contracts/session.ts";
4
+ import type { Inspection } from "./state.ts";
5
+
6
+ /** Turn and lifecycle events only invalidate the development views. */
7
+ export function observeSession(session: PersistentSession, inspection: Inspection) {
8
+ const stopEvents = session.store.subscribe(inspection.invalidate);
9
+ const stopLifecycle = session.subscribeSession(inspection.invalidate);
10
+ const agent: SessionAgent = {
11
+ idle: () => session.agent.idle(),
12
+ send(input) { const result = session.agent.send(input); if (result.accepted && !result.duplicate) inspection.invalidate(); return result; },
13
+ notifyExternal(notice) { const result = session.agent.notifyExternal(notice); if (result.accepted && !result.duplicate) inspection.invalidate(); return result; },
14
+ notify(notice) { const result = session.agent.notify(notice); if (result.accepted && !result.duplicate) inspection.invalidate(); return result; },
15
+ };
16
+ return { agent, stop() { stopEvents(); stopLifecycle(); } };
17
+ }
18
+
19
+ export function observeModel(
20
+ inspection: Inspection,
21
+ channelId: string,
22
+ createModel: (onRequest: (body: string) => void) => Model,
23
+ turnId?: number,
24
+ ): Model {
25
+ const model = createModel((body) => {
26
+ // Capture the actual serialized request at the provider boundary, before
27
+ // fetch, rather than reconstructing it later from changing channel history.
28
+ inspection.request(channelId, body, turnId);
29
+ });
30
+ return async (messages, tools, signal) => {
31
+ const response = await model(messages, tools, signal);
32
+ inspection.response(channelId, response);
33
+ return response;
34
+ };
35
+ }
@@ -0,0 +1,56 @@
1
+ import type { Inspection } from "./state.ts";
2
+
3
+ /** Read-only development UI, bound to loopback only. */
4
+ export function serveInspector(inspection: Inspection, port = 3000) {
5
+ return Bun.serve({
6
+ hostname: "127.0.0.1", port,
7
+ async fetch(request, server) {
8
+ const url = new URL(request.url);
9
+ if (request.method !== "GET") return new Response("Read only", { status: 405 });
10
+ if (request.headers.get("host") !== server.url.host) return new Response("Invalid host", { status: 403 });
11
+ if (url.pathname === "/") return new Response(Bun.file(new URL("./index.html", import.meta.url)), {
12
+ headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" },
13
+ });
14
+ const json = (body: unknown) => Response.json(body, { headers: { "Cache-Control": "no-store" } });
15
+ try {
16
+ if (url.pathname === "/state") return json(inspection.status());
17
+ if (url.pathname === "/context") return json(inspection.liveContext());
18
+ if (url.pathname === "/timeline") {
19
+ const cursor = url.searchParams.get("before");
20
+ if (cursor !== null && (!/^\d+$/.test(cursor) || !Number.isSafeInteger(Number(cursor)) || Number(cursor) < 1))
21
+ return new Response("Invalid timeline position", { status: 400 });
22
+ return json(inspection.timeline(cursor === null ? undefined : Number(cursor)));
23
+ }
24
+ if (url.pathname === "/channel" || url.pathname === "/calls") {
25
+ const id = url.searchParams.get("id");
26
+ return id ? json(url.pathname === "/calls" ? inspection.modelCalls(id) : inspection.channel(id)) : new Response("Channel ID is required", { status: 400 });
27
+ }
28
+ } catch (error) {
29
+ return new Response(error instanceof Error ? error.message : String(error), { status: 500 });
30
+ }
31
+ if (url.pathname !== "/events") return new Response("Not found", { status: 404 });
32
+ server.timeout(request, 0);
33
+ let unsubscribe = () => {};
34
+ let timer: ReturnType<typeof setTimeout> | undefined;
35
+ const stream = new ReadableStream<Uint8Array>({
36
+ start(controller) {
37
+ const send = () => {
38
+ // Drop slow connections; EventSource reconnects with a fresh snapshot.
39
+ if ((controller.desiredSize ?? 0) <= 0) {
40
+ unsubscribe(); controller.close(); return;
41
+ }
42
+ controller.enqueue(new TextEncoder().encode("data: changed\n\n"));
43
+ };
44
+ unsubscribe = inspection.subscribe(() => {
45
+ timer ??= setTimeout(() => { timer = undefined; send(); }, 40);
46
+ });
47
+ send();
48
+ },
49
+ cancel() { clearTimeout(timer); unsubscribe(); },
50
+ });
51
+ return new Response(stream, { headers: {
52
+ "Content-Type": "text/event-stream", "Cache-Control": "no-cache",
53
+ } });
54
+ },
55
+ });
56
+ }