@qlairoslabs/acp-client 0.12.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 (288) hide show
  1. package/CHANGELOG-consumer-fixes.md +17 -10
  2. package/CHANGELOG-controller-interface.md +258 -0
  3. package/CHANGELOG-metering.md +29 -0
  4. package/CHANGELOG-operation-lifecycle.md +15 -1
  5. package/CONSUMER_GUIDE.md +984 -6
  6. package/MIGRATION-0.10-to-0.12.md +4 -1
  7. package/MIGRATION-0.12-to-0.13.md +288 -0
  8. package/README.md +17 -16
  9. package/package.json +11 -2
  10. package/src/acp-client-handlers.ts +48 -0
  11. package/src/activity.ts +3 -0
  12. package/src/adapters.ts +25 -0
  13. package/src/agent/adoption/provider-attachment.ts +33 -0
  14. package/src/agent/adoption/provider-session-delete.ts +1 -1
  15. package/src/agent/adoption/provider-sessions.ts +3 -2
  16. package/src/agent/append-assistant-message.ts +91 -0
  17. package/src/agent/config.ts +54 -6
  18. package/src/agent/conversation-manager.ts +95 -158
  19. package/src/agent/manager-settings.ts +1 -0
  20. package/src/agent/native-channel-lifecycle.ts +111 -0
  21. package/src/agent/native-operations.ts +39 -0
  22. package/src/agent/persisted-lifecycle.ts +44 -4
  23. package/src/agent/persistence-policy/context.ts +13 -0
  24. package/src/agent/persistence-policy/resolver.ts +7 -0
  25. package/src/agent/persistence-policy/types.ts +1 -0
  26. package/src/agent/record-capture.ts +1 -0
  27. package/src/agent-adapter-registry.ts +33 -7
  28. package/src/agent-conversation-contracts.ts +14 -1
  29. package/src/agent-conversation-errors.ts +8 -0
  30. package/src/agent-conversation-owner.ts +9 -4
  31. package/src/agent-session-config.ts +137 -0
  32. package/src/agent-session.ts +440 -934
  33. package/src/agent.ts +168 -0
  34. package/src/capabilities.ts +2 -0
  35. package/src/checkpointing/recovery.ts +3 -0
  36. package/src/cli/index.ts +3 -3
  37. package/src/cli/managed.ts +2 -2
  38. package/src/client.ts +56 -96
  39. package/src/connection-attempt.ts +95 -0
  40. package/src/controller-connection.ts +115 -0
  41. package/src/controller.ts +158 -148
  42. package/src/conversation-controller/capabilities.ts +88 -0
  43. package/src/conversation-controller/contracts.ts +208 -0
  44. package/src/conversation-controller/factory.ts +39 -0
  45. package/src/conversation-controller/guards.ts +98 -0
  46. package/src/conversation-controller/index.ts +20 -0
  47. package/src/conversation-startup.ts +35 -0
  48. package/src/conversation-turns/backend-turns.ts +373 -0
  49. package/src/conversation-turns/clear-operations.ts +37 -0
  50. package/src/conversation-turns/context.ts +135 -0
  51. package/src/conversation-turns/index.ts +4 -0
  52. package/src/conversation-turns/record-helpers.ts +75 -0
  53. package/src/conversation-turns/recording.ts +235 -0
  54. package/src/conversation-turns/run-turn.ts +367 -0
  55. package/src/conversation-turns/turn-run.ts +57 -0
  56. package/src/errors.ts +41 -0
  57. package/src/handoff-options.ts +81 -0
  58. package/src/identity/checkpoint-backed.ts +1 -1
  59. package/src/index.ts +59 -3
  60. package/src/internal-inference/coordination/manager.ts +11 -0
  61. package/src/internal-inference/runtime/harness-runtime.ts +4 -4
  62. package/src/launcher.ts +37 -2
  63. package/src/media/parts.ts +5 -0
  64. package/src/message-status.ts +83 -0
  65. package/src/metering/engine.ts +39 -64
  66. package/src/metering/measurement-provenance.ts +36 -0
  67. package/src/metering/native/durability.ts +115 -0
  68. package/src/metering/native/ledger.ts +104 -0
  69. package/src/metering/native/operation.ts +85 -0
  70. package/src/metering/native/projection.ts +114 -0
  71. package/src/metering/native/proof.ts +51 -0
  72. package/src/metering/native/requirements.ts +10 -0
  73. package/src/metering/native/retirement.ts +92 -0
  74. package/src/metering/native/source.ts +90 -0
  75. package/src/metering/record.ts +38 -1
  76. package/src/metering/state.ts +13 -3
  77. package/src/native/approvals.ts +186 -0
  78. package/src/native/capabilities.ts +17 -0
  79. package/src/native/channel-changes.ts +211 -0
  80. package/src/native/connection.ts +56 -0
  81. package/src/native/controller.ts +592 -0
  82. package/src/native/delegation-sender.ts +26 -0
  83. package/src/native/errors.ts +35 -0
  84. package/src/native/functions.ts +156 -0
  85. package/src/native/host-config.ts +59 -0
  86. package/src/native/host.ts +978 -0
  87. package/src/native/item-receipts.ts +15 -0
  88. package/src/native/metering.ts +12 -0
  89. package/src/native/records.ts +166 -0
  90. package/src/native/recovery.ts +186 -0
  91. package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
  92. package/src/native/reminders/idle.ts +70 -0
  93. package/src/native/reminders/limits.ts +19 -0
  94. package/src/native/reminders/notifications.ts +29 -0
  95. package/src/native/reminders/routine-guard.ts +66 -0
  96. package/src/native/reminders/routine-schedule.ts +25 -0
  97. package/src/native/reminders/routine-wire.ts +21 -0
  98. package/src/native/reminders/schedule.ts +97 -0
  99. package/src/native/reminders/service.ts +280 -0
  100. package/src/native/reminders/supervisor.ts +91 -0
  101. package/src/native/reminders/sync.ts +301 -0
  102. package/src/native/reminders/wire.ts +197 -0
  103. package/src/native/submission-withdrawal.ts +65 -0
  104. package/src/native/usage.ts +15 -0
  105. package/src/native/worker-delivery.ts +61 -0
  106. package/src/native-harness/README.md +726 -0
  107. package/src/native-harness/package.json +24 -0
  108. package/src/native-harness/scripts/build-routine-zones.py +47 -0
  109. package/src/native-harness/src/capabilities/context/build.ts +59 -0
  110. package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
  111. package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
  112. package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
  113. package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
  114. package/src/native-harness/src/capabilities/context/session.ts +93 -0
  115. package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
  116. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
  117. package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
  118. package/src/native-harness/src/capabilities/model/runner.ts +116 -0
  119. package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
  120. package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
  121. package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
  122. package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
  123. package/src/native-harness/src/capabilities/model/usage.ts +15 -0
  124. package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
  125. package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
  126. package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
  127. package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
  128. package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
  129. package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
  130. package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
  131. package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
  132. package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
  133. package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
  134. package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
  135. package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
  136. package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
  137. package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
  138. package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
  139. package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
  140. package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
  141. package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
  142. package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
  143. package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
  144. package/src/native-harness/src/capabilities/tools/reminders/index.ts +97 -0
  145. package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
  146. package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
  147. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
  148. package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
  149. package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
  150. package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
  151. package/src/native-harness/src/client.ts +18 -0
  152. package/src/native-harness/src/contracts/agent.ts +105 -0
  153. package/src/native-harness/src/contracts/config-permissions.ts +49 -0
  154. package/src/native-harness/src/contracts/context.ts +112 -0
  155. package/src/native-harness/src/contracts/events.ts +47 -0
  156. package/src/native-harness/src/contracts/input-limits.ts +7 -0
  157. package/src/native-harness/src/contracts/inspection.ts +22 -0
  158. package/src/native-harness/src/contracts/loop.ts +31 -0
  159. package/src/native-harness/src/contracts/model-execution.ts +83 -0
  160. package/src/native-harness/src/contracts/operator-controls.ts +106 -0
  161. package/src/native-harness/src/contracts/output.ts +13 -0
  162. package/src/native-harness/src/contracts/protocol.ts +320 -0
  163. package/src/native-harness/src/contracts/reminders.ts +134 -0
  164. package/src/native-harness/src/contracts/routines.ts +20 -0
  165. package/src/native-harness/src/contracts/scenario.ts +42 -0
  166. package/src/native-harness/src/contracts/session-file.ts +20 -0
  167. package/src/native-harness/src/contracts/session.ts +184 -0
  168. package/src/native-harness/src/contracts/storage.ts +597 -0
  169. package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
  170. package/src/native-harness/src/contracts/tools.ts +133 -0
  171. package/src/native-harness/src/governance/permissions/gate.ts +129 -0
  172. package/src/native-harness/src/governance/policy/resolve.ts +32 -0
  173. package/src/native-harness/src/index.ts +322 -0
  174. package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
  175. package/src/native-harness/src/interfaces/cli/development.ts +145 -0
  176. package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
  177. package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
  178. package/src/native-harness/src/interfaces/cli/main.ts +47 -0
  179. package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
  180. package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
  181. package/src/native-harness/src/interfaces/cli/start.ts +106 -0
  182. package/src/native-harness/src/interfaces/client.ts +225 -0
  183. package/src/native-harness/src/interfaces/inspector/index.html +283 -0
  184. package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
  185. package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
  186. package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
  187. package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
  188. package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
  189. package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
  190. package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
  191. package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
  192. package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
  193. package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
  194. package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
  195. package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
  196. package/src/native-harness/src/interfaces/protocol/server.ts +519 -0
  197. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +126 -0
  198. package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
  199. package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
  200. package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
  201. package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
  202. package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
  203. package/src/native-harness/src/kernel/channels.ts +409 -0
  204. package/src/native-harness/src/kernel/loop.ts +45 -0
  205. package/src/native-harness/src/runtime/config/development.ts +23 -0
  206. package/src/native-harness/src/runtime/config/managed.ts +2 -0
  207. package/src/native-harness/src/runtime/config/paths.ts +33 -0
  208. package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
  209. package/src/native-harness/src/runtime/reminder-validation.ts +125 -0
  210. package/src/native-harness/src/runtime/reminders.ts +66 -0
  211. package/src/native-harness/src/state/storage/archive.ts +257 -0
  212. package/src/native-harness/src/state/storage/engine.ts +1204 -0
  213. package/src/native-harness/src/state/storage/inference.ts +124 -0
  214. package/src/native-harness/src/state/storage/memory-reminders.ts +103 -0
  215. package/src/native-harness/src/state/storage/memory.ts +354 -0
  216. package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
  217. package/src/native-harness/src/state/storage/reminder-archive.ts +104 -0
  218. package/src/native-harness/src/state/storage/reminder-change.ts +138 -0
  219. package/src/native-harness/src/state/storage/reminder-tables.ts +35 -0
  220. package/src/native-harness/src/state/storage/retrieval.ts +122 -0
  221. package/src/native-harness/src/state/storage/routine-row.ts +25 -0
  222. package/src/native-harness/src/state/storage/script-identity.ts +7 -0
  223. package/src/native-harness/src/state/storage/session-file.ts +85 -0
  224. package/src/native-harness/src/state/storage/sqlite-reminders.ts +174 -0
  225. package/src/native-harness/src/state/storage/sqlite.ts +632 -0
  226. package/src/native-harness/src/testing.ts +190 -0
  227. package/src/native-harness/src/util/config.ts +66 -0
  228. package/src/native-harness/src/util/intake.ts +7 -0
  229. package/src/native-harness/src/util/json.ts +41 -0
  230. package/src/native-harness/src/util/message-position.ts +3 -0
  231. package/src/native-harness/src/util/reminder-schedule.ts +44 -0
  232. package/src/native-harness/src/util/schema.ts +40 -0
  233. package/src/native-harness/src/util/timeline-text.ts +72 -0
  234. package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
  235. package/src/native-harness/tsconfig.json +20 -0
  236. package/src/observation/agent-event-bus.ts +44 -18
  237. package/src/observation/index.ts +1 -0
  238. package/src/operations/contracts.ts +11 -3
  239. package/src/operations/errors.ts +5 -0
  240. package/src/operations/stale-policy.ts +1 -1
  241. package/src/operations/supervisor.ts +34 -10
  242. package/src/orchestrator/acp-delivery.ts +68 -0
  243. package/src/orchestrator/assignments.ts +27 -0
  244. package/src/orchestrator/busy.ts +15 -0
  245. package/src/orchestrator/config.ts +41 -0
  246. package/src/orchestrator/consumer-api.ts +24 -0
  247. package/src/orchestrator/contracts.ts +71 -0
  248. package/src/orchestrator/durable-assignments.ts +111 -0
  249. package/src/orchestrator/native-delegation.ts +103 -0
  250. package/src/orchestrator/orchestrator.ts +318 -0
  251. package/src/orchestrator/permissions.ts +28 -0
  252. package/src/orchestrator/policy.ts +44 -0
  253. package/src/orchestrator/pool.ts +123 -0
  254. package/src/orchestrator/tool-descriptions.ts +11 -0
  255. package/src/permissions/acp.ts +18 -0
  256. package/src/permissions/arrival.ts +13 -0
  257. package/src/permissions/consumer-config.ts +19 -0
  258. package/src/permissions/conversation.ts +288 -0
  259. package/src/permissions/matcher.ts +87 -0
  260. package/src/permissions/outcome.ts +26 -0
  261. package/src/permissions/policy.ts +86 -0
  262. package/src/permissions/request.ts +26 -0
  263. package/src/persistence/activity-projection.ts +1 -0
  264. package/src/persistence/backend.ts +34 -1
  265. package/src/persistence/channels.ts +23 -0
  266. package/src/persistence/index.ts +4 -0
  267. package/src/persistence/protocol-method.ts +5 -0
  268. package/src/persistence/reminder-wake.ts +49 -0
  269. package/src/persistence/reminders.ts +385 -0
  270. package/src/persistence/sqlite-backend.ts +84 -6
  271. package/src/persistence/sqlite-channels.ts +65 -0
  272. package/src/persistence/sqlite-reminders.ts +85 -0
  273. package/src/persistence/sqlite-schema.ts +108 -3
  274. package/src/persistence/sqlite-worker-delivery.ts +374 -0
  275. package/src/persistence/sqlite-workers.ts +59 -0
  276. package/src/persistence/worker-delivery-contract.ts +104 -0
  277. package/src/persistence/worker-terminal-reason.ts +29 -0
  278. package/src/persistence/workers.ts +19 -0
  279. package/src/provider-notices.ts +137 -0
  280. package/src/repl/commands.ts +2 -2
  281. package/src/steering/combine.ts +3 -1
  282. package/src/steering/contracts.ts +11 -2
  283. package/src/steering/controller.ts +3 -2
  284. package/src/terminals.ts +9 -6
  285. package/src/transport/acp-transport.ts +24 -14
  286. package/src/types.ts +15 -12
  287. package/src/updates.ts +14 -2
  288. package/src/wire-log.ts +1 -1
