@qlairoslabs/acp-client 0.13.0-alpha.1 → 0.13.1-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 (263) hide show
  1. package/CONSUMER_GUIDE.md +147 -8
  2. package/MIGRATION-0.12-to-0.13.md +20 -7
  3. package/package.json +9 -2
  4. package/src/agent/conversation-manager.ts +1 -0
  5. package/src/agent/native-operations.ts +39 -0
  6. package/src/agent-session-config.ts +2 -0
  7. package/src/agent-session.ts +1 -0
  8. package/src/agent.ts +97 -2
  9. package/src/client.ts +5 -3
  10. package/src/controller-connection.ts +1 -0
  11. package/src/controller.ts +2 -0
  12. package/src/index.ts +1 -0
  13. package/src/launcher.ts +2 -0
  14. package/src/native/approvals.ts +20 -3
  15. package/src/native/controller.ts +3 -2
  16. package/src/native/host.ts +73 -4
  17. package/src/native-harness/scripts/build-routine-zones.py +47 -0
  18. package/src/native-harness/src/capabilities/context/session.ts +2 -1
  19. package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
  20. package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
  21. package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
  22. package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
  23. package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
  24. package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
  25. package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
  26. package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
  27. package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
  28. package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
  29. package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
  30. package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
  31. package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
  32. package/src/native-harness/src/capabilities/tools/reminders/index.ts +27 -5
  33. package/src/native-harness/src/contracts/config-permissions.ts +3 -1
  34. package/src/native-harness/src/contracts/protocol.ts +1 -1
  35. package/src/native-harness/src/contracts/reminders.ts +4 -2
  36. package/src/native-harness/src/contracts/routines.ts +20 -0
  37. package/src/native-harness/src/contracts/session-file.ts +1 -0
  38. package/src/native-harness/src/contracts/session.ts +2 -2
  39. package/src/native-harness/src/contracts/storage.ts +11 -10
  40. package/src/native-harness/src/index.ts +6 -2
  41. package/src/native-harness/src/interfaces/protocol/server.ts +11 -9
  42. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +7 -0
  43. package/src/native-harness/src/kernel/channels.ts +8 -4
  44. package/src/native-harness/src/runtime/config/paths.ts +7 -1
  45. package/src/native-harness/src/runtime/reminder-validation.ts +31 -10
  46. package/src/native-harness/src/runtime/reminders.ts +2 -2
  47. package/src/native-harness/src/state/storage/archive.ts +27 -9
  48. package/src/native-harness/src/state/storage/engine.ts +214 -23
  49. package/src/native-harness/src/state/storage/memory-reminders.ts +31 -6
  50. package/src/native-harness/src/state/storage/memory.ts +15 -2
  51. package/src/native-harness/src/state/storage/reminder-archive.ts +53 -12
  52. package/src/native-harness/src/state/storage/reminder-change.ts +60 -14
  53. package/src/native-harness/src/state/storage/reminder-tables.ts +11 -3
  54. package/src/native-harness/src/state/storage/routine-row.ts +25 -0
  55. package/src/native-harness/src/state/storage/sqlite-reminders.ts +48 -8
  56. package/src/native-harness/src/state/storage/sqlite.ts +11 -4
  57. package/src/native-harness/src/testing.ts +1 -1
  58. package/src/native-harness/src/util/config.ts +10 -2
  59. package/src/native-harness/src/util/intake.ts +7 -0
  60. package/src/orchestrator/permissions.ts +6 -3
  61. package/src/permissions/conversation.ts +13 -5
  62. package/src/permissions/matcher.ts +2 -0
  63. package/src/permissions/outcome.ts +12 -1
  64. package/src/permissions/policy.ts +13 -8
  65. package/src/terminals.ts +9 -6
  66. package/src/native/reminders/reminders.test.ts +0 -553
  67. package/src/native/reminders/routine-config.typecheck.ts +0 -13
  68. package/src/native/reminders/wire.typecheck.ts +0 -13
  69. package/src/native-harness/.res/README.md +0 -1
  70. package/src/native-harness/.res/architecture/README.md +0 -21
  71. package/src/native-harness/.res/architecture/context-and-data.md +0 -31
  72. package/src/native-harness/.res/architecture/execution.md +0 -42
  73. package/src/native-harness/.res/architecture/overview.md +0 -44
  74. package/src/native-harness/.res/architecture/persistence.md +0 -56
  75. package/src/native-harness/.res/architecture/suspend-and-resume.md +0 -45
  76. package/src/native-harness/.res/architecture/technical-architecture.md +0 -50
  77. package/src/native-harness/.res/decisions/0001-basic-loop.md +0 -11
  78. package/src/native-harness/.res/decisions/0002-channel-input.md +0 -17
  79. package/src/native-harness/.res/decisions/0003-inference-inspection.md +0 -14
  80. package/src/native-harness/.res/decisions/0004-shared-context.md +0 -21
  81. package/src/native-harness/.res/decisions/0005-notice-inbox.md +0 -20
  82. package/src/native-harness/.res/decisions/0006-explicit-notices.md +0 -12
  83. package/src/native-harness/.res/decisions/0007-channel-output.md +0 -12
  84. package/src/native-harness/.res/decisions/0008-browser-client.md +0 -16
  85. package/src/native-harness/.res/decisions/0009-scripted-model.md +0 -18
  86. package/src/native-harness/.res/decisions/0010-inprocess-protocol.md +0 -19
  87. package/src/native-harness/.res/decisions/0011-stdio-transport.md +0 -21
  88. package/src/native-harness/.res/decisions/0012-session-storage-contract.md +0 -37
  89. package/src/native-harness/.res/decisions/0013-durable-delivery-contract.md +0 -64
  90. package/src/native-harness/.res/decisions/0014-channel-controls-contract.md +0 -73
  91. package/src/native-harness/.res/decisions/0015-session-file-contract.md +0 -72
  92. package/src/native-harness/.res/decisions/0016-configuration-permissions.md +0 -159
  93. package/src/native-harness/.res/decisions/0017-openrouter-managed-config.md +0 -69
  94. package/src/native-harness/.res/decisions/0018-tool-dispatch-evidence.md +0 -78
  95. package/src/native-harness/.res/decisions/0019-model-execution.md +0 -188
  96. package/src/native-harness/.res/decisions/0020-startup-channel-changes.md +0 -71
  97. package/src/native-harness/.res/decisions/0021-tools-and-host-callbacks.md +0 -100
  98. package/src/native-harness/.res/decisions/0022-operator-controls.md +0 -115
  99. package/src/native-harness/.res/decisions/0023-long-running-mock.md +0 -82
  100. package/src/native-harness/.res/decisions/0024-callback-policy-names.md +0 -46
  101. package/src/native-harness/.res/decisions/0025-external-notices.md +0 -364
  102. package/src/native-harness/.res/decisions/0026-bounded-context.md +0 -81
  103. package/src/native-harness/.res/decisions/0027-development-instructions.md +0 -22
  104. package/src/native-harness/.res/decisions/0028-debug-tools.md +0 -16
  105. package/src/native-harness/.res/decisions/0029-bounded-model-call-pages.md +0 -37
  106. package/src/native-harness/.res/decisions/0030-timeline-retrieval.md +0 -145
  107. package/src/native-harness/.res/decisions/0031-one-off-reminders.md +0 -173
  108. package/src/native-harness/.res/docs/11-15.md +0 -148
  109. package/src/native-harness/.res/docs/BUSINESS_RULES.md +0 -111
  110. package/src/native-harness/.res/docs/WORK.md +0 -65
  111. package/src/native-harness/.res/docs/_/11-16-persistence/LOG.md +0 -312
  112. package/src/native-harness/.res/docs/_/11-16-persistence/PLAN.md +0 -77
  113. package/src/native-harness/.res/docs/_/11-16-persistence/SPEC.md +0 -313
  114. package/src/native-harness/.res/docs/_/11-19-channel-controls/LOG.md +0 -160
  115. package/src/native-harness/.res/docs/_/11-19-channel-controls/PLAN.md +0 -89
  116. package/src/native-harness/.res/docs/_/11-19-channel-controls/SPEC.md +0 -135
  117. package/src/native-harness/.res/docs/_/11-19-config-permissions/LOG.md +0 -143
  118. package/src/native-harness/.res/docs/_/11-19-config-permissions/PLAN.md +0 -93
  119. package/src/native-harness/.res/docs/_/11-19-config-permissions/SPEC.md +0 -181
  120. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/11-20-LOG.md +0 -433
  121. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PLAN.md +0 -60
  122. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PROTOCOL.md +0 -141
  123. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/SPEC.md +0 -168
  124. package/src/native-harness/.res/docs/attachments/0001-DESIGN/SPEC.md +0 -111
  125. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/PLAN.md +0 -129
  126. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/SPEC.md +0 -135
  127. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/LOG.md +0 -437
  128. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/PLAN.md +0 -127
  129. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/SPEC.md +0 -203
  130. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/LOG.md +0 -292
  131. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/PLAN.md +0 -91
  132. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/SPEC.md +0 -187
  133. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/LOG.md +0 -148
  134. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/PLAN.md +0 -95
  135. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/SPEC.md +0 -200
  136. package/src/native-harness/.res/docs/model-execution/0002-AMENDMENT-accounting/SPEC.md +0 -80
  137. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/LOG.md +0 -206
  138. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/PLAN.md +0 -106
  139. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/SPEC.md +0 -297
  140. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/LOG.md +0 -41
  141. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/PLAN.md +0 -36
  142. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/SPEC.md +0 -84
  143. package/src/native-harness/.res/docs/shell-execution/0001-DESIGN/SPEC.md +0 -147
  144. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/LOG.md +0 -15
  145. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/PLAN.md +0 -107
  146. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/SPEC.md +0 -114
  147. package/src/native-harness/.res/docs/todos/11-19-TODO-auto_review-approve.md +0 -24
  148. package/src/native-harness/.res/docs/todos/11-20-TODO-user-entered-tool-code.md +0 -23
  149. package/src/native-harness/.res/docs/todos/11-21-TODO-node-resource-coordination.md +0 -103
  150. package/src/native-harness/.res/docs/todos/11-22-TODO-harness-m1-sequence.md +0 -50
  151. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/LOG.md +0 -337
  152. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/PLAN.md +0 -76
  153. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/SPEC.md +0 -204
  154. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/LOG.md +0 -73
  155. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/SPEC.md +0 -64
  156. package/src/native-harness/.res/docs/tools-and-callbacks/0003-DESIGN-attachment-tools/SPEC.md +0 -58
  157. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/LOG.md +0 -45
  158. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/PLAN.md +0 -108
  159. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/SPEC.md +0 -169
  160. package/src/native-harness/.res/docs/web-tools/0001-DESIGN/SPEC.md +0 -128
  161. package/src/native-harness/.res/marketing-draft.md +0 -22
  162. package/src/native-harness/.res/sandbox/1-simple-harness/README.md +0 -285
  163. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-1.md +0 -19
  164. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-10.md +0 -138
  165. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-11.md +0 -148
  166. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-12.md +0 -172
  167. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-13.md +0 -194
  168. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-14.md +0 -233
  169. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-15.md +0 -249
  170. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-16.md +0 -265
  171. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-17.md +0 -279
  172. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-18.md +0 -293
  173. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-19.md +0 -307
  174. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-2.md +0 -29
  175. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-20.md +0 -317
  176. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-21.md +0 -327
  177. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-3.md +0 -40
  178. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-4.md +0 -59
  179. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-5.md +0 -69
  180. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-6.md +0 -79
  181. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-7.md +0 -89
  182. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-8.md +0 -102
  183. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-9.md +0 -116
  184. package/src/native-harness/.res/sandbox/1-simple-harness/conversation.jsonl +0 -49
  185. package/src/native-harness/.res/sandbox/1-simple-harness/doc.md +0 -87
  186. package/src/native-harness/.res/sandbox/1-simple-harness/harness.py +0 -289
  187. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 2.py +0 -221
  188. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 3.py +0 -287
  189. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy.py +0 -165
  190. package/src/native-harness/.res/sandbox/1-simple-harness/state.json +0 -22
  191. package/src/native-harness/.res/sandbox/1-simple-harness/system-prompt.md +0 -2
  192. package/src/native-harness/AGENTS.md +0 -70
  193. package/src/native-harness/ARCHITECTURE.md +0 -249
  194. package/src/native-harness/bun.lock +0 -26
  195. package/src/native-harness/test/agent.test.ts +0 -130
  196. package/src/native-harness/test/approval-gate.test.ts +0 -255
  197. package/src/native-harness/test/approval-protocol.test.ts +0 -94
  198. package/src/native-harness/test/boundaries.test.ts +0 -18
  199. package/src/native-harness/test/channel-controls.test.ts +0 -322
  200. package/src/native-harness/test/client-abort.test.ts +0 -136
  201. package/src/native-harness/test/config-policy.test.ts +0 -301
  202. package/src/native-harness/test/conformance/storage.ts +0 -1141
  203. package/src/native-harness/test/context.test.ts +0 -177
  204. package/src/native-harness/test/crash.test.ts +0 -187
  205. package/src/native-harness/test/debug-tools.test.ts +0 -67
  206. package/src/native-harness/test/development-cli.test.ts +0 -67
  207. package/src/native-harness/test/development.test.ts +0 -171
  208. package/src/native-harness/test/dispatch-evidence.test.ts +0 -58
  209. package/src/native-harness/test/e2e.test.ts +0 -186
  210. package/src/native-harness/test/external-notices.test.ts +0 -101
  211. package/src/native-harness/test/fixtures/approval-e2e.jsonl +0 -4
  212. package/src/native-harness/test/fixtures/crash-scenario.jsonl +0 -5
  213. package/src/native-harness/test/fixtures/development-lifecycle.jsonl +0 -10
  214. package/src/native-harness/test/fixtures/echo-scenario.jsonl +0 -3
  215. package/src/native-harness/test/fixtures/format2-schema.ts +0 -27
  216. package/src/native-harness/test/fixtures/format3-schema.ts +0 -16
  217. package/src/native-harness/test/fixtures/hold-scenario.jsonl +0 -4
  218. package/src/native-harness/test/fixtures/model-e2e.jsonl +0 -3
  219. package/src/native-harness/test/fixtures/storage-owner.ts +0 -20
  220. package/src/native-harness/test/format-reply.test.ts +0 -10
  221. package/src/native-harness/test/helpers/operator-view.ts +0 -41
  222. package/src/native-harness/test/helpers/scenario.ts +0 -9
  223. package/src/native-harness/test/helpers/session.ts +0 -38
  224. package/src/native-harness/test/helpers/stdio.ts +0 -46
  225. package/src/native-harness/test/inspector.test.ts +0 -77
  226. package/src/native-harness/test/listeners.test.ts +0 -49
  227. package/src/native-harness/test/loop.test.ts +0 -88
  228. package/src/native-harness/test/model-channel-double.test.ts +0 -87
  229. package/src/native-harness/test/model-crash.test.ts +0 -62
  230. package/src/native-harness/test/model-delivery-regressions.test.ts +0 -55
  231. package/src/native-harness/test/model-e2e.test.ts +0 -71
  232. package/src/native-harness/test/model-final-filter.test.ts +0 -30
  233. package/src/native-harness/test/model-large-reply.test.ts +0 -28
  234. package/src/native-harness/test/model-live-queue.test.ts +0 -33
  235. package/src/native-harness/test/model-runner.test.ts +0 -117
  236. package/src/native-harness/test/model-storage.test.ts +0 -99
  237. package/src/native-harness/test/model-stream-adapter.test.ts +0 -26
  238. package/src/native-harness/test/model-stream-public.test.ts +0 -77
  239. package/src/native-harness/test/notices.test.ts +0 -64
  240. package/src/native-harness/test/openrouter-config.test.ts +0 -218
  241. package/src/native-harness/test/operator-controls.test.ts +0 -132
  242. package/src/native-harness/test/output.test.ts +0 -44
  243. package/src/native-harness/test/owner-config.test.ts +0 -64
  244. package/src/native-harness/test/permissions-e2e.test.ts +0 -68
  245. package/src/native-harness/test/persistence.test.ts +0 -236
  246. package/src/native-harness/test/portability.test.ts +0 -337
  247. package/src/native-harness/test/protocol.test.ts +0 -160
  248. package/src/native-harness/test/reminder-clock.test.ts +0 -61
  249. package/src/native-harness/test/reminder-stdio.test.ts +0 -140
  250. package/src/native-harness/test/reminder-storage.test.ts +0 -124
  251. package/src/native-harness/test/scenario-jsonl.test.ts +0 -112
  252. package/src/native-harness/test/scripted.test.ts +0 -92
  253. package/src/native-harness/test/session-file.test.ts +0 -51
  254. package/src/native-harness/test/startup-channel-changes.test.ts +0 -256
  255. package/src/native-harness/test/stdio.test.ts +0 -132
  256. package/src/native-harness/test/storage-memory.test.ts +0 -4
  257. package/src/native-harness/test/storage-sqlite.test.ts +0 -420
  258. package/src/native-harness/test/suspension.test.ts +0 -430
  259. package/src/native-harness/test/timeline-retrieval.test.ts +0 -211
  260. package/src/native-harness/test/tools-catalog.test.ts +0 -468
  261. package/src/native-harness/test/tools-protocol.test.ts +0 -418
  262. package/src/native-harness/test/transfers.test.ts +0 -94
  263. package/src/native-harness/test/web-chat.test.ts +0 -35
