@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,71 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync, existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { spawnHarness } from "./helpers/stdio.ts";
6
+ import type { ChannelEvent } from "../src/contracts/events.ts";
7
+ const script = new URL("./fixtures/model-e2e.jsonl", import.meta.url).pathname;
8
+ const until = async (fn: () => boolean, what: string) => { for (let i = 0; i < 1000; i++) { if (fn()) return; await new Promise(resolve => setTimeout(resolve, 5)); } throw new Error(`Timed out: ${what}`); };
9
+ const push = (channel: string, id: string) => ({ channel, item: { id, kind: "user_message" as const, sender: channel, content: [{ type: "text" as const, text: id }] } });
10
+
11
+ test("scripted stdio: partial reply times out without retry while another channel completes, then reopen retains evidence", async () => {
12
+ const home = mkdtempSync(join(tmpdir(), "harness-model-e2e-")), effects = join(home, "effects.log");
13
+ const first = spawnHarness({ home, effects, stallChannel: "alice", modelTimeoutMs: 1500 }); const events: ChannelEvent[] = [];
14
+ let closed = false;
15
+ try {
16
+ first.client.onChannelEvent(event => events.push(event));
17
+ await first.client.initialize({ protocolVersion: 1, host: { name: "test", version: "0" }, callbacks: [], subscription: { text: "stream", tools: "full" } });
18
+ await first.client.createSession({ sessionId: "s", participants: [], channels: {}, config: { version: 1, system: "test", model: { protocol: "scripted", script }, defaultPolicy: "allow", policies: { allow: { fallback: "allow", tools: {} } } } });
19
+ await first.client.push(push("alice", "a1"));
20
+ await until(() => events.some(event => event.channel === "alice" && event.event.type === "text_delta"), "Alice partial");
21
+ const delta = events.find(event => event.channel === "alice" && event.event.type === "text_delta")!.event;
22
+ if (delta.type !== "text_delta") throw new Error("missing delta"); expect(delta.text).toBe("Partial reply");
23
+ await first.client.push(push("bob", "b1"));
24
+ await until(() => events.some(event => event.channel === "bob" && event.event.type === "turn_ended" && event.event.outcome === "completed"), "Bob completes");
25
+ await until(() => events.some(event => event.channel === "alice" && event.event.type === "turn_ended" && event.event.outcome === "failed"), "Alice times out");
26
+ expect(events.find(event => event.channel === "alice" && event.event.type === "text_incomplete")?.event).toMatchObject({ messageId: delta.messageId, reason: "timeout" });
27
+ expect(events.find(event => event.channel === "alice" && event.event.type === "turn_ended")?.event).toMatchObject({ outcome: "failed", error: "timeout" });
28
+ expect(events.findIndex(event => event.channel === "bob" && event.event.type === "turn_ended")).toBeLessThan(events.findIndex(event => event.channel === "alice" && event.event.type === "turn_ended"));
29
+ expect(events.some(event => event.channel === "alice" && event.event.type === "message_completed")).toBe(false);
30
+ expect(existsSync(effects) ? readFileSync(effects, "utf8") : "").toBe("");
31
+ expect(events.some(event => event.channel === "alice" && event.event.type === "tool_call")).toBe(false);
32
+ const summaries = (await first.client.modelCalls()).calls, alice = summaries.find(call => call.channel === "alice")!;
33
+ expect(alice).toMatchObject({ messageId: delta.messageId, outcome: "timeout", attempts: [{ outcome: "timeout", usage: { inputTokens: 7 }, scriptStep: 0 }] });
34
+ expect(alice.attempts).toHaveLength(1);
35
+ expect(summaries.find(call => call.channel === "bob")?.outcome).toBe("succeeded");
36
+ await first.client.push(push("alice", "a2"));
37
+ await until(() => events.some(event => event.channel === "alice" && event.event.type === "message_completed"), "fresh work");
38
+ await until(() => events.filter(event => event.channel === "alice" && event.event.type === "turn_ended").length === 2, "fresh turn ends");
39
+ expect(events.find(event => event.channel === "alice" && event.event.type === "message_completed")?.event).toMatchObject({ parts: [{ text: "Fresh work completed" }] });
40
+ await first.close(); closed = true;
41
+ const second = spawnHarness({ home });
42
+ try {
43
+ await second.client.initialize(); await second.client.openSession({ sessionId: "s" });
44
+ const loaded = await second.client.reconcileChannel({ channel: "alice", itemIds: ["a1"] });
45
+ expect(loaded.items.find(item => item.id === "a1")?.milestone).toBe("seen");
46
+ expect((await second.client.channelMessages({ channel: "alice" })).messages.some(message => message.messageId === delta.messageId)).toBe(false);
47
+ const restored = (await second.client.modelCalls()).calls.find(call => call.callId === alice.callId);
48
+ expect(restored).toMatchObject({ outcome: "timeout", attempts: [{ usage: { inputTokens: 7 }, outcome: "timeout" }] });
49
+ } finally { await second.close(); }
50
+ } finally { if (!closed) await first.close(); rmSync(home, { recursive: true, force: true }); }
51
+ }, 15000);
52
+
53
+ for (const mode of ["in-process", "stdio"] as const) for (const text of ["final", "stream"] as const)
54
+ test(`${mode} ${text}: text-and-tool response and later reply retain message boundaries`, async () => {
55
+ const { createInProcessHarness } = await import("../src/testing.ts");
56
+ const home = mkdtempSync(join(tmpdir(), "model-modes-")), options = { home, streamResponses: true };
57
+ const harness = mode === "stdio" ? spawnHarness(options) : createInProcessHarness(options), events: ChannelEvent[] = [];
58
+ const echoScript = new URL("./fixtures/echo-scenario.jsonl", import.meta.url).pathname;
59
+ try {
60
+ harness.client.onChannelEvent(event => events.push(event));
61
+ await harness.client.initialize({ protocolVersion: 1, host: { name: "test", version: "0" }, callbacks: [], subscription: { text, tools: "full" } });
62
+ await harness.client.createSession({ sessionId: "s", participants: [], channels: {}, config: { version: 1, system: "test", model: { protocol: "scripted", script: echoScript }, defaultPolicy: "allow", policies: { allow: { fallback: "allow", tools: {} } } } });
63
+ await harness.client.push(push("alice", "m")); await until(() => events.some(event => event.event.type === "turn_ended"), "turn completion");
64
+ const ordered = events.map(event => event.event), completed = ordered.filter(event => event.type === "message_completed"), deltas = ordered.filter(event => event.type === "text_delta");
65
+ expect(completed).toHaveLength(2); expect(completed.map(event => event.parts?.[0]?.text)).toEqual(["I'll echo that.", "The tool returned hello."]);
66
+ expect(ordered.findIndex(event => event.type === "message_completed")).toBeLessThan(ordered.findIndex(event => event.type === "tool_call" && event.status === "started"));
67
+ if (text === "stream") { expect(deltas.map(event => event.messageId)).toEqual(completed.map(event => event.messageId!)); }
68
+ else expect(deltas).toEqual([]);
69
+ const loaded = await harness.client.channelMessages({ channel: "alice" }); expect(loaded.messages.filter(message => message.actor.kind === "agent").map(message => message.messageId)).toEqual(completed.map(event => event.messageId!));
70
+ } finally { await harness.close(); rmSync(home, { recursive: true, force: true }); }
71
+ }, 15000);
@@ -0,0 +1,30 @@
1
+ import { expect, test } from "bun:test";
2
+ import { createProtocolServer } from "../src/interfaces/protocol/server.ts";
3
+ import { HarnessClient, createInProcessTransport } from "../src/client.ts";
4
+ import type { PersistentSession } from "../src/contracts/session.ts";
5
+ import type { ChannelEvent, EventSink } from "../src/contracts/events.ts";
6
+
7
+ test("final subscription filters ephemeral text and keeps committed and lifecycle events", async () => {
8
+ let publish!: EventSink;
9
+ const session = { subscribe(listener: EventSink) { publish = listener; return () => {}; }, subscribeSession() { return () => {}; },
10
+ approvals: { setConsumer() {}, disconnect() {} }, start() {} } as unknown as PersistentSession;
11
+ const server = createProtocolServer(async () => ({ session, close() {} }));
12
+ const client = new HarnessClient(createInProcessTransport(server)); const received: ChannelEvent[] = [];
13
+ try {
14
+ await client.initialize(); await client.createSession({ sessionId: "s", participants: [], channels: {} });
15
+ client.onChannelEvent(event => received.push(event));
16
+ const events: ChannelEvent[] = [
17
+ { channel: "a", event: { type: "text_delta", turnId: "1", messageId: "m", text: "partial" } },
18
+ { channel: "a", event: { type: "text_gap", turnId: "1", messageId: "m" } },
19
+ { channel: "a", event: { type: "text_incomplete", turnId: "1", messageId: "m", reason: "failed" } },
20
+ { channel: "a", revision: 1, event: { type: "items_receipt", turnId: "1", items: ["x"], milestone: "seen" } },
21
+ { channel: "a", revision: 2, event: { type: "message_completed", turnId: "1", messageId: "m", parts: [{ type: "text", text: "done" }] } },
22
+ { channel: "a", event: { type: "tool_call", turnId: "1", id: "tool", name: "echo", status: "started" } },
23
+ { channel: "a", revision: 3, event: { type: "turn_ended", turnId: "1", outcome: "completed" } },
24
+ ];
25
+ events.forEach(publish);
26
+ await new Promise(resolve => setTimeout(resolve, 0));
27
+ expect(received.map(event => event.event.type)).toEqual(["items_receipt", "message_completed", "tool_call", "turn_ended"]);
28
+ expect(received[1]?.event).toMatchObject({ messageId: "m", parts: [{ text: "done" }] });
29
+ } finally { client.close(); server.dispose(); }
30
+ });
@@ -0,0 +1,28 @@
1
+ import { modelScenario } from "./helpers/scenario.ts";
2
+ import { expect, test } from "bun:test";
3
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { createInProcessHarness } from "../src/testing.ts";
7
+ import { spawnHarness } from "./helpers/stdio.ts";
8
+ import type { ChannelEvent } from "../src/contracts/events.ts";
9
+ for (const mode of ["in-process", "stdio"] as const) test(`${mode}: oversized completion is a stable reference readable in bounded byte pages`, async () => {
10
+ const home = mkdtempSync(join(tmpdir(), "large-model-")), script = join(home, "script.jsonl"), answer = "🚀".repeat(300_000);
11
+ writeFileSync(script, modelScenario([{ content: answer }]));
12
+ const harness = mode === "stdio" ? spawnHarness({ home }) : createInProcessHarness({ home }); const events: ChannelEvent[] = [];
13
+ try {
14
+ harness.client.onChannelEvent(event => events.push(event)); await harness.client.initialize();
15
+ await harness.client.createSession({ sessionId: "s", participants: [], channels: {}, config: { version: 1, system: "test", model: { protocol: "scripted", script }, defaultPolicy: "allow", policies: { allow: { fallback: "allow", tools: {} } } } });
16
+ await harness.client.push({ channel: "a", item: { id: "i", kind: "user_message", sender: "u", content: [{ type: "text", text: "hi" }] } });
17
+ for (let i = 0; i < 600 && !events.some(e => e.event.type === "turn_ended"); i++) await new Promise(resolve => setTimeout(resolve, 5));
18
+ const completion = events.find(e => e.event.type === "message_completed")?.event;
19
+ if (!completion || completion.type !== "message_completed" || !completion.messageId) throw new Error("missing completion");
20
+ expect(completion.reference).toBe(true); expect(completion.parts).toBeUndefined();
21
+ const buffers: Buffer[] = []; let offset = 0;
22
+ for (;;) { const page = await harness.client.request("session/message/read", { messageId: completion.messageId, offset });
23
+ const bytes = Buffer.from(page.data, "base64"); expect(bytes.length).toBeLessThanOrEqual(524288); buffers.push(bytes);
24
+ if (page.nextOffset === undefined) break; offset = page.nextOffset; }
25
+ expect(Buffer.concat(buffers).toString("utf8")).toBe(answer);
26
+ const loaded = await harness.client.channelMessages({ channel: "a" }); expect(loaded.messages.find(message => message.actor.kind === "agent")).toMatchObject({ messageId: completion.messageId, reference: true });
27
+ } finally { await harness.close(); rmSync(home, { recursive: true, force: true }); }
28
+ }, 15000);
@@ -0,0 +1,33 @@
1
+ import { expect, test } from "bun:test";
2
+ import { LiveQueue } from "../src/interfaces/protocol/live-queue.ts";
3
+ const message = (event: object) => ({ jsonrpc: "2.0", method: "channel/event", params: { channel: "a", event } });
4
+ test("a slow consumer drops deltas with one gap and keeps completion in order", async () => {
5
+ const sent: any[] = []; let release!: () => void, first = true;
6
+ const queue = new LiveQueue(async value => { sent.push(value); if (first) { first = false; await new Promise<void>(resolve => { release = resolve; }); } }, () => {}, 800);
7
+ queue.send(message({ type: "text_delta", turnId: "1", messageId: "m", text: "a".repeat(200) }));
8
+ queue.send(message({ type: "text_delta", turnId: "1", messageId: "m", text: "b".repeat(200) }));
9
+ queue.send(message({ type: "text_delta", turnId: "1", messageId: "m", text: "c".repeat(300) }));
10
+ queue.send(message({ type: "text_delta", turnId: "1", messageId: "m", text: "d" }));
11
+ release(); await queue.flush();
12
+ queue.send(message({ type: "message_completed", turnId: "1", messageId: "m", reference: true })); await queue.flush();
13
+ expect(sent.map(item => item.params.event.type)).toEqual(["text_delta", "text_delta", "text_gap", "message_completed"]);
14
+ expect(sent.filter(item => item.params.event.type === "text_gap")).toHaveLength(1);
15
+ });
16
+ test("a fully blocked queue refuses nondroppable events", () => {
17
+ const queue = new LiveQueue(() => new Promise<void>(() => {}), () => {}, 350);
18
+ queue.send(message({ type: "text_delta", turnId: "1", messageId: "m", text: "a".repeat(200) }));
19
+ expect(() => queue.send(message({ type: "turn_ended", turnId: "2", outcome: "completed", error: "b".repeat(200) }))).toThrow("queue");
20
+ });
21
+
22
+ test("a nondroppable overflow fails stdio and stops the session", async () => {
23
+ const { serveProtocolStdio } = await import("../src/interfaces/protocol/stdio-server.ts");
24
+ let publish!: (value: any) => void, stopped = false;
25
+ const endpoint = { subscribe(listener: (value: any) => void) { publish = listener; return () => {}; },
26
+ request: async (request: { method: string }) => { if (request.method === "session/stop") stopped = true; return { jsonrpc: "2.0" as const, id: 1, result: {} }; },
27
+ disconnect() {} };
28
+ const input = new ReadableStream<Uint8Array>({ start() {} });
29
+ const running = serveProtocolStdio(endpoint, input, () => new Promise<void>(() => {}));
30
+ const large = message({ type: "turn_ended", turnId: "1", outcome: "failed", error: "x".repeat(700_000) });
31
+ publish(large); publish(large);
32
+ await expect(running).rejects.toThrow("queue"); expect(stopped).toBe(true);
33
+ });
@@ -0,0 +1,117 @@
1
+ import { expect, test } from "bun:test";
2
+ import { runModelCall } from "../src/capabilities/model/runner.ts";
3
+ import type { ModelAttempt, ModelAttemptEvent, ModelCallStore } from "../src/contracts/model-execution.ts";
4
+
5
+ const success = { role: "assistant" as const, content: "done", calls: [], stopReason: "complete" as const };
6
+ const ok = <T>(value: T) => ({ ok: true as const, value, revision: 1 });
7
+ function harness(scripts: ModelAttemptEvent[][]) {
8
+ const records: string[] = [], requests: unknown[] = [];
9
+ let index = 0;
10
+ const store = {
11
+ startCall: () => ok({ callId: "c", messageId: "m" }),
12
+ startAttempt: () => { const id = String(index++); records.push(`start:${id}`); return ok({ attemptId: id, scriptStep: Number(id) }); },
13
+ recordProviderRequestId: () => ok(undefined), confirm: () => ok([]), recordUsage: () => ok(undefined),
14
+ finishAttempt: (_c: string, id: string, outcome: string) => { records.push(`${id}:${outcome}`); return ok(undefined); },
15
+ finishCall: (_c: string, outcome: string) => { records.push(`call:${outcome}`); return ok(undefined); },
16
+ commitResponse: () => { records.push("commit"); return ok({}); },
17
+ } as unknown as ModelCallStore;
18
+ const attempt = (step?: number): ModelAttempt => async function* (request) { requests.push(structuredClone(request)); for (const e of scripts[step!] ?? []) yield e; };
19
+ const run = (delta?: (event: { messageId: string; text: string }) => void) => runModelCall({ turnId: "1", itemIds: [], request: { messages: [], tools: [] }, scripted: true, store, attempt, delta, settings: { retryDelayMs: 1, timeoutMs: 1000 } });
20
+ return { records, requests, run, store };
21
+ }
22
+ test("transient pre-output failure retries one identical frozen request", async () => {
23
+ const h = harness([[{ type: "seen" }, { type: "failure", kind: "transient", message: "try" }], [{ type: "response", response: success }]]);
24
+ expect(await h.run()).toMatchObject({ messageId: "m", response: success });
25
+ expect(h.requests).toHaveLength(2); expect(h.requests[0]).toEqual(h.requests[1]);
26
+ expect(h.records).toEqual(["start:0", "0:transient_failure", "start:1", "commit"]);
27
+ });
28
+ for (const deliver of [false, true]) test(`partial text closes retry with ${deliver ? "stream" : "final"} delivery`, async () => {
29
+ const h = harness([[{ type: "text_delta", text: "partial" }, { type: "failure", kind: "transient", message: "try" }], [{ type: "response", response: success }]]);
30
+ const events: string[] = []; await expect(h.run(deliver ? e => events.push(e.text) : undefined)).rejects.toMatchObject({ outcome: "failed" });
31
+ expect(h.requests).toHaveLength(1); expect(h.records).not.toContain("commit"); expect(events).toEqual(deliver ? ["partial"] : []);
32
+ });
33
+ test("a malformed tool request is never committed", async () => {
34
+ const h = harness([[{ type: "response", response: { role: "assistant", content: null, stopReason: "tool_calls", calls: [{ id: "x", name: "a", arguments: "{" }] } }]]);
35
+ await expect(h.run()).rejects.toMatchObject({ outcome: "failed" }); expect(h.records).not.toContain("commit");
36
+ });
37
+ test("interrupt fences a stalled adapter and its late terminal", async () => {
38
+ const h = harness([]), stop = new AbortController(); let release!: (value: IteratorResult<ModelAttemptEvent>) => void;
39
+ const iterator = { next: () => new Promise<IteratorResult<ModelAttemptEvent>>(resolve => { release = resolve; }) };
40
+ const promise = runModelCall({ turnId: "1", itemIds: [], request: { messages: [], tools: [] }, scripted: true, store: h.store,
41
+ attempt: () => () => ({ [Symbol.asyncIterator]: () => iterator }), signal: stop.signal, settings: { timeoutMs: 1000 } });
42
+ await Promise.resolve(); stop.abort(); await expect(promise).rejects.toMatchObject({ outcome: "interrupted" });
43
+ release({ done: false, value: { type: "response", response: success } }); await Promise.resolve(); expect(h.records).not.toContain("commit");
44
+ });
45
+
46
+ test("retry does not begin when the remaining deadline is shorter than its delay", async () => {
47
+ const h = harness([[{ type: "failure", kind: "transient", message: "try" }]]);
48
+ await expect(runModelCall({ turnId: "1", itemIds: [], request: { messages: [], tools: [] }, scripted: true, store: h.store,
49
+ attempt: () => async function* () { yield { type: "failure", kind: "transient", message: "try" }; }, settings: { timeoutMs: 10 } })).rejects.toMatchObject({ outcome: "timeout" });
50
+ expect(h.records).toEqual(["start:0", "0:transient_failure", "call:timeout"]);
51
+ });
52
+
53
+ test("provider output limit ends without committing or dispatchable tool requests", async () => {
54
+ const h = harness([[{ type: "text_delta", text: "partial" }, { type: "response", response: { role: "assistant", content: "partial", calls: [], stopReason: "output_limit" } }]]);
55
+ await expect(h.run()).rejects.toMatchObject({ outcome: "output_limit" });
56
+ expect(h.records).toEqual(["start:0", "0:output_limit", "call:output_limit"]);
57
+ });
58
+
59
+ test("timeout aborts a stalled attempt and ignores its late response", async () => {
60
+ const h = harness([]); let release!: (value: IteratorResult<ModelAttemptEvent>) => void; let signal!: AbortSignal;
61
+ const iterator = { next: () => new Promise<IteratorResult<ModelAttemptEvent>>(resolve => { release = resolve; }) };
62
+ const promise = runModelCall({ turnId: "1", itemIds: [], request: { messages: [], tools: [] }, scripted: true, store: h.store,
63
+ attempt: () => (_request, attemptSignal) => { signal = attemptSignal; return { [Symbol.asyncIterator]: () => iterator }; }, settings: { timeoutMs: 5 } });
64
+ await expect(promise).rejects.toMatchObject({ outcome: "timeout" }); expect(signal.aborted).toBe(true);
65
+ release({ done: false, value: { type: "response", response: success } }); await Promise.resolve(); expect(h.records).not.toContain("commit");
66
+ });
67
+
68
+ test("atomic model commit precedes tool dispatch in the turn loop", async () => {
69
+ const { runTurn } = await import("../src/kernel/loop.ts");
70
+ const h = harness([[{ type: "response", response: { role: "assistant", content: "working", stopReason: "tool_calls", calls: [{ id: "x", name: "echo", arguments: "{}" }] } }], [{ type: "response", response: success }]]);
71
+ const context = { append: () => { h.records.push("append-tool-result"); },
72
+ dispatchTool: async () => { h.records.push("dispatch"); return { content: "ok", dispatched: true }; },
73
+ finish: () => true };
74
+ const infer = async () => (await h.run()).response;
75
+ // Each logical call reserves its own attempt sequence in storage. Here use
76
+ // independent harnesses so the example can stop after the tool iteration.
77
+ let count = 0;
78
+ await runTurn({ ...context, checkpoint: () => count++ > 0 }, infer, async () => "ok");
79
+ expect(h.records).toEqual(["start:0", "commit", "dispatch", "append-tool-result"]);
80
+ });
81
+
82
+ test("interrupt during retry delay prevents the next attempt", async () => {
83
+ const h = harness([]), controller = new AbortController();
84
+ const promise = runModelCall({ turnId: "1", itemIds: [], request: { messages: [], tools: [] }, scripted: true, store: h.store, signal: controller.signal,
85
+ attempt: () => async function* () { yield { type: "failure", kind: "transient", message: "try" }; }, settings: { timeoutMs: 2000, retryDelayMs: 1000 } });
86
+ await new Promise(resolve => setTimeout(resolve, 2)); controller.abort();
87
+ await expect(promise).rejects.toMatchObject({ outcome: "interrupted" }); expect(h.records).toEqual(["start:0", "0:transient_failure", "call:interrupted"]);
88
+ });
89
+
90
+ test("a failed atomic response commit cannot produce a dispatchable response", async () => {
91
+ const h = harness([[{ type: "response", response: success }]]);
92
+ h.store.commitResponse = () => ({ ok: false, error: { code: "invalid_state", message: "turn fenced" } });
93
+ await expect(h.run()).rejects.toThrow("turn fenced"); expect(h.records).not.toContain("commit");
94
+ });
95
+
96
+ test("a stalled channel does not prevent an independent channel from completing", async () => {
97
+ const alice = harness([]), bob = harness([[{ type: "response", response: success }]]), stop = new AbortController();
98
+ const pending = runModelCall({ turnId: "alice", itemIds: [], request: { messages: [], tools: [] }, scripted: true, store: alice.store,
99
+ signal: stop.signal, attempt: () => () => ({ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }) }) });
100
+ expect((await bob.run()).response.content).toBe("done"); expect(bob.records).toContain("commit");
101
+ stop.abort(); await expect(pending).rejects.toMatchObject({ outcome: "interrupted" });
102
+ const fresh = harness([[{ type: "response", response: success }]]); expect((await fresh.run()).response.content).toBe("done");
103
+ });
104
+
105
+ test("scripted and OpenRouter attempt adapters run through the commit boundary", async () => {
106
+ const { scriptedAttempt } = await import("../src/capabilities/model/scripted.ts");
107
+ const { openRouterAttempt } = await import("../src/capabilities/model/openrouter-stream.ts");
108
+ const script = { version: 1, responses: [{ content: "scripted" }] }, first = harness([]);
109
+ const scripted = await runModelCall({ turnId: "1", itemIds: [], request: { messages: [], tools: [] }, scripted: true, store: first.store,
110
+ attempt: step => scriptedAttempt(script, step!) });
111
+ expect(scripted.response.content).toBe("scripted"); expect(first.records).toContain("commit");
112
+ const data = `data: ${JSON.stringify({ id: "r", choices: [{ delta: { content: "provider" }, finish_reason: "stop" }] })}\n\ndata: [DONE]\n\n`;
113
+ const fetcher = (async () => new Response(data)) as unknown as typeof fetch, second = harness([]), deltas: string[] = [];
114
+ const provider = await runModelCall({ turnId: "2", itemIds: [], request: { messages: [], tools: [] }, scripted: false, store: second.store,
115
+ attempt: () => openRouterAttempt("fake", "model", fetcher), delta: event => deltas.push(event.text) });
116
+ expect(provider.response.content).toBe("provider"); expect(deltas).toEqual(["provider"]); expect(second.records).toContain("commit");
117
+ });
@@ -0,0 +1,99 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { aggregateUsage } from "../src/capabilities/model/usage.ts";
6
+ import { createMemoryStorageAdapter } from "../src/state/storage/memory.ts";
7
+ import { createSqliteStorageAdapter } from "../src/state/storage/sqlite.ts";
8
+ import type { StorageResult } from "../src/contracts/storage.ts";
9
+ const take = <T>(result: StorageResult<T>): T => { if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`); return result.value; };
10
+ for (const kind of ["memory", "sqlite"] as const) test(`${kind}: model calls retain receipts, usage, identity and script reservations across reopen`, () => {
11
+ const dir = mkdtempSync(join(tmpdir(), "model-store-"));
12
+ const adapter = kind === "memory" ? createMemoryStorageAdapter() : createSqliteStorageAdapter(join(dir, "s.db"));
13
+ const identity = { sessionId: "s", compatibilityKey: "key" };
14
+ try {
15
+ let storage = take(adapter.open({ mode: "create", identity }));
16
+ take(storage.acceptItem({ itemId: "i", kind: "participant_message", channelId: "a", senderId: "u", text: "hello" }));
17
+ const turn = take(storage.beginTurn("a"))!.turn, call = take(storage.startCall(String(turn.turnId), ["i"]));
18
+ const attempt = take(storage.startAttempt(call.callId, true)); expect(attempt.scriptStep).toBe(0);
19
+ take(storage.recordProviderRequestId(call.callId, attempt.attemptId, "provider")); take(storage.confirm(call.callId, attempt.attemptId, "seen"));
20
+ take(storage.recordUsage(call.callId, attempt.attemptId, { inputTokens: 9 }));
21
+ expect(storage.recordUsage(call.callId, attempt.attemptId, { inputTokens: -1 }).ok).toBe(false);
22
+ take(storage.close()); storage = take(adapter.open({ mode: "open", identity }));
23
+ const view = take(storage.snapshot()); expect(take(storage.readCalls()).calls).toEqual(view.modelCalls); expect(view.items[0]!.milestone).toBe("seen");
24
+ expect(view.modelCalls[0]).toMatchObject({ outcome: "interrupted", attempts: [{ outcome: "interrupted", providerRequestId: "provider", usage: { inputTokens: 9 }, scriptStep: 0 }] });
25
+ expect(view.scriptPositions.a).toBe(1);
26
+ take(storage.acceptItem({ itemId: "i2", kind: "participant_message", channelId: "a", senderId: "u", text: "next" }));
27
+ const nextTurn = take(storage.beginTurn("a"))!.turn, next = take(storage.startCall(String(nextTurn.turnId), ["i2"]));
28
+ expect(next.messageId).not.toBe(call.messageId);
29
+ const nextAttempt = take(storage.startAttempt(next.callId, true)); expect(nextAttempt.scriptStep).toBe(1);
30
+ const response = { role: "assistant" as const, content: "done", calls: [], stopReason: "complete" as const };
31
+ take(storage.commitResponse(next.callId, nextAttempt.attemptId, response));
32
+ const committed = take(storage.snapshot()); expect(committed.modelCalls.at(-1)?.outcome).toBe("succeeded");
33
+ expect(committed.timeline.at(-1)?.messageId).toBe(next.messageId);
34
+ take(storage.finishTurn(nextTurn.turnId, { status: "completed" }));
35
+ const archive = take(storage.exportArchive()); expect(archive.archiveVersion).toBe(5);
36
+ const destination = kind === "memory" ? createMemoryStorageAdapter() : createSqliteStorageAdapter(join(dir, "copy.db"));
37
+ take(destination.importArchive(archive));
38
+ const copy = take(destination.open({ mode: "open", identity })); expect(take(copy.readCalls("1", 1)).calls).toEqual(committed.modelCalls.slice(1)); expect(take(copy.snapshot()).timeline.at(-1)?.messageId).toBe(next.messageId); take(copy.close());
39
+ take(storage.close());
40
+ storage = take(adapter.open({ mode: "open", identity })); expect(take(storage.snapshot()).timeline.at(-1)?.messageId).toBe(next.messageId); take(storage.close());
41
+ } finally { rmSync(dir, { recursive: true, force: true }); }
42
+ });
43
+
44
+ for (const kind of ["memory", "sqlite"] as const) test(`${kind}: interrupted channel accepts and completes fresh input`, async () => {
45
+ const { createSession } = await import("../src/index.ts");
46
+ const dir = mkdtempSync(join(tmpdir(), "model-channel-")), adapter = kind === "memory" ? createMemoryStorageAdapter() : createSqliteStorageAdapter(join(dir, "s.db"));
47
+ const storage = take(adapter.open({ mode: "create", identity: { sessionId: "s", compatibilityKey: "key" } }));
48
+ let entered = false, release!: () => void, runs = 0;
49
+ const session = createSession({ systemPrompt: "test", storage, configureTurn: () => ({ tools: [], executeTool: async () => "unused", model: async () => {
50
+ if (++runs === 1) { entered = true; await new Promise<void>(resolve => { release = resolve; }); return { role: "assistant", content: "late", calls: [] }; }
51
+ return { role: "assistant", content: "fresh", calls: [] };
52
+ } }) });
53
+ const until = async (check: () => boolean) => { for (let i = 0; i < 500; i++) { if (check()) return; await new Promise(resolve => setTimeout(resolve, 5)); } throw new Error("timed out"); };
54
+ try {
55
+ session.start(); expect(session.agent.send({ channelId: "a", participantId: "u", itemId: "one", text: "first" }).accepted).toBe(true);
56
+ await until(() => entered); const turn = session.snapshot().turns[0]!;
57
+ expect(session.channels.interrupt("a", turn.turnId).ok).toBe(true);
58
+ expect(session.agent.send({ channelId: "a", participantId: "u", itemId: "two", text: "second" }).accepted).toBe(true);
59
+ await until(() => session.snapshot().turns.some(value => value.turnId !== turn.turnId && value.state.status === "completed"));
60
+ release(); await new Promise(resolve => setTimeout(resolve, 5));
61
+ expect(session.snapshot().timeline.filter(entry => entry.message.role === "assistant").map(entry => entry.message.content)).toEqual(["fresh"]);
62
+ } finally { session.stop("test complete"); storage.close(); rmSync(dir, { recursive: true, force: true }); }
63
+ });
64
+
65
+ for (const kind of ["memory", "sqlite"] as const) test(`${kind}: retry keeps absolute per-attempt usage without double counting`, () => {
66
+ const dir = mkdtempSync(join(tmpdir(), "model-usage-")), adapter = kind === "memory" ? createMemoryStorageAdapter() : createSqliteStorageAdapter(join(dir, "s.db"));
67
+ const identity = { sessionId: "s", compatibilityKey: "k" };
68
+ try {
69
+ let storage = take(adapter.open({ mode: "create", identity }));
70
+ take(storage.acceptItem({ itemId: "i", kind: "participant_message", channelId: "a", senderId: "u", text: "hi" }));
71
+ const turn = take(storage.beginTurn("a"))!.turn, call = take(storage.startCall(String(turn.turnId), ["i"]));
72
+ const first = take(storage.startAttempt(call.callId, true)); take(storage.recordUsage(call.callId, first.attemptId, { inputTokens: 2 }));
73
+ take(storage.recordUsage(call.callId, first.attemptId, { inputTokens: 4 })); take(storage.finishAttempt(call.callId, first.attemptId, "transient_failure"));
74
+ const second = take(storage.startAttempt(call.callId, true)); expect(second.scriptStep).toBe(1);
75
+ take(storage.recordUsage(call.callId, second.attemptId, { inputTokens: 3, outputTokens: 5 }));
76
+ take(storage.commitResponse(call.callId, second.attemptId, { role: "assistant", content: "ok", calls: [], stopReason: "complete" }));
77
+ take(storage.recordUsage(call.callId, second.attemptId, { inputTokens: 999 })); // late report is ignored
78
+ take(storage.finishTurn(turn.turnId, { status: "completed" })); take(storage.close()); storage = take(adapter.open({ mode: "open", identity }));
79
+ const summary = take(storage.readCalls()).calls[0]!; expect(summary.attempts.map(value => value.usage)).toEqual([{ inputTokens: 4 }, { inputTokens: 3, outputTokens: 5 }]);
80
+ expect(aggregateUsage(summary.attempts)).toEqual({ inputTokens: 7, outputTokens: 5 });
81
+ expect(summary.attempts.some(item => item.usage?.totalTokens !== undefined)).toBe(false); take(storage.close());
82
+ } finally { rmSync(dir, { recursive: true, force: true }); }
83
+ });
84
+
85
+ test("format 4 upgrades its script counter once from assistant history", async () => {
86
+ const { Database } = await import("bun:sqlite"), dir = mkdtempSync(join(tmpdir(), "model-v4-")), path = join(dir, "s.db"), identity = { sessionId: "s", compatibilityKey: "k" };
87
+ const adapter = createSqliteStorageAdapter(path);
88
+ try {
89
+ let storage = take(adapter.open({ mode: "create", identity }));
90
+ take(storage.acceptItem({ itemId: "i", kind: "participant_message", channelId: "a", senderId: "u", text: "hi" }));
91
+ const turn = take(storage.beginTurn("a"))!.turn;
92
+ take(storage.appendMessage(turn.turnId, { role: "assistant", content: "one", calls: [] }));
93
+ take(storage.appendMessage(turn.turnId, { role: "assistant", content: "two", calls: [] }));
94
+ take(storage.finishTurn(turn.turnId, { status: "completed" })); take(storage.close());
95
+ const db = new Database(path); db.exec("UPDATE meta SET value = '4' WHERE key = 'formatVersion'; DELETE FROM meta WHERE key = 'modelState'; ALTER TABLE items DROP COLUMN external_source; ALTER TABLE entries DROP COLUMN external_source"); db.close();
96
+ storage = take(adapter.open({ mode: "open", identity })); expect(take(storage.snapshot()).scriptPositions.a).toBe(2); take(storage.close());
97
+ storage = take(adapter.open({ mode: "open", identity })); expect(take(storage.snapshot()).scriptPositions.a).toBe(2); take(storage.close());
98
+ } finally { rmSync(dir, { recursive: true, force: true }); }
99
+ });
@@ -0,0 +1,26 @@
1
+ import { expect, test } from "bun:test";
2
+ import { openRouterAttempt } from "../src/capabilities/model/openrouter-stream.ts";
3
+ import { scriptedAttempt } from "../src/capabilities/model/scripted.ts";
4
+
5
+ test("provider fragments assemble one tool call and usage before terminal", async () => {
6
+ const chunks = [
7
+ { id: "req", choices: [{ delta: { content: "hello", tool_calls: [{ index: 0, id: "call", function: { name: "echo", arguments: "{\"x\":" } }] } }] },
8
+ { choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: "1}" } }] }, finish_reason: "tool_calls" }] },
9
+ { choices: [], usage: { prompt_tokens: 4, completion_tokens: 2, total_tokens: 6 } },
10
+ ];
11
+ let wire: string | undefined;
12
+ const fetcher = (async (_url, init) => {
13
+ wire = String(init?.body);
14
+ return new Response(chunks.map(c => `data: ${JSON.stringify(c)}\n\n`).join("") + "data: [DONE]\n\n");
15
+ }) as typeof fetch;
16
+ const events = []; for await (const event of openRouterAttempt("secret", "model", fetcher)({ messages: [], tools: [], takenItemIds: ["local-item"] }, new AbortController().signal)) events.push(event);
17
+ expect(JSON.parse(wire!)).toEqual({ model: "model", stream: true, stream_options: { include_usage: true }, messages: [] });
18
+ expect(events.map(e => e.type)).toEqual(["accepted", "text_delta", "seen", "seen", "usage", "response"]);
19
+ expect(events.at(-1)).toMatchObject({ type: "response", providerRequestId: "req", response: { stopReason: "tool_calls", calls: [{ id: "call", name: "echo", arguments: '{"x":1}' }] } });
20
+ });
21
+
22
+ test("script adapter reads its explicitly reserved step", async () => {
23
+ const events = []; const script = { version: 1, responses: [{ content: "first" }, { content: "second" }] };
24
+ for await (const event of scriptedAttempt(script, 1)({ messages: [], tools: [] }, new AbortController().signal)) events.push(event);
25
+ expect(events).toMatchObject([{ type: "response", response: { content: "second", stopReason: "complete" } }]);
26
+ });
@@ -0,0 +1,77 @@
1
+ import { expect, test } from "bun:test";
2
+ import { createSession } from "../src/index.ts";
3
+ import { createProtocolServer } from "../src/interfaces/protocol/server.ts";
4
+ import { HarnessClient, createInProcessTransport } from "../src/client.ts";
5
+ import { bindModelAttempt } from "../src/capabilities/model/attempt.ts";
6
+ import type { Model } from "../src/contracts/loop.ts";
7
+ import type { ChannelEvent } from "../src/contracts/events.ts";
8
+
9
+ for (const text of ["final", "stream"] as const) test(`${text} subscription keeps model message IDs and completion before tool dispatch`, async () => {
10
+ const model: Model = async () => { throw new Error("attempt adapter expected"); }; let attempts = 0;
11
+ bindModelAttempt(model, { scripted: false, create: () => async function* () {
12
+ const first = ++attempts === 1; yield { type: "text_delta", text: first ? "working" : "done" };
13
+ yield { type: "response", response: { role: "assistant", content: first ? "working" : "done", stopReason: first ? "tool_calls" : "complete",
14
+ calls: first ? [{ id: "tool", name: "echo", arguments: "{}" }] : [] } };
15
+ } });
16
+ const session = createSession({ systemPrompt: "test", configureTurn: () => ({ model, tools: [], executeTool: async () => "ok" }) });
17
+ const server = createProtocolServer(async () => ({ session, close() {} }), { durable: true }), client = new HarnessClient(createInProcessTransport(server)); const events: ChannelEvent[] = [];
18
+ try {
19
+ client.onChannelEvent(event => events.push(event));
20
+ await client.initialize({ protocolVersion: 1, host: { name: "test", version: "0" }, callbacks: [], subscription: { text, tools: "full" } });
21
+ await client.createSession({ sessionId: "s", participants: [], channels: {} });
22
+ await client.push({ channel: "a", item: { id: "i", kind: "user_message", sender: "u", content: [{ type: "text", text: "hi" }] } });
23
+ for (let i = 0; i < 500 && !events.some(event => event.event.type === "turn_ended"); i++) await new Promise(resolve => setTimeout(resolve, 5));
24
+ const all = events.map(value => value.event), completed = all.filter(event => event.type === "message_completed"), deltas = all.filter(event => event.type === "text_delta");
25
+ expect(completed).toHaveLength(2); expect(all.findIndex(event => event.type === "message_completed")).toBeLessThan(all.findIndex(event => event.type === "tool_call" && event.status === "started"));
26
+ if (text === "stream") { expect(deltas).toHaveLength(2); expect(deltas.map(e => e.messageId)).toEqual(completed.map(e => e.messageId!)); }
27
+ else expect(deltas).toHaveLength(0);
28
+ const loaded = await client.channelMessages({ channel: "a" }); expect(loaded.messages.filter(message => message.actor.kind === "agent").map(message => message.messageId)).toEqual(completed.map(event => event.messageId!));
29
+ } finally { client.close(); server.dispose(); session.stop("done"); }
30
+ });
31
+
32
+ test("a slow streaming reader drops Alice deltas while Bob still commits", async () => {
33
+ const { LiveQueue } = await import("../src/interfaces/protocol/live-queue.ts");
34
+ const model: Model = async () => { throw new Error("attempt adapter expected"); };
35
+ const session = createSession({ systemPrompt: "test", configureTurn: turn => {
36
+ const bound: Model = (...args) => model(...args);
37
+ bindModelAttempt(bound, { scripted: false, create: () => async function* () {
38
+ const text = turn.channelId === "alice" ? "x".repeat(1_200_000) : "bob";
39
+ if (turn.channelId === "alice") { yield { type: "text_delta", text: text.slice(0, 600_000) }; yield { type: "text_delta", text: text.slice(600_000) }; }
40
+ else yield { type: "text_delta", text };
41
+ yield { type: "response", response: { role: "assistant", content: text, calls: [], stopReason: "complete" } };
42
+ } });
43
+ return { model: bound, tools: [], executeTool: async () => "unused" };
44
+ } });
45
+ const server = createProtocolServer(async () => ({ session, close() {} }), { durable: true });
46
+ const client = new HarnessClient(createInProcessTransport(server)); const sent: any[] = []; let release!: () => void, first = true, failure: unknown;
47
+ const queue = new LiveQueue(async item => { sent.push(item); if (first) { first = false; await new Promise<void>(resolve => { release = resolve; }); } }, error => { failure = error; });
48
+ try {
49
+ await client.initialize({ protocolVersion: 1, host: { name: "test", version: "0" }, callbacks: [], subscription: { text: "stream", tools: "full" } });
50
+ await client.createSession({ sessionId: "s", participants: [], channels: {} }); const unsubscribe = server.subscribe(value => queue.send(value));
51
+ session.agent.send({ channelId: "alice", participantId: "a", text: "hi" }); session.agent.send({ channelId: "bob", participantId: "b", text: "hi" });
52
+ for (let i = 0; i < 500 && !session.snapshot().turns.some(turn => turn.channelId === "bob" && turn.state.status === "completed"); i++) await new Promise(resolve => setTimeout(resolve, 5));
53
+ expect(session.snapshot().turns.find(turn => turn.channelId === "bob")?.state.status).toBe("completed"); expect(failure).toBeUndefined();
54
+ release(); await queue.flush(); unsubscribe();
55
+ expect(sent.some(value => value.params?.channel === "alice" && value.params.event.type === "text_gap")).toBe(true);
56
+ expect(session.snapshot().timeline.some(entry => entry.channelId === "bob" && entry.message.role === "assistant" && entry.message.content === "bob")).toBe(true);
57
+ } finally { client.close(); server.dispose(); session.stop("done"); }
58
+ });
59
+
60
+ test("a storage commit failure terminates an already published draft", async () => {
61
+ const { createMemoryStorageAdapter } = await import("../src/state/storage/memory.ts");
62
+ const opened = createMemoryStorageAdapter().open({ mode: "create", identity: { sessionId: "s", compatibilityKey: "k" } });
63
+ if (!opened.ok) throw new Error(opened.error.message); const storage = opened.value;
64
+ storage.commitResponse = () => ({ ok: false, error: { code: "storage_failure", message: "injected" } });
65
+ const model: Model = async () => { throw new Error("unused"); };
66
+ bindModelAttempt(model, { scripted: false, create: () => async function* () {
67
+ yield { type: "text_delta", text: "draft" }; yield { type: "response", response: { role: "assistant", content: "draft", calls: [], stopReason: "complete" } };
68
+ } });
69
+ const session = createSession({ systemPrompt: "test", storage, configureTurn: () => ({ model, tools: [], executeTool: async () => "unused" }) });
70
+ const events: ChannelEvent[] = []; session.subscribe(event => events.push(event)); session.start();
71
+ try {
72
+ session.agent.send({ channelId: "a", participantId: "u", text: "hi" });
73
+ for (let i = 0; i < 500 && !events.some(event => event.event.type === "turn_ended"); i++) await new Promise(resolve => setTimeout(resolve, 5));
74
+ expect(events.map(event => event.event.type)).toContain("text_incomplete");
75
+ expect(events.some(event => event.event.type === "message_completed")).toBe(false);
76
+ } finally { session.stop("done"); storage.close(); }
77
+ });
@@ -0,0 +1,64 @@
1
+ import { expect, test } from "bun:test";
2
+ import { createSession } from "../src/index.ts";
3
+ import { renderContextEntry } from "../src/capabilities/context/build.ts";
4
+ import { executeNotice } from "../src/capabilities/tools/builtin/notify-channel.ts";
5
+ import { ask, turnsEnd } from "./helpers/session.ts";
6
+
7
+ test("notices during inference keep the turn alive and are consumed once, without a pass limit", async () => {
8
+ let calls = 0;
9
+ const session = createSession({ systemPrompt: "system", configureTurn: turn => ({ tools: [], executeTool: async () => "unused",
10
+ model: async messages => {
11
+ calls++;
12
+ if (calls > 1) expect(messages.some(m => m.content?.includes(`Notice ${calls - 1}`))).toBe(true);
13
+ if (calls < 4) expect(session.agent.notify({ channelId: turn.channelId, fromChannelId: "charlie", text: `Notice ${calls}` }))
14
+ .toMatchObject({ accepted: true, duplicate: false, milestone: "received" });
15
+ return { role: "assistant", content: "done", calls: [] };
16
+ } }) });
17
+ session.start();
18
+ expect(await ask(session, { channelId: "bob", participantId: "bob", text: "work" })).toBe("done");
19
+ expect(calls).toBe(4);
20
+ expect(session.store.snapshot().filter(e => e.from === "channel:charlie")).toHaveLength(3);
21
+ expect(session.store.snapshot().filter(e => e.kind === "channel_notice").every(e => e.sourceChannelId === "charlie")).toBe(true);
22
+ expect(session.snapshot().turns).toHaveLength(1);
23
+ expect(session.snapshot().turns[0]!.itemIds).toHaveLength(4);
24
+ });
25
+
26
+ test("a notice that arrives as its target turn completes reaches exactly one later turn", async () => {
27
+ const requests: number[] = [];
28
+ const session = createSession({ systemPrompt: "system", configureTurn: turn => ({ tools: [], executeTool: async () => "unused",
29
+ model: async () => { requests.push(turn.turnId); return { role: "assistant", content: "done", calls: [] }; } }) });
30
+ session.start();
31
+ // The earliest possible moment after the finish commit: its own event.
32
+ let raced = false;
33
+ session.subscribe(({ event }) => {
34
+ if (event.type !== "turn_ended" || raced) return;
35
+ raced = true;
36
+ expect(session.agent.notify({ channelId: "bob", fromChannelId: "charlie", text: "Stop work" })).toMatchObject({ accepted: true });
37
+ });
38
+ const log = turnsEnd(session, 2);
39
+ session.agent.send({ channelId: "bob", participantId: "bob", text: "hello" });
40
+ await log.done;
41
+ expect(requests).toEqual([1, 2]);
42
+ const idle = turnsEnd(session);
43
+ expect(session.agent.notify({ channelId: "bob", fromChannelId: "charlie", text: "Idle notice" })).toMatchObject({ accepted: true });
44
+ await idle.done;
45
+ expect(requests).toEqual([1, 2, 3]);
46
+ const notices = session.store.snapshot().filter(e => e.kind === "channel_notice");
47
+ expect(notices.map(e => [e.turnId, e.message.content])).toEqual([[2, "Stop work"], [3, "Idle notice"]]);
48
+ expect(session.snapshot().items.filter(item => item.kind === "channel_notice").map(item => item.turnId)).toEqual([2, 3]);
49
+ const rendered = renderContextEntry(notices[0]!);
50
+ expect(rendered.content).toContain('Internal notice from channel "charlie"');
51
+ expect(rendered.content).not.toContain('Participant:');
52
+ expect(session.agent.notify({ channelId: "missing", fromChannelId: "charlie", text: "hello" }).accepted).toBe(false);
53
+ });
54
+
55
+ test("notify tool returns acceptance without waiting", () => {
56
+ const receipt = executeNotice({ channelId: "bob", text: "Stop work" }, (channelId, text) => {
57
+ expect({ channelId, text }).toEqual({ channelId: "bob", text: "Stop work" });
58
+ return { accepted: true, itemId: "auto:3", duplicate: false, milestone: "received" };
59
+ });
60
+ expect(receipt).toEqual({ accepted: true });
61
+ expect(executeNotice({ channelId: "nobody", text: "hi" }, () =>
62
+ ({ accepted: false, code: "not_found", error: "Unknown channel: nobody" })))
63
+ .toEqual({ accepted: false, error: "Unknown channel: nobody" });
64
+ });