@@ -0,0 +1,125 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { LoadedScenario, ScenarioModelRecord, ScenarioSend } from "../../contracts/scenario.ts";
3
+ import { parseUniqueJson } from "../../util/json.ts";
4
+ import { ScriptedModelError } from "./scripted-error.ts";
5
+
6
+ const hash = (data: string | Uint8Array) => createHash("sha256").update(data).digest("hex");
7
+ export const scriptedCompatibilityKey = (digest: string, system: string) =>
8
+ `scripted-jsonl-v1:${digest}:${hash(JSON.stringify(system))}`;
9
+
10
+ function object(value: unknown): Record<string, unknown> {
11
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected an object");
12
+ return value as Record<string, unknown>;
13
+ }
14
+ function fields(value: Record<string, unknown>, names: readonly string[]) {
15
+ for (const key of Object.keys(value)) if (!names.includes(key)) throw new Error(`Unknown field ${key}`);
16
+ }
17
+ function text(value: unknown, name: string): string {
18
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${name} must be a nonblank string`);
19
+ return value;
20
+ }
21
+ function count(value: unknown, name: string): number {
22
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${name} must be a nonnegative safe integer`);
23
+ return value;
24
+ }
25
+ function list(value: unknown, name: string): unknown[] {
26
+ if (value === undefined) return [];
27
+ if (!Array.isArray(value)) throw new Error(`${name} must be an array`);
28
+ return value;
29
+ }
30
+ function canonical(value: unknown): unknown {
31
+ if (Array.isArray(value)) return value.map(canonical);
32
+ if (typeof value === "number" && !Number.isFinite(value)) throw new Error("Non-finite JSON number");
33
+ if (value === null || typeof value !== "object") return value;
34
+ const record = object(value);
35
+ return Object.fromEntries(Object.keys(record).sort().map(key => [key, canonical(record[key])]));
36
+ }
37
+ function model(raw: Record<string, unknown>): ScenarioModelRecord {
38
+ fields(raw, ["type", "channelId", "delayMs", "chunks", "usage", "content", "calls", "failure", "wait"]);
39
+ const channelId = raw.channelId === undefined ? undefined : text(raw.channelId, "channelId");
40
+ const delayMs = raw.delayMs === undefined ? 0 : count(raw.delayMs, "delayMs");
41
+ const chunks = list(raw.chunks, "chunks").map(value => {
42
+ const chunk = object(value); fields(chunk, ["afterMs", "text"]);
43
+ if (typeof chunk.text !== "string" || chunk.text.length === 0) throw new Error("chunk.text must be nonempty");
44
+ return { afterMs: count(chunk.afterMs, "afterMs"), text: chunk.text };
45
+ });
46
+ const usage = raw.usage === undefined ? undefined : object(raw.usage);
47
+ if (usage) {
48
+ fields(usage, ["inputTokens", "outputTokens", "totalTokens"]);
49
+ for (const [key, value] of Object.entries(usage)) count(value, key);
50
+ }
51
+ const common = { type: "model" as const, channelId, delayMs, chunks, usage };
52
+ if (["content", "failure", "wait"].filter(key => Object.hasOwn(raw, key)).length !== 1)
53
+ throw new Error("Expected exactly one of content, failure or wait");
54
+ if (Object.hasOwn(raw, "content")) {
55
+ if (raw.content !== null && typeof raw.content !== "string") throw new Error("content must be a string or null");
56
+ if (chunks.length && (raw.content === null || chunks.map(chunk => chunk.text).join("") !== raw.content))
57
+ throw new Error("chunks must equal the final content");
58
+ const ids = new Set<string>();
59
+ const calls = list(raw.calls, "calls").map(value => {
60
+ const call = object(value); fields(call, ["id", "name", "arguments"]);
61
+ const id = text(call.id, "call.id");
62
+ if (ids.has(id)) throw new Error(`Duplicate call ID ${id}`);
63
+ ids.add(id);
64
+ return { id, name: text(call.name, "call.name"), arguments: canonical(object(call.arguments)) as Record<string, unknown> };
65
+ });
66
+ return { ...common, content: raw.content, calls };
67
+ }
68
+ if (Object.hasOwn(raw, "calls")) throw new Error("calls requires content");
69
+ if (Object.hasOwn(raw, "wait")) {
70
+ if (raw.wait !== "cancel") throw new Error("wait must be cancel");
71
+ return { ...common, wait: raw.wait };
72
+ }
73
+ const failure = object(raw.failure); fields(failure, ["kind", "message"]);
74
+ const kind = failure.kind;
75
+ if (kind !== "transient" && kind !== "provider" && kind !== "invalid_request" && kind !== "invalid_config") throw new Error("Unknown failure kind");
76
+ return { ...common, failure: { kind, message: text(failure.message, "failure.message") } };
77
+ }
78
+
79
+ export function parseScenario(bytes: Uint8Array, path = "<scenario>"): LoadedScenario {
80
+ const source = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
81
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
82
+ const defaultModels: ScenarioModelRecord[] = [], channelModels = new Map<string, ScenarioModelRecord[]>();
83
+ const sends: ScenarioSend[] = [], inputIds = new Set<string>();
84
+ let name = "", line = 0;
85
+ try {
86
+ for (let start = 0; start < source.length;) {
87
+ const newline = source.indexOf(10, start), end = newline < 0 ? source.length : newline;
88
+ line++;
89
+ const raw = object(parseUniqueJson(decoder.decode(source.subarray(start, end))));
90
+ start = end + 1;
91
+ if (line === 1) {
92
+ fields(raw, ["type", "version", "name"]);
93
+ if (raw.type !== "scenario" || raw.version !== 1) throw new Error("Expected scenario version 1");
94
+ name = text(raw.name, "name");
95
+ } else if (raw.type === "model") {
96
+ const record = model(raw);
97
+ if (record.channelId === undefined) defaultModels.push(record);
98
+ else {
99
+ const sequence = channelModels.get(record.channelId) ?? [];
100
+ sequence.push(record); channelModels.set(record.channelId, sequence);
101
+ }
102
+ } else if (raw.type === "send") {
103
+ fields(raw, ["type", "atMs", "channelId", "participantId", "inputId", "text"]);
104
+ const inputId = text(raw.inputId, "inputId");
105
+ if (inputIds.has(inputId)) throw new Error(`Duplicate input ID ${inputId}`);
106
+ inputIds.add(inputId);
107
+ sends.push({ type: "send", inputId, atMs: count(raw.atMs, "atMs"), channelId: text(raw.channelId, "channelId"),
108
+ participantId: text(raw.participantId, "participantId"), text: text(raw.text, "text") });
109
+ } else throw new Error("Unexpected record type");
110
+ }
111
+ if (!defaultModels.length && !channelModels.size) throw new Error("Expected at least one model record");
112
+ } catch (error) {
113
+ throw new ScriptedModelError("invalid_script", `${path}:${Math.max(1, line)}: ${error instanceof Error ? error.message : String(error)}`);
114
+ }
115
+ const sequence = (records: ScenarioModelRecord[]) => records.map(({ type: _type, channelId: _channel, ...record }) => canonical(record));
116
+ const pairs = [...channelModels.keys()].sort().map(channel => [channel, sequence(channelModels.get(channel)!)]);
117
+ return { name, defaultModels, channelModels, sends, fileDigest: hash(source), modelDigest: hash(JSON.stringify([sequence(defaultModels), pairs])) };
118
+ }
119
+
120
+ export async function loadScenario(path: string): Promise<LoadedScenario> {
121
+ let data: ArrayBuffer;
122
+ try { data = await Bun.file(path).arrayBuffer(); }
123
+ catch (error) { throw new ScriptedModelError("script_load_failed", `Cannot read script ${path}: ${String(error)}`); }
124
+ return parseScenario(new Uint8Array(data), path);
125
+ }
@@ -0,0 +1,6 @@
1
+ export class ScriptedModelError extends Error {
2
+ constructor(public readonly code: "invalid_script" | "script_load_failed" | "script_exhausted", message: string) {
3
+ super(message);
4
+ this.name = "ScriptedModelError";
5
+ }
6
+ }
@@ -0,0 +1,81 @@
1
+ import { ScriptedModelError } from "./scripted-error.ts";
2
+ export { ScriptedModelError } from "./scripted-error.ts";
3
+ import type { Message, Model, ToolDefinition } from "../../contracts/loop.ts";
4
+
5
+ type Answer = Extract<Message, { role: "assistant" }>;
6
+ export interface CapturedRequest {
7
+ messages: Message[];
8
+ tools: ToolDefinition[];
9
+ }
10
+
11
+ function invalid(message: string): never { throw new ScriptedModelError("invalid_script", message); }
12
+ function object(value: unknown): value is Record<string, unknown> {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+ function fields(value: Record<string, unknown>, allowed: string[], path: string) {
16
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) invalid(`${path}: unknown field ${key}`);
17
+ }
18
+
19
+ function parseScript(value: unknown): Answer[] {
20
+ if (!object(value)) invalid("Script must be an object");
21
+ fields(value, ["version", "responses"], "script");
22
+ if (value.version !== 1) invalid("Expected script version 1");
23
+ if (!Array.isArray(value.responses) || !value.responses.length) invalid("responses must be a nonempty array");
24
+ return value.responses.map((response: unknown, index: number) => {
25
+ const path = `responses[${index}]`;
26
+ if (!object(response)) invalid(`${path} must be an object`);
27
+ fields(response, ["content", "calls"], path);
28
+ if (response.content !== null && typeof response.content !== "string") invalid(`${path}.content must be a string or null`);
29
+ const rawCalls = response.calls === undefined ? [] : response.calls;
30
+ if (!Array.isArray(rawCalls)) invalid(`${path}.calls must be an array`);
31
+ const ids = new Set<string>();
32
+ const calls = rawCalls.map((call: unknown, callIndex: number) => {
33
+ const location = `${path}.calls[${callIndex}]`;
34
+ if (!object(call)) invalid(`${location} must be an object`);
35
+ fields(call, ["id", "name", "arguments"], location);
36
+ if (typeof call.id !== "string" || !call.id.trim() || ids.has(call.id)) invalid(`${location}.id must be nonempty and unique within the response`);
37
+ if (typeof call.name !== "string" || !call.name.trim()) invalid(`${location}.name must be nonempty`);
38
+ if (!object(call.arguments)) invalid(`${location}.arguments must be a JSON object`);
39
+ ids.add(call.id);
40
+ return { id: call.id, name: call.name, arguments: JSON.stringify(call.arguments) };
41
+ });
42
+ return { role: "assistant", content: response.content, calls };
43
+ });
44
+ }
45
+
46
+ /** Consume one response per invocation, independently of all other instances.
47
+ * `startAt` skips responses already consumed by an earlier process, so a
48
+ * reopened session continues its script instead of replaying it. */
49
+ export function createScriptedModel(script: unknown, startAt = 0) {
50
+ // The JSON round trip enforces file-equivalent data and detaches input objects.
51
+ let answers: Answer[];
52
+ try { answers = parseScript(JSON.parse(JSON.stringify(script))); }
53
+ catch (error) {
54
+ if (error instanceof ScriptedModelError) throw error;
55
+ invalid(`Script must be JSON-serializable: ${String(error)}`);
56
+ }
57
+ const requests: CapturedRequest[] = [];
58
+ let position = startAt;
59
+ const modelAt = (step: number): Model => async (messages, tools) => {
60
+ requests.push(structuredClone({ messages: [...messages], tools: [...tools] }));
61
+ const answer = answers[step];
62
+ if (!answer) throw new ScriptedModelError("script_exhausted", `Script exhausted at model call ${requests.length}; ${answers.length} responses configured`);
63
+ position = step + 1;
64
+ return structuredClone(answer);
65
+ };
66
+ const model: Model = (messages, tools, signal) => modelAt(position)(messages, tools, signal);
67
+ return { model, modelAt, requests: () => structuredClone(requests), remaining: () => answers.length - position };
68
+ }
69
+
70
+ /** Run the step reserved by storage. Attempts never derive position from replies. */
71
+ export function scriptedAttempt(script: unknown, step: number): import("../../contracts/model-execution.ts").ModelAttempt {
72
+ const scripted = createScriptedModel(script, step);
73
+ return async function* (request, signal) {
74
+ try {
75
+ const answer = await scripted.model(request.messages, request.tools, signal);
76
+ if (!signal.aborted) yield { type: "response", response: { ...answer, stopReason: answer.calls.length ? "tool_calls" : "complete" } };
77
+ } catch (error) {
78
+ if (!signal.aborted) yield { type: "failure", kind: "invalid_request", message: String(error) };
79
+ }
80
+ };
81
+ }
@@ -0,0 +1,15 @@
1
+ import type { ModelAttemptSummary, ModelUsage } from "../../contracts/model-execution.ts";
2
+
3
+ /** Sum each attempt's latest absolute report once. Unknown fields stay absent;
4
+ * total is provider-reported and is never inferred from input plus output. */
5
+ export function aggregateUsage(attempts: readonly ModelAttemptSummary[]): ModelUsage {
6
+ const result: ModelUsage = {};
7
+ for (const attempt of attempts) for (const key of ["inputTokens", "outputTokens", "totalTokens"] as const) {
8
+ const value = attempt.usage?.[key];
9
+ if (value === undefined) continue;
10
+ const sum = (result[key] ?? 0) + value;
11
+ if (!Number.isSafeInteger(sum)) throw new RangeError("Aggregated usage exceeds safe integer range");
12
+ result[key] = sum;
13
+ }
14
+ return result;
15
+ }
@@ -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
+ }