@@ -485,7 +485,7 @@ export class NativeController implements ConversationController, ChannelPort {
485
485
  // that end must not wait behind the question.
486
486
  if (turn.approvals.has(event.requestId)) return;
487
487
  turn.approvals.add(event.requestId);
488
- const approval = this.#approve(event, handlers,
488
+ const approval = this.#approve(turn, event, handlers,
489
489
  AbortSignal.any([approvals.signal, attachment]), signal);
490
490
  if (recordingPermissionHandlers.has(handlers.onPermissionRequest!)) {
491
491
  approvalWork.add(approval);
@@ -524,9 +524,10 @@ export class NativeController implements ConversationController, ChannelPort {
524
524
  });
525
525
  }
526
526
 
527
- async #approve(event: Extract<TurnScoped, { type: "approval_requested" }>, handlers: PromptHandlers, cancelled: AbortSignal, signal: (output: ProviderOutput) => void): Promise<void> {
527
+ async #approve(turn: Turn, event: Extract<TurnScoped, { type: "approval_requested" }>, handlers: PromptHandlers, cancelled: AbortSignal, signal: (output: ProviderOutput) => void): Promise<void> {
528
528
  const ticket = this.#host.approvalFor(event);
529
529
  if (!ticket) return;
530
+ ticket.onCancelTurn?.(() => { turn.cancelRequested = true; });
530
531
  const sessionId = this.#host.sessionId;
