@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,26 +1,89 @@
1
1
  import type { ModelAttempt, ModelAttemptEvent } from "../../contracts/model-execution.ts";
2
2
  import type { Message } from "../../contracts/loop.ts";
3
+ import { projectVisionParts, VisionInputError } from "../attachments/vision.ts";
4
+ import { ATTACHMENT_LIMITS } from "../../contracts/attachments.ts";
5
+ import { createHash } from "node:crypto";
3
6
 
4
- function wireMessage(message: Message): unknown {
5
- if (message.role === "assistant") return message.providerState ?? { role: "assistant", content: message.content,
7
+ function wireMessage(message: Message, preserveProviderState: boolean): unknown {
8
+ if (message.role === "assistant") return (preserveProviderState ? message.providerState : undefined) ?? { role: "assistant", content: message.content,
6
9
  ...(message.calls.length ? { tool_calls: message.calls.map(c => ({ id: c.id, type: "function", function: { name: c.name, arguments: c.arguments } })) } : {}) };
7
10
  return message.role === "tool" ? { role: "tool", content: message.content, tool_call_id: message.callId } : message;
8
11
  }
9
12
  /** OpenRouter SSE translation stays at the provider boundary; tool fragments are
10
13
  * private until a valid terminal response is assembled by the adapter. */
11
- export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void): ModelAttempt {
14
+ type Vision = Parameters<typeof projectVisionParts>[1] & { verify?: (metadata: import("../../contracts/attachments.ts").AttachmentMetadata, signal: AbortSignal) => Promise<void> };
15
+ export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void, vision?: Vision): ModelAttempt {
16
+ return chatAttempt(apiKey, model, fetcher, onRequest, undefined, vision);
17
+ }
18
+ export function openAICompatibleAttempt(baseUrl: string, model: string, apiKey?: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void, metadata?: Vision["metadata"]): ModelAttempt {
19
+ const references: Vision | undefined = metadata ? { supported: false, metadata, read: () => { throw new Error("Image bytes unavailable for text-only model"); } } : undefined;
20
+ return chatAttempt(apiKey, model, fetcher, onRequest, `${baseUrl}/chat/completions`, references);
21
+ }
22
+ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof fetch, onRequest?: (body: string) => void, endpoint?: string, vision?: Vision): ModelAttempt {
12
23
  return async function* (request, signal) {
13
- const body = JSON.stringify({ model, stream: true, stream_options: { include_usage: true }, messages: request.messages.map(wireMessage),
14
- ...(request.tools.length ? { tools: request.tools.map(tool => ({ type: "function", function: tool })) } : {}) });
15
- onRequest?.(body);
24
+ const imageUrls: string[] = [];
25
+ let messages: unknown[];
26
+ try {
27
+ let imageBytes = 0;
28
+ const unavailable = new Set<string>();
29
+ const images = new Map<string, ReturnType<NonNullable<typeof vision>["metadata"]>>();
30
+ for (const message of request.messages) if (message.role === "user" && message.parts) {
31
+ if (!vision) throw new VisionInputError("unsupported_image", "No attachment resolver is configured");
32
+ for (const part of message.parts) if (part.type === "attachment") {
33
+ const metadata = vision.metadata(part.id);
34
+ if (!metadata) unavailable.add(part.id);
35
+ else if (metadata.mediaType.startsWith("image/")) { imageBytes += metadata.bytes; images.set(part.id, metadata); }
36
+ }
37
+ }
38
+ if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Attachment metadata is unavailable", [...unavailable]);
39
+ if (endpoint && images.size) throw new VisionInputError("unsupported_image", "The configured model does not support image input", [...images.keys()]);
40
+ if (imageBytes > ATTACHMENT_LIMITS.imageBytesPerTurn) throw new VisionInputError("transfer_limit", "Image request exceeds the turn budget");
41
+ if (images.size && !vision!.supported) throw new VisionInputError("unsupported_image", "The configured model does not support image input", [...images.keys()]);
42
+ const bytes = new Map<string, Uint8Array>();
43
+ for (const [id, metadata] of images) try {
44
+ await vision!.verify?.(metadata!, signal);
45
+ const value = vision!.read(metadata!);
46
+ if (value.length !== metadata!.bytes || createHash("sha256").update(value).digest("hex") !== metadata!.sha256) throw new Error("Integrity failure");
47
+ bytes.set(id, value);
48
+ } catch { unavailable.add(id); }
49
+ if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Image bytes are unavailable", [...unavailable]);
50
+ messages = request.messages.map(message => {
51
+ if (message.role !== "user" || !message.parts) return wireMessage(message, endpoint === undefined);
52
+ if (!vision) throw new VisionInputError("unsupported_image", "No attachment resolver is configured");
53
+ const content = projectVisionParts(message.parts, { ...vision, read: metadata => bytes.get(metadata.id)! });
54
+ for (const part of content) if (part.type === "image_url") imageUrls.push(part.image_url.url);
55
+ const separator = message.content.indexOf("\n\n");
56
+ const attribution = message.content.startsWith("Participant: ") && separator >= 0 ? message.content.slice(0, separator + 2) : "";
57
+ if (endpoint) return { role: "user", content: attribution + content.map(part => part.type === "text" ? part.text : "").join("") };
58
+ return { role: "user", content: attribution ? [{ type: "text", text: attribution }, ...content] : content };
59
+ });
60
+ } catch (error) {
61
+ if (error instanceof VisionInputError) { yield { type: "failure", kind: "invalid_request", code: error.code, attachmentIds: error.attachmentIds, message: error.message }; return; }
62
+ throw error;
63
+ }
64
+ const body = JSON.stringify({ model, stream: true, stream_options: { include_usage: true }, messages,
65
+ ...(request.tools.length ? { tools: request.tools.map(tool => ({ type: "function", function: tool })), ...(endpoint ? { tool_choice: "auto" } : {}) } : {}) });
66
+ const redact = (text: string) => {
67
+ let safe = apiKey ? text.replaceAll(apiKey, "[REDACTED]") : text;
68
+ for (const url of imageUrls) { safe = safe.replaceAll(url, "[REDACTED_IMAGE]"); const encoded = url.slice(url.indexOf(",") + 1); if (encoded) safe = safe.replaceAll(encoded, "[REDACTED_IMAGE]"); }
69
+ return safe;
70
+ };
71
+ const errorText = (error: unknown) => endpoint ? "Chat Completions transport failed" : redact(String(error));
72
+ onRequest?.(imageUrls.length ? redact(body) : body);
16
73
  let response: Response;
17
- try { response = await fetcher("https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" }, body, signal }); }
18
- catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: String(error).replaceAll(apiKey, "[REDACTED]") }; return; }
74
+ try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: { ...(apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` }), "Content-Type": "application/json" }, body, signal, ...(endpoint ? { redirect: "manual" } : {}) }); }
75
+ catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; return; }
19
76
  if (!response.ok) {
20
- const text = (await response.text()).replaceAll(apiKey, "[REDACTED]");
77
+ if (endpoint) {
78
+ void response.body?.cancel().catch(() => {});
79
+ if (response.status >= 300 && response.status < 400) { yield { type: "failure", kind: "provider", message: "redirect_refused" }; return; }
80
+ yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `Chat Completions HTTP ${response.status}` }; return;
81
+ }
82
+ const text = redact(await response.text());
21
83
  yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `OpenRouter HTTP ${response.status}: ${text}` }; return;
22
84
  }
23
- const requestId = response.headers.get("x-request-id") ?? undefined;
85
+ const safeRequestId = (id: string | undefined) => endpoint && apiKey && id?.includes(apiKey) ? undefined : id;
86
+ const requestId = safeRequestId(response.headers.get("x-request-id") ?? undefined);
24
87
  if (!response.body) return;
25
88
  let content = "", buffer = "", stop: string | undefined, providerId = requestId, reasoning = "";
26
89
  const reasoningDetails: unknown[] = [];
@@ -35,8 +98,8 @@ export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof
35
98
  if (!line.startsWith("data:")) continue;
36
99
  const data = line.slice(5).trim(); if (!data || data === "[DONE]") continue;
37
100
  let payload: { id?: string; usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }; choices?: { finish_reason?: string | null; delta?: { content?: string | null; reasoning?: string | null; reasoning_details?: unknown[]; tool_calls?: { index: number; id?: string; function?: { name?: string; arguments?: string } }[] } }[] };
38
- try { payload = JSON.parse(data); } catch { yield { type: "failure", kind: "provider", message: "Malformed OpenRouter stream" }; return; }
39
- if (!providerId && payload.id) providerId = payload.id;
101
+ try { payload = JSON.parse(data); } catch { yield { type: "failure", kind: "provider", message: endpoint ? "Malformed Chat Completions stream" : "Malformed OpenRouter stream" }; return; }
102
+ if (!providerId && payload.id) providerId = safeRequestId(payload.id);
40
103
  // A parsed response frame, unlike an HTTP success header, is evidence
41
104
  // the provider has accepted the inference request.
42
105
  if (!confirmed) { confirmed = true; yield { type: "accepted", ...(providerId ? { providerRequestId: providerId } : {}) }; }
@@ -59,14 +122,14 @@ export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof
59
122
  const ordered = [...fragments.entries()].sort((a, b) => a[0] - b[0]);
60
123
  if (ordered.some(([n], i) => n !== i)) { yield { type: "failure", kind: "provider", message: "Non-contiguous tool fragments" }; return; }
61
124
  const stopReason = stop === "stop" ? "complete" : stop === "tool_calls" ? "tool_calls" : stop === "length" ? "output_limit" : undefined;
62
- if (!stopReason) { yield { type: "failure", kind: "provider", message: `Unsupported finish reason: ${stop}` }; return; }
125
+ if (!stopReason) { yield { type: "failure", kind: "provider", message: endpoint ? "Unsupported Chat Completions finish reason" : `Unsupported finish reason: ${stop}` }; return; }
63
126
  const calls = ordered.map(([, value]) => value);
64
127
  const message = { role: "assistant" as const, content: content || null, calls };
65
- const event: ModelAttemptEvent = { type: "response", response: { ...message, stopReason, providerState: { role: "assistant", content: message.content,
128
+ const event: ModelAttemptEvent = { type: "response", response: { ...message, stopReason, ...(endpoint ? {} : { providerState: { role: "assistant", content: message.content,
66
129
  ...(reasoning ? { reasoning } : {}), ...(reasoningDetails.length ? { reasoning_details: reasoningDetails } : {}),
67
- ...(calls.length ? { tool_calls: calls.map(call => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } })) } : {}) } }, ...(providerId ? { providerRequestId: providerId } : {}) };
130
+ ...(calls.length ? { tool_calls: calls.map(call => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } })) } : {}) } }) }, ...(providerId ? { providerRequestId: providerId } : {}) };
68
131
  yield event;
69
- } catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: String(error).replaceAll(apiKey, "[REDACTED]") }; }
70
- finally { reader.releaseLock(); }
132
+ } catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; }
133
+ finally { if (endpoint) void reader.cancel().catch(() => {}); reader.releaseLock(); }
71
134
  };
72
135
  }
@@ -4,7 +4,8 @@ import type { StorageResult, TimelineEntry } from "../../contracts/storage.ts";
4
4
  /** One deadline covers the first attempt, retry wait and retry. */
5
5
  export const MODEL_EXECUTION_DEFAULTS: Readonly<ModelExecutionSettings> = { timeoutMs: 120_000, retryDelayMs: 1_000, maxRetries: 1 };
6
6
  export class ModelCallError extends Error {
7
- constructor(readonly outcome: Exclude<CallOutcome, "running" | "succeeded">, message: string) { super(message); this.name = "ModelCallError"; }
7
+ constructor(readonly outcome: Exclude<CallOutcome, "running" | "succeeded">, message: string,
8
+ readonly attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure) { super(message); this.name = "ModelCallError"; }
8
9
  }
9
10
  class ModelStorageError extends Error {}
10
11
  function take<T>(result: StorageResult<T>): T {
@@ -40,11 +41,12 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
40
41
  const call = take(options.store.startCall(options.turnId, options.itemIds));
41
42
  options.started?.(call.callId);
42
43
  let deadline = 0, output = false;
43
- const finish = (outcome: Exclude<CallOutcome, "running" | "succeeded">, detail: string = outcome): never => {
44
+ const finish = (outcome: Exclude<CallOutcome, "running" | "succeeded">, detail: string = outcome,
45
+ attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure): never => {
44
46
  const result = options.store.finishCall(call.callId, outcome);
45
47
  if (!result.ok && !(outcome === "interrupted" && result.error.code === "invalid_state")) take(result);
46
48
  if (output) options.incomplete?.({ messageId: call.messageId, reason: outcome });
47
- throw new ModelCallError(outcome, detail);
49
+ throw new ModelCallError(outcome, detail, attachmentFailure);
48
50
  };
49
51
  for (let ordinal = 0; ordinal <= Math.min(1, settings.maxRetries); ordinal++) {
50
52
  if (options.signal?.aborted) return finish("interrupted");
@@ -102,6 +104,7 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
102
104
  const attemptOutcome = failure === "transient" ? "transient_failure" : failure === "provider" ? "provider_failure" : failure;
103
105
  take(options.store.finishAttempt(call.callId, attempt.attemptId, attemptOutcome));
104
106
  if (terminal?.type === "failure" && terminal.message === "script_exhausted" && options.scripted) return finish("failed", "script_exhausted");
107
+ if (terminal?.type === "failure" && terminal.code) return finish("failed", terminal.message, { code: terminal.code, attachmentIds: [...terminal.attachmentIds ?? []] });
105
108
  if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) return finish(failure === "incomplete" ? "incomplete" : "failed");
106
109
  if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout");
107
110
  const delay = await new Promise<"ready" | "interrupted">(resolve => {
@@ -0,0 +1,50 @@
1
+ import type { CronFields } from "./cron-fields.ts";
2
+
3
+ const dayMs = 86_400_000;
4
+ const minuteMs = 60_000;
5
+ const cycleDays = 146_097;
6
+ const cycleStart = Date.UTC(2000, 0, 1);
7
+
8
+ function upperBound(values: readonly number[], target: number): number {
9
+ let lo = 0, hi = values.length;
10
+ while (lo < hi) {
11
+ const mid = Math.floor((lo + hi) / 2);
12
+ if (values[mid]! <= target) lo = mid + 1;
13
+ else hi = mid;
14
+ }
15
+ return lo;
16
+ }
17
+
18
+ /** Index a Gregorian cycle once and use it for range arithmetic. Local civil
19
+ * ordinals are signed around 2000-01-01 and do not apply zone transitions. */
20
+ export function cronCivilCalendar(fields: CronFields, check = () => {}) {
21
+ const days: number[] = [];
22
+ const date = new Date(cycleStart);
23
+ for (let offset = 0; offset < cycleDays; offset++) {
24
+ if (offset % 256 === 0) check();
25
+ date.setTime(cycleStart + offset * dayMs);
26
+ if (fields.matchesDay({ day: date.getUTCDate(), month: date.getUTCMonth() + 1, weekday: date.getUTCDay() })) days.push(offset);
27
+ }
28
+ if (!days.length) return;
29
+ const minutes = fields.minutesOfDay;
30
+ const cycleSize = days.length * minutes.length;
31
+ return {
32
+ /** Number of civil matches through the instant, relative to the cycle origin. */
33
+ rank(through: number): number {
34
+ const elapsed = through - cycleStart;
35
+ const day = Math.floor(elapsed / dayMs);
36
+ const cycle = Math.floor(day / cycleDays);
37
+ const offset = day - cycle * cycleDays;
38
+ const before = upperBound(days, offset - 1);
39
+ return cycle * cycleSize + before * minutes.length + (days[before] === offset
40
+ ? upperBound(minutes, (elapsed - day * dayMs) / minuteMs)
41
+ : 0);
42
+ },
43
+ at(ordinal: number): number {
44
+ const cycle = Math.floor(ordinal / cycleSize);
45
+ const offset = ordinal - cycle * cycleSize;
46
+ const day = cycle * cycleDays + days[Math.floor(offset / minutes.length)]!;
47
+ return cycleStart + day * dayMs + minutes[offset % minutes.length]! * minuteMs;
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,46 @@
1
+ const dayMinutes = 24 * 60;
2
+
3
+ interface CalendarDay {
4
+ day: number;
5
+ month: number;
6
+ weekday: number;
7
+ }
8
+
9
+ export interface CronFields {
10
+ minutesOfDay: readonly number[];
11
+ matchesDay(day: CalendarDay): boolean;
12
+ }
13
+
14
+ function expand(field: string, min: number, max: number, check: () => void): number[] | undefined {
15
+ const values = new Set<number>();
16
+ for (const expression of field.split(",")) {
17
+ check();
18
+ const match = /^(\*|([0-9]{1,2})(?:-([0-9]{1,2}))?)(?:\/([0-9]{1,2}))?$/.exec(expression);
19
+ if (!match) return;
20
+ const wildcard = match[1] === "*";
21
+ const start = wildcard ? min : Number(match[2]);
22
+ const end = wildcard ? max : Number(match[3] ?? match[2]);
23
+ const step = Number(match[4] ?? 1);
24
+ if (start < min || end > max || end < start || step < 1 || (match[4] && !wildcard && !match[3])) return;
25
+ for (let value = start; value <= end; value += step) values.add(value);
26
+ }
27
+ return [...values].sort((left, right) => left - right);
28
+ }
29
+
30
+ export function parseRoutineCron(expression: string, check = () => {}): CronFields | undefined {
31
+ check();
32
+ const fields = expression.trim().split(/\s+/);
33
+ if (fields.length !== 5) return;
34
+ const minutes = expand(fields[0]!, 0, 59, check), hours = expand(fields[1]!, 0, 23, check);
35
+ const days = expand(fields[2]!, 1, 31, check), months = expand(fields[3]!, 1, 12, check);
36
+ const weekdays = expand(fields[4]!, 0, 6, check);
37
+ if (!minutes || !hours || !days || !months || !weekdays) return;
38
+ const minutesOfDay = hours.flatMap(hour => minutes.map(minute => hour * 60 + minute));
39
+ const wrapsAt = minutesOfDay[0]! + dayMinutes;
40
+ const spaced = minutesOfDay.every((minute, index) => (minutesOfDay[index + 1] ?? wrapsAt) - minute >= 10);
41
+ if (!spaced) return;
42
+ return {
43
+ minutesOfDay,
44
+ matchesDay: ({ day, month, weekday }) => days.includes(day) && months.includes(month) && weekdays.includes(weekday),
45
+ };
46
+ }
@@ -0,0 +1,32 @@
1
+ import { cronCivilCalendar } from "./cron-calendar.ts";
2
+ import { parseRoutineCron } from "./cron-fields.ts";
3
+ import { zonedCalendar, type ZoneTransition } from "./cron-zone.ts";
4
+
5
+ const PROOF_BUDGET_MS = 250;
6
+ class ProofBudget extends Error {}
7
+
8
+ export interface ProofZoneRange {
9
+ start: number;
10
+ end: number;
11
+ initialOffset: number;
12
+ transitions: readonly ZoneTransition[];
13
+ }
14
+
15
+ /** Prove the supplied versioned zone span. The caller supplies historical
16
+ * transitions and a complete future cycle with boundary pairs. */
17
+ export function proveRoutineCron(expression: string, zone: ProofZoneRange, now = () => performance.now()) {
18
+ const deadline = now() + PROOF_BUDGET_MS;
19
+ const check = () => { if (now() >= deadline) throw new ProofBudget(); };
20
+ try {
21
+ const fields = parseRoutineCron(expression, check);
22
+ if (!fields) return { kind: "invalid_schedule" } as const;
23
+ const civil = cronCivilCalendar(fields, check);
24
+ if (!civil) return { kind: "invalid_schedule" } as const;
25
+ const calendar = zonedCalendar(civil, zone.start, zone.end, zone.initialOffset, zone.transitions, check);
26
+ check();
27
+ return calendar ? { kind: "valid", calendar } as const : { kind: "invalid_schedule" } as const;
28
+ } catch (error) {
29
+ if (error instanceof ProofBudget) return { kind: "proof_budget" } as const;
30
+ throw error;
31
+ }
32
+ }
@@ -0,0 +1,53 @@
1
+ import type { RoutineCalendar } from "../../contracts/routines.ts";
2
+ import type { cronCivilCalendar } from "./cron-calendar.ts";
3
+
4
+ export interface ZoneTransition { at: number; offset: number }
5
+ type CivilCalendar = NonNullable<ReturnType<typeof cronCivilCalendar>>;
6
+
7
+ /** Build one UTC range index from ordered concrete transitions. The bindings
8
+ * layer must supply the versioned zone rules for the whole supported span. */
9
+ export function zonedCalendar(
10
+ civil: CivilCalendar, start: number, end: number, initialOffset: number, transitions: readonly ZoneTransition[],
11
+ check = () => {},
12
+ ): RoutineCalendar | undefined {
13
+ const segments: { offset: number; first: number; before: number; end: number; after: number }[] = [];
14
+ let cursor = start, offset = initialOffset, total = 0, localFence = -Infinity;
15
+ let previous: number | undefined;
16
+ for (const transition of [...transitions, { at: end + 1, offset }]) {
17
+ check();
18
+ const stop = transition.at;
19
+ if (stop <= cursor || stop > end + 1) return;
20
+ const first = civil.rank(Math.max(cursor + offset - 1, localFence));
21
+ const after = civil.rank(stop + offset - 1);
22
+ if (after > first) {
23
+ const firstUtc = civil.at(first) - offset;
24
+ if (previous !== undefined && firstUtc - previous < 600_000) return;
25
+ previous = civil.at(after - 1) - offset;
26
+ segments.push({ offset, first, before: total, end: stop - 1, after: total + after - first });
27
+ total += after - first;
28
+ }
29
+ localFence = Math.max(localFence, stop + offset - 1);
30
+ cursor = stop;
31
+ offset = transition.offset;
32
+ }
33
+ function find(predicate: (segment: typeof segments[number]) => boolean) {
34
+ let lo = 0, hi = segments.length;
35
+ while (lo < hi) {
36
+ const mid = Math.floor((lo + hi) / 2);
37
+ if (predicate(segments[mid]!)) hi = mid;
38
+ else lo = mid + 1;
39
+ }
40
+ return segments[lo];
41
+ }
42
+ function at(ordinal: number) {
43
+ if (!Number.isSafeInteger(ordinal) || ordinal < 0 || ordinal >= total) return;
44
+ const segment = find(segment => segment.after > ordinal)!;
45
+ return civil.at(segment.first + ordinal - segment.before) - segment.offset;
46
+ }
47
+ function rank(through: number) {
48
+ const segment = find(segment => segment.end >= through);
49
+ if (!segment) return total;
50
+ return segment.before + Math.max(0, civil.rank(through + segment.offset) - segment.first);
51
+ }
52
+ return { at, rank, nextCalendarMatch: through => at(rank(through)) };
53
+ }
@@ -0,0 +1,34 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { gunzipSync } from "node:zlib";
3
+ import type { ProofZoneRange } from "./cron-proof.ts";
4
+
5
+ type Zone = [initialSeconds: number, changes: [utcSeconds: number, offsetSeconds: number][]];
6
+ type Catalog = [version: string, tailStart: number, tailPeriod: number, zones: Record<string, Zone>, aliases: Record<string, string>];
7
+
8
+ let catalog: Catalog | undefined;
9
+ const start = Date.parse("0000-01-01T00:00:00.000Z");
10
+ const end = Date.parse("9999-12-31T23:59:59.999Z");
11
+ const milliseconds = 1000;
12
+
13
+ export function resolveRoutineZone(name: string): (ProofZoneRange & { timezone: string; timezoneVersion: string }) | undefined {
14
+ catalog ??= JSON.parse(gunzipSync(readFileSync(new URL("./iana-zones.json.gz", import.meta.url))).toString()) as Catalog;
15
+ const [timezoneVersion, tailStart, period, zones, aliases] = catalog;
16
+ let timezone = name;
17
+ const visited = new Set<string>();
18
+ while (Object.hasOwn(aliases, timezone)) {
19
+ if (visited.has(timezone)) return;
20
+ visited.add(timezone);
21
+ timezone = aliases[timezone]!;
22
+ }
23
+ if (!Object.hasOwn(zones, timezone)) return;
24
+ const [initialOffset, changes] = zones[timezone]!;
25
+ const transitions = changes.map(([at, offset]) => ({ at: at * milliseconds, offset: offset * milliseconds }));
26
+ const tail = changes.filter(([at]) => at >= tailStart);
27
+ for (let shift = period; tail.length && (tailStart + shift) * milliseconds <= end; shift += period) {
28
+ for (const [at, offset] of tail) {
29
+ if ((at + shift) * milliseconds <= end)
30
+ transitions.push({ at: (at + shift) * milliseconds, offset: offset * milliseconds });
31
+ }
32
+ }
33
+ return { timezone, timezoneVersion, start, end, initialOffset: initialOffset * milliseconds, transitions };
34
+ }
@@ -0,0 +1,30 @@
1
+ import type { IntervalRoutineSchedule, RoutineCalendar } from "../../contracts/routines.ts";
2
+ import { reminderInstant, REMINDER_LIMITS } from "../../util/reminder-schedule.ts";
3
+
4
+ const lastInstant = Date.parse("9999-12-31T23:59:59.999Z");
5
+
6
+ export function intervalCalendar(schedule: IntervalRoutineSchedule, anchor: number, processedThrough?: number): RoutineCalendar | undefined {
7
+ const { every, count, until, startAt } = schedule;
8
+ if (!Number.isSafeInteger(anchor) || !Number.isSafeInteger(every) || every < REMINDER_LIMITS.minIntervalMs) return;
9
+ if (count !== undefined && (until !== undefined || !Number.isSafeInteger(count) || count < 1)) return;
10
+ const start = startAt === undefined ? anchor + every : reminderInstant(startAt);
11
+ const last = until === undefined ? lastInstant : reminderInstant(until);
12
+ if (start === undefined || last === undefined || !Number.isSafeInteger(start) || start - anchor < REMINDER_LIMITS.minIntervalMs) return;
13
+ if (processedThrough !== undefined && !Number.isSafeInteger(processedThrough)) return;
14
+ const skipped = processedThrough === undefined || processedThrough < start ? 0 : Math.floor((processedThrough - start) / every) + 1;
15
+ const first = start + skipped * every;
16
+ if (!Number.isSafeInteger(first) || first > last) return;
17
+ const size = Math.min(count ?? Infinity, Math.floor((last - first) / every) + 1);
18
+ return {
19
+ at(ordinal) {
20
+ return Number.isSafeInteger(ordinal) && ordinal >= 0 && ordinal < size ? first + ordinal * every : undefined;
21
+ },
22
+ rank(through) {
23
+ return Math.max(0, Math.min(size, Math.floor((through - first) / every) + 1));
24
+ },
25
+ nextCalendarMatch(instant) {
26
+ const next = first + Math.max(0, Math.floor((instant - first) / every) + 1) * every;
27
+ return next <= lastInstant ? next : undefined;
28
+ },
29
+ };
30
+ }
@@ -0,0 +1,47 @@
1
+ import type { OneOffReminder, Reminder, ReminderChannelEvent } from "../../contracts/reminders.ts";
2
+ import type { RoutineCalendar } from "../../contracts/routines.ts";
3
+ import { routineExpiry } from "./routine-expiry.ts";
4
+ import { routineOccurrenceIdentity, type RoutineStep } from "./routine-occurrence.ts";
5
+
6
+ export type RoutineReminder = Exclude<Reminder, OneOffReminder>;
7
+
8
+ export interface RoutineAdvance {
9
+ reminder: RoutineReminder;
10
+ disposition?: Extract<ReminderChannelEvent, { type: "routine_disposition" }>;
11
+ notice?: ReturnType<typeof routineOccurrenceIdentity> & { text: string };
12
+ }
13
+
14
+ /** Compute one committed cursor step. The owner must write the row and accept
15
+ * the optional notice atomically, and publish only the returned dispositions. */
16
+ export function advanceRoutine(
17
+ row: RoutineReminder, calendar: RoutineCalendar, step: RoutineStep, now: number,
18
+ grace: number | null | undefined, overlapping: boolean,
19
+ ): RoutineAdvance {
20
+ const first = calendar.at(step.first), last = calendar.at(step.last);
21
+ const count = step.last - step.first + 1;
22
+ if (first === undefined || last === undefined || count < 1 || (row.remainingCount !== undefined && row.remainingCount < count))
23
+ throw new RangeError("Invalid routine step");
24
+ const remainingCount = row.remainingCount === undefined ? undefined : row.remainingCount - count;
25
+ const next = remainingCount === 0 ? undefined : calendar.at(step.last + 1);
26
+ const identity = routineOccurrenceIdentity(row.id, last);
27
+ const candidate = step.kind === "enqueue";
28
+ const expiry = candidate ? routineExpiry(calendar, last, grace).expiresAt : null;
29
+ const reason = !candidate ? step.kind : expiry !== null && expiry <= now ? "expired"
30
+ : row.overlap === "skip" && overlapping ? "overlap" : step.represented > 1 ? "coalesced" : undefined;
31
+ const queued = candidate && (reason === undefined || reason === "coalesced");
32
+ const nextExpiry = next === undefined ? { expiresAfter: null, expiresAt: null } : routineExpiry(calendar, next, grace);
33
+ const reminder: RoutineReminder = { ...row, remainingCount,
34
+ state: next === undefined ? "done" : "active", nextRunAt: next === undefined ? null : new Date(next).toISOString(),
35
+ expiresAfter: nextExpiry.expiresAfter, expiresAt: nextExpiry.expiresAt === null ? null : new Date(nextExpiry.expiresAt).toISOString(),
36
+ lastOccurrenceId: identity.occurrenceId,
37
+ ...(queued ? { noticeId: identity.noticeId, lastRunAt: new Date(now).toISOString() } : {}),
38
+ };
39
+ return {
40
+ reminder,
41
+ ...(reason === undefined ? {} : { disposition: { type: "routine_disposition", reminderId: row.id,
42
+ firstScheduledAt: new Date(first).toISOString(), lastScheduledAt: identity.scheduledAt, count, reason } }),
43
+ ...(queued ? { notice: { ...identity, text: step.represented > 1
44
+ ? `${row.text}\n\nMissed occurrences: ${step.represented}. Last scheduled: ${identity.scheduledAt}.`
45
+ : row.text } } : {}),
46
+ };
47
+ }
@@ -0,0 +1,47 @@
1
+ import type { RoutineCalendar, RoutineDeliveryOptions } from "../../contracts/routines.ts";
2
+ import { REMINDER_LIMITS } from "../../util/reminder-schedule.ts";
3
+ import { routineExpiry } from "./routine-expiry.ts";
4
+
5
+ export const MAX_ROUTINE_CATCH_UP = 10;
6
+ export interface OrdinalRange { first: number; last: number }
7
+
8
+ function range(first: number, last: number): OrdinalRange[] {
9
+ return first <= last ? [{ first, last }] : [];
10
+ }
11
+
12
+ function append(ranges: OrdinalRange[], ordinal: number) {
13
+ const tail = ranges.at(-1);
14
+ if (tail?.last === ordinal - 1) tail.last = ordinal;
15
+ else ranges.push({ first: ordinal, last: ordinal });
16
+ }
17
+
18
+ /** Select expired and missed ranges before the fixed episode cutoff.
19
+ * Ordinals preserve the exact represented occurrences without materializing
20
+ * the backlog. Current-minute occurrences are handled by normal admission. */
21
+ export function routineBacklog(
22
+ calendar: RoutineCalendar, next: number, cutoff: number, grace: number | null | undefined,
23
+ policy: NonNullable<RoutineDeliveryOptions["missedRuns"]>,
24
+ ) {
25
+ const last = calendar.rank(Math.floor(cutoff / 60_000) * 60_000 - 1) - 1;
26
+ const expired: OrdinalRange[] = [], live: OrdinalRange[] = [];
27
+ if (grace === null) live.push(...range(next, last));
28
+ else {
29
+ const certainExpiry = Math.min(last, calendar.rank(cutoff - REMINDER_LIMITS.maxExpiryGraceMs) - 1);
30
+ expired.push(...range(next, certainExpiry));
31
+ for (let ordinal = Math.max(next, certainExpiry + 1); ordinal <= last; ordinal++) {
32
+ const timing = routineExpiry(calendar, calendar.at(ordinal)!, grace);
33
+ append(timing.expiresAt! <= cutoff ? expired : live, ordinal);
34
+ }
35
+ }
36
+
37
+ if (policy === "skip") return { expired, discarded: live, queue: [], coalesced: [] };
38
+ if (policy === "coalesce") return { expired, discarded: [], queue: [], coalesced: live };
39
+ const queue: number[] = [], discarded: OrdinalRange[] = [];
40
+ for (let index = live.length - 1; index >= 0; index--) {
41
+ const { first, last } = live[index]!;
42
+ const retained = Math.min(last - first + 1, MAX_ROUTINE_CATCH_UP - queue.length);
43
+ for (let ordinal = last; ordinal > last - retained; ordinal--) queue.push(ordinal);
44
+ discarded.push(...range(first, last - retained));
45
+ }
46
+ return { expired, discarded: discarded.reverse(), queue: queue.reverse(), coalesced: [] };
47
+ }
@@ -0,0 +1,15 @@
1
+ import type { RoutineCalendar } from "../../contracts/routines.ts";
2
+ import { REMINDER_LIMITS } from "../../util/reminder-schedule.ts";
3
+
4
+ /** End constraints do not affect expiry. The index supplies the next match
5
+ * on the underlying calendar, even when this occurrence is the last run. */
6
+ export function routineExpiry(calendar: RoutineCalendar, instant: number, grace?: number | null) {
7
+ if (grace === null) return { expiresAfter: null, expiresAt: null };
8
+ const { minExpiryGraceMs, maxExpiryGraceMs, expiryMultiplier } = REMINDER_LIMITS;
9
+ if (grace !== undefined && (!Number.isSafeInteger(grace) || grace < minExpiryGraceMs || grace > maxExpiryGraceMs))
10
+ throw new RangeError("Invalid routine expiry grace");
11
+ const next = calendar.nextCalendarMatch(instant);
12
+ if (grace === undefined && next === undefined) throw new RangeError("The calendar cannot determine the next match");
13
+ const expiresAfter = grace ?? Math.max(minExpiryGraceMs, Math.min(maxExpiryGraceMs, (next! - instant) * expiryMultiplier));
14
+ return { expiresAfter, expiresAt: instant + expiresAfter };
15
+ }
@@ -0,0 +1,65 @@
1
+ import type { RoutineCalendar, RoutineDeliveryOptions } from "../../contracts/routines.ts";
2
+ import { routineBacklog, type OrdinalRange } from "./routine-backlog.ts";
3
+ import { routineExpiry } from "./routine-expiry.ts";
4
+
5
+ type SkipReason = "expired" | "missed" | "catch_up_limit";
6
+ export type RoutineStep = OrdinalRange & (
7
+ | { kind: SkipReason }
8
+ | { kind: "enqueue"; represented: number }
9
+ | { kind: "coalesced" }
10
+ );
11
+
12
+ /** Build one episode's chronological steps. A persisted cursor can consume
13
+ * these in transaction-sized batches without reclassifying elapsed work. */
14
+ export function planRoutineEpisode(
15
+ calendar: RoutineCalendar, next: number, cutoff: number, grace: number | null | undefined,
16
+ missed: NonNullable<RoutineDeliveryOptions["missedRuns"]>,
17
+ ): RoutineStep[] {
18
+ const backlog = routineBacklog(calendar, next, cutoff, grace, missed);
19
+ const steps: RoutineStep[] = backlog.expired.map(range => ({ ...range, kind: "expired" }));
20
+ for (const range of backlog.discarded) steps.push({ ...range, kind: missed === "skip" ? "missed" : "catch_up_limit" });
21
+ for (const ordinal of backlog.queue) steps.push({ first: ordinal, last: ordinal, kind: "enqueue", represented: 1 });
22
+ const represented = backlog.coalesced.reduce((sum, range) => sum + range.last - range.first + 1, 0);
23
+ for (const [index, range] of backlog.coalesced.entries()) {
24
+ if (index + 1 === backlog.coalesced.length) steps.push({ ...range, kind: "enqueue", represented });
25
+ else steps.push({ ...range, kind: "coalesced" });
26
+ }
27
+ const current = calendar.rank(cutoff) - 1;
28
+ if (current >= next && current >= calendar.rank(Math.floor(cutoff / 60_000) * 60_000 - 1)) {
29
+ const expiry = routineExpiry(calendar, calendar.at(current)!, grace).expiresAt;
30
+ steps.push(expiry !== null && expiry <= cutoff ? { first: current, last: current, kind: "expired" }
31
+ : { first: current, last: current, kind: "enqueue", represented: 1 });
32
+ }
33
+ return steps.sort((left, right) => left.first - right.first);
34
+ }
35
+
36
+ export function routineOccurrenceIdentity(reminderId: string, instant: number) {
37
+ const scheduledAt = new Date(instant).toISOString();
38
+ return { scheduledAt, occurrenceId: `reminder:${reminderId}:${scheduledAt}`,
39
+ noticeId: `reminder-notice:${reminderId}:${scheduledAt}` };
40
+ }
41
+
42
+ type ExpiredDisposition = {
43
+ type: "routine_disposition";
44
+ reminderId: string;
45
+ firstScheduledAt: string;
46
+ lastScheduledAt: string;
47
+ count: number;
48
+ reason: "expired";
49
+ };
50
+
51
+ /** The disposition describes consumption only. The returned cursor and
52
+ * remaining count are for updating the authoritative row in the same commit. */
53
+ export function expireRoutineRange(reminderId: string, calendar: RoutineCalendar, range: OrdinalRange, remainingCount?: number) {
54
+ const first = calendar.at(range.first), last = calendar.at(range.last);
55
+ const count = range.last - range.first + 1;
56
+ if (first === undefined || last === undefined || count < 1 || (remainingCount !== undefined && count > remainingCount))
57
+ throw new RangeError("Invalid routine expiry range");
58
+ const remaining = remainingCount === undefined ? undefined : remainingCount - count;
59
+ const next = remaining === 0 ? undefined : calendar.at(range.last + 1);
60
+ const event: ExpiredDisposition = {
61
+ type: "routine_disposition", reminderId, reason: "expired", count,
62
+ firstScheduledAt: new Date(first).toISOString(), lastScheduledAt: new Date(last).toISOString(),
63
+ };
64
+ return { event, remainingCount: remaining, nextRunAt: next === undefined ? null : new Date(next).toISOString() };
65
+ }