@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 type { ReminderSchedule, RoutineDeliveryOptions } from "../contracts/reminders.ts";
2
+ import { reminderInstant } from "../util/reminder-schedule.ts";
3
+ import type { ReminderChange, ReminderListParams } from "../contracts/reminders.ts";
4
+ import { SESSION_INPUT_MAX_BYTES } from "../contracts/input-limits.ts";
5
+
6
+ export class ReminderShapeError extends Error {}
7
+
8
+ const bad = (field: string): never => { throw new ReminderShapeError(`Invalid reminder ${field}`); };
9
+
10
+ const record = (value: unknown): Record<string, unknown> => {
11
+ if (!value || typeof value !== "object" || Array.isArray(value)) return bad("object");
12
+ return value as Record<string, unknown>;
13
+ };
14
+
15
+ function keys(value: Record<string, unknown>, allowed: readonly string[]) {
16
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) bad(key);
17
+ }
18
+
19
+ function text(value: unknown, field: string): string {
20
+ if (typeof value !== "string" || !value.trim() || Buffer.byteLength(value) > SESSION_INPUT_MAX_BYTES) return bad(field);
21
+ return value;
22
+ }
23
+
24
+ function positive(value: unknown, field: string): number {
25
+ if (!Number.isSafeInteger(value) || (value as number) < 1) return bad(field);
26
+ return value as number;
27
+ }
28
+
29
+ function instant(value: unknown, field: string) {
30
+ const raw = text(value, field), ms = reminderInstant(raw);
31
+ return ms === undefined ? raw : new Date(ms).toISOString();
32
+ }
33
+
34
+ function schedule(value: unknown): ReminderSchedule {
35
+ const input = record(value);
36
+ if ("at" in input) {
37
+ keys(input, ["at"]);
38
+ return { at: instant(input.at, "schedule.at") };
39
+ }
40
+ if (input.count !== undefined && input.until !== undefined) return bad("schedule end");
41
+ const end = input.count !== undefined ? { count: positive(input.count, "schedule.count") }
42
+ : input.until !== undefined ? { until: instant(input.until, "schedule.until") } : {};
43
+ if ("every" in input) {
44
+ keys(input, ["every", "startAt", "count", "until"]);
45
+ return { ...end, every: positive(input.every, "schedule.every"),
46
+ ...(input.startAt === undefined ? {} : { startAt: instant(input.startAt, "schedule.startAt") }) };
47
+ }
48
+ keys(input, ["cron", "timezone", "count", "until"]);
49
+ return { ...end, cron: text(input.cron, "schedule.cron"), timezone: text(input.timezone, "schedule.timezone") };
50
+ }
51
+
52
+ function delivery(payload: Record<string, unknown>): RoutineDeliveryOptions {
53
+ const { missedRuns, overlap } = payload;
54
+ if (missedRuns !== undefined && missedRuns !== "coalesce" && missedRuns !== "skip" && missedRuns !== "each") return bad("missedRuns");
55
+ if (overlap !== undefined && overlap !== "skip" && overlap !== "queue") return bad("overlap");
56
+ return { ...(missedRuns === undefined ? {} : { missedRuns }), ...(overlap === undefined ? {} : { overlap }) };
57
+ }
58
+
59
+ function grace(value: unknown) {
60
+ if (value === undefined || value === null) return value;
61
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) return bad("expiresAfter");
62
+ return value;
63
+ }
64
+
65
+ function policyNames(value: unknown): string[] {
66
+ if (value === undefined) return [];
67
+ if (!Array.isArray(value) || value.length > 100) return bad("policyNames");
68
+ return [...new Set(value.map(name => text(name, "policyNames")))].sort();
69
+ }
70
+
71
+ /** Validate both batch shape and individual live requests before any mutation. */
72
+ export function parseReminderChange(value: unknown): ReminderChange {
73
+ const input = record(value);
74
+ keys(input, ["reminderId", "changeId", "op", "payload"]);
75
+ const id = { reminderId: text(input.reminderId, "reminderId"), changeId: positive(input.changeId, "changeId") };
76
+ const payload = record(input.payload);
77
+ switch (input.op) {
78
+ case "create": {
79
+ keys(payload, ["channel", "schedule", "text", "acceptedAt", "policyNames", "expiresAfter", "missedRuns", "overlap"]);
80
+ const expiresAfter = grace(payload.expiresAfter);
81
+ return { ...id, op: "create", payload: {
82
+ ...delivery(payload), channel: text(payload.channel, "channel"), schedule: schedule(payload.schedule),
83
+ text: text(payload.text, "text"), acceptedAt: instant(payload.acceptedAt, "acceptedAt"),
84
+ policyNames: policyNames(payload.policyNames), ...(expiresAfter === undefined ? {} : { expiresAfter }),
85
+ } };
86
+ }
87
+ case "update": {
88
+ keys(payload, ["schedule", "acceptedAt", "text", "state", "expiresAfter", "missedRuns", "overlap"]);
89
+ if (!Object.keys(payload).length || (payload.schedule === undefined) !== (payload.acceptedAt === undefined)) return bad("edit");
90
+ const state = payload.state;
91
+ if (state !== undefined && state !== "active" && state !== "paused") return bad("state");
92
+ const expiresAfter = grace(payload.expiresAfter);
93
+ const edit: Omit<Extract<ReminderChange, { op: "update" }>["payload"], "schedule" | "acceptedAt"> = {
94
+ ...delivery(payload),
95
+ ...(payload.text === undefined ? {} : { text: text(payload.text, "text") }),
96
+ ...(state === undefined ? {} : { state }),
97
+ ...(expiresAfter === undefined ? {} : { expiresAfter }),
98
+ };
99
+ return { ...id, op: "update", payload: payload.schedule === undefined ? edit
100
+ : { ...edit, schedule: schedule(payload.schedule), acceptedAt: instant(payload.acceptedAt, "acceptedAt") } };
101
+ }
102
+ case "cancel":
103
+ keys(payload, []);
104
+ return { ...id, op: "cancel", payload: {} };
105
+ default: return bad("operation");
106
+ }
107
+ }
108
+
109
+ export function parseReminderBatch(value: unknown): ReminderChange[] {
110
+ if (value === undefined) return [];
111
+ if (!Array.isArray(value) || value.length > 100) return bad("batch");
112
+ return value.map(parseReminderChange);
113
+ }
114
+
115
+ export function parseReminderList(value: unknown): ReminderListParams {
116
+ const input = record(value);
117
+ keys(input, ["channel", "after", "limit"]);
118
+ const limit = input.limit === undefined ? 50 : positive(input.limit, "limit");
119
+ if (limit > 100) return bad("limit");
120
+ return {
121
+ limit,
122
+ ...(input.channel === undefined ? {} : { channel: text(input.channel, "channel") }),
123
+ ...(input.after === undefined ? {} : { after: text(input.after, "after") }),
124
+ };
125
+ }
@@ -0,0 +1,66 @@
1
+ import type { ReminderChannelEvent, ReminderChange, ReminderClock, ReminderSessionEvent } from "../contracts/reminders.ts";
2
+ import type { ReminderStorage, StorageResult } from "../contracts/storage.ts";
3
+ import { createReminderTimer } from "./reminder-timer.ts";
4
+
5
+ export function createReminderRuntime(
6
+ storage: ReminderStorage,
7
+ clock: ReminderClock,
8
+ executable: () => boolean,
9
+ publish: (channel: string, event: ReminderChannelEvent, revision: number) => void,
10
+ publishWake: (event: ReminderSessionEvent) => void,
11
+ wakeChannel: (channel: string) => void,
12
+ ) {
13
+ let running = false, closed = false, wakeRevision = -1;
14
+ let armed: string | null = null;
15
+ const timer = createReminderTimer(clock, () => {
16
+ armed = null;
17
+ if (running && executable()) process();
18
+ });
19
+ const value = <T>(result: StorageResult<T>): T => {
20
+ if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
21
+ return result.value;
22
+ };
23
+ function refresh() {
24
+ if (closed || !running) return;
25
+ const wake = value(storage.reminderWake());
26
+ if (wake.reminderRevision !== wakeRevision) {
27
+ wakeRevision = wake.reminderRevision;
28
+ publishWake({ type: "reminders_due", nextDueAt: wake.nextDueAt, revision: wake.reminderRevision });
29
+ }
30
+ const deadline = wake.nextDueAt !== null && executable() ? wake.nextDueAt : null;
31
+ if (armed !== deadline) { armed = deadline; timer.arm(deadline); }
32
+ }
33
+ function process() {
34
+ if (closed || !executable()) return;
35
+ const committed = storage.fireDueReminders(clock.now());
36
+ if (!committed.ok) throw new Error(committed.error.message);
37
+ for (const { channel, event } of committed.value) {
38
+ publish(channel, event, committed.revision);
39
+ if (event.type === "reminder_fired") wakeChannel(channel);
40
+ }
41
+ refresh();
42
+ }
43
+ return {
44
+ start() {
45
+ if (running || closed) return;
46
+ running = true;
47
+ refresh();
48
+ },
49
+ stop() { closed = true; running = false; timer.stop(); },
50
+ refresh, process,
51
+ change(change: ReminderChange) {
52
+ const prior = value(storage.readReminder(change.reminderId));
53
+ const result = storage.changeReminder(change, clock.now());
54
+ if (result.ok && result.value.outcome === "applied") {
55
+ const current = value(storage.readReminder(change.reminderId));
56
+ if (current && JSON.stringify(current) !== JSON.stringify(prior)) {
57
+ publish(current.channel, current.state === "cancelled"
58
+ ? { type: "reminder_cancelled", reminderId: current.id, by: "host" }
59
+ : { type: "reminder_changed", reminder: current }, result.revision);
60
+ }
61
+ }
62
+ refresh();
63
+ return result;
64
+ },
65
+ };
66
+ }
@@ -0,0 +1,257 @@
1
+ import { migrateImportedRoutines } from "./engine.ts";
2
+ import { validateReminderArchive } from "./reminder-archive.ts";
3
+ import type { SessionArchive, SessionArchiveV1, StoredSession } from "../../contracts/storage.ts";
4
+ import { Fail, isJson, signatureOf, type Meta, type Tables } from "./engine.ts";
5
+ import { validateConfig } from "./session-file.ts";
6
+ import { legacyItemSignature, policyItemSignature } from "./policy-metadata.ts";
7
+
8
+ const bad = (message: string): never => { throw new Fail("invalid_archive", message); };
9
+ const str = (value: unknown): value is string => typeof value === "string" && value.length > 0;
10
+ const nonblank = (value: unknown): value is string => str(value) && value.trim().length > 0;
11
+ const int = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) > 0;
12
+ const MILESTONES = ["received", "taken", "delivered", "seen", "withdrawn"];
13
+ const CHANNEL_STATES = ["open", "suspended", "retired"];
14
+
15
+ /** Validate both records before a destination is created or modified. */
16
+ export function validateSessionPayload(value: unknown) {
17
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join() !== "archive,config") bad("Invalid session file payload");
18
+ const payload = value as { archive: SessionArchive; config: unknown };
19
+ if (![2, 3, 4, 5, 6, 7].includes((payload.archive as { archiveVersion?: number })?.archiveVersion ?? 0)) bad("Invalid session file archive version");
20
+ const archive = validateArchive(payload.archive);
21
+ let config: ReturnType<typeof validateConfig>;
22
+ try { config = validateConfig(payload.config, (payload.archive as { archiveVersion: number }).archiveVersion === 2); } catch (error) { return bad(String(error)); }
23
+ return { archive, config };
24
+ }
25
+
26
+ /** Check the whole logical archive before anything is written, and return it
27
+ * in the current (version 2) shape. Version 1, written by the persistence
28
+ * revision, reads as every channel `open` and unnamed. Rejects every state a
29
+ * legal export cannot produce, including a `suspending` lifecycle or channel, a
30
+ * running turn, a checkpoint nothing holds, or a live turn on a retired channel,
31
+ * which the next open would treat as an unclean exit or must never run. */
32
+ export function validateArchive(value: unknown): SessionArchive {
33
+ if (!isJson(value) || !value || typeof value !== "object") bad("Archive is not JSON data");
34
+ const raw = value as any;
35
+ if (raw.format !== "harness-session" || ![1, 2, 3, 4, 5, 6, 7].includes(raw.archiveVersion)) bad("Unsupported archive format or version");
36
+ const v1 = raw.archiveVersion === 1;
37
+ const legacy = raw.archiveVersion < 3;
38
+ if (!raw.snapshot || !raw.allocation || !raw.snapshot.session || !Array.isArray(raw.snapshot.channels)) bad("Archive is missing its snapshot or allocation state");
39
+ const policyArchive = legacy ? { ...raw, archiveVersion: 3, snapshot: { ...raw.snapshot,
40
+ session: { ...raw.snapshot.session, formatVersion: 4 },
41
+ channels: v1 ? raw.snapshot.channels.map((channel: any) => ({ ...channel, lifecycle: "open" as const })) : raw.snapshot.channels,
42
+ turns: Array.isArray(raw.snapshot.turns) ? raw.snapshot.turns.map((turn: any) => turn?.state?.status === "suspended"
43
+ ? { ...turn, state: { ...turn.state, checkpoint: { ...turn.state.checkpoint, policyFingerprint: JSON.stringify([["__legacy_allow", "allow", []]]) } } } : turn) : raw.snapshot.turns,
44
+ items: Array.isArray(raw.snapshot.items) ? raw.snapshot.items.map((item: any) => {
45
+ if (!item || item.signature !== legacyItemSignature(item)) bad("Invalid legacy item signature");
46
+ return { ...item, signature: policyItemSignature(item), policy: { resolved: "__legacy_allow", inherited: [] } };
47
+ }) : raw.snapshot.items } } : raw;
48
+ const old = raw.archiveVersion < 4;
49
+ const positions: Record<string, number> = {};
50
+ if (old && Array.isArray(policyArchive.snapshot.timeline)) for (const entry of policyArchive.snapshot.timeline)
51
+ if (entry.message?.role === "assistant") Object.defineProperty(positions, entry.channelId, { value: (Object.hasOwn(positions, entry.channelId) ? positions[entry.channelId]! : 0) + 1, writable: true, configurable: true, enumerable: true });
52
+ const previousFormat = [0, 2, 3, 4, 5, 6, 7, 8][raw.archiveVersion];
53
+ if (raw.snapshot.session.formatVersion !== previousFormat) bad("Unsupported session format");
54
+ const archive: SessionArchive = { ...policyArchive, archiveVersion: raw.archiveVersion >= 7 ? 7 : raw.archiveVersion === 6 ? 6 : 5, snapshot: { ...policyArchive.snapshot,
55
+ session: { ...policyArchive.snapshot.session, formatVersion: raw.archiveVersion >= 7 ? 8 : raw.archiveVersion === 6 ? 7 : 6 },
56
+ ...(old ? { modelCalls: [], scriptPositions: positions } : {}) } };
57
+ const snapshot = archive.snapshot, allocation = archive.allocation;
58
+ const { session, revision } = snapshot;
59
+ if ((session.formatVersion !== 6 && session.formatVersion !== 7 && session.formatVersion !== 8) || !str(session.sessionId) || !str(session.createdAt) || typeof session.compatibilityKey !== "string")
60
+ bad("Unsupported session format");
61
+ if (session.lifecycle !== "running" && session.lifecycle !== "suspended") bad("Archive was not exported from an idle or suspended session");
62
+ if (!Number.isSafeInteger(revision) || revision < 0 || allocation.nextSeq !== revision + 1 || !int(allocation.nextTurnId) || !int(allocation.nextItemNumber))
63
+ bad("Inconsistent allocation state");
64
+ for (const list of [snapshot.channels, snapshot.participants, snapshot.turns, snapshot.items, snapshot.timeline])
65
+ if (!Array.isArray(list)) bad("Archive lists are malformed");
66
+ const channels = new Map<string, string>();
67
+ for (const channel of snapshot.channels) {
68
+ if (!channel || !str(channel.channelId) || channels.has(channel.channelId)) bad("Invalid or duplicate channel");
69
+ if (!CHANNEL_STATES.includes(channel.lifecycle) || (channel.displayName !== undefined && !str(channel.displayName)))
70
+ bad(`Channel ${channel.channelId} has an invalid lifecycle or name`);
71
+ if (channel.policy !== undefined && !str(channel.policy)) bad(`Channel ${channel.channelId} has invalid policy`);
72
+ channels.set(channel.channelId, channel.lifecycle);
73
+ }
74
+ if (snapshot.participants.some(participant => !participant || !str(participant.participantId))) bad("Invalid participant");
75
+
76
+ const turns = new Map<number, { channelId: string; itemIds: string[] }>(), live = new Set<string>();
77
+ let previous = 0;
78
+ for (const turn of snapshot.turns) {
79
+ if (!turn || !int(turn.turnId) || turn.turnId <= previous || turn.turnId >= allocation.nextTurnId || !channels.has(turn.channelId)
80
+ || !int(turn.startedSeq) || turn.startedSeq > revision || !str(turn.startedAt) || typeof turn.compatibilityKey !== "string"
81
+ || !Array.isArray(turn.itemIds) || !turn.state) bad("Invalid turn record");
82
+ previous = turn.turnId;
83
+ const state = turn.state;
84
+ if (state.status === "suspended") {
85
+ // Held by the session suspension, or by the channel's own committed one.
86
+ if (channels.get(turn.channelId) === "retired") bad(`Retired channel ${turn.channelId} holds a checkpoint`);
87
+ if ((session.lifecycle !== "suspended" && channels.get(turn.channelId) !== "suspended") || live.has(turn.channelId)
88
+ || state.checkpoint?.nextStep !== "inference" || !int(state.checkpoint.afterSeq) || typeof state.checkpoint.policyFingerprint !== "string") bad("Invalid checkpoint");
89
+ live.add(turn.channelId);
90
+ } else if (state.status === "failed" || state.status === "interrupted") {
91
+ if (!str(state.reason) || !Array.isArray(state.uncertainCallIds) || state.uncertainCallIds.some(id => !str(id))) bad("Invalid turn outcome");
92
+ } else if (state.status !== "completed") bad("Archive holds a turn that is still running");
93
+ turns.set(turn.turnId, { channelId: turn.channelId, itemIds: [] });
94
+ }
95
+
96
+ const entries = new Map<number, (typeof snapshot.timeline)[number]>();
97
+ const calls = new Map<number, { all: Set<string>; outstanding: Set<string> }>();
98
+ previous = 0;
99
+ for (const entry of snapshot.timeline) {
100
+ const turn = entry && turns.get(entry.turnId), message = entry?.message;
101
+ if (!turn || !int(entry.seq) || entry.seq <= previous || entry.seq > revision || entry.channelId !== turn.channelId
102
+ || !str(entry.at) || !str(entry.from) || !message) bad("Invalid timeline entry");
103
+ if (entry.kind === "external_notice" && (raw.archiveVersion < 5 || message.role !== "user"
104
+ || !nonblank(entry.itemId) || entry.sourceChannelId !== undefined || (entry.externalSource !== undefined && !nonblank(entry.externalSource))
105
+ || entry.from !== (entry.externalSource ?? "host"))) bad("Invalid external timeline entry");
106
+ if (entry.kind !== "external_notice" && entry.externalSource !== undefined) bad("Unexpected external attribution");
107
+ if (message.role === "user") { if (typeof message.content !== "string") bad("Invalid input entry"); }
108
+ else if (message.role === "assistant") {
109
+ if (!Array.isArray(message.calls)) bad("Invalid assistant entry");
110
+ const state = calls.get(entry.turnId) ?? { all: new Set<string>(), outstanding: new Set<string>() };
111
+ for (const call of message.calls) {
112
+ if (!str(call.id) || state.all.has(call.id)) bad("Invalid or duplicate tool call ID");
113
+ state.all.add(call.id); state.outstanding.add(call.id);
114
+ }
115
+ calls.set(entry.turnId, state);
116
+ } else if (message.role === "tool") {
117
+ if (!str(message.callId) || !calls.get(entry.turnId)?.outstanding.delete(message.callId)) bad("Tool result has no matching call");
118
+ } else bad("Invalid timeline message");
119
+ previous = entry.seq; entries.set(entry.seq, entry);
120
+ }
121
+ for (const turn of snapshot.turns) {
122
+ const { all, outstanding } = calls.get(turn.turnId) ?? { all: new Set<string>(), outstanding: new Set<string>() };
123
+ const dispatched = (turn.state as { dispatchedCallIds?: unknown }).dispatchedCallIds;
124
+ if (dispatched !== undefined && (!Array.isArray(dispatched) || dispatched.some(id => !str(id) || !all.has(id))
125
+ || new Set(dispatched).size !== dispatched.length)) bad("Invalid dispatched call evidence");
126
+ if (turn.state.status === "suspended" && outstanding.size) bad("Checkpoint has an unanswered tool call");
127
+ }
128
+
129
+ const revoked = (snapshot as { revokedTools?: unknown }).revokedTools;
130
+ if (revoked !== undefined && (!Array.isArray(revoked) || revoked.some(name => !str(name)) || new Set(revoked).size !== revoked.length
131
+ || JSON.stringify([...revoked].sort()) !== JSON.stringify(revoked))) bad("Invalid revoked tools");
132
+ if (!Array.isArray(snapshot.modelCalls) || !snapshot.scriptPositions || typeof snapshot.scriptPositions !== "object" || Array.isArray(snapshot.scriptPositions)) bad("Invalid model execution records");
133
+ for (const [channel, next] of Object.entries(snapshot.scriptPositions))
134
+ if (!channels.has(channel) || !Number.isSafeInteger(next) || (next as number) < 0) bad("Invalid scripted position");
135
+ const callIds = new Set<string>(), messageIds = new Set<string>(), reservations = new Set<string>();
136
+ let previousCallId = 0;
137
+ for (const call of snapshot.modelCalls) {
138
+ if (!call || !/^[1-9]\d*$/.test(call.callId) || !Number.isSafeInteger(Number(call.callId)) || callIds.has(call.callId)
139
+ || !str(call.messageId) || messageIds.has(call.messageId) || !turns.has(Number(call.turnId)) || turns.get(Number(call.turnId))!.channelId !== call.channel
140
+ || !str(call.startedAt) || !str(call.endedAt) || !["succeeded", "failed", "incomplete", "output_limit", "timeout", "interrupted"].includes(call.outcome)
141
+ || !Array.isArray(call.attempts) || call.attempts.length > 2) bad("Invalid model call");
142
+ if (Number(call.callId) <= previousCallId) bad("Model calls are not in creation order");
143
+ previousCallId = Number(call.callId);
144
+ if (call.messageId !== `model:${call.callId}`) bad("Invalid reserved message ID");
145
+ callIds.add(call.callId); messageIds.add(call.messageId);
146
+ for (const [ordinal, attempt] of call.attempts.entries()) {
147
+ if (!attempt || attempt.ordinal !== ordinal || attempt.attemptId !== `${call.callId}:${ordinal}` || !str(attempt.startedAt) || !str(attempt.endedAt)
148
+ || !["succeeded", "transient_failure", "invalid_request", "invalid_config", "provider_failure", "incomplete", "output_limit", "timeout", "interrupted"].includes(attempt.outcome)
149
+ || (attempt.providerRequestId !== undefined && !str(attempt.providerRequestId)) || (attempt.retryReason !== undefined && !str(attempt.retryReason))
150
+ || (attempt.scriptStep !== undefined && (!Number.isSafeInteger(attempt.scriptStep) || attempt.scriptStep < 0))) bad("Invalid model attempt");
151
+ if (attempt.scriptStep !== undefined) {
152
+ const key = `${call.channel}\0${attempt.scriptStep}`;
153
+ if (reservations.has(key) || attempt.scriptStep >= (Object.hasOwn(snapshot.scriptPositions, call.channel) ? snapshot.scriptPositions[call.channel]! : 0)) bad("Invalid script reservation");
154
+ reservations.add(key);
155
+ }
156
+ if (attempt.usage && (typeof attempt.usage !== "object" || Object.keys(attempt.usage).some(key => !["inputTokens", "outputTokens", "totalTokens"].includes(key))
157
+ || Object.values(attempt.usage).some(value => !Number.isSafeInteger(value) || (value as number) < 0))) bad("Invalid model usage");
158
+ }
159
+ const succeeded = call.attempts.filter(attempt => attempt.outcome === "succeeded");
160
+ if (call.outcome === "succeeded" ? succeeded.length !== 1 || call.attempts.at(-1)?.outcome !== "succeeded" : succeeded.length !== 0)
161
+ bad("Call and attempt outcomes disagree");
162
+ const matched = snapshot.timeline.filter(entry => entry.messageId === call.messageId);
163
+ if (call.outcome === "succeeded" ? matched.length !== 1 || matched[0]!.message.role !== "assistant" || matched[0]!.turnId !== Number(call.turnId) : matched.length !== 0)
164
+ bad("Model call and committed response disagree");
165
+ }
166
+ for (const entry of snapshot.timeline) if (entry.messageId && !messageIds.has(entry.messageId)) bad("Unknown model message ID");
167
+
168
+ const ids = new Set<string>(), accepted = new Set<number>(), externalEntries = new Set<number>();
169
+ for (const item of [...snapshot.items].sort((a, b) => (a?.entrySeq ?? 0) - (b?.entrySeq ?? 0))) {
170
+ if (!item || !str(item.itemId) || ids.has(item.itemId) || !channels.has(item.channelId) || !MILESTONES.includes(item.milestone)
171
+ || !int(item.acceptedSeq) || item.acceptedSeq > revision || accepted.has(item.acceptedSeq) || !str(item.acceptedAt)
172
+ || (v1 && item.milestone === "withdrawn") || (item.milestone === "withdrawn") !== (item.withdrawnAt !== undefined)
173
+ || (item.withdrawnAt !== undefined && !str(item.withdrawnAt))) bad("Invalid or duplicate item");
174
+ accepted.add(item.acceptedSeq);
175
+ if (item.kind === "external_notice") {
176
+ const names = item.inheritedPolicyNames;
177
+ if (raw.archiveVersion < 5 || item.sourceChannelId !== undefined || item.sourceTurnId !== undefined
178
+ || item.explicitPolicy !== undefined || item.senderId !== (item.externalSource ?? "host")
179
+ || !nonblank(item.itemId) || !nonblank(item.text)
180
+ || (item.externalSource !== undefined && !nonblank(item.externalSource))
181
+ || !Array.isArray(names) || names.some(name => !nonblank(name) || name === "__legacy_allow")
182
+ || JSON.stringify(names) !== JSON.stringify([...new Set(names)].sort())
183
+ || JSON.stringify(names) !== JSON.stringify(item.policy?.inherited)) bad("Invalid external notice metadata");
184
+ } else if (!["participant_message", "channel_notice"].includes(item.kind)
185
+ || item.externalSource !== undefined || item.inheritedPolicyNames !== undefined) bad("Invalid item kind or attribution");
186
+ if (![item.kind, item.senderId, item.text].every(str) || item.signature !== signatureOf(item)) bad(`Item ${item.itemId} does not match its signature`);
187
+ if (!item.policy || !str(item.policy.resolved) || !Array.isArray(item.policy.inherited) || item.policy.inherited.some(name => !str(name))
188
+ || (item.policy.explicit !== undefined && !str(item.policy.explicit)) || (item.policy.explicit ?? null) !== (item.explicitPolicy ?? null)) bad(`Item ${item.itemId} has invalid policy metadata`);
189
+ ids.add(item.itemId);
190
+ const auto = /^auto:(0|[1-9]\d*)$/.exec(item.itemId);
191
+ if (auto && Number(auto[1]) >= allocation.nextItemNumber) bad("Item counter would reissue an allocated ID");
192
+ if (item.milestone === "received" || item.milestone === "withdrawn") {
193
+ if (item.turnId !== undefined || item.entrySeq !== undefined) bad(`${item.milestone === "received" ? "Pending" : "Withdrawn"} item is linked to a turn`);
194
+ if (item.milestone === "received" && channels.get(item.channelId) === "retired") bad("Retired channel holds pending input");
195
+ if (item.milestone === "received" && session.lifecycle === "running") bad("Archive of a running session holds pending input");
196
+ } else {
197
+ const entry = entries.get(item.entrySeq as number), turn = turns.get(item.turnId as number);
198
+ if (!turn || !entry || entry.itemId !== item.itemId || entry.turnId !== item.turnId) bad(`Item ${item.itemId} has no matching timeline entry`);
199
+ if (item.kind === "external_notice" && (entry!.kind !== item.kind || entry!.externalSource !== item.externalSource
200
+ || entry!.channelId !== item.channelId || entry!.message.content !== item.text)) bad("External notice and timeline disagree");
201
+ if (item.kind === "external_notice") externalEntries.add(entry!.seq);
202
+ turn!.itemIds.push(item.itemId);
203
+ }
204
+ }
205
+ for (const entry of snapshot.timeline)
206
+ if (entry.kind === "external_notice" && !externalEntries.has(entry.seq)) bad("External timeline entry has no inbox item");
207
+ for (const turn of snapshot.turns)
208
+ if (JSON.stringify(turn.itemIds) !== JSON.stringify(turns.get(turn.turnId)!.itemIds)) bad(`Turn ${turn.turnId} does not match its items`);
209
+ if (archive.archiveVersion >= 6) {
210
+ validateReminderArchive(archive.reminderState, snapshot);
211
+ const guard = archive.reminderState?.guard;
212
+ if (archive.archiveVersion === 7) {
213
+ if (guard && (!Number.isSafeInteger(guard.limit) || guard.limit < 1 || !Array.isArray(guard.counters)))
214
+ bad("Invalid archived unattended guard");
215
+ const seen = new Set<string>();
216
+ for (const counter of guard?.counters ?? []) {
217
+ if (!counter || !snapshot.channels.some(channel => channel.channelId === counter.channel)
218
+ || seen.has(counter.channel) || !Number.isSafeInteger(counter.spent) || counter.spent < 0 || counter.spent > guard!.limit)
219
+ bad("Invalid archived unattended turn counter");
220
+ seen.add(counter.channel);
221
+ }
222
+ } else if (guard !== undefined) bad("Unattended guard requires archive version 7");
223
+ }
224
+ else if (raw.reminderState !== undefined) bad("Reminder state requires archive version 6");
225
+ return archive;
226
+ }
227
+
228
+ export function archiveMeta(archive: SessionArchive, sessionId?: string): Meta {
229
+ const { session, revision } = archive.snapshot;
230
+ return { sessionId: sessionId ?? session.sessionId, formatVersion: session.formatVersion, createdAt: session.createdAt,
231
+ compatibilityKey: session.compatibilityKey, lifecycle: session.lifecycle, revision,
232
+ nextTurnId: archive.allocation.nextTurnId, nextItemNumber: archive.allocation.nextItemNumber };
233
+ }
234
+
235
+ /** Write a validated archive into empty tables that already hold `archiveMeta`. */
236
+ export function restoreArchive(tables: Tables, archive: SessionArchive): void {
237
+ const snapshot = archive.snapshot;
238
+ tables.transaction(() => {
239
+ for (const { participantIds: _derived, ...channel } of snapshot.channels) tables.putChannel(channel);
240
+ for (const participant of snapshot.participants) tables.addParticipant(participant.participantId);
241
+ for (const { itemIds: _derived, ...turn } of snapshot.turns) tables.putTurn(turn);
242
+ for (const entry of snapshot.timeline) tables.addEntry(entry);
243
+ for (const item of snapshot.items) tables.putItem(item);
244
+ const entryIds = Object.fromEntries(snapshot.timeline.filter(entry => entry.messageId).map(entry => [String(entry.seq), entry.messageId!]));
245
+ const max = snapshot.modelCalls.reduce((n, call) => Math.max(n, Number(call.callId) || 0), 0);
246
+ tables.setModelState({ nextCall: max + 1, calls: snapshot.modelCalls, itemIds: {}, scriptPositions: snapshot.scriptPositions, entryIds });
247
+ if (archive.reminderState) {
248
+ tables.reminders.restore(archive.reminderState);
249
+ migrateImportedRoutines(tables);
250
+ }
251
+ if (snapshot.revokedTools !== undefined) tables.setRevokedTools(snapshot.revokedTools);
252
+ });
253
+ }
254
+
255
+ export function storedSession(meta: Meta): StoredSession {
256
+ return { sessionId: meta.sessionId, formatVersion: meta.formatVersion >= 8 ? 8 : meta.formatVersion === 7 ? 7 : 6, createdAt: meta.createdAt, lifecycle: meta.lifecycle, compatibilityKey: meta.compatibilityKey };
257
+ }