531
532
  signal({ kind: "permission_started", sessionId });
532
533
  try { await runNativeApproval(ticket, event, handlers, cancelled, this.#log); }
@@ -85,7 +85,8 @@ const REQUIRED_METHODS = ["session/open", "channel/observe", "channel/reconcile"
85
85
  export class NativeHarnessHost {
86
86
  readonly sessionId: string;
87
87
  readonly records: NativeHostRecords;
88
- readonly #config: NativeHarnessHostConfig;
88
+ #config: NativeHarnessHostConfig;
89
+ #restartTransition?: Promise<void>;
89
90
  readonly #log: Logger;
90
91
  reminderSync?: ReminderSync;
91
92
  reminderWake?: ReminderWakeSupervisor;
@@ -121,7 +122,7 @@ export class NativeHarnessHost {
121
122
  || this.#changes.busy || [...this.#ports.values()].some(port => port.busy());
122
123
  }
123
124
 
124
- #idleStop(window: number, stillIdle: () => boolean): Promise<ConditionalStopResult> {
125
+ #idleStop(window: number, stillIdle: () => boolean, onStopped?: () => void): Promise<ConditionalStopResult> {
125
126
  if (this.#idling) return this.#idling;
126
127
  const connection = this.#connection;
127
128
  if (this.#stoppingExplicitly || !connection || !stillIdle() || this.#localBusy()) return Promise.resolve({ stopped: false, reason: "busy" });
@@ -130,6 +131,7 @@ export class NativeHarnessHost {
130
131
  await this.reminderSync?.settled();
131
132
  if (result.stopped && this.#connection === connection) {
132
133
  this.#connection = null;
134
+ onStopped?.();
133
135
  this.#approvals.stop();
134
136
  for (const port of this.#ports.values()) port.disconnected();
135
137
  try { await connection.kill(); } finally { this.#setState("stopped"); }
@@ -240,8 +242,9 @@ export class NativeHarnessHost {
240
242
 
241
243
  #observeApproval(connection: NativeConnection, { channel, event }: ChannelEvent): void {
242
244
  if (event.type === "approval_requested") {
243
- this.#approvals.observe(channel, event, async decision =>
244
- this.#connection === connection && this.#answerApproval(event.requestId, decision));
245
+ this.#approvals.observe(channel, event,
246
+ async decision => this.#connection === connection && this.#answerApproval(event.requestId, decision),
247
+ async () => this.#connection === connection && this.interrupt(channel, event.turnId, "unanswered permission"));
245
248
  } else if (event.type === "approval_closed") {
246
249
  this.#approvals.closed(event);
247
250
  }
@@ -301,8 +304,72 @@ export class NativeHarnessHost {
301
304
  }
302
305
  }
303
306
 
307
+ async waitForIdle(signal?: AbortSignal): Promise<void> {
308
+ for (;;) {
309
+ signal?.throwIfAborted();
310
+ if (!this.#localBusy() && !this.#starting && !this.#stoppingExplicitly) {
311
+ const connection = this.#connection;
312
+ if (!connection) return;
313
+ const status = await connection.client.status();
314
+ signal?.throwIfAborted();
315
+ if (connection === this.#connection && !this.#localBusy() &&
316
+ (status.execution === "idle" || status.execution === "suspended") && status.channels.every(
317
+ channel => !channel.activeTurn && !channel.waitingForResume && channel.pending.length === 0,
318
+ )) return;
319
+ }
320
+ await new Promise<void>(resolve => setTimeout(resolve, 25));
321
+ }
322
+ }
323
+
324
+ async restartForAgent(options: import("../agent/native-operations.ts").NativeRestartOptions,
325
+ interrupted: { channel: string; turnId: string }[]): Promise<void> {
326
+ const { signal, when = "idle" } = options;
327
+ signal?.throwIfAborted();
328
+ let configured = false;
329
+ const configure = () => {
330
+ if (configured) return;
331
+ configured = true;
332
+ if (options.functions !== undefined) {
333
+ this.#functions?.dispose();
334
+ this.#functions = null;
335
+ }
336
+ this.#config = { ...this.#config, ...(options.config ? { config: options.config } : {}),
337
+ ...(options.functions !== undefined ? { functions: options.functions ?? undefined } : {}) };
338
+ };
339
+ if (when === "idle") {
340
+ for (;;) {
341
+ await this.waitForIdle(signal);
342
+ if (!this.#connection) break;
343
+ if ((await this.#idleStop(0, () => !signal?.aborted, configure)).stopped) break;
344
+ await new Promise<void>(resolve => setTimeout(resolve, 25));
345
+ }
346
+ configure();
347
+ } else {
348
+ const transition = async () => {
349
+ await this.#starting;
350
+ const connection = this.#connection;
351
+ if (connection) {
352
+ const { channels } = await connection.client.status();
353
+ await Promise.all(channels.map(async ({ channel, activeTurn }) => {
354
+ if (activeTurn?.state === "running" && await this.interrupt(channel, activeTurn.turnId, "agent_restart")) {
355
+ interrupted.push({ channel, turnId: activeTurn.turnId });
356
+ }
357
+ }));
358
+ }
359
+ await this.stop();
360
+ configure();
361
+ };
362
+ const pending = this.#restartTransition = transition();
363
+ try { await pending; }
364
+ finally { if (this.#restartTransition === pending) this.#restartTransition = undefined; }
365
+ }
366
+ signal?.throwIfAborted();
367
+ await this.restart();
368
+ }
369
+
304
370
  /** Starts the harness if it is not running. Concurrent callers share one start. */
305
371
  ensureStarted(): Promise<void> {
372
+ if (this.#restartTransition) return this.#restartTransition.then(() => this.ensureStarted());
306
373
  if (this.#idling) return this.#idling.catch(() => {}).then(() => this.ensureStarted());
307
374
  if (this.#wakeFailure) { this.#wakeFailure = null; this.#restarts.length = 0; }
308
375
  this.reminderIdle?.activity();
@@ -678,6 +745,7 @@ export class NativeHarnessHost {
678
745
  * definite refusal (suspended or retired channel, unknown policy, a conflicting id) rejects it.
679
746
  */
680
747
  async push(input: Omit<Submission, "state">): Promise<ItemStatus> {
748
+ if (this.#restartTransition) await this.#restartTransition;
681
749
  this.records.saveSubmission({ ...input, state: "saved" });
682
750
  const waiter = this.#waiters.get(input.id) ?? deferred<ItemStatus>();
683
751
  this.#waiters.set(input.id, waiter);
@@ -760,6 +828,7 @@ export class NativeHarnessHost {
760
828
  * the harness.
761
829
  */
762
830
  async changeChannel(channel: string, desire: ChannelDesire): Promise<ChannelChangeOutcome> {
831
+ if (this.#restartTransition) await this.#restartTransition;
763
832
  if (this.#idling) await this.ensureStarted();
764
833
  this.reminderIdle?.activity();
765
834
  const result = await this.#changes.change(channel, desire, this.#state === "running");
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env python3
2
+ """Build the public-domain IANA offset catalog from a matching zoneinfo tree."""
3
+ import calendar
4
+ import gzip
5
+ import json
6
+ import re
7
+ import subprocess
8
+ import sys
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+ from zoneinfo import ZoneInfo
12
+
13
+ root = Path(sys.argv[1] if len(sys.argv) > 1 else "/usr/share/zoneinfo").resolve()
14
+ source = (root / "tzdata.zi").read_text().splitlines()
15
+ version = source[0].split()[2]
16
+ epoch = calendar.timegm((2100, 1, 1, 0, 0, 0))
17
+ cycle = 146097 * 86400
18
+ zones = {}
19
+ aliases = {}
20
+ for line in source:
21
+ fields = line.split()
22
+ if fields and fields[0] == "L":
23
+ aliases[fields[2]] = fields[1]
24
+ if not fields or fields[0] != "Z":
25
+ continue
26
+ name = fields[1]
27
+ with (root / name).open("rb") as file:
28
+ zone = ZoneInfo.from_file(file)
29
+ initial = int(datetime(1800, 1, 1, tzinfo=timezone.utc).astimezone(zone).utcoffset().total_seconds())
30
+ changes = []
31
+ last = initial
32
+ listing = subprocess.check_output(["zdump", "-v", "-c", "1800,2900", str(root / name)], text=True)
33
+ for match in re.finditer(r" (\w{3} \w{3} +\d+ \d\d:\d\d:\d\d \d+) UT = .* gmtoff=(-?\d+)$", listing, re.M):
34
+ offset = int(match[2])
35
+ if offset != last:
36
+ instant = calendar.timegm(datetime.strptime(match[1], "%a %b %d %H:%M:%S %Y").timetuple())
37
+ changes.append((instant, offset))
38
+ last = offset
39
+ first = [(at - epoch, offset) for at, offset in changes if epoch <= at < epoch + cycle]
40
+ second = [(at - epoch - cycle, offset) for at, offset in changes if epoch + cycle <= at]
41
+ if first != second:
42
+ raise RuntimeError(f"Unproved 400-year tail for {name}")
43
+ zones[name] = [initial, [row for row in changes if row[0] < epoch + cycle]]
44
+
45
+ output = Path(__file__).resolve().parents[1] / "src/capabilities/reminders/iana-zones.json.gz"
46
+ output.write_bytes(gzip.compress(json.dumps([version, epoch, cycle, zones, aliases], separators=(",", ":"), sort_keys=True).encode(), mtime=0))
47
+ print(version, len(zones), len(aliases), output.stat().st_size)
@@ -1,3 +1,4 @@
1
+ import { SESSION_INTAKE_LIMITS } from "../../util/intake.ts";
1
2
  import { isTimelineTool } from "../../util/timeline-tool-names.ts";
2
3
  import type { ContextLimits, InferenceContext, InferenceStorageReads, ContextBuildResult, ContextCapture, ContextTurnOutcome } from "../../contracts/context.ts";
3
4
  import { SESSION_INPUT_MAX_BYTES } from "../../contracts/input-limits.ts";
@@ -7,7 +8,7 @@ import { buildContext } from "./build.ts";
7
8
  import { composeSystemPrompt } from "./load-instructions.ts";
8
9
 
9
10
  export const CONTEXT_LIMITS: ContextLimits = {
10
- maxInputBytes: SESSION_INPUT_MAX_BYTES, maxTakenTextBytes: SESSION_INPUT_MAX_BYTES, maxTakenItems: 16,
11
+ maxInputBytes: SESSION_INPUT_MAX_BYTES, ...SESSION_INTAKE_LIMITS,
11
12
  maxReadBytes: 256 * 1024, maxReadRecords: 64, maxSharedCandidates: 128,
12
13
  contextTokens: 16_384, outputReserveTokens: 2048, estimationMarginTokens: 1024,
13
14
  };
@@ -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
+ }