@qlairoslabs/acp-client 0.12.1 → 0.13.0-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 (467) 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 +845 -6
  6. package/MIGRATION-0.10-to-0.12.md +4 -1
  7. package/MIGRATION-0.12-to-0.13.md +275 -0
  8. package/README.md +17 -16
  9. package/package.json +4 -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 +94 -158
  19. package/src/agent/manager-settings.ts +1 -0
  20. package/src/agent/native-channel-lifecycle.ts +111 -0
  21. package/src/agent/persisted-lifecycle.ts +44 -4
  22. package/src/agent/persistence-policy/context.ts +13 -0
  23. package/src/agent/persistence-policy/resolver.ts +7 -0
  24. package/src/agent/persistence-policy/types.ts +1 -0
  25. package/src/agent/record-capture.ts +1 -0
  26. package/src/agent-adapter-registry.ts +33 -7
  27. package/src/agent-conversation-contracts.ts +14 -1
  28. package/src/agent-conversation-errors.ts +8 -0
  29. package/src/agent-conversation-owner.ts +9 -4
  30. package/src/agent-session-config.ts +135 -0
  31. package/src/agent-session.ts +439 -934
  32. package/src/agent.ts +73 -0
  33. package/src/capabilities.ts +2 -0
  34. package/src/checkpointing/recovery.ts +3 -0
  35. package/src/cli/index.ts +3 -3
  36. package/src/cli/managed.ts +2 -2
  37. package/src/client.ts +52 -94
  38. package/src/connection-attempt.ts +95 -0
  39. package/src/controller-connection.ts +114 -0
  40. package/src/controller.ts +156 -148
  41. package/src/conversation-controller/capabilities.ts +88 -0
  42. package/src/conversation-controller/contracts.ts +208 -0
  43. package/src/conversation-controller/factory.ts +39 -0
  44. package/src/conversation-controller/guards.ts +98 -0
  45. package/src/conversation-controller/index.ts +20 -0
  46. package/src/conversation-startup.ts +35 -0
  47. package/src/conversation-turns/backend-turns.ts +373 -0
  48. package/src/conversation-turns/clear-operations.ts +37 -0
  49. package/src/conversation-turns/context.ts +135 -0
  50. package/src/conversation-turns/index.ts +4 -0
  51. package/src/conversation-turns/record-helpers.ts +75 -0
  52. package/src/conversation-turns/recording.ts +235 -0
  53. package/src/conversation-turns/run-turn.ts +367 -0
  54. package/src/conversation-turns/turn-run.ts +57 -0
  55. package/src/errors.ts +41 -0
  56. package/src/handoff-options.ts +81 -0
  57. package/src/identity/checkpoint-backed.ts +1 -1
  58. package/src/index.ts +58 -3
  59. package/src/internal-inference/coordination/manager.ts +11 -0
  60. package/src/internal-inference/runtime/harness-runtime.ts +4 -4
  61. package/src/launcher.ts +35 -2
  62. package/src/media/parts.ts +5 -0
  63. package/src/message-status.ts +83 -0
  64. package/src/metering/engine.ts +39 -64
  65. package/src/metering/measurement-provenance.ts +36 -0
  66. package/src/metering/native/durability.ts +115 -0
  67. package/src/metering/native/ledger.ts +104 -0
  68. package/src/metering/native/operation.ts +85 -0
  69. package/src/metering/native/projection.ts +114 -0
  70. package/src/metering/native/proof.ts +51 -0
  71. package/src/metering/native/requirements.ts +10 -0
  72. package/src/metering/native/retirement.ts +92 -0
  73. package/src/metering/native/source.ts +90 -0
  74. package/src/metering/record.ts +38 -1
  75. package/src/metering/state.ts +13 -3
  76. package/src/native/approvals.ts +169 -0
  77. package/src/native/capabilities.ts +17 -0
  78. package/src/native/channel-changes.ts +211 -0
  79. package/src/native/connection.ts +56 -0
  80. package/src/native/controller.ts +591 -0
  81. package/src/native/delegation-sender.ts +26 -0
  82. package/src/native/errors.ts +35 -0
  83. package/src/native/functions.ts +156 -0
  84. package/src/native/host-config.ts +59 -0
  85. package/src/native/host.ts +909 -0
  86. package/src/native/item-receipts.ts +15 -0
  87. package/src/native/metering.ts +12 -0
  88. package/src/native/records.ts +166 -0
  89. package/src/native/recovery.ts +186 -0
  90. package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
  91. package/src/native/reminders/idle.ts +70 -0
  92. package/src/native/reminders/limits.ts +19 -0
  93. package/src/native/reminders/notifications.ts +29 -0
  94. package/src/native/reminders/reminders.test.ts +553 -0
  95. package/src/native/reminders/routine-config.typecheck.ts +13 -0
  96. package/src/native/reminders/routine-guard.ts +66 -0
  97. package/src/native/reminders/routine-schedule.ts +25 -0
  98. package/src/native/reminders/routine-wire.ts +21 -0
  99. package/src/native/reminders/schedule.ts +97 -0
  100. package/src/native/reminders/service.ts +280 -0
  101. package/src/native/reminders/supervisor.ts +91 -0
  102. package/src/native/reminders/sync.ts +301 -0
  103. package/src/native/reminders/wire.ts +197 -0
  104. package/src/native/reminders/wire.typecheck.ts +13 -0
  105. package/src/native/submission-withdrawal.ts +65 -0
  106. package/src/native/usage.ts +15 -0
  107. package/src/native/worker-delivery.ts +61 -0
  108. package/src/native-harness/.res/README.md +1 -0
  109. package/src/native-harness/.res/architecture/README.md +21 -0
  110. package/src/native-harness/.res/architecture/context-and-data.md +31 -0
  111. package/src/native-harness/.res/architecture/execution.md +42 -0
  112. package/src/native-harness/.res/architecture/overview.md +44 -0
  113. package/src/native-harness/.res/architecture/persistence.md +56 -0
  114. package/src/native-harness/.res/architecture/suspend-and-resume.md +45 -0
  115. package/src/native-harness/.res/architecture/technical-architecture.md +50 -0
  116. package/src/native-harness/.res/decisions/0001-basic-loop.md +11 -0
  117. package/src/native-harness/.res/decisions/0002-channel-input.md +17 -0
  118. package/src/native-harness/.res/decisions/0003-inference-inspection.md +14 -0
  119. package/src/native-harness/.res/decisions/0004-shared-context.md +21 -0
  120. package/src/native-harness/.res/decisions/0005-notice-inbox.md +20 -0
  121. package/src/native-harness/.res/decisions/0006-explicit-notices.md +12 -0
  122. package/src/native-harness/.res/decisions/0007-channel-output.md +12 -0
  123. package/src/native-harness/.res/decisions/0008-browser-client.md +16 -0
  124. package/src/native-harness/.res/decisions/0009-scripted-model.md +18 -0
  125. package/src/native-harness/.res/decisions/0010-inprocess-protocol.md +19 -0
  126. package/src/native-harness/.res/decisions/0011-stdio-transport.md +21 -0
  127. package/src/native-harness/.res/decisions/0012-session-storage-contract.md +37 -0
  128. package/src/native-harness/.res/decisions/0013-durable-delivery-contract.md +64 -0
  129. package/src/native-harness/.res/decisions/0014-channel-controls-contract.md +73 -0
  130. package/src/native-harness/.res/decisions/0015-session-file-contract.md +72 -0
  131. package/src/native-harness/.res/decisions/0016-configuration-permissions.md +159 -0
  132. package/src/native-harness/.res/decisions/0017-openrouter-managed-config.md +69 -0
  133. package/src/native-harness/.res/decisions/0018-tool-dispatch-evidence.md +78 -0
  134. package/src/native-harness/.res/decisions/0019-model-execution.md +188 -0
  135. package/src/native-harness/.res/decisions/0020-startup-channel-changes.md +71 -0
  136. package/src/native-harness/.res/decisions/0021-tools-and-host-callbacks.md +100 -0
  137. package/src/native-harness/.res/decisions/0022-operator-controls.md +115 -0
  138. package/src/native-harness/.res/decisions/0023-long-running-mock.md +82 -0
  139. package/src/native-harness/.res/decisions/0024-callback-policy-names.md +46 -0
  140. package/src/native-harness/.res/decisions/0025-external-notices.md +364 -0
  141. package/src/native-harness/.res/decisions/0026-bounded-context.md +81 -0
  142. package/src/native-harness/.res/decisions/0027-development-instructions.md +22 -0
  143. package/src/native-harness/.res/decisions/0028-debug-tools.md +16 -0
  144. package/src/native-harness/.res/decisions/0029-bounded-model-call-pages.md +37 -0
  145. package/src/native-harness/.res/decisions/0030-timeline-retrieval.md +145 -0
  146. package/src/native-harness/.res/decisions/0031-one-off-reminders.md +173 -0
  147. package/src/native-harness/.res/docs/11-15.md +148 -0
  148. package/src/native-harness/.res/docs/BUSINESS_RULES.md +111 -0
  149. package/src/native-harness/.res/docs/WORK.md +65 -0
  150. package/src/native-harness/.res/docs/_/11-16-persistence/LOG.md +312 -0
  151. package/src/native-harness/.res/docs/_/11-16-persistence/PLAN.md +77 -0
  152. package/src/native-harness/.res/docs/_/11-16-persistence/SPEC.md +313 -0
  153. package/src/native-harness/.res/docs/_/11-19-channel-controls/LOG.md +160 -0
  154. package/src/native-harness/.res/docs/_/11-19-channel-controls/PLAN.md +89 -0
  155. package/src/native-harness/.res/docs/_/11-19-channel-controls/SPEC.md +135 -0
  156. package/src/native-harness/.res/docs/_/11-19-config-permissions/LOG.md +143 -0
  157. package/src/native-harness/.res/docs/_/11-19-config-permissions/PLAN.md +93 -0
  158. package/src/native-harness/.res/docs/_/11-19-config-permissions/SPEC.md +181 -0
  159. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/11-20-LOG.md +433 -0
  160. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PLAN.md +60 -0
  161. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PROTOCOL.md +141 -0
  162. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/SPEC.md +168 -0
  163. package/src/native-harness/.res/docs/attachments/0001-DESIGN/SPEC.md +111 -0
  164. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/PLAN.md +129 -0
  165. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/SPEC.md +135 -0
  166. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/LOG.md +437 -0
  167. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/PLAN.md +127 -0
  168. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/SPEC.md +203 -0
  169. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/LOG.md +292 -0
  170. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/PLAN.md +91 -0
  171. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/SPEC.md +187 -0
  172. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/LOG.md +148 -0
  173. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/PLAN.md +95 -0
  174. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/SPEC.md +200 -0
  175. package/src/native-harness/.res/docs/model-execution/0002-AMENDMENT-accounting/SPEC.md +80 -0
  176. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/LOG.md +206 -0
  177. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/PLAN.md +106 -0
  178. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/SPEC.md +297 -0
  179. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/LOG.md +41 -0
  180. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/PLAN.md +36 -0
  181. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/SPEC.md +84 -0
  182. package/src/native-harness/.res/docs/shell-execution/0001-DESIGN/SPEC.md +147 -0
  183. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/LOG.md +15 -0
  184. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/PLAN.md +107 -0
  185. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/SPEC.md +114 -0
  186. package/src/native-harness/.res/docs/todos/11-19-TODO-auto_review-approve.md +24 -0
  187. package/src/native-harness/.res/docs/todos/11-20-TODO-user-entered-tool-code.md +23 -0
  188. package/src/native-harness/.res/docs/todos/11-21-TODO-node-resource-coordination.md +103 -0
  189. package/src/native-harness/.res/docs/todos/11-22-TODO-harness-m1-sequence.md +50 -0
  190. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/LOG.md +337 -0
  191. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/PLAN.md +76 -0
  192. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/SPEC.md +204 -0
  193. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/LOG.md +73 -0
  194. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/SPEC.md +64 -0
  195. package/src/native-harness/.res/docs/tools-and-callbacks/0003-DESIGN-attachment-tools/SPEC.md +58 -0
  196. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/LOG.md +45 -0
  197. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/PLAN.md +108 -0
  198. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/SPEC.md +169 -0
  199. package/src/native-harness/.res/docs/web-tools/0001-DESIGN/SPEC.md +128 -0
  200. package/src/native-harness/.res/marketing-draft.md +22 -0
  201. package/src/native-harness/.res/sandbox/1-simple-harness/README.md +285 -0
  202. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-1.md +19 -0
  203. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-10.md +138 -0
  204. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-11.md +148 -0
  205. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-12.md +172 -0
  206. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-13.md +194 -0
  207. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-14.md +233 -0
  208. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-15.md +249 -0
  209. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-16.md +265 -0
  210. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-17.md +279 -0
  211. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-18.md +293 -0
  212. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-19.md +307 -0
  213. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-2.md +29 -0
  214. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-20.md +317 -0
  215. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-21.md +327 -0
  216. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-3.md +40 -0
  217. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-4.md +59 -0
  218. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-5.md +69 -0
  219. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-6.md +79 -0
  220. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-7.md +89 -0
  221. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-8.md +102 -0
  222. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-9.md +116 -0
  223. package/src/native-harness/.res/sandbox/1-simple-harness/conversation.jsonl +49 -0
  224. package/src/native-harness/.res/sandbox/1-simple-harness/doc.md +87 -0
  225. package/src/native-harness/.res/sandbox/1-simple-harness/harness.py +289 -0
  226. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 2.py +221 -0
  227. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 3.py +287 -0
  228. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy.py +165 -0
  229. package/src/native-harness/.res/sandbox/1-simple-harness/state.json +22 -0
  230. package/src/native-harness/.res/sandbox/1-simple-harness/system-prompt.md +2 -0
  231. package/src/native-harness/AGENTS.md +70 -0
  232. package/src/native-harness/ARCHITECTURE.md +249 -0
  233. package/src/native-harness/README.md +726 -0
  234. package/src/native-harness/bun.lock +26 -0
  235. package/src/native-harness/package.json +24 -0
  236. package/src/native-harness/src/capabilities/context/build.ts +59 -0
  237. package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
  238. package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
  239. package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
  240. package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
  241. package/src/native-harness/src/capabilities/context/session.ts +92 -0
  242. package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
  243. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
  244. package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
  245. package/src/native-harness/src/capabilities/model/runner.ts +116 -0
  246. package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
  247. package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
  248. package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
  249. package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
  250. package/src/native-harness/src/capabilities/model/usage.ts +15 -0
  251. package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
  252. package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
  253. package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
  254. package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
  255. package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
  256. package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
  257. package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
  258. package/src/native-harness/src/capabilities/tools/reminders/index.ts +75 -0
  259. package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
  260. package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
  261. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
  262. package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
  263. package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
  264. package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
  265. package/src/native-harness/src/client.ts +18 -0
  266. package/src/native-harness/src/contracts/agent.ts +105 -0
  267. package/src/native-harness/src/contracts/config-permissions.ts +47 -0
  268. package/src/native-harness/src/contracts/context.ts +112 -0
  269. package/src/native-harness/src/contracts/events.ts +47 -0
  270. package/src/native-harness/src/contracts/input-limits.ts +7 -0
  271. package/src/native-harness/src/contracts/inspection.ts +22 -0
  272. package/src/native-harness/src/contracts/loop.ts +31 -0
  273. package/src/native-harness/src/contracts/model-execution.ts +83 -0
  274. package/src/native-harness/src/contracts/operator-controls.ts +106 -0
  275. package/src/native-harness/src/contracts/output.ts +13 -0
  276. package/src/native-harness/src/contracts/protocol.ts +320 -0
  277. package/src/native-harness/src/contracts/reminders.ts +132 -0
  278. package/src/native-harness/src/contracts/scenario.ts +42 -0
  279. package/src/native-harness/src/contracts/session-file.ts +19 -0
  280. package/src/native-harness/src/contracts/session.ts +184 -0
  281. package/src/native-harness/src/contracts/storage.ts +596 -0
  282. package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
  283. package/src/native-harness/src/contracts/tools.ts +133 -0
  284. package/src/native-harness/src/governance/permissions/gate.ts +129 -0
  285. package/src/native-harness/src/governance/policy/resolve.ts +32 -0
  286. package/src/native-harness/src/index.ts +318 -0
  287. package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
  288. package/src/native-harness/src/interfaces/cli/development.ts +145 -0
  289. package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
  290. package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
  291. package/src/native-harness/src/interfaces/cli/main.ts +47 -0
  292. package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
  293. package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
  294. package/src/native-harness/src/interfaces/cli/start.ts +106 -0
  295. package/src/native-harness/src/interfaces/client.ts +225 -0
  296. package/src/native-harness/src/interfaces/inspector/index.html +283 -0
  297. package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
  298. package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
  299. package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
  300. package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
  301. package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
  302. package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
  303. package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
  304. package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
  305. package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
  306. package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
  307. package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
  308. package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
  309. package/src/native-harness/src/interfaces/protocol/server.ts +517 -0
  310. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +119 -0
  311. package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
  312. package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
  313. package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
  314. package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
  315. package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
  316. package/src/native-harness/src/kernel/channels.ts +405 -0
  317. package/src/native-harness/src/kernel/loop.ts +45 -0
  318. package/src/native-harness/src/runtime/config/development.ts +23 -0
  319. package/src/native-harness/src/runtime/config/managed.ts +2 -0
  320. package/src/native-harness/src/runtime/config/paths.ts +27 -0
  321. package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
  322. package/src/native-harness/src/runtime/reminder-validation.ts +104 -0
  323. package/src/native-harness/src/runtime/reminders.ts +66 -0
  324. package/src/native-harness/src/state/storage/archive.ts +239 -0
  325. package/src/native-harness/src/state/storage/engine.ts +1013 -0
  326. package/src/native-harness/src/state/storage/inference.ts +124 -0
  327. package/src/native-harness/src/state/storage/memory-reminders.ts +78 -0
  328. package/src/native-harness/src/state/storage/memory.ts +341 -0
  329. package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
  330. package/src/native-harness/src/state/storage/reminder-archive.ts +63 -0
  331. package/src/native-harness/src/state/storage/reminder-change.ts +92 -0
  332. package/src/native-harness/src/state/storage/reminder-tables.ts +27 -0
  333. package/src/native-harness/src/state/storage/retrieval.ts +122 -0
  334. package/src/native-harness/src/state/storage/script-identity.ts +7 -0
  335. package/src/native-harness/src/state/storage/session-file.ts +85 -0
  336. package/src/native-harness/src/state/storage/sqlite-reminders.ts +134 -0
  337. package/src/native-harness/src/state/storage/sqlite.ts +625 -0
  338. package/src/native-harness/src/testing.ts +190 -0
  339. package/src/native-harness/src/util/config.ts +58 -0
  340. package/src/native-harness/src/util/json.ts +41 -0
  341. package/src/native-harness/src/util/message-position.ts +3 -0
  342. package/src/native-harness/src/util/reminder-schedule.ts +44 -0
  343. package/src/native-harness/src/util/schema.ts +40 -0
  344. package/src/native-harness/src/util/timeline-text.ts +72 -0
  345. package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
  346. package/src/native-harness/test/agent.test.ts +130 -0
  347. package/src/native-harness/test/approval-gate.test.ts +255 -0
  348. package/src/native-harness/test/approval-protocol.test.ts +94 -0
  349. package/src/native-harness/test/boundaries.test.ts +18 -0
  350. package/src/native-harness/test/channel-controls.test.ts +322 -0
  351. package/src/native-harness/test/client-abort.test.ts +136 -0
  352. package/src/native-harness/test/config-policy.test.ts +301 -0
  353. package/src/native-harness/test/conformance/storage.ts +1141 -0
  354. package/src/native-harness/test/context.test.ts +177 -0
  355. package/src/native-harness/test/crash.test.ts +187 -0
  356. package/src/native-harness/test/debug-tools.test.ts +67 -0
  357. package/src/native-harness/test/development-cli.test.ts +67 -0
  358. package/src/native-harness/test/development.test.ts +171 -0
  359. package/src/native-harness/test/dispatch-evidence.test.ts +58 -0
  360. package/src/native-harness/test/e2e.test.ts +186 -0
  361. package/src/native-harness/test/external-notices.test.ts +101 -0
  362. package/src/native-harness/test/fixtures/approval-e2e.jsonl +4 -0
  363. package/src/native-harness/test/fixtures/crash-scenario.jsonl +5 -0
  364. package/src/native-harness/test/fixtures/development-lifecycle.jsonl +10 -0
  365. package/src/native-harness/test/fixtures/echo-scenario.jsonl +3 -0
  366. package/src/native-harness/test/fixtures/format2-schema.ts +27 -0
  367. package/src/native-harness/test/fixtures/format3-schema.ts +16 -0
  368. package/src/native-harness/test/fixtures/hold-scenario.jsonl +4 -0
  369. package/src/native-harness/test/fixtures/model-e2e.jsonl +3 -0
  370. package/src/native-harness/test/fixtures/storage-owner.ts +20 -0
  371. package/src/native-harness/test/format-reply.test.ts +10 -0
  372. package/src/native-harness/test/helpers/operator-view.ts +41 -0
  373. package/src/native-harness/test/helpers/scenario.ts +9 -0
  374. package/src/native-harness/test/helpers/session.ts +38 -0
  375. package/src/native-harness/test/helpers/stdio.ts +46 -0
  376. package/src/native-harness/test/inspector.test.ts +77 -0
  377. package/src/native-harness/test/listeners.test.ts +49 -0
  378. package/src/native-harness/test/loop.test.ts +88 -0
  379. package/src/native-harness/test/model-channel-double.test.ts +87 -0
  380. package/src/native-harness/test/model-crash.test.ts +62 -0
  381. package/src/native-harness/test/model-delivery-regressions.test.ts +55 -0
  382. package/src/native-harness/test/model-e2e.test.ts +71 -0
  383. package/src/native-harness/test/model-final-filter.test.ts +30 -0
  384. package/src/native-harness/test/model-large-reply.test.ts +28 -0
  385. package/src/native-harness/test/model-live-queue.test.ts +33 -0
  386. package/src/native-harness/test/model-runner.test.ts +117 -0
  387. package/src/native-harness/test/model-storage.test.ts +99 -0
  388. package/src/native-harness/test/model-stream-adapter.test.ts +26 -0
  389. package/src/native-harness/test/model-stream-public.test.ts +77 -0
  390. package/src/native-harness/test/notices.test.ts +64 -0
  391. package/src/native-harness/test/openrouter-config.test.ts +218 -0
  392. package/src/native-harness/test/operator-controls.test.ts +132 -0
  393. package/src/native-harness/test/output.test.ts +44 -0
  394. package/src/native-harness/test/owner-config.test.ts +64 -0
  395. package/src/native-harness/test/permissions-e2e.test.ts +68 -0
  396. package/src/native-harness/test/persistence.test.ts +236 -0
  397. package/src/native-harness/test/portability.test.ts +337 -0
  398. package/src/native-harness/test/protocol.test.ts +160 -0
  399. package/src/native-harness/test/reminder-clock.test.ts +61 -0
  400. package/src/native-harness/test/reminder-stdio.test.ts +140 -0
  401. package/src/native-harness/test/reminder-storage.test.ts +124 -0
  402. package/src/native-harness/test/scenario-jsonl.test.ts +112 -0
  403. package/src/native-harness/test/scripted.test.ts +92 -0
  404. package/src/native-harness/test/session-file.test.ts +51 -0
  405. package/src/native-harness/test/startup-channel-changes.test.ts +256 -0
  406. package/src/native-harness/test/stdio.test.ts +132 -0
  407. package/src/native-harness/test/storage-memory.test.ts +4 -0
  408. package/src/native-harness/test/storage-sqlite.test.ts +420 -0
  409. package/src/native-harness/test/suspension.test.ts +430 -0
  410. package/src/native-harness/test/timeline-retrieval.test.ts +211 -0
  411. package/src/native-harness/test/tools-catalog.test.ts +468 -0
  412. package/src/native-harness/test/tools-protocol.test.ts +418 -0
  413. package/src/native-harness/test/transfers.test.ts +94 -0
  414. package/src/native-harness/test/web-chat.test.ts +35 -0
  415. package/src/native-harness/tsconfig.json +20 -0
  416. package/src/observation/agent-event-bus.ts +44 -18
  417. package/src/observation/index.ts +1 -0
  418. package/src/operations/contracts.ts +11 -3
  419. package/src/operations/errors.ts +5 -0
  420. package/src/operations/stale-policy.ts +1 -1
  421. package/src/operations/supervisor.ts +34 -10
  422. package/src/orchestrator/acp-delivery.ts +68 -0
  423. package/src/orchestrator/assignments.ts +27 -0
  424. package/src/orchestrator/busy.ts +15 -0
  425. package/src/orchestrator/config.ts +41 -0
  426. package/src/orchestrator/consumer-api.ts +24 -0
  427. package/src/orchestrator/contracts.ts +71 -0
  428. package/src/orchestrator/durable-assignments.ts +111 -0
  429. package/src/orchestrator/native-delegation.ts +103 -0
  430. package/src/orchestrator/orchestrator.ts +318 -0
  431. package/src/orchestrator/permissions.ts +25 -0
  432. package/src/orchestrator/policy.ts +44 -0
  433. package/src/orchestrator/pool.ts +123 -0
  434. package/src/orchestrator/tool-descriptions.ts +11 -0
  435. package/src/permissions/acp.ts +18 -0
  436. package/src/permissions/arrival.ts +13 -0
  437. package/src/permissions/consumer-config.ts +19 -0
  438. package/src/permissions/conversation.ts +280 -0
  439. package/src/permissions/matcher.ts +85 -0
  440. package/src/permissions/outcome.ts +15 -0
  441. package/src/permissions/policy.ts +81 -0
  442. package/src/permissions/request.ts +26 -0
  443. package/src/persistence/activity-projection.ts +1 -0
  444. package/src/persistence/backend.ts +34 -1
  445. package/src/persistence/channels.ts +23 -0
  446. package/src/persistence/index.ts +4 -0
  447. package/src/persistence/protocol-method.ts +5 -0
  448. package/src/persistence/reminder-wake.ts +49 -0
  449. package/src/persistence/reminders.ts +385 -0
  450. package/src/persistence/sqlite-backend.ts +84 -6
  451. package/src/persistence/sqlite-channels.ts +65 -0
  452. package/src/persistence/sqlite-reminders.ts +85 -0
  453. package/src/persistence/sqlite-schema.ts +108 -3
  454. package/src/persistence/sqlite-worker-delivery.ts +374 -0
  455. package/src/persistence/sqlite-workers.ts +59 -0
  456. package/src/persistence/worker-delivery-contract.ts +104 -0
  457. package/src/persistence/worker-terminal-reason.ts +29 -0
  458. package/src/persistence/workers.ts +19 -0
  459. package/src/provider-notices.ts +137 -0
  460. package/src/repl/commands.ts +2 -2
  461. package/src/steering/combine.ts +3 -1
  462. package/src/steering/contracts.ts +11 -2
  463. package/src/steering/controller.ts +3 -2
  464. package/src/transport/acp-transport.ts +24 -14
  465. package/src/types.ts +15 -12
  466. package/src/updates.ts +14 -2
  467. package/src/wire-log.ts +1 -1
