@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,418 @@
1
+ import { modelScenario } from "./helpers/scenario.ts";
2
+ import { inspectOperatorView } from "./helpers/operator-view.ts";
3
+ import { afterAll, expect, test } from "bun:test";
4
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { FunctionError, HarnessClient, createStdioTransport, type ClientTransport, type ChannelEvent, type FunctionCall, type FunctionResult, type ProtocolConfig, type ResultRead, type ToolCatalogInput, type ToolRegistration } from "../src/client.ts";
8
+ import { createInProcessHarness } from "../src/testing.ts";
9
+ import { spawnHarness } from "./helpers/stdio.ts";
10
+
11
+ // Decision 0021 over the protocol: catalog on open, `functions/call` from the
12
+ // harness to the host, cancellation, result references, in process and over
13
+ // real `serve --stdio` children.
14
+ const root = mkdtempSync(join(tmpdir(), "harness-tools-"));
15
+ afterAll(() => rmSync(root, { recursive: true, force: true }));
16
+ function deferred<T = void>() { let resolve!: (value: T) => void; const promise = new Promise<T>(res => { resolve = res; }); return { promise, resolve }; }
17
+ async function until(check: () => boolean | Promise<boolean>, what: string) {
18
+ for (let i = 0; i < 800; i++) { if (await check()) return; await new Promise(resolve => setTimeout(resolve, 5)); }
19
+ throw new Error(`Timed out waiting for ${what}`);
20
+ }
21
+ let scripts = 0;
22
+ /** One script file; every channel runs its own copy from the first response. */
23
+ function script(responses: { content: string | null; calls?: { id: string; name: string; arguments: Record<string, unknown> }[] }[]) {
24
+ const path = join(root, `script-${++scripts}.jsonl`);
25
+ writeFileSync(path, modelScenario(responses));
26
+ return path;
27
+ }
28
+ const callThen = (name: string, args: Record<string, unknown>, ...more: { content: string | null; calls?: any[] }[]) =>
29
+ script([{ content: null, calls: [{ id: "t1", name, arguments: args }] }, ...(more.length ? more : [{ content: "done" }])]);
30
+ const config = (path: string, fallback: "allow" | "ask" = "allow"): ProtocolConfig => ({ version: 1, system: "Tools", model: { protocol: "scripted", script: path },
31
+ defaultPolicy: "main", policies: { main: { fallback, tools: {} } } });
32
+ const tool = (name: string, group: ToolRegistration["group"] = "fixed", extra: Partial<ToolRegistration> = {}): ToolRegistration => ({ name, group, handler: `${name}_handler`,
33
+ description: `Test tool ${name}`, parameters: { type: "object", properties: { q: { type: "string" } }, required: ["q"], additionalProperties: false }, ...extra });
34
+ const push = (channel: string, id: string, text = "go") => ({ channel, item: { id, kind: "user_message" as const, sender: `user-${channel}`, content: [{ type: "text" as const, text }] } });
35
+ const hello = (functions?: string[]) => ({ protocolVersion: 1 as const, host: { name: "test", version: "0" }, callbacks: functions ? ["functions/call"] : [],
36
+ ...(functions ? { functions } : {}), approval: true, subscription: { text: "final" as const, tools: "full" as const } });
37
+ function watch(client: HarnessClient) {
38
+ const events: ChannelEvent[] = [];
39
+ client.onChannelEvent(event => { events.push(event); });
40
+ const ended = (channel: string, count = 1) => events.filter(event => event.channel === channel && event.event.type === "turn_ended").length >= count;
41
+ const toolEvents = (channel: string) => events.flatMap(event => event.channel === channel && event.event.type === "tool_call" ? [event.event] : []);
42
+ const output = (channel: string, status = "completed") => JSON.parse(toolEvents(channel).findLast(event => event.status === status)!.output!);
43
+ return { events, ended, toolEvents, output };
44
+ }
45
+ type Harness = { client: HarnessClient; close(): void | Promise<void> };
46
+ const open = (transport: "in-process" | "stdio", options: Parameters<typeof spawnHarness>[0] = {}): Harness => transport === "stdio" ? spawnHarness(options) : createInProcessHarness(options);
47
+
48
+ for (const transport of ["in-process", "stdio"] as const) {
49
+ test(`${transport}: concurrent callbacks answer the right requests; status stays responsive and shows the tool phase`, async () => {
50
+ const harness = open(transport), { client } = harness, seen = watch(client);
51
+ const calls: FunctionCall[] = [], gates = { a: deferred<FunctionResult>(), b: deferred<FunctionResult>() };
52
+ client.serveFunctions(call => { calls.push(call); return gates[call.channel as "a" | "b"].promise; });
53
+ try {
54
+ const described = await client.initialize(hello(["lookup_handler"]));
55
+ expect(described.description.capabilities.functions).toBe(true);
56
+ await client.createSession({ sessionId: "s", config: config(callThen("lookup", { q: "x" })), participants: [], channels: {}, tools: { catalog: [tool("lookup")] } });
57
+ expect((await client.tools()).tools).toEqual([{ name: "lookup", group: "fixed", handler: "lookup_handler", available: true }, { name: "read_tool_result", group: "builtin", available: true }]);
58
+ await client.push(push("a", "a1")); await client.push(push("b", "b1"));
59
+ await until(() => calls.length === 2, "both callbacks");
60
+ expect(calls.map(call => [call.channel, call.tool, call.handler, call.sessionId, call.arguments])).toContainEqual(["a", "lookup", "lookup_handler", "s", { q: "x" }]);
61
+ expect(calls.map(call => call.policyNames)).toEqual([["main"], ["main"]]);
62
+ const ids = Object.fromEntries(calls.map(call => [call.channel, call.invocationId]));
63
+ expect(new Set(Object.values(ids)).size).toBe(2);
64
+ // The control connection answers while both handlers are quiet.
65
+ const status = await client.status();
66
+ for (const channel of status.channels) {
67
+ expect(channel.activeTurn).toMatchObject({ state: "running", phase: { kind: "tool", id: ids[channel.channel] } });
68
+ expect(Date.parse(channel.activeTurn!.phase!.since)).toBeLessThanOrEqual(Date.now());
69
+ }
70
+ expect((await client.toolInvocation(ids.a!)).invocation).toMatchObject({ state: "started", channel: "a", tool: "lookup", toolCallId: "t1" });
71
+ // Answer in the opposite order of the requests: each result lands in its own channel.
72
+ gates.b.resolve({ output: "for-b" });
73
+ await until(() => seen.ended("b"), "b");
74
+ expect(seen.ended("a")).toBe(false);
75
+ gates.a.resolve({ output: "for-a" });
76
+ await until(() => seen.ended("a"), "a");
77
+ expect(seen.output("a")).toEqual({ ok: true, output: "for-a" });
78
+ expect(seen.output("b")).toEqual({ ok: true, output: "for-b" });
79
+ expect(seen.toolEvents("a").map(event => [event.status, event.invocationId])).toEqual([["started", ids.a], ["completed", ids.a]]);
80
+ expect((await client.toolInvocations("1")).invocations).toHaveLength(1);
81
+ expect(calls).toHaveLength(2);
82
+ await expect(client.toolInvocation("99:nope")).rejects.toMatchObject({ code: "not_found" });
83
+ } finally { await harness.close(); }
84
+ });
85
+
86
+ test(`${transport}: a deadline or an interrupt cancels exactly its own call; late answers are ignored; a typed error reaches the model`, async () => {
87
+ const harness = open(transport), { client } = harness, seen = watch(client);
88
+ const running = new Map<string, { call: FunctionCall; signal: AbortSignal; answer: ReturnType<typeof deferred<FunctionResult>> }>();
89
+ client.serveFunctions((call, signal) => {
90
+ if (call.channel === "e") throw new FunctionError("quota_exceeded", "No quota left");
91
+ const answer = deferred<FunctionResult>(); running.set(call.channel, { call, signal, answer }); return answer.promise;
92
+ });
93
+ try {
94
+ await client.initialize(hello(["quick_handler", "slow_handler"]));
95
+ const path = script([{ content: null, calls: [{ id: "t1", name: "slow", arguments: { q: "x" } }] }, { content: "done" }]);
96
+ await client.createSession({ sessionId: "s", config: config(path), participants: [], channels: {}, tools: { catalog: [tool("quick", "fixed", { deadlineMs: 60 }), tool("slow")] } });
97
+ await client.push(push("a", "a1")); await client.push(push("b", "b1")); await client.push(push("e", "e1"));
98
+ await until(() => running.has("a") && running.has("b"), "two untimed callbacks");
99
+ // A typed handler error is a paired failure and that turn completes.
100
+ await until(() => seen.ended("e"), "typed error turn");
101
+ expect(seen.output("e", "failed")).toMatchObject({ ok: false, code: "quota_exceeded", message: "No quota left" });
102
+ // Interrupt a's turn: only a's handler is cancelled.
103
+ await client.interruptTurn({ channel: "a", turn: running.get("a")!.call.turnId, reason: "operator" });
104
+ await until(() => running.get("a")!.signal.aborted, "a's cancellation");
105
+ expect((running.get("a")!.signal.reason as Error).message).toBe("operator");
106
+ expect(running.get("b")!.signal.aborted).toBe(false);
107
+ expect((await client.toolInvocation(running.get("a")!.call.invocationId)).invocation).toMatchObject({ state: "interrupted", effect: "unknown" });
108
+ // A late answer for the interrupted call starts nothing.
109
+ running.get("a")!.answer.resolve({ output: "late" });
110
+ running.get("b")!.answer.resolve({ output: "on time" });
111
+ await until(() => seen.ended("b"), "b");
112
+ expect(seen.output("b")).toEqual({ ok: true, output: "on time" });
113
+ expect(seen.events.filter(event => event.channel === "a" && event.event.type === "turn_ended").map(event => (event.event as any).outcome)).toEqual(["interrupted"]);
114
+ expect(seen.toolEvents("a").map(event => event.status)).toEqual(["started"]);
115
+ } finally { await harness.close(); }
116
+
117
+ // The deadline: a separate session whose script calls the short-deadline tool.
118
+ const second = open(transport), late = deferred<FunctionResult>(), signals: AbortSignal[] = [], view = watch(second.client);
119
+ second.client.serveFunctions((_call, signal) => { signals.push(signal); return late.promise; });
120
+ try {
121
+ await second.client.initialize(hello(["quick_handler"]));
122
+ await second.client.createSession({ sessionId: "s", config: config(callThen("quick", { q: "x" }, { content: "after timeout" })), participants: [], channels: {},
123
+ tools: { catalog: [tool("quick", "fixed", { deadlineMs: 60 })] } });
124
+ await second.client.push(push("q", "q1"));
125
+ await until(() => view.ended("q"), "timed out turn");
126
+ expect(signals).toHaveLength(1);
127
+ expect(signals[0]!.aborted).toBe(true);
128
+ expect((signals[0]!.reason as Error).message).toBe("tool deadline");
129
+ expect(view.output("q", "interrupted")).toMatchObject({ ok: false, code: "tool_timeout", effect: "unknown" });
130
+ expect(view.events.findLast(event => event.event.type === "turn_ended")!.event).toMatchObject({ outcome: "completed" });
131
+ expect(view.events.filter(event => event.event.type === "message_completed")).toHaveLength(1);
132
+ late.resolve({ output: "too late" });
133
+ await new Promise(resolve => setTimeout(resolve, 60));
134
+ expect((await second.client.toolInvocations("1")).invocations).toMatchObject([{ state: "interrupted", code: "tool_timeout" }]);
135
+ expect(view.events.filter(event => event.event.type === "message_completed")).toHaveLength(1);
136
+ expect(signals).toHaveLength(1);
137
+ } finally { await second.close(); }
138
+ });
139
+ }
140
+
141
+ test("stdio: a result larger than one frame crosses by reference; only the producing channel reads it, by ID", async () => {
142
+ const requests = join(root, "large-requests.log");
143
+ // Channel a: produce, read a part, then try a path. Channel b runs the same
144
+ // script: its own call is small, and its read of a's ID is refused.
145
+ const path = script([{ content: null, calls: [{ id: "t1", name: "lookup", arguments: { q: "big" } }] },
146
+ { content: null, calls: [{ id: "t2", name: "read_tool_result", arguments: { result_id: "res-1", offset: 2_000_000, length: 16 } }] },
147
+ { content: null, calls: [{ id: "t3", name: "read_tool_result", arguments: { result_id: "/etc/passwd" } }] }, { content: "done" }]);
148
+ const harness = spawnHarness({ requests }), { client } = harness, seen = watch(client);
149
+ const full = "abcdefghij".repeat(300_000); // 3 MB: three protocol frames
150
+ const store = new Map<string, string>(), reads: ResultRead[] = [];
151
+ client.serveFunctions(call => {
152
+ if (call.channel !== "a") return { output: "small" };
153
+ store.set("res-1", full);
154
+ return { preview: full.slice(0, 32), reference: { resultId: "res-1", bytes: full.length, retention: "temporary", expiresAt: new Date(Date.now() + 60_000).toISOString() } };
155
+ }, read => {
156
+ reads.push(read);
157
+ const text = store.get(read.resultId);
158
+ if (text === undefined) throw new FunctionError("result_expired", "That result is gone");
159
+ const part = text.slice(read.offset, read.offset + read.length);
160
+ return { text: part, eof: read.offset + part.length >= text.length, totalBytes: text.length };
161
+ });
162
+ try {
163
+ await client.initialize(hello(["lookup_handler"]));
164
+ await client.createSession({ sessionId: "s", config: config(path), participants: [], channels: {}, tools: { catalog: [tool("lookup")] } });
165
+ await client.push(push("a", "a1"));
166
+ await until(() => seen.ended("a"), "a");
167
+ const outputs = seen.toolEvents("a").filter(event => event.status !== "started").map(event => JSON.parse(event.output!));
168
+ expect(outputs[0]).toMatchObject({ ok: true, preview: full.slice(0, 32), result_id: "res-1", bytes: 3_000_000 });
169
+ expect(outputs[1]).toEqual({ ok: true, text: full.slice(2_000_000, 2_000_016), total_bytes: 3_000_000, eof: false, next_offset: 2_000_016 });
170
+ expect(outputs[2]).toMatchObject({ ok: false, code: "result_not_found" });
171
+ expect(reads).toEqual([{ resultId: "res-1", invocationId: "1:t1", channel: "a", offset: 2_000_000, length: 16 }]);
172
+ expect((await client.toolInvocation("1:t1")).invocation).toMatchObject({ state: "succeeded", reference: { resultId: "res-1", bytes: 3_000_000, retention: "temporary" } });
173
+ // The model saw the preview and the ID, never the bytes.
174
+ const sent = readFileSync(requests, "utf8");
175
+ expect(sent.length).toBeLessThan(200_000);
176
+ expect(sent).toContain("res-1");
177
+ // Another channel, which sees the ID in shared history, cannot read it.
178
+ await client.push(push("b", "b1"));
179
+ await until(() => seen.ended("b"), "b");
180
+ const other = seen.toolEvents("b").filter(event => event.status !== "started").map(event => JSON.parse(event.output!));
181
+ expect(other[0]).toEqual({ ok: true, output: "small" });
182
+ expect(other[1]).toMatchObject({ ok: false, code: "result_forbidden" });
183
+ expect(reads).toHaveLength(1);
184
+ // The producer dropped the bytes: reading reports expiry; the call keeps its outcome.
185
+ store.clear();
186
+ await client.push(push("a", "a2"));
187
+ await until(() => seen.ended("a", 2), "a again");
188
+ } finally { await harness.close(); }
189
+ });
190
+
191
+ test("stdio: revoking a tool while its approval is pending skips the call; the next inference omits it; the revocation survives reopen", async () => {
192
+ const home = mkdtempSync(join(root, "revoke-")), requests = join(home, "requests.log");
193
+ const path = callThen("send", { q: "x" }, { content: "skipped it" }, { content: "second turn" });
194
+ const tools: ToolCatalogInput = { catalog: [tool("send", "revocable"), tool("lookup")] };
195
+ const offered = () => readFileSync(requests, "utf8").split("\n").filter(Boolean).map(line => JSON.parse(line).tools as string[]);
196
+ const first = spawnHarness({ home, requests }), seen = watch(first.client);
197
+ let handled = 0;
198
+ first.client.serveFunctions(() => { handled++; return { output: "ran" }; });
199
+ await first.client.initialize(hello(["send_handler", "lookup_handler"]));
200
+ await first.client.createSession({ sessionId: "s", config: config(path, "ask"), participants: [], channels: {}, tools });
201
+ await first.client.push(push("a", "a1"));
202
+ await until(() => seen.events.some(event => event.event.type === "approval_requested"), "approval request");
203
+ const request = seen.events.find(event => event.event.type === "approval_requested")!.event as Extract<ChannelEvent["event"], { type: "approval_requested" }>;
204
+ expect(request).toMatchObject({ tool: "send", toolCallId: "t1", arguments: '{"q":"x"}' });
205
+ expect((await first.client.status()).channels[0]!.activeTurn).toMatchObject({ phase: { kind: "approval", id: request.requestId } });
206
+ expect((await first.client.toolInvocation("1:t1")).invocation.state).toBe("waiting_for_approval");
207
+ expect((await first.client.revokeTool("send")).tool).toEqual({ name: "send", group: "revocable", handler: "send_handler", available: false, reason: "revoked" });
208
+ // The old request can no longer authorize anything.
209
+ await expect(first.client.respondApproval(request.requestId, "allow_once")).rejects.toMatchObject({ code: "not_found" });
210
+ await until(() => seen.ended("a"), "turn");
211
+ expect(handled).toBe(0);
212
+ expect(seen.toolEvents("a").map(event => event.status)).toEqual(["skipped"]);
213
+ expect(seen.output("a", "skipped")).toMatchObject({ ok: false, code: "tool_unavailable" });
214
+ expect((await first.client.toolInvocation("1:t1")).invocation).toMatchObject({ state: "skipped", code: "tool_unavailable", effect: "none" });
215
+ expect(offered()).toEqual([["echo", "record", "hold", "notify_channel", "schedule_reminder", "list_reminders", "cancel_reminder", "lookup", "read_tool_result", "send"], ["echo", "record", "hold", "notify_channel", "schedule_reminder", "list_reminders", "cancel_reminder", "lookup", "read_tool_result"]]);
216
+ await expect(first.client.revokeTool("lookup")).rejects.toMatchObject({ code: "invalid_state" });
217
+ await expect(first.client.removeTool("send")).rejects.toMatchObject({ code: "invalid_state" });
218
+ await expect(first.client.revokeTool("nope")).rejects.toMatchObject({ code: "not_found" });
219
+ await first.close();
220
+
221
+ // Reopen in a new process: the grant is still revoked; a handler this
222
+ // connection does not serve makes its tool unavailable too.
223
+ const second = spawnHarness({ home, requests }), again = watch(second.client);
224
+ try {
225
+ await second.client.initialize(hello(["send_handler"]));
226
+ await inspectOperatorView(second.client, { sessionId: "s", tools });
227
+ expect((await second.client.tools()).tools).toEqual([
228
+ { name: "send", group: "revocable", handler: "send_handler", available: false, reason: "revoked" },
229
+ { name: "lookup", group: "fixed", handler: "lookup_handler", available: false, reason: "handler_missing" },
230
+ { name: "read_tool_result", group: "builtin", available: true }]);
231
+ expect((await second.client.toolInvocation("1:t1")).invocation).toMatchObject({ state: "skipped", code: "tool_unavailable" });
232
+ await second.client.push(push("a", "a2"));
233
+ await until(() => again.ended("a"), "second turn");
234
+ expect(offered().at(-1)).toEqual(["echo", "record", "hold", "notify_channel", "schedule_reminder", "list_reminders", "cancel_reminder", "read_tool_result"]);
235
+ // A repeated load with the same catalog is a view; a different one is refused.
236
+ await inspectOperatorView(second.client, { sessionId: "s", tools });
237
+ await expect(second.client.openSession({ sessionId: "s", tools: { catalog: [tool("other")] } })).rejects.toMatchObject({ code: "invalid_state" });
238
+ expect((await second.client.restoreTool("send")).tool.available).toBe(true);
239
+ } finally { await second.close(); }
240
+ });
241
+
242
+ test("stdio: a callback whose outcome is lost stays uncertain after reopen and its handler never runs again", async () => {
243
+ const home = mkdtempSync(join(root, "lost-"));
244
+ const path = callThen("lookup", { q: "x" }, { content: "done" }, { content: "fresh" });
245
+ const tools: ToolCatalogInput = { catalog: [tool("lookup")] };
246
+ let handled = 0;
247
+ const first = spawnHarness({ home });
248
+ first.client.serveFunctions(() => { handled++; return new Promise<FunctionResult>(() => {}); });
249
+ await first.client.initialize(hello(["lookup_handler"]));
250
+ await first.client.createSession({ sessionId: "s", config: config(path), participants: [], channels: {}, tools });
251
+ await first.client.push(push("a", "a1"));
252
+ await until(() => handled === 1, "the callback");
253
+ // The process dies after dispatch, before any answer.
254
+ first.child.kill("SIGKILL"); await first.child.exited; first.client.close();
255
+
256
+ const second = spawnHarness({ home }), seen = watch(second.client);
257
+ second.client.serveFunctions(() => { handled++; return { output: "again" }; });
258
+ try {
259
+ await second.client.initialize(hello(["lookup_handler"]));
260
+ const loaded = await inspectOperatorView(second.client, { sessionId: "s", tools });
261
+ expect(loaded.status.channels[0]!.unresolved).toMatchObject({ state: "interrupted", uncertainCalls: ["t1"] });
262
+ expect((await second.client.toolInvocation("1:t1")).invocation).toMatchObject({ state: "interrupted", effect: "unknown", tool: "lookup", arguments: '{"q":"x"}' });
263
+ await new Promise(resolve => setTimeout(resolve, 100));
264
+ expect(handled).toBe(1);
265
+ expect(seen.events.filter(event => event.event.type === "tool_call")).toEqual([]);
266
+ } finally { await second.close(); }
267
+ });
268
+
269
+ test("negotiation and catalog validation: bad input opens nothing; a server refuses callbacks it was not offered", async () => {
270
+ const harness = createInProcessHarness(), { client } = harness;
271
+ try {
272
+ await expect(client.initialize({ ...hello(), callbacks: ["other/callback"] })).rejects.toMatchObject({ code: "invalid_params" });
273
+ await expect(client.initialize({ ...hello(), functions: ["x"] })).rejects.toMatchObject({ code: "invalid_params" });
274
+ await expect(client.initialize({ ...hello(["x"]), functions: ["x", "x"] })).rejects.toMatchObject({ code: "invalid_params" });
275
+ await client.initialize(hello(["lookup_handler"]));
276
+ const base = { sessionId: "s", config: config(callThen("lookup", { q: "x" })), participants: [], channels: {} };
277
+ for (const catalog of [[tool("a"), tool("a")], [tool("echo")], [tool("read_tool_result")], [{ ...tool("a"), group: "odd" }]])
278
+ await expect(client.createSession({ ...base, tools: { catalog: catalog as ToolRegistration[] } })).rejects.toMatchObject({ code: "invalid_params" });
279
+ await expect(client.createSession({ ...base, tools: { catalog: [tool("a")], enabled: ["a"] } })).rejects.toMatchObject({ code: "invalid_params" });
280
+ await expect(client.status()).rejects.toMatchObject({ code: "not_ready" });
281
+ // Nothing was opened by the refused requests: the same ID can still be created, without a catalog.
282
+ await client.createSession(base);
283
+ expect((await client.tools()).tools).toEqual([]);
284
+ await expect(client.revokeTool("lookup")).rejects.toMatchObject({ code: "not_found" });
285
+ } finally { harness.close(); }
286
+ });
287
+
288
+ test("stdio: invalid callback arguments are paired without approval or dispatch", async () => {
289
+ const requests = join(root, "invalid-arguments-requests.log");
290
+ const harness = spawnHarness({ requests });
291
+ const { client } = harness;
292
+ const seen = watch(client);
293
+ let handled = 0;
294
+ client.serveFunctions(() => { handled++; return { output: "unexpected" }; });
295
+ try {
296
+ await client.initialize(hello(["lookup_handler"]));
297
+ await client.createSession({ sessionId: "s", config: config(callThen("lookup", { q: 42 }), "ask"),
298
+ participants: [], channels: {}, tools: { catalog: [tool("lookup")] } });
299
+ await client.push(push("a", "a1"));
300
+ await until(() => seen.ended("a"), "turn completion");
301
+ expect(handled).toBe(0);
302
+ expect(seen.events.some(event => event.event.type === "approval_requested")).toBe(false);
303
+ expect(seen.toolEvents("a").map(event => event.status)).toEqual(["skipped"]);
304
+ expect(seen.output("a", "skipped")).toMatchObject({ ok: false, code: "invalid_arguments" });
305
+ const [, next] = readFileSync(requests, "utf8").trim().split("\n").map(line => JSON.parse(line));
306
+ const paired = next.messages.find((message: { role: string }) => message.role === "tool");
307
+ expect(paired.callId).toBe("t1");
308
+ expect(JSON.parse(paired.content)).toMatchObject({ code: "invalid_arguments" });
309
+ } finally { await harness.close(); }
310
+ });
311
+
312
+ for (const transport of ["in-process", "stdio"] as const) test(`${transport}: notice contributors freeze across approval and pending deny applies after take`, async () => {
313
+ const path = join(root, `policy-snapshot-${transport}.jsonl`);
314
+ const lookup = (id: string) => ({ channelId: "owner", content: null, calls: [{ id, name: "lookup", arguments: { q: "x", policyNames: ["forged"] } }] });
315
+ writeFileSync(path, modelScenario([
316
+ { channelId: "guest", content: null, calls: [{ id: "notice", name: "notify_channel", arguments: { channelId: "owner", text: "wake" } }] },
317
+ { channelId: "guest", content: "sent" }, lookup("first"), lookup("second"), { channelId: "owner", content: "done" },
318
+ { ...lookup("refused"), channelId: "deny" }, { channelId: "deny", content: "done" },
319
+ ]));
320
+ const harness = open(transport), { client } = harness, seen = watch(client);
321
+ const callbacks: FunctionCall[] = [];
322
+ client.serveFunctions(call => { callbacks.push(call); return { output: true }; });
323
+ try {
324
+ await client.initialize(hello(["lookup_handler"]));
325
+ await client.createSession({ sessionId: "s", participants: [], channels: {}, tools: { catalog: [tool("lookup", "fixed", {
326
+ parameters: { type: "object" },
327
+ })] }, config: { ...config(path), defaultPolicy: "guest", policies: {
328
+ guest: { fallback: "allow", tools: {} }, owner: { fallback: "allow", tools: { lookup: "ask" } },
329
+ blocked: { fallback: "allow", tools: { lookup: "deny" } },
330
+ } } });
331
+ await client.createChannel({ channel: "owner", policy: "owner" });
332
+ await client.push(push("guest", "start"));
333
+ await until(() => seen.events.some(({ event }) => event.type === "approval_requested"), "notice approval");
334
+ const request = seen.events.find(({ event }) => event.type === "approval_requested")!.event;
335
+ if (request.type !== "approval_requested") throw new Error("Missing approval");
336
+ const pending = push("owner", "pending");
337
+ await client.push({ ...pending, item: { ...pending.item, policy: "blocked" } });
338
+ expect((await client.status()).channels.find(channel => channel.channel === "owner")?.pending).toContain("pending");
339
+ expect(callbacks).toHaveLength(0);
340
+ await client.respondApproval(request.requestId, "allow_once");
341
+ await until(() => seen.ended("owner"), "owner completion");
342
+ expect(callbacks).toHaveLength(1);
343
+ expect(callbacks[0]).toMatchObject({ policyNames: ["guest", "owner"], arguments: { policyNames: ["forged"] } });
344
+ expect(seen.events.some(({ event }) => event.type === "turn_took" && event.items.includes("pending"))).toBe(true);
345
+ expect(seen.output("owner", "skipped")).toMatchObject({ code: "policy_denied" });
346
+
347
+ await client.createChannel({ channel: "deny", policy: "owner" });
348
+ await client.push(push("deny", "refuse"));
349
+ await until(() => seen.events.some(({ channel, event }) => channel === "deny" && event.type === "approval_requested"), "denial request");
350
+ const denied = seen.events.find(({ channel, event }) => channel === "deny" && event.type === "approval_requested")!.event;
351
+ if (denied.type !== "approval_requested") throw new Error("Missing denial request");
352
+ await client.respondApproval(denied.requestId, "deny");
353
+ await until(() => seen.ended("deny"), "denied turn completion");
354
+ expect(seen.output("deny", "skipped")).toMatchObject({ code: "approval_denied" });
355
+ expect(callbacks).toHaveLength(1);
356
+ } finally { await harness.close(); }
357
+ }, 15000);
358
+
359
+ for (const transport of ["in-process", "stdio"] as const) test(`${transport}: legacy authorization sends an explicit empty policy list`, async () => {
360
+ const harness = open(transport), { client } = harness, seen = watch(client);
361
+ const policies: string[][] = [];
362
+ client.serveFunctions(call => { policies.push(call.policyNames); return { output: true }; });
363
+ try {
364
+ await client.initialize(hello(["lookup_handler"]));
365
+ await client.createSession({ sessionId: "s", participants: [], channels: {}, tools: { catalog: [tool("lookup")] },
366
+ config: { ...config(callThen("lookup", { q: "legacy" })), defaultPolicy: "__legacy_allow",
367
+ policies: { __legacy_allow: { fallback: "allow", tools: {} } } } });
368
+ await client.push(push("a", "legacy"));
369
+ await until(() => seen.ended("a"), "legacy turn");
370
+ expect(policies).toEqual([[]]);
371
+ } finally { await harness.close(); }
372
+ });
373
+
374
+ for (const transport of ["in-process", "stdio"] as const) test(`${transport}: malformed callback policy fields return invalid_params before the handler`, async () => {
375
+ const answers: { id: number; error?: { data?: { code?: string } } }[] = [];
376
+ let receive!: Parameters<NonNullable<ClientTransport["subscribeCallbacks"]>>[0];
377
+ let stream!: ReadableStreamDefaultController<Uint8Array>;
378
+ const local: ClientTransport = {
379
+ send() {}, close() {}, onClose: () => () => {}, subscribe: () => () => {},
380
+ subscribeCallbacks(listener) { receive = listener; return () => {}; },
381
+ respond(answer) { answers.push(answer); },
382
+ };
383
+ const client = new HarnessClient(transport === "in-process" ? local : createStdioTransport({
384
+ readable: new ReadableStream<Uint8Array>({ start(controller) { stream = controller; } }),
385
+ async write(bytes) { answers.push(JSON.parse(new TextDecoder().decode(bytes))); },
386
+ async end() { stream.close(); },
387
+ }));
388
+ let invoked = 0;
389
+ client.serveFunctions(() => { invoked++; return { output: true }; });
390
+ try {
391
+ const malformed = [undefined, "main", [1], [""], ["main", "main"], ["__legacy_allow"]];
392
+ for (const [index, policyNames] of malformed.entries()) {
393
+ const request = { jsonrpc: "2.0", id: index + 1, method: "functions/call", params: {
394
+ invocationId: `1:${index}`, sessionId: "s", channel: "a", turnId: "1", tool: "lookup", handler: "lookup_handler",
395
+ arguments: {}, ...(policyNames === undefined ? {} : { policyNames }),
396
+ } };
397
+ if (transport === "stdio") stream.enqueue(new TextEncoder().encode(JSON.stringify(request) + "\n"));
398
+ else receive(request as Parameters<typeof receive>[0]);
399
+ }
400
+ await until(() => answers.length === malformed.length, "invalid_params replies");
401
+ expect(answers.map(answer => answer.error?.data?.code)).toEqual(malformed.map(() => "invalid_params"));
402
+ expect(invoked).toBe(0);
403
+ } finally { client.close(); }
404
+ });
405
+
406
+ for (const transport of ["in-process", "stdio"] as const) test(`${transport}: consumer invalid_params records one paired failure without retry`, async () => {
407
+ const harness = open(transport), { client } = harness, seen = watch(client);
408
+ let dispatched = 0;
409
+ client.serveFunctions(() => { dispatched++; throw new FunctionError("invalid_params", "Rejected policy metadata"); });
410
+ try {
411
+ await client.initialize(hello(["lookup_handler"]));
412
+ await client.createSession({ sessionId: "s", config: config(callThen("lookup", { q: "x" })), participants: [], channels: {}, tools: { catalog: [tool("lookup")] } });
413
+ await client.push(push("a", "first"));
414
+ await until(() => seen.ended("a"), "failed tool result followed by successful turn");
415
+ expect(dispatched).toBe(1);
416
+ expect(seen.output("a", "failed")).toMatchObject({ ok: false, code: "invalid_params" });
417
+ } finally { await harness.close(); }
418
+ });
@@ -0,0 +1,94 @@
1
+ import { afterAll, expect, test } from "bun:test";
2
+ import { chmodSync, mkdtempSync, readdirSync, rmSync, truncateSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createTransfers, TransferFault } from "../src/interfaces/protocol/transfers.ts";
6
+ import { HarnessClient } from "../src/client.ts";
7
+ import type { ClientTransport, RpcRequest, RpcResponse } from "../src/contracts/protocol.ts";
8
+
9
+ const root = mkdtempSync(join(tmpdir(), "harness-transfers-test-"));
10
+ afterAll(() => { chmodSync(root, 0o700); rmSync(root, { recursive: true, force: true }); });
11
+ const fresh = () => mkdtempSync(join(root, "t-"));
12
+ const hash = "0".repeat(64);
13
+ const limits = { chunkBytes: 4, maxBytes: 64, idleMs: 60000 } as never;
14
+ const files = (directory: string) => readdirSync(directory).filter(name => name.startsWith(".transfer-"));
15
+
16
+ test("an upload whose file cannot be created frees the connection's one transfer slot", () => {
17
+ const directory = fresh();
18
+ const transfers = createTransfers(directory, limits);
19
+ // Read-only directory: creating the transfer file fails (not when running as root).
20
+ chmodSync(directory, 0o500);
21
+ let refused = false;
22
+ try { transfers.openUpload(8, hash); } catch (error) { refused = !(error instanceof TransferFault); }
23
+ chmodSync(directory, 0o700);
24
+ // Root ignores directory permissions, so the failure cannot be provoked there.
25
+ if (process.getuid?.() === 0) { transfers.dispose(); return; }
26
+ expect(refused).toBe(true);
27
+ // The failed open did not leave the slot occupied.
28
+ const id = transfers.openUpload(8, hash);
29
+ expect(transfers.write(id, 0, Buffer.from("abcd").toString("base64"))).toBe(4);
30
+ transfers.dispose();
31
+ expect(files(directory)).toEqual([]);
32
+ });
33
+
34
+ test("a failed append ends the upload instead of leaving an offset that cannot be retried", () => {
35
+ const directory = fresh();
36
+ const transfers = createTransfers(directory, limits);
37
+ const id = transfers.openUpload(8, hash);
38
+ expect(transfers.write(id, 0, Buffer.from("abcd").toString("base64"))).toBe(4);
39
+ // Make the file unwritable underneath the open transfer.
40
+ const path = join(directory, files(directory)[0]!);
41
+ rmSync(path); chmodSync(directory, 0o500);
42
+ let failed = false;
43
+ try { transfers.write(id, 4, Buffer.from("efgh").toString("base64")); } catch (error) { failed = !(error instanceof TransferFault); }
44
+ chmodSync(directory, 0o700);
45
+ // Root ignores directory permissions, so the failure cannot be provoked there.
46
+ if (process.getuid?.() === 0) { transfers.dispose(); return; }
47
+ expect(failed).toBe(true);
48
+ // The transfer is gone: the same offset cannot be appended twice, and a new one can open.
49
+ expect(() => transfers.write(id, 4, Buffer.from("efgh").toString("base64"))).toThrow("Unknown transfer");
50
+ expect(typeof transfers.openUpload(8, hash)).toBe("string");
51
+ transfers.dispose();
52
+ });
53
+
54
+ test("a download returns only the bytes it read and reports the end only at the announced length", () => {
55
+ const directory = fresh();
56
+ const transfers = createTransfers(directory, limits);
57
+ const id = transfers.offer(new TextEncoder().encode("abcdefghij"), hash);
58
+ expect(transfers.read(id, 0)).toEqual({ data: Buffer.from("abcd").toString("base64"), eof: false });
59
+ expect(transfers.read(id, 8)).toEqual({ data: Buffer.from("ij").toString("base64"), eof: true });
60
+ // The file loses its tail underneath the transfer: a short read is short, and is not the end.
61
+ truncateSync(join(directory, files(directory)[0]!), 6);
62
+ expect(transfers.read(id, 4)).toEqual({ data: Buffer.from("ef").toString("base64"), eof: false });
63
+ expect(transfers.read(id, 6)).toEqual({ data: "", eof: false });
64
+ transfers.dispose();
65
+ expect(files(directory)).toEqual([]);
66
+ });
67
+
68
+ test("startup removes only transfer files whose process is gone", () => {
69
+ const directory = fresh();
70
+ const dead = Bun.spawnSync(["true"]).pid;
71
+ // PID 1 exists and cannot be signalled by an unprivileged process (EPERM); as root the signal simply succeeds.
72
+ for (const pid of [dead, 1, process.pid]) writeFileSync(join(directory, `.transfer-${pid}-left`), "x");
73
+ writeFileSync(join(directory, "session.sqlite"), "x");
74
+ createTransfers(directory, limits).dispose();
75
+ expect(readdirSync(directory).sort()).toEqual([`.transfer-1-left`, `.transfer-${process.pid}-left`, "session.sqlite"].sort());
76
+ });
77
+
78
+ test("a download that stops making progress fails the export instead of reading the same offset again", async () => {
79
+ for (const stalled of [{ data: "", eof: false }, { data: Buffer.from("too many bytes").toString("base64"), eof: false }]) {
80
+ const requests: RpcRequest[] = [];
81
+ let deliver!: (message: RpcResponse) => void;
82
+ const transport: ClientTransport = { subscribe(listener) { deliver = listener as typeof deliver; return () => {}; }, onClose: () => () => {}, close() {},
83
+ send(request) {
84
+ requests.push(request);
85
+ const result = request.method === "session/export" ? { bytes: 8, sha256: hash, transferId: "t" } : request.method === "transfer/read" ? stalled : {};
86
+ queueMicrotask(() => deliver({ jsonrpc: "2.0", id: request.id, result }));
87
+ } };
88
+ const client = new HarnessClient(transport, 500);
89
+ await expect(client.exportArchive()).rejects.toMatchObject({ code: "invalid_archive" });
90
+ // One read, then the transfer was closed.
91
+ expect(requests.map(request => request.method)).toEqual(["session/export", "transfer/read", "transfer/close"]);
92
+ client.close();
93
+ }
94
+ });
@@ -0,0 +1,35 @@
1
+ import { expect, test } from "bun:test";
2
+ import { serveWebChat } from "../src/interfaces/web-chat/server.ts";
3
+ import { createChannelHandler } from "../src/interfaces/protocol/local.ts";
4
+ import { createChannelOutputs, publishChannelEvent } from "../src/interfaces/protocol/output.ts";
5
+ import { createSession } from "../src/index.ts";
6
+ import { lastInput } from "./helpers/session.ts";
7
+
8
+ test("LAN chat uses the same agent, requires pairing and delivers notice-started output", async () => {
9
+ const outputs = createChannelOutputs();
10
+ const session = createSession({ systemPrompt: "test", configureTurn: () => ({
11
+ model: async messages => ({ role: "assistant", content: lastInput(messages), calls: [] }),
12
+ tools: [], executeTool: async () => "unused",
13
+ }) });
14
+ session.subscribe(event => publishChannelEvent(outputs, event));
15
+ session.start();
16
+ const agent = session.agent;
17
+ const chat = serveWebChat(createChannelHandler(session, outputs), 0, "test-pairing");
18
+ const base = `http://127.0.0.1:${chat.server.port}`;
19
+ let reader: { cancel(): Promise<void> } | undefined;
20
+ try {
21
+ expect((await fetch(base)).status).toBe(200);
22
+ expect((await fetch(`${base}/events?channelId=bob`)).status).toBe(401);
23
+ expect((await fetch(`${base}/state?token=test-pairing`)).status).toBe(404);
24
+ expect((await fetch(`${base}/messages`, { method: "POST", headers: { Authorization: "Bearer test-pairing", Origin: "http://elsewhere" }, body: "{}" })).status).toBe(403);
25
+ const events = await fetch(`${base}/events?channelId=bob&token=test-pairing`);
26
+ const stream = events.body!.getReader(); reader = stream;
27
+ expect(new TextDecoder().decode((await stream.read()).value)).toContain("event: ready");
28
+ const response = await fetch(`${base}/messages`, { method: "POST", headers: { Authorization: "Bearer test-pairing", Origin: base },
29
+ body: JSON.stringify({channelId:"bob",participantId:"bob",text:"hello"}) });
30
+ expect(await response.json()).toEqual({ answer: "hello" });
31
+ expect(new TextDecoder().decode((await stream.read()).value)).toContain('"text":"hello"');
32
+ expect(agent.notify({ channelId: "bob", fromChannelId: "alice", text: "Alice says hi" }).accepted).toBe(true);
33
+ expect(new TextDecoder().decode((await stream.read()).value)).toContain("Alice says hi");
34
+ } finally { await reader?.cancel(); await chat.server.stop(true); }
35
+ });
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "lib": ["ESNext"],
4
+ "target": "ESNext",
5
+ "module": "Preserve",
6
+ "moduleResolution": "bundler",
7
+ "moduleDetection": "force",
8
+ "allowImportingTsExtensions": true,
9
+ "verbatimModuleSyntax": true,
10
+ "noEmit": true,
11
+ "strict": true,
12
+ "skipLibCheck": true,
13
+ "noUncheckedIndexedAccess": true,
14
+ "noFallthroughCasesInSwitch": true,
15
+ "noImplicitOverride": true,
16
+ "types": ["bun"]
17
+ },
18
+ "include": ["**/*.ts"],
19
+ "exclude": ["node_modules", ".res"]
20
+ }