@qlairoslabs/acp-client 0.13.0-alpha.1 → 0.13.2-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 (343) hide show
  1. package/CONSUMER_GUIDE.md +181 -8
  2. package/MIGRATION-0.12-to-0.13.md +20 -7
  3. package/package.json +13 -2
  4. package/src/agent/config.ts +2 -0
  5. package/src/agent/conversation-manager.ts +1 -0
  6. package/src/agent/native-operations.ts +40 -0
  7. package/src/agent-session-config.ts +2 -0
  8. package/src/agent-session.ts +12 -2
  9. package/src/agent.ts +100 -2
  10. package/src/client.ts +5 -3
  11. package/src/controller-connection.ts +1 -0
  12. package/src/controller.ts +2 -0
  13. package/src/index.ts +3 -0
  14. package/src/launcher.ts +2 -0
  15. package/src/native/approvals.ts +20 -3
  16. package/src/native/capabilities.ts +2 -2
  17. package/src/native/connection.ts +1 -1
  18. package/src/native/controller.ts +5 -3
  19. package/src/native/host-config.ts +2 -0
  20. package/src/native/host.ts +83 -4
  21. package/src/native/mcp.ts +47 -0
  22. package/src/native/recovery.ts +8 -7
  23. package/src/native/reminders/routine-guard.ts +4 -3
  24. package/src/native/reminders/routine-wire.ts +1 -1
  25. package/src/native-harness/README.md +58 -1
  26. package/src/native-harness/package.json +4 -0
  27. package/src/native-harness/scripts/build-routine-zones.py +47 -0
  28. package/src/native-harness/src/capabilities/attachments/admission.ts +42 -0
  29. package/src/native-harness/src/capabilities/attachments/image-validation.ts +98 -0
  30. package/src/native-harness/src/capabilities/attachments/input.ts +1 -0
  31. package/src/native-harness/src/capabilities/attachments/read.ts +76 -0
  32. package/src/native-harness/src/capabilities/attachments/recovery.ts +26 -0
  33. package/src/native-harness/src/capabilities/attachments/selection.ts +37 -0
  34. package/src/native-harness/src/capabilities/attachments/service.ts +75 -0
  35. package/src/native-harness/src/capabilities/attachments/upload.ts +164 -0
  36. package/src/native-harness/src/capabilities/attachments/vision.ts +45 -0
  37. package/src/native-harness/src/capabilities/context/build.ts +5 -0
  38. package/src/native-harness/src/capabilities/context/session.ts +2 -1
  39. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +80 -17
  40. package/src/native-harness/src/capabilities/model/runner.ts +6 -3
  41. package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
  42. package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
  43. package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
  44. package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
  45. package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
  46. package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
  47. package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
  48. package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
  49. package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
  50. package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
  51. package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
  52. package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
  53. package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
  54. package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
  55. package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
  56. package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
  57. package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
  58. package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
  59. package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
  60. package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
  61. package/src/native-harness/src/capabilities/tools/reminders/index.ts +27 -5
  62. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
  63. package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
  64. package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
  65. package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
  66. package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
  67. package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
  68. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
  69. package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
  70. package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
  71. package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
  72. package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
  73. package/src/native-harness/src/contracts/agent.ts +3 -1
  74. package/src/native-harness/src/contracts/attachments.ts +62 -0
  75. package/src/native-harness/src/contracts/config-permissions.ts +14 -3
  76. package/src/native-harness/src/contracts/context.ts +1 -1
  77. package/src/native-harness/src/contracts/events.ts +2 -2
  78. package/src/native-harness/src/contracts/loop.ts +3 -3
  79. package/src/native-harness/src/contracts/mcp.ts +22 -0
  80. package/src/native-harness/src/contracts/model-execution.ts +2 -1
  81. package/src/native-harness/src/contracts/operator-controls.ts +8 -1
  82. package/src/native-harness/src/contracts/protocol.ts +21 -5
  83. package/src/native-harness/src/contracts/reminders.ts +4 -2
  84. package/src/native-harness/src/contracts/routines.ts +20 -0
  85. package/src/native-harness/src/contracts/session-file.ts +2 -0
  86. package/src/native-harness/src/contracts/session.ts +8 -3
  87. package/src/native-harness/src/contracts/storage.ts +32 -13
  88. package/src/native-harness/src/contracts/tools.ts +2 -0
  89. package/src/native-harness/src/contracts/web.ts +16 -0
  90. package/src/native-harness/src/governance/permissions/gate.ts +9 -2
  91. package/src/native-harness/src/governance/policy/resolve.ts +6 -1
  92. package/src/native-harness/src/index.ts +48 -12
  93. package/src/native-harness/src/interfaces/cli/development.ts +108 -53
  94. package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
  95. package/src/native-harness/src/interfaces/cli/start.ts +22 -13
  96. package/src/native-harness/src/interfaces/client.ts +8 -2
  97. package/src/native-harness/src/interfaces/inspector/index.html +7 -1
  98. package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
  99. package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
  100. package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
  101. package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
  102. package/src/native-harness/src/interfaces/protocol/server.ts +102 -36
  103. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +8 -0
  104. package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
  105. package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
  106. package/src/native-harness/src/kernel/channels.ts +27 -15
  107. package/src/native-harness/src/kernel/loop.ts +1 -1
  108. package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
  109. package/src/native-harness/src/runtime/config/managed.ts +1 -1
  110. package/src/native-harness/src/runtime/config/paths.ts +8 -1
  111. package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
  112. package/src/native-harness/src/runtime/reminder-validation.ts +31 -10
  113. package/src/native-harness/src/runtime/reminders.ts +2 -2
  114. package/src/native-harness/src/state/storage/archive.ts +113 -12
  115. package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
  116. package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
  117. package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
  118. package/src/native-harness/src/state/storage/engine.ts +396 -45
  119. package/src/native-harness/src/state/storage/inference.ts +30 -2
  120. package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
  121. package/src/native-harness/src/state/storage/memory-reminders.ts +31 -6
  122. package/src/native-harness/src/state/storage/memory.ts +32 -4
  123. package/src/native-harness/src/state/storage/reminder-archive.ts +53 -12
  124. package/src/native-harness/src/state/storage/reminder-change.ts +60 -14
  125. package/src/native-harness/src/state/storage/reminder-tables.ts +11 -3
  126. package/src/native-harness/src/state/storage/routine-row.ts +25 -0
  127. package/src/native-harness/src/state/storage/session-file.ts +22 -9
  128. package/src/native-harness/src/state/storage/sqlite-reminders.ts +48 -8
  129. package/src/native-harness/src/state/storage/sqlite.ts +59 -11
  130. package/src/native-harness/src/state/storage/web-tables.ts +47 -0
  131. package/src/native-harness/src/testing.ts +151 -56
  132. package/src/native-harness/src/util/attachment-input.ts +42 -0
  133. package/src/native-harness/src/util/config.ts +64 -9
  134. package/src/native-harness/src/util/intake.ts +7 -0
  135. package/src/native-harness/src/util/mcp-config.ts +102 -0
  136. package/src/native-harness/src/util/web-config.ts +34 -0
  137. package/src/native-harness/src/util/web-usage.ts +33 -0
  138. package/src/orchestrator/permissions.ts +6 -3
  139. package/src/permissions/conversation.ts +13 -5
  140. package/src/permissions/matcher.ts +2 -0
  141. package/src/permissions/outcome.ts +12 -1
  142. package/src/permissions/policy.ts +13 -8
  143. package/src/steering/combine.ts +1 -0
  144. package/src/steering/contracts.ts +3 -0
  145. package/src/terminals.ts +9 -6
  146. package/src/native/reminders/reminders.test.ts +0 -553
  147. package/src/native/reminders/routine-config.typecheck.ts +0 -13
  148. package/src/native/reminders/wire.typecheck.ts +0 -13
  149. package/src/native-harness/.res/README.md +0 -1
  150. package/src/native-harness/.res/architecture/README.md +0 -21
  151. package/src/native-harness/.res/architecture/context-and-data.md +0 -31
  152. package/src/native-harness/.res/architecture/execution.md +0 -42
  153. package/src/native-harness/.res/architecture/overview.md +0 -44
  154. package/src/native-harness/.res/architecture/persistence.md +0 -56
  155. package/src/native-harness/.res/architecture/suspend-and-resume.md +0 -45
  156. package/src/native-harness/.res/architecture/technical-architecture.md +0 -50
  157. package/src/native-harness/.res/decisions/0001-basic-loop.md +0 -11
  158. package/src/native-harness/.res/decisions/0002-channel-input.md +0 -17
  159. package/src/native-harness/.res/decisions/0003-inference-inspection.md +0 -14
  160. package/src/native-harness/.res/decisions/0004-shared-context.md +0 -21
  161. package/src/native-harness/.res/decisions/0005-notice-inbox.md +0 -20
  162. package/src/native-harness/.res/decisions/0006-explicit-notices.md +0 -12
  163. package/src/native-harness/.res/decisions/0007-channel-output.md +0 -12
  164. package/src/native-harness/.res/decisions/0008-browser-client.md +0 -16
  165. package/src/native-harness/.res/decisions/0009-scripted-model.md +0 -18
  166. package/src/native-harness/.res/decisions/0010-inprocess-protocol.md +0 -19
  167. package/src/native-harness/.res/decisions/0011-stdio-transport.md +0 -21
  168. package/src/native-harness/.res/decisions/0012-session-storage-contract.md +0 -37
  169. package/src/native-harness/.res/decisions/0013-durable-delivery-contract.md +0 -64
  170. package/src/native-harness/.res/decisions/0014-channel-controls-contract.md +0 -73
  171. package/src/native-harness/.res/decisions/0015-session-file-contract.md +0 -72
  172. package/src/native-harness/.res/decisions/0016-configuration-permissions.md +0 -159
  173. package/src/native-harness/.res/decisions/0017-openrouter-managed-config.md +0 -69
  174. package/src/native-harness/.res/decisions/0018-tool-dispatch-evidence.md +0 -78
  175. package/src/native-harness/.res/decisions/0019-model-execution.md +0 -188
  176. package/src/native-harness/.res/decisions/0020-startup-channel-changes.md +0 -71
  177. package/src/native-harness/.res/decisions/0021-tools-and-host-callbacks.md +0 -100
  178. package/src/native-harness/.res/decisions/0022-operator-controls.md +0 -115
  179. package/src/native-harness/.res/decisions/0023-long-running-mock.md +0 -82
  180. package/src/native-harness/.res/decisions/0024-callback-policy-names.md +0 -46
  181. package/src/native-harness/.res/decisions/0025-external-notices.md +0 -364
  182. package/src/native-harness/.res/decisions/0026-bounded-context.md +0 -81
  183. package/src/native-harness/.res/decisions/0027-development-instructions.md +0 -22
  184. package/src/native-harness/.res/decisions/0028-debug-tools.md +0 -16
  185. package/src/native-harness/.res/decisions/0029-bounded-model-call-pages.md +0 -37
  186. package/src/native-harness/.res/decisions/0030-timeline-retrieval.md +0 -145
  187. package/src/native-harness/.res/decisions/0031-one-off-reminders.md +0 -173
  188. package/src/native-harness/.res/docs/11-15.md +0 -148
  189. package/src/native-harness/.res/docs/BUSINESS_RULES.md +0 -111
  190. package/src/native-harness/.res/docs/WORK.md +0 -65
  191. package/src/native-harness/.res/docs/_/11-16-persistence/LOG.md +0 -312
  192. package/src/native-harness/.res/docs/_/11-16-persistence/PLAN.md +0 -77
  193. package/src/native-harness/.res/docs/_/11-16-persistence/SPEC.md +0 -313
  194. package/src/native-harness/.res/docs/_/11-19-channel-controls/LOG.md +0 -160
  195. package/src/native-harness/.res/docs/_/11-19-channel-controls/PLAN.md +0 -89
  196. package/src/native-harness/.res/docs/_/11-19-channel-controls/SPEC.md +0 -135
  197. package/src/native-harness/.res/docs/_/11-19-config-permissions/LOG.md +0 -143
  198. package/src/native-harness/.res/docs/_/11-19-config-permissions/PLAN.md +0 -93
  199. package/src/native-harness/.res/docs/_/11-19-config-permissions/SPEC.md +0 -181
  200. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/11-20-LOG.md +0 -433
  201. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PLAN.md +0 -60
  202. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PROTOCOL.md +0 -141
  203. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/SPEC.md +0 -168
  204. package/src/native-harness/.res/docs/attachments/0001-DESIGN/SPEC.md +0 -111
  205. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/PLAN.md +0 -129
  206. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/SPEC.md +0 -135
  207. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/LOG.md +0 -437
  208. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/PLAN.md +0 -127
  209. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/SPEC.md +0 -203
  210. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/LOG.md +0 -292
  211. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/PLAN.md +0 -91
  212. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/SPEC.md +0 -187
  213. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/LOG.md +0 -148
  214. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/PLAN.md +0 -95
  215. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/SPEC.md +0 -200
  216. package/src/native-harness/.res/docs/model-execution/0002-AMENDMENT-accounting/SPEC.md +0 -80
  217. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/LOG.md +0 -206
  218. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/PLAN.md +0 -106
  219. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/SPEC.md +0 -297
  220. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/LOG.md +0 -41
  221. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/PLAN.md +0 -36
  222. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/SPEC.md +0 -84
  223. package/src/native-harness/.res/docs/shell-execution/0001-DESIGN/SPEC.md +0 -147
  224. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/LOG.md +0 -15
  225. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/PLAN.md +0 -107
  226. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/SPEC.md +0 -114
  227. package/src/native-harness/.res/docs/todos/11-19-TODO-auto_review-approve.md +0 -24
  228. package/src/native-harness/.res/docs/todos/11-20-TODO-user-entered-tool-code.md +0 -23
  229. package/src/native-harness/.res/docs/todos/11-21-TODO-node-resource-coordination.md +0 -103
  230. package/src/native-harness/.res/docs/todos/11-22-TODO-harness-m1-sequence.md +0 -50
  231. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/LOG.md +0 -337
  232. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/PLAN.md +0 -76
  233. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/SPEC.md +0 -204
  234. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/LOG.md +0 -73
  235. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/SPEC.md +0 -64
  236. package/src/native-harness/.res/docs/tools-and-callbacks/0003-DESIGN-attachment-tools/SPEC.md +0 -58
  237. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/LOG.md +0 -45
  238. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/PLAN.md +0 -108
  239. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/SPEC.md +0 -169
  240. package/src/native-harness/.res/docs/web-tools/0001-DESIGN/SPEC.md +0 -128
  241. package/src/native-harness/.res/marketing-draft.md +0 -22
  242. package/src/native-harness/.res/sandbox/1-simple-harness/README.md +0 -285
  243. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-1.md +0 -19
  244. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-10.md +0 -138
  245. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-11.md +0 -148
  246. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-12.md +0 -172
  247. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-13.md +0 -194
  248. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-14.md +0 -233
  249. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-15.md +0 -249
  250. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-16.md +0 -265
  251. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-17.md +0 -279
  252. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-18.md +0 -293
  253. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-19.md +0 -307
  254. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-2.md +0 -29
  255. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-20.md +0 -317
  256. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-21.md +0 -327
  257. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-3.md +0 -40
  258. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-4.md +0 -59
  259. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-5.md +0 -69
  260. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-6.md +0 -79
  261. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-7.md +0 -89
  262. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-8.md +0 -102
  263. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-9.md +0 -116
  264. package/src/native-harness/.res/sandbox/1-simple-harness/conversation.jsonl +0 -49
  265. package/src/native-harness/.res/sandbox/1-simple-harness/doc.md +0 -87
  266. package/src/native-harness/.res/sandbox/1-simple-harness/harness.py +0 -289
  267. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 2.py +0 -221
  268. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 3.py +0 -287
  269. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy.py +0 -165
  270. package/src/native-harness/.res/sandbox/1-simple-harness/state.json +0 -22
  271. package/src/native-harness/.res/sandbox/1-simple-harness/system-prompt.md +0 -2
  272. package/src/native-harness/AGENTS.md +0 -70
  273. package/src/native-harness/ARCHITECTURE.md +0 -249
  274. package/src/native-harness/bun.lock +0 -26
  275. package/src/native-harness/test/agent.test.ts +0 -130
  276. package/src/native-harness/test/approval-gate.test.ts +0 -255
  277. package/src/native-harness/test/approval-protocol.test.ts +0 -94
  278. package/src/native-harness/test/boundaries.test.ts +0 -18
  279. package/src/native-harness/test/channel-controls.test.ts +0 -322
  280. package/src/native-harness/test/client-abort.test.ts +0 -136
  281. package/src/native-harness/test/config-policy.test.ts +0 -301
  282. package/src/native-harness/test/conformance/storage.ts +0 -1141
  283. package/src/native-harness/test/context.test.ts +0 -177
  284. package/src/native-harness/test/crash.test.ts +0 -187
  285. package/src/native-harness/test/debug-tools.test.ts +0 -67
  286. package/src/native-harness/test/development-cli.test.ts +0 -67
  287. package/src/native-harness/test/development.test.ts +0 -171
  288. package/src/native-harness/test/dispatch-evidence.test.ts +0 -58
  289. package/src/native-harness/test/e2e.test.ts +0 -186
  290. package/src/native-harness/test/external-notices.test.ts +0 -101
  291. package/src/native-harness/test/fixtures/approval-e2e.jsonl +0 -4
  292. package/src/native-harness/test/fixtures/crash-scenario.jsonl +0 -5
  293. package/src/native-harness/test/fixtures/development-lifecycle.jsonl +0 -10
  294. package/src/native-harness/test/fixtures/echo-scenario.jsonl +0 -3
  295. package/src/native-harness/test/fixtures/format2-schema.ts +0 -27
  296. package/src/native-harness/test/fixtures/format3-schema.ts +0 -16
  297. package/src/native-harness/test/fixtures/hold-scenario.jsonl +0 -4
  298. package/src/native-harness/test/fixtures/model-e2e.jsonl +0 -3
  299. package/src/native-harness/test/fixtures/storage-owner.ts +0 -20
  300. package/src/native-harness/test/format-reply.test.ts +0 -10
  301. package/src/native-harness/test/helpers/operator-view.ts +0 -41
  302. package/src/native-harness/test/helpers/scenario.ts +0 -9
  303. package/src/native-harness/test/helpers/session.ts +0 -38
  304. package/src/native-harness/test/helpers/stdio.ts +0 -46
  305. package/src/native-harness/test/inspector.test.ts +0 -77
  306. package/src/native-harness/test/listeners.test.ts +0 -49
  307. package/src/native-harness/test/loop.test.ts +0 -88
  308. package/src/native-harness/test/model-channel-double.test.ts +0 -87
  309. package/src/native-harness/test/model-crash.test.ts +0 -62
  310. package/src/native-harness/test/model-delivery-regressions.test.ts +0 -55
  311. package/src/native-harness/test/model-e2e.test.ts +0 -71
  312. package/src/native-harness/test/model-final-filter.test.ts +0 -30
  313. package/src/native-harness/test/model-large-reply.test.ts +0 -28
  314. package/src/native-harness/test/model-live-queue.test.ts +0 -33
  315. package/src/native-harness/test/model-runner.test.ts +0 -117
  316. package/src/native-harness/test/model-storage.test.ts +0 -99
  317. package/src/native-harness/test/model-stream-adapter.test.ts +0 -26
  318. package/src/native-harness/test/model-stream-public.test.ts +0 -77
  319. package/src/native-harness/test/notices.test.ts +0 -64
  320. package/src/native-harness/test/openrouter-config.test.ts +0 -218
  321. package/src/native-harness/test/operator-controls.test.ts +0 -132
  322. package/src/native-harness/test/output.test.ts +0 -44
  323. package/src/native-harness/test/owner-config.test.ts +0 -64
  324. package/src/native-harness/test/permissions-e2e.test.ts +0 -68
  325. package/src/native-harness/test/persistence.test.ts +0 -236
  326. package/src/native-harness/test/portability.test.ts +0 -337
  327. package/src/native-harness/test/protocol.test.ts +0 -160
  328. package/src/native-harness/test/reminder-clock.test.ts +0 -61
  329. package/src/native-harness/test/reminder-stdio.test.ts +0 -140
  330. package/src/native-harness/test/reminder-storage.test.ts +0 -124
  331. package/src/native-harness/test/scenario-jsonl.test.ts +0 -112
  332. package/src/native-harness/test/scripted.test.ts +0 -92
  333. package/src/native-harness/test/session-file.test.ts +0 -51
  334. package/src/native-harness/test/startup-channel-changes.test.ts +0 -256
  335. package/src/native-harness/test/stdio.test.ts +0 -132
  336. package/src/native-harness/test/storage-memory.test.ts +0 -4
  337. package/src/native-harness/test/storage-sqlite.test.ts +0 -420
  338. package/src/native-harness/test/suspension.test.ts +0 -430
  339. package/src/native-harness/test/timeline-retrieval.test.ts +0 -211
  340. package/src/native-harness/test/tools-catalog.test.ts +0 -468
  341. package/src/native-harness/test/tools-protocol.test.ts +0 -418
  342. package/src/native-harness/test/transfers.test.ts +0 -94
  343. package/src/native-harness/test/web-chat.test.ts +0 -35
@@ -1,71 +0,0 @@
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);
@@ -1,30 +0,0 @@
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
- });
@@ -1,28 +0,0 @@
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);
@@ -1,33 +0,0 @@
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
- });
@@ -1,117 +0,0 @@
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
- });
@@ -1,99 +0,0 @@
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
- });
@@ -1,26 +0,0 @@
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
- });
@@ -1,77 +0,0 @@
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
- });
@@ -1,64 +0,0 @@
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
- });