@@ -0,0 +1,124 @@
1
+ import type { ContextLimits, ContextTurnOutcome, InferenceRead, InferenceStorageReads } from "../../contracts/context.ts";
2
+ import type { TimelineEntry } from "../../contracts/storage.ts";
3
+
4
+ /** Charge the serialized message, the UTF-8 bytes of variable entry fields,
5
+ * and a fixed allowance for scalar fields and record framing. */
6
+ export const entryOverhead = 128;
7
+ export const byteLength = (value: string) => Buffer.byteLength(value, "utf8");
8
+
9
+ export interface ContextRow {
10
+ seq: number;
11
+ bytes: number;
12
+ textBytes?: number;
13
+ kind: "input" | "assistant" | "other";
14
+ }
15
+
16
+ export interface ContextRows {
17
+ contextTurnStart(channelId: string, turnId: number): number | undefined;
18
+ contextTrigger(turnId: number): ContextRow | undefined;
19
+ contextPreviousResponse(turnId: number): number;
20
+ contextInputs(turnId: number, after: number, limit: number): ContextRow[];
21
+ contextActive(turnId: number, limit: number): ContextRow[];
22
+ contextLocal(channelId: string, before: number, limit: number): ContextRow[];
23
+ contextRecent(before: number, limit: number, legacy?: boolean): ContextRow[];
24
+ contextShared(channelId: string, candidates: number): ContextRow[];
25
+ contextPolicies(turnId: number, limit: number, bytes: number): { names: string[]; bytes: number } | undefined;
26
+ contextUnfinished(turnId: number, maxBytes: number): { outcome: ContextTurnOutcome; bytes: number } | undefined;
27
+ contextEntry(seq: number): TimelineEntry;
28
+ contextHistoricalEntry(seq: number): TimelineEntry;
29
+ }
30
+
31
+ export function validReadLimits(limits: ContextLimits): boolean {
32
+ return [limits.maxReadRecords, limits.maxReadBytes, limits.maxSharedCandidates, limits.maxInputBytes, limits.maxTakenTextBytes, limits.maxTakenItems]
33
+ .every(n => Number.isSafeInteger(n) && n > 0 && n < Number.MAX_SAFE_INTEGER);
34
+ }
35
+
36
+ /** Every adapter supplies headers first. Only rows charged to the same budget
37
+ * can cross the body-read boundary, including rows discarded after validation. */
38
+ export function readInference(rows: ContextRows, input: Parameters<InferenceStorageReads["readInferenceContext"]>[0],
39
+ turnStart: number): InferenceRead | { code: "context_limit" } {
40
+ const { channelId, turnId, limits } = input;
41
+ const { maxReadRecords, maxReadBytes, maxSharedCandidates } = limits;
42
+ const overflow = { code: "context_limit" } as const;
43
+ const trigger = rows.contextTrigger(turnId);
44
+ const taken = rows.contextInputs(turnId, rows.contextPreviousResponse(turnId), maxReadRecords + 1);
45
+ if (taken.length > limits.maxTakenItems ||
46
+ taken.reduce((total, row) => total + (row.textBytes ?? 0), 0) > limits.maxTakenTextBytes ||
47
+ (trigger?.textBytes ?? 0) > limits.maxInputBytes || taken.some(row => (row.textBytes ?? 0) > limits.maxInputBytes)) return overflow;
48
+ const requiredRows = trigger && trigger.seq !== taken[0]?.seq ? [trigger, ...taken] : taken;
49
+ const requiredBytes = requiredRows.reduce((total, row) => total + row.bytes, 0);
50
+ if (requiredRows.length > maxReadRecords || requiredBytes > maxReadBytes) return overflow;
51
+ const policies = rows.contextPolicies(turnId, maxReadRecords, maxReadBytes - requiredBytes);
52
+ if (!policies) return overflow;
53
+
54
+ let records = maxReadRecords - requiredRows.length;
55
+ let bytes = maxReadBytes - requiredBytes - policies.bytes;
56
+ function charge(group: readonly ContextRow[], reserveRecords = 0, reserveBytes = 0) {
57
+ const cost = group.reduce((total, row) => total + row.bytes, 0);
58
+ if (group.length > records - reserveRecords || cost > bytes - reserveBytes) return false;
59
+ records -= group.length;
60
+ bytes -= cost;
61
+ return true;
62
+ }
63
+ const required = requiredRows.map(row => rows.contextEntry(row.seq));
64
+ const takenItemIds = required.slice(required.length - taken.length).map(entry => entry.itemId!);
65
+ const requiredSeqs = new Set(requiredRows.map(row => row.seq));
66
+
67
+ // The newest bounded suffix can start with orphaned tool results. Start a
68
+ // group only at an assistant row and verify its entire result set after load.
69
+ const groups: ContextRow[][] = [];
70
+ let exchange: ContextRow[] | undefined;
71
+ if (records && bytes) for (const row of rows.contextActive(turnId, maxReadRecords).reverse()) {
72
+ if (row.kind === "assistant") { exchange = [row]; groups.push(exchange); }
73
+ else if (row.kind === "other") exchange?.push(row);
74
+ else if (!requiredSeqs.has(row.seq)) groups.push([row]);
75
+ }
76
+ const optionalTurn: TimelineEntry[] = [];
77
+ for (const group of groups.reverse()) {
78
+ if (!charge(group)) continue;
79
+ const entries = group.map(row => rows.contextEntry(row.seq));
80
+ const first = entries[0]!.message;
81
+ if (first.role === "assistant") {
82
+ const results = new Set(entries.slice(1).flatMap(({ message }) => message.role === "tool" ? [message.callId] : []));
83
+ if (results.size !== entries.length - 1 || results.size !== first.calls.length || first.calls.some(call => !results.has(call.id))) continue;
84
+ }
85
+ optionalTurn.push(...entries);
86
+ }
87
+
88
+ const localHistory: TimelineEntry[] = [], sharedHistory: TimelineEntry[] = [];
89
+ if (records && bytes) {
90
+ const local = rows.contextLocal(channelId, turnStart, maxReadRecords);
91
+ const shared = rows.contextShared(channelId, maxSharedCandidates).slice(0, maxReadRecords);
92
+ // Reserve room for a recent shared exchange even when a long local
93
+ // transcript can fill every record slot. Return unused space to local.
94
+ let reserveRecords = 0, reserveBytes = 0;
95
+ const sharedSlots = records > 1 ? Math.max(1, Math.floor(records / 3)) : 0;
96
+ for (const row of shared) {
97
+ if (reserveRecords === sharedSlots) break;
98
+ if (reserveBytes + row.bytes > Math.floor(bytes / 3)) continue;
99
+ reserveRecords++;
100
+ reserveBytes += row.bytes;
101
+ }
102
+ const deferred: ContextRow[] = [];
103
+ for (const row of local) {
104
+ if (charge([row], reserveRecords, reserveBytes))
105
+ localHistory.push(rows.contextHistoricalEntry(row.seq));
106
+ else deferred.push(row);
107
+ }
108
+ for (const row of shared) if (charge([row])) sharedHistory.push(rows.contextHistoricalEntry(row.seq));
109
+ for (const row of deferred) if (charge([row])) localHistory.push(rows.contextHistoricalEntry(row.seq));
110
+ }
111
+ const unfinished: ContextTurnOutcome[] = [];
112
+ const historicalTurns = new Set([...localHistory, ...sharedHistory].sort((a, b) => b.seq - a.seq).map(row => row.turnId));
113
+ for (const id of historicalTurns) {
114
+ if (!records || !bytes) break;
115
+ const record = rows.contextUnfinished(id, bytes);
116
+ if (!record) continue;
117
+ bytes -= record.bytes;
118
+ records--;
119
+ unfinished.push(record.outcome);
120
+ }
121
+ const order = (a: TimelineEntry, b: TimelineEntry) => a.seq - b.seq;
122
+ return { required, optionalTurn: optionalTurn.sort(order), localHistory: localHistory.sort(order),
123
+ sharedHistory: sharedHistory.sort(order), unfinished, takenItemIds, policyNames: policies.names };
124
+ }
@@ -0,0 +1,78 @@
1
+ import type { ReminderWake } from "../../contracts/reminders.ts";
2
+ import type { ReminderReceipt } from "./reminder-change.ts";
3
+ import type { ReminderRow, ReminderTables } from "./reminder-tables.ts";
4
+
5
+ export interface MemoryReminderState {
6
+ rows: Map<string, ReminderRow>;
7
+ creates: Map<string, ReminderReceipt>;
8
+ receipts: Map<string, Map<number, ReminderReceipt>>;
9
+ highWater: Map<string, number>;
10
+ listingRevision: number;
11
+ wake: ReminderWake;
12
+ }
13
+
14
+ export const emptyMemoryReminders = (): MemoryReminderState => ({
15
+ rows: new Map(), creates: new Map(), receipts: new Map(), highWater: new Map(), listingRevision: 0,
16
+ wake: { nextDueAt: null, reminderRevision: 0 },
17
+ });
18
+
19
+ export function memoryReminderTables(
20
+ state: MemoryReminderState, log: (undo: () => void) => void, eligible: (channel: string) => boolean,
21
+ ): ReminderTables {
22
+ function put<K, V>(map: Map<K, V>, key: K, value: V) {
23
+ const previous = map.get(key);
24
+ log(() => { if (previous === undefined) map.delete(key); else map.set(key, previous); });
25
+ map.set(key, structuredClone(value));
26
+ }
27
+
28
+ return {
29
+ activate() {},
30
+ archive() {
31
+ return structuredClone({ rows: [...state.rows.values()], receipts: [...state.receipts.values()].flatMap(rows => [...rows.values()]),
32
+ listingRevision: state.listingRevision, wake: state.wake });
33
+ },
34
+ restore(saved) {
35
+ for (const row of saved.rows) this.put(row);
36
+ for (const receipt of saved.receipts) this.saveReceipt(receipt);
37
+ this.setWake(saved.wake);
38
+ const before = state.listingRevision;
39
+ log(() => { state.listingRevision = before; });
40
+ state.listingRevision = saved.listingRevision;
41
+ },
42
+ get: id => structuredClone(state.rows.get(id)),
43
+ put(row) {
44
+ put(state.rows, row.reminder.id, row);
45
+ const before = state.listingRevision++;
46
+ log(() => { state.listingRevision = before; });
47
+ },
48
+ originalCreate: id => structuredClone(state.creates.get(id)),
49
+ receipt: (id, version) => structuredClone(state.receipts.get(id)?.get(version)),
50
+ highWater: id => state.highWater.get(id) ?? 0,
51
+ saveReceipt(receipt) {
52
+ const { reminderId, changeId } = receipt.result;
53
+ if (receipt.fingerprint.startsWith('["create",') && !state.creates.has(reminderId)) put(state.creates, reminderId, receipt);
54
+ const existing = state.receipts.get(reminderId);
55
+ if (existing) put(existing, changeId, receipt);
56
+ else put(state.receipts, reminderId, new Map([[changeId, receipt]]));
57
+ put(state.highWater, reminderId, Math.max(state.highWater.get(reminderId) ?? 0, changeId));
58
+ },
59
+ list: (channel, after, limit) => structuredClone([...state.rows.values()]
60
+ .filter(row => row.sequence > after && (channel === undefined || row.reminder.channel === channel))
61
+ .slice(0, limit)),
62
+ blocked: (channel, after, limit) => structuredClone([...state.rows.values()]
63
+ .filter(row => row.sequence > after && row.reminder.state === "blocked" && row.reminder.blockedReason === "invalid_policy"
64
+ && (channel === undefined || row.reminder.channel === channel))
65
+ .slice(0, limit)),
66
+ eligible: (through, limit) => structuredClone([...state.rows.values()]
67
+ .filter(({ reminder }) => reminder.nextRunAt !== null && (through === null || reminder.nextRunAt <= through) && eligible(reminder.channel))
68
+ .sort((a, b) => a.reminder.nextRunAt!.localeCompare(b.reminder.nextRunAt!) || a.sequence - b.sequence)
69
+ .slice(0, limit)),
70
+ listingRevision: () => state.listingRevision,
71
+ wake: () => structuredClone(state.wake),
72
+ setWake(wake) {
73
+ const before = state.wake;
74
+ log(() => { state.wake = before; });
75
+ state.wake = structuredClone(wake);
76
+ },
77
+ };
78
+ }
@@ -0,0 +1,341 @@
1
+ import { emptyMemoryReminders, memoryReminderTables, type MemoryReminderState } from "./memory-reminders.ts";
2
+ import { historicalCandidate, historicalRetrievalProjection, retrievalMessage, timelineTokens, timelineBytes } from "../../util/timeline-text.ts";
3
+ import { byteLength, entryOverhead, type ContextRow } from "./inference.ts";
4
+ import { checkScriptIdentity } from "./script-identity.ts";
5
+ import type { SessionStorageAdapter, StoredItem, TimelineEntry } from "../../contracts/storage.ts";
6
+ import { Fail, createEngine, failure, recover, referencesCompatible, type ChannelRow, type Meta, type Tables, type TurnRow, type ModelState } from "./engine.ts";
7
+ import { archiveMeta, restoreArchive, storedSession, validateArchive, validateSessionPayload } from "./archive.ts";
8
+ import { validateManagedConfig } from "../../util/config.ts";
9
+
10
+ type ContextEntry = ContextRow & { entry: TimelineEntry };
11
+
12
+ interface Data {
13
+ reminders: MemoryReminderState;
14
+ bySeq: Map<number, ContextEntry>;
15
+ retrievalReplies: Map<string, number>;
16
+ historicalCandidates: TimelineEntry[];
17
+ retrievalCalls: Map<number, Set<string>>;
18
+ retrievalIndex: Map<number, { bytes: number; words: Set<string> }>;
19
+ byTurn: Map<number, ContextEntry[]>;
20
+ inputs: Map<number, ContextEntry[]>;
21
+ assistants: Map<number, ContextEntry[]>;
22
+ turnPolicies: Map<number, Set<string>>;
23
+ revokedTools?: string[];
24
+ modelState?: ModelState;
25
+ config?: import("../../contracts/session-file.ts").PortableSessionConfig;
26
+ meta: Meta;
27
+ channels: Map<string, ChannelRow>; participants: Set<string>;
28
+ items: Map<string, StoredItem>; turns: Map<number, TurnRow>; entries: TimelineEntry[]; conversation: Map<string, TimelineEntry[]>; replies: Map<number, TimelineEntry[]>;
29
+ }
30
+ const empty = (meta: Meta): Data => ({ meta, reminders: emptyMemoryReminders(), channels: new Map(), participants: new Set(), items: new Map(), turns: new Map(), entries: [], bySeq: new Map(), retrievalReplies: new Map(), retrievalIndex: new Map(), historicalCandidates: [], retrievalCalls: new Map(), byTurn: new Map(), inputs: new Map(), assistants: new Map(), turnPolicies: new Map(), conversation: new Map(), replies: new Map() });
31
+ const copy = <T>(value: T): T => structuredClone(value);
32
+ const live = (turn: TurnRow) => turn.state.status === "running" || turn.state.status === "suspended";
33
+
34
+ /** Rows in maps. Each write records how to undo itself, so a throwing
35
+ * transaction leaves no partial change without copying the whole session. */
36
+ function memoryTables(data: Data): Tables {
37
+ let undo: (() => void)[] | undefined;
38
+ const log = (step: () => void) => { undo?.push(step); };
39
+ const before = (rows: readonly { seq: number }[], seq: number) => {
40
+ let low = 0, high = rows.length;
41
+ while (low < high) {
42
+ const mid = (low + high) >>> 1;
43
+ if (rows[mid]!.seq < seq) low = mid + 1; else high = mid;
44
+ }
45
+ return low;
46
+ };
47
+ const recent = <T>(rows: T[], limit: number, end = rows.length) => rows.slice(Math.max(0, end - limit), end).reverse();
48
+ const header = ({ seq, bytes, kind, entry }: ContextEntry): ContextRow => ({
49
+ seq, ...(entry.itemId === undefined ? {} : { textBytes: byteLength(data.items.get(entry.itemId)?.text ?? "") }),
50
+ bytes: bytes + byteLength(data.modelState?.entryIds[String(seq)] ?? entry.messageId ?? ""), kind,
51
+ });
52
+ const historicalHeader = (row: ContextEntry): ContextRow => {
53
+ const base = header(row), projected = historicalRetrievalProjection(row.entry.message);
54
+ return projected === row.entry.message ? base : { ...base,
55
+ bytes: base.bytes - byteLength(JSON.stringify(row.entry.message)) + byteLength(JSON.stringify(projected)) };
56
+ };
57
+ return {
58
+ reminders: memoryReminderTables(data.reminders, log, channel => data.channels.get(channel)?.lifecycle === "open"),
59
+ contextTurnStart(channelId, turnId) {
60
+ const turn = data.turns.get(turnId);
61
+ return turn?.channelId === channelId ? turn.startedSeq : undefined;
62
+ },
63
+ contextTrigger(turnId) {
64
+ const first = data.inputs.get(turnId)?.[0];
65
+ return first && header(first);
66
+ },
67
+ contextPreviousResponse: turnId => data.assistants.get(turnId)?.at(-1)?.seq ?? 0,
68
+ contextInputs(turnId, after, limit) {
69
+ const rows = data.inputs.get(turnId) ?? [];
70
+ const start = before(rows, after + 1);
71
+ return rows.slice(start, start + limit).map(header);
72
+ },
73
+ contextActive: (turnId, limit) => recent(data.byTurn.get(turnId) ?? [], limit).map(header),
74
+ contextLocal(channelId, start, limit) {
75
+ const rows = data.conversation.get(channelId) ?? [];
76
+ return recent(rows, limit, before(rows, start)).map(row => historicalHeader(data.bySeq.get(row.seq)!));
77
+ },
78
+ contextRecent(cursor, limit) {
79
+ return recent(data.entries, limit, before(data.entries, cursor)).map(row => header(data.bySeq.get(row.seq)!));
80
+ },
81
+ contextShared(channelId, limit) {
82
+ return recent(data.historicalCandidates, limit).filter(row => row.channelId !== channelId &&
83
+ (row.kind === "participant_message" || (row.message.role === "assistant" && !!row.message.content)))
84
+ .map(row => historicalHeader(data.bySeq.get(row.seq)!));
85
+ },
86
+ contextPolicies(turnId, limit, budget) {
87
+ const names = data.turnPolicies.get(turnId);
88
+ if (!names) return { names: [], bytes: 0 };
89
+ if (names.size > limit) return undefined;
90
+ let bytes = 0;
91
+ for (const name of names) {
92
+ bytes += byteLength(name) + 1;
93
+ if (bytes > budget) return undefined;
94
+ }
95
+ return { names: [...names].sort(), bytes };
96
+ },
97
+ contextUnfinished(turnId, budget) {
98
+ const turn = data.turns.get(turnId);
99
+ if (!turn || (turn.state.status !== "failed" && turn.state.status !== "interrupted")) return undefined;
100
+ const { channelId, state } = turn;
101
+ const bytes = entryOverhead + byteLength(channelId) + byteLength(JSON.stringify(state));
102
+ return bytes <= budget ? { outcome: { channelId, turnId, state }, bytes } : undefined;
103
+ },
104
+ retrievalCandidates(terms, channel, limit) {
105
+ const rows: { seq: number; bytes: number }[] = [];
106
+ const entries = channel === undefined ? data.entries : data.conversation.get(channel) ?? [];
107
+ for (let i = entries.length - 1; i >= 0 && rows.length < limit; i--) {
108
+ const seq = entries[i]!.seq, indexed = data.retrievalIndex.get(seq);
109
+ if (indexed && terms.every(term => indexed.words.has(term))) rows.push({ seq, bytes: indexed.bytes });
110
+ }
111
+ return rows;
112
+ },
113
+ retrievalEntry(seq) {
114
+ const entry = data.bySeq.get(seq)?.entry;
115
+ if (!entry) return;
116
+ const messageId = data.modelState?.entryIds[String(seq)] ?? entry.messageId;
117
+ return copy(messageId === undefined ? entry : { ...entry, messageId });
118
+ },
119
+ retrievalReplyId: id => data.retrievalReplies.get(id),
120
+ contextHistoricalEntry(seq) {
121
+ const saved = this.contextEntry(seq);
122
+ return { ...saved, message: historicalRetrievalProjection(saved.message) };
123
+ },
124
+ contextEntry(seq) {
125
+ const entry = data.bySeq.get(seq)!.entry;
126
+ const messageId = data.modelState?.entryIds[String(seq)] ?? entry.messageId;
127
+ // The engine detaches the selected values at the transaction boundary.
128
+ return messageId ? { ...entry, messageId } : entry;
129
+ },
130
+ modelCallPage(after, count) {
131
+ const calls = data.modelState?.calls ?? [];
132
+ if (after === undefined) return copy(calls.slice(0, count));
133
+ let lo = 0, hi = calls.length;
134
+ while (lo < hi) {
135
+ const mid = Math.floor((lo + hi) / 2);
136
+ if (Number(calls[mid]!.callId) < Number(after)) lo = mid + 1;
137
+ else hi = mid;
138
+ }
139
+ if (calls[lo]?.callId !== after) throw new Fail("not_found", "Unknown call cursor");
140
+ return copy(calls.slice(lo + 1, lo + 1 + count));
141
+ },
142
+ getModelState: () => copy(data.modelState),
143
+ setModelState(state) { const old = data.modelState; log(() => { data.modelState = old; }); data.modelState = copy(state); },
144
+ getRevokedTools: () => copy(data.revokedTools),
145
+ setRevokedTools(names) { const old = data.revokedTools; log(() => { data.revokedTools = old; }); data.revokedTools = [...names]; },
146
+ getConfig: () => copy(data.config),
147
+ setConfig(config) { const old = data.config; log(() => { data.config = old; }); data.config = copy(config); },
148
+ transaction(run) {
149
+ if (undo) return run();
150
+ undo = [];
151
+ try { return run(); }
152
+ catch (error) { for (const step of undo.reverse()) step(); throw error; }
153
+ finally { undo = undefined; }
154
+ },
155
+ getMeta: () => ({ ...data.meta }),
156
+ setMeta(meta) { const old = data.meta; log(() => { data.meta = old; }); data.meta = { ...meta }; },
157
+ channel: id => copy(data.channels.get(id)),
158
+ putChannel(channel) {
159
+ const old = data.channels.get(channel.channelId);
160
+ log(() => { if (old) data.channels.set(channel.channelId, old); else data.channels.delete(channel.channelId); });
161
+ data.channels.set(channel.channelId, copy(channel));
162
+ },
163
+ channels: () => copy([...data.channels.values()]),
164
+ addParticipant(id) { if (!data.participants.has(id)) { data.participants.add(id); log(() => data.participants.delete(id)); } },
165
+ participants: () => [...data.participants],
166
+ item: id => copy(data.items.get(id)),
167
+ putItem(item) {
168
+ const old = data.items.get(item.itemId);
169
+ log(() => { if (old) data.items.set(item.itemId, old); else data.items.delete(item.itemId); });
170
+ data.items.set(item.itemId, copy(item));
171
+ if (old?.turnId !== undefined || item.turnId === undefined) return;
172
+ const turnId = item.turnId;
173
+ let names = data.turnPolicies.get(turnId);
174
+ if (!names) {
175
+ names = new Set();
176
+ data.turnPolicies.set(turnId, names);
177
+ log(() => { data.turnPolicies.delete(turnId); });
178
+ }
179
+ const policy = item.policy;
180
+ for (const name of policy ? [policy.resolved, ...policy.inherited] : ["__legacy_allow"]) {
181
+ if (names.has(name)) continue;
182
+ const namesForUndo = names;
183
+ names.add(name);
184
+ log(() => { namesForUndo.delete(name); });
185
+ }
186
+ },
187
+ pendingItems: (channelId, limit) => copy([...data.items.values()].filter(item => item.channelId === channelId && item.milestone === "received")
188
+ .sort((a, b) => a.acceptedSeq - b.acceptedSeq).slice(0, limit ?? Infinity)),
189
+ itemsOfTurn: turnId => copy([...data.items.values()].filter(item => item.turnId === turnId).sort((a, b) => a.entrySeq! - b.entrySeq!)),
190
+ items: () => copy([...data.items.values()].sort((a, b) => a.acceptedSeq - b.acceptedSeq)),
191
+ turn: id => copy(data.turns.get(id)),
192
+ putTurn(turn) {
193
+ const old = data.turns.get(turn.turnId);
194
+ // Same invariant the SQLite schema enforces with a partial unique index.
195
+ if (live(turn)) for (const other of data.turns.values())
196
+ if (other.turnId !== turn.turnId && other.channelId === turn.channelId && live(other)) throw new Error("Channel already has a live turn");
197
+ log(() => { if (old) data.turns.set(turn.turnId, old); else data.turns.delete(turn.turnId); });
198
+ data.turns.set(turn.turnId, copy(turn));
199
+ },
200
+ liveTurn: channelId => copy([...data.turns.values()].find(turn => turn.channelId === channelId && live(turn))),
201
+ turns: () => copy([...data.turns.values()].sort((a, b) => a.turnId - b.turnId)),
202
+ latestTurn: id => copy([...data.turns.values()].findLast(turn => turn.channelId === id)),
203
+ liveTurns: () => copy([...data.turns.values()].filter(live)),
204
+ policyNames: () => [...new Set([...data.channels.values()].flatMap(channel => channel.policy ? [channel.policy] : [])
205
+ .concat([...data.items.values()].flatMap(item => item.policy ? [item.policy.resolved, ...item.policy.inherited] : ["__legacy_allow"])))],
206
+ pendingCount: id => [...data.items.values()].filter(item => item.channelId === id && item.milestone === "received").length,
207
+ readRange(range) {
208
+ const older = range.direction === "older";
209
+ const select = (rows: TimelineEntry[]) => {
210
+ const before = (seq: number) => older ? seq <= range.throughRevision && seq < (range.exclusiveSeq ?? Infinity) : seq <= (range.exclusiveSeq ?? 0);
211
+ let low = 0, high = rows.length;
212
+ while (low < high) {
213
+ const mid = (low + high) >>> 1;
214
+ if (before(rows[mid]!.seq)) low = mid + 1; else high = mid;
215
+ }
216
+ return older ? rows.slice(Math.max(0, low - range.limit - 1), low).reverse()
217
+ : rows.slice(low, low + range.limit + 1).filter(row => row.seq <= range.throughRevision);
218
+ };
219
+ const rows = range.kind === "conversation" ? select(data.conversation.get(range.channel!) ?? [])
220
+ : range.kind === "replies" ? (range.turnIds ?? []).flatMap(id => select(data.replies.get(id) ?? []))
221
+ .filter(row => row.channelId === range.channel).sort((a, b) => older ? b.seq - a.seq : a.seq - b.seq).slice(0, range.limit + 1)
222
+ : select(data.entries);
223
+ return copy(rows.map(row => {
224
+ const messageId = data.modelState?.entryIds[String(row.seq)];
225
+ return messageId ? { ...row, messageId } : row;
226
+ }));
227
+ },
228
+ addEntry(entry) {
229
+ const saved = copy(entry);
230
+ if (saved.messageId !== undefined) {
231
+ const id = saved.messageId;
232
+ data.retrievalReplies.set(id, saved.seq);
233
+ log(() => { data.retrievalReplies.delete(id); });
234
+ }
235
+ const append = <T>(rows: T[], row: T) => { rows.push(row); log(() => { rows.pop(); }); };
236
+ const indexed = <K, T>(index: Map<K, T[]>, key: K, row: T) => {
237
+ let rows = index.get(key);
238
+ if (!rows) { rows = []; index.set(key, rows); log(() => { index.delete(key); }); }
239
+ append(rows, row);
240
+ };
241
+ const searchable = retrievalMessage(saved);
242
+ if (searchable) {
243
+ data.retrievalIndex.set(saved.seq, { bytes: timelineBytes(searchable.text),
244
+ words: new Set(timelineTokens(searchable.text).map(word => word.folded)) });
245
+ log(() => { data.retrievalIndex.delete(saved.seq); });
246
+ }
247
+ if (historicalCandidate(saved.message, id => {
248
+ let calls = data.retrievalCalls.get(saved.turnId);
249
+ if (!calls) {
250
+ calls = new Set();
251
+ data.retrievalCalls.set(saved.turnId, calls);
252
+ log(() => { data.retrievalCalls.delete(saved.turnId); });
253
+ }
254
+ if (!calls.has(id)) {
255
+ const registered = calls;
256
+ registered.add(id);
257
+ log(() => { registered.delete(id); });
258
+ }
259
+ }, id => data.retrievalCalls.get(saved.turnId)?.has(id) ?? false)) append(data.historicalCandidates, saved);
260
+ append(data.entries, saved);
261
+ const kind = saved.message.role === "assistant" ? "assistant" : saved.itemId !== undefined ? "input" : "other";
262
+ const bytes = entryOverhead + byteLength(JSON.stringify(saved.message)) +
263
+ byteLength(saved.at) + byteLength(saved.channelId) + byteLength(saved.from) + byteLength(saved.kind ?? "") +
264
+ byteLength(saved.sourceChannelId ?? "") + byteLength(saved.itemId ?? "") + byteLength(saved.externalSource ?? "");
265
+ const contextRow: ContextEntry = { entry: saved, seq: saved.seq, bytes, kind };
266
+ data.bySeq.set(saved.seq, contextRow);
267
+ log(() => { data.bySeq.delete(saved.seq); });
268
+ indexed(data.byTurn, saved.turnId, contextRow);
269
+ if (kind === "input") indexed(data.inputs, saved.turnId, contextRow);
270
+ if (kind === "assistant") indexed(data.assistants, saved.turnId, contextRow);
271
+ const reply = entry.message.role === "assistant" && !!entry.message.content;
272
+ if (reply || entry.kind === "participant_message") {
273
+ indexed(data.conversation, entry.channelId, saved);
274
+ }
275
+ if (reply) indexed(data.replies, entry.turnId, saved);
276
+ },
277
+ entriesOfTurn: turnId => copy(data.entries.filter(entry => entry.turnId === turnId)),
278
+ entries: () => copy(data.entries),
279
+ };
280
+ }
281
+
282
+ /** One in-memory location with the same semantics as a database file: the
283
+ * session outlives its handle, so close and open behave like a restart within
284
+ * one process. Nothing survives the process itself. */
285
+ export function createMemoryStorageAdapter(): SessionStorageAdapter {
286
+ let data: Data | undefined;
287
+ let owned = false;
288
+ return {
289
+ readSavedConfig() {
290
+ if (!data) return failure(new Fail("not_found", "No session exists at this location"));
291
+ if (owned) return failure(new Fail("owner_conflict", "Session storage already has an owner"));
292
+ return { ok: true, value: copy(data.config), revision: data.meta.revision };
293
+ },
294
+ importSessionFile(payload, options) {
295
+ try {
296
+ const { archive, config } = validateSessionPayload(payload);
297
+ if (options?.sessionId !== undefined && (typeof options.sessionId !== "string" || !options.sessionId.trim())) throw new Fail("invalid_input", "sessionId must be a nonempty string");
298
+ if (data) throw new Fail("already_exists", "A session already exists at this location");
299
+ const next = empty(archiveMeta(copy(archive), options?.sessionId));
300
+ const tables = memoryTables(next); tables.transaction(() => { restoreArchive(tables, archive); tables.setConfig(config); });
301
+ data = next;
302
+ return { ok: true, value: storedSession(next.meta), revision: next.meta.revision };
303
+ } catch (error) { return failure(error); }
304
+ },
305
+ open(options) {
306
+ try {
307
+ const identity = options?.identity;
308
+ if (!identity || typeof identity.sessionId !== "string" || !identity.sessionId.trim() || typeof identity.compatibilityKey !== "string"
309
+ || (options.mode !== "create" && options.mode !== "open")) throw new Fail("invalid_input", "Open needs a mode, sessionId and compatibilityKey");
310
+ let config; try { config = options.config === undefined ? undefined : validateManagedConfig(options.config); } catch (error) { throw new Fail("invalid_input", String(error)); }
311
+ if (owned) throw new Fail("owner_conflict", "Session storage already has an owner");
312
+ if (options.mode === "create") {
313
+ if (data) throw new Fail("already_exists", "A session already exists at this location");
314
+ checkScriptIdentity(identity.compatibilityKey, options.requiredScriptDigest);
315
+ data = empty({ sessionId: identity.sessionId, formatVersion: 6, createdAt: new Date().toISOString(),
316
+ compatibilityKey: identity.compatibilityKey, lifecycle: "running", revision: 0, nextTurnId: 1, nextItemNumber: 1 });
317
+ } else {
318
+ if (!data) throw new Fail("not_found", "No session exists at this location");
319
+ if (data.meta.sessionId !== identity.sessionId) throw new Fail("incompatible", "Location holds a different session");
320
+ checkScriptIdentity(data.meta.compatibilityKey, options.requiredScriptDigest);
321
+ }
322
+ const tables = memoryTables(data);
323
+ if (referencesCompatible(tables, config)) recover(tables);
324
+ owned = true;
325
+ return { ok: true, value: createEngine(tables, identity.compatibilityKey, () => { owned = false; }, config), revision: data.meta.revision };
326
+ } catch (error) { return failure(error); }
327
+ },
328
+ importArchive(raw, options) {
329
+ try {
330
+ const archive = validateArchive(raw);
331
+ if (options?.sessionId !== undefined && (typeof options.sessionId !== "string" || !options.sessionId.trim()))
332
+ throw new Fail("invalid_input", "sessionId must be a nonempty string");
333
+ if (data) throw new Fail("already_exists", "A session already exists at this location");
334
+ const next = empty(archiveMeta(copy(archive), options?.sessionId));
335
+ restoreArchive(memoryTables(next), archive);
336
+ data = next; // Published only after every row was written.
337
+ return { ok: true, value: storedSession(next.meta), revision: next.meta.revision };
338
+ } catch (error) { return failure(error); }
339
+ },
340
+ };
341
+ }
@@ -0,0 +1,32 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ItemPolicy, ManagedConfig } from "../../contracts/config-permissions.ts";
3
+
4
+ /** Policy identity includes the caller's actual override, never the resolved
5
+ * policy: a channel edit must not change the signature of an accepted item. */
6
+ export interface PolicyInputIdentity {
7
+ kind: string; channelId: string; senderId: string; sourceChannelId?: string;
8
+ text: string; explicitPolicy?: string | null;
9
+ }
10
+ const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
11
+ export function legacyItemSignature(item: PolicyInputIdentity): string {
12
+ return digest([item.kind, item.channelId, item.senderId, item.sourceChannelId ?? null, item.text]);
13
+ }
14
+ export function policyItemSignature(item: PolicyInputIdentity): string {
15
+ return digest([item.kind, item.channelId, item.senderId, item.sourceChannelId ?? null, item.text, item.explicitPolicy ?? null]);
16
+ }
17
+ /** The references contributed by a source turn include every earlier notice's
18
+ * inherited restrictions. First occurrence order keeps the record stable. */
19
+ export function contributingPolicies(items: readonly ItemPolicy[]): string[] {
20
+ return [...new Set(items.flatMap(item => [item.resolved, ...item.inherited]))];
21
+ }
22
+ export function fingerprint(config: ManagedConfig, references: readonly string[]): string {
23
+ return JSON.stringify([...new Set(references)].sort().map(name => {
24
+ const policy = Object.hasOwn(config.policies, name) ? config.policies[name] : undefined;
25
+ if (!policy) throw new Error(`Unknown policy: ${name}`);
26
+ return [name, policy.fallback, Object.keys(policy.tools).sort().map(tool => [tool, policy.tools[tool]])];
27
+ }));
28
+ }
29
+
30
+ export function externalNoticeSignature(channel: string, source: string | undefined, text: string, names: readonly string[]): string {
31
+ return digest(["external_notice", channel, source ?? null, text, [...new Set(names)].sort()]);
32
+ }
@@ -0,0 +1,63 @@
1
+ import type { OneOffReminder, ReminderArchiveState } from "../../contracts/reminders.ts";
2
+ import type { StorageSnapshot } from "../../contracts/storage.ts";
3
+ import { normalizeReminderSchedule, reminderInstant } from "../../util/reminder-schedule.ts";
4
+ import { Fail } from "./engine.ts";
5
+
6
+ const bad = (): never => { throw new Fail("invalid_archive", "Invalid archived reminder state"); };
7
+ const text = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
8
+ const integer = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0;
9
+ const iso = (value: unknown): boolean => typeof value === "string" &&
10
+ reminderInstant(value) !== undefined && new Date(Date.parse(value)).toISOString() === value;
11
+
12
+ export function validateReminderArchive(state: ReminderArchiveState | undefined, snapshot: StorageSnapshot): void {
13
+ if (!state || !Array.isArray(state.rows) || !Array.isArray(state.receipts) || !integer(state.listingRevision) ||
14
+ !state.wake || !integer(state.wake.reminderRevision) ||
15
+ (state.wake.nextDueAt !== null && !iso(state.wake.nextDueAt))) return bad();
16
+ const channels = new Map(snapshot.channels.map(channel => [channel.channelId, channel.lifecycle]));
17
+ const items = new Map(snapshot.items.map(item => [item.itemId, item]));
18
+ const ids = new Set<string>(), receipts = new Set<string>();
19
+ const validRow = (row: OneOffReminder): boolean => {
20
+ if (!row || !text(row.id) || !channels.has(row.channel) || !text(row.text) ||
21
+ (row.createdBy !== "host" && row.createdBy !== "agent") || !Array.isArray(row.policyNames) ||
22
+ !row.policyNames.every(text) || new Set(row.policyNames).size !== row.policyNames.length ||
23
+ !row.schedule || !iso(row.schedule.at) || !iso(row.acceptedAt) ||
24
+ !["active", "paused", "blocked", "done", "cancelled", "expired"].includes(row.state)) return false;
25
+ const schedule = normalizeReminderSchedule(row.schedule.at, row.acceptedAt, row.expiresAfter, Date.parse(row.acceptedAt));
26
+ return !!schedule && row.expiresAfter === schedule.expiresAfter && row.expiresAt === schedule.expiresAt &&
27
+ row.nextRunAt === (row.state === "active" ? row.schedule.at : null);
28
+ };
29
+ let sequence = 0, nextDueAt: string | null = null;
30
+ for (const entry of state.rows) {
31
+ if (!entry || !integer(entry.sequence) || entry.sequence <= sequence || entry.sequence > snapshot.revision ||
32
+ typeof entry.defaultedExpiry !== "boolean" || !validRow(entry.reminder) || ids.has(entry.reminder.id) || (entry.original !== undefined && !text(entry.original))) return bad();
33
+ const row = entry.reminder;
34
+ if (entry.defaultedExpiry) {
35
+ const defaulted = normalizeReminderSchedule(row.schedule.at, row.acceptedAt, undefined, Date.parse(row.acceptedAt));
36
+ if (defaulted?.expiresAfter !== row.expiresAfter) return bad();
37
+ }
38
+ sequence = entry.sequence;
39
+ ids.add(row.id);
40
+ if (row.state === "done") {
41
+ const notice = items.get(row.noticeId ?? "");
42
+ if (row.noticeId !== `reminder-notice:${row.id}:${row.schedule.at}` ||
43
+ row.lastOccurrenceId !== `reminder:${row.id}:${row.schedule.at}` || !iso(row.lastRunAt) ||
44
+ notice?.kind !== "external_notice" || notice.channelId !== row.channel || notice.text !== row.text ||
45
+ notice.externalSource !== `reminder:${row.id}`) return bad();
46
+ } else if (row.noticeId !== undefined || row.lastRunAt !== undefined) return bad();
47
+ if (snapshot.session.lifecycle === "running" && channels.get(row.channel) === "open" && row.nextRunAt !== null &&
48
+ (nextDueAt === null || row.nextRunAt < nextDueAt)) nextDueAt = row.nextRunAt;
49
+ }
50
+ if ((!state.rows.length && !state.receipts.length) || state.listingRevision < state.rows.length ||
51
+ state.wake.nextDueAt !== nextDueAt || (nextDueAt !== null && !state.wake.reminderRevision)) return bad();
52
+ for (const receipt of state.receipts) {
53
+ const result = receipt?.result;
54
+ if (!result || !text(receipt.fingerprint) || !text(result.reminderId) || !integer(result.changeId) || !result.changeId) return bad();
55
+ const key = JSON.stringify([result.reminderId, result.changeId]);
56
+ if (receipts.has(key)) return bad();
57
+ receipts.add(key);
58
+ if (result.outcome === "applied") {
59
+ if (!validRow(result.reminder) || result.reminder.id !== result.reminderId || !ids.has(result.reminderId)) return bad();
60
+ } else if (result.outcome !== "blocked" || !["invalid_policy", "channel_missing", "channel_retired", "invalid_schedule",
61
+ "limit_exceeded", "conflict", "not_found", "stale", "invalid_state"].includes(result.reason)) return bad();
62
+ }
63
+ }