@proofoftech/flowsafe 0.19.0 → 0.21.0

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 (297) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +68 -6
  3. package/deployment-identity-protocol.d.mts +70 -1
  4. package/deployment-identity-protocol.mjs +423 -5
  5. package/dist/agent-host/index.d.ts +1 -1
  6. package/dist/agent-host/index.d.ts.map +1 -1
  7. package/dist/agent-host/index.js.map +1 -1
  8. package/dist/agent-host/router.d.ts.map +1 -1
  9. package/dist/agent-host/router.js +17 -4
  10. package/dist/agent-host/router.js.map +1 -1
  11. package/dist/agent-host/thread-host.d.ts +14 -1
  12. package/dist/agent-host/thread-host.d.ts.map +1 -1
  13. package/dist/agent-host/thread-host.js +865 -308
  14. package/dist/agent-host/thread-host.js.map +1 -1
  15. package/dist/agent-host/thread-topology.d.ts +43 -1
  16. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  17. package/dist/agent-host/thread-topology.js +301 -28
  18. package/dist/agent-host/thread-topology.js.map +1 -1
  19. package/dist/agent-runner/durable-agent-runner.d.ts +107 -8
  20. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  21. package/dist/agent-runner/durable-agent-runner.js +427 -55
  22. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  23. package/dist/agent-runner/index.d.ts +1 -1
  24. package/dist/agent-runner/index.d.ts.map +1 -1
  25. package/dist/agent-runner/index.js.map +1 -1
  26. package/dist/approval-api/actor-context.d.ts +4 -0
  27. package/dist/approval-api/actor-context.d.ts.map +1 -1
  28. package/dist/approval-api/actor-context.js +53 -5
  29. package/dist/approval-api/actor-context.js.map +1 -1
  30. package/dist/approval-api/d1-store.d.ts.map +1 -1
  31. package/dist/approval-api/d1-store.js +6 -3
  32. package/dist/approval-api/d1-store.js.map +1 -1
  33. package/dist/approval-api/principal-identity.d.ts +32 -0
  34. package/dist/approval-api/principal-identity.d.ts.map +1 -0
  35. package/dist/approval-api/principal-identity.js +69 -0
  36. package/dist/approval-api/principal-identity.js.map +1 -0
  37. package/dist/approval-api/principal.d.ts +10 -13
  38. package/dist/approval-api/principal.d.ts.map +1 -1
  39. package/dist/approval-api/principal.js +10 -46
  40. package/dist/approval-api/principal.js.map +1 -1
  41. package/dist/approval-api/retention.d.ts +1 -2
  42. package/dist/approval-api/retention.d.ts.map +1 -1
  43. package/dist/approval-api/retention.js.map +1 -1
  44. package/dist/approval-api/router.d.ts.map +1 -1
  45. package/dist/approval-api/router.js +9 -1
  46. package/dist/approval-api/router.js.map +1 -1
  47. package/dist/approval-api/service.d.ts +29 -14
  48. package/dist/approval-api/service.d.ts.map +1 -1
  49. package/dist/approval-api/service.js +83 -25
  50. package/dist/approval-api/service.js.map +1 -1
  51. package/dist/approval-api/types.d.ts +12 -0
  52. package/dist/approval-api/types.d.ts.map +1 -1
  53. package/dist/approval-api/types.js +12 -0
  54. package/dist/approval-api/types.js.map +1 -1
  55. package/dist/audit-export/index.d.ts +2 -2
  56. package/dist/audit-export/index.js +2 -2
  57. package/dist/background-tasks/d1-storage.d.ts +4 -3
  58. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  59. package/dist/background-tasks/d1-storage.js +7 -13
  60. package/dist/background-tasks/d1-storage.js.map +1 -1
  61. package/dist/background-tasks/host.d.ts +127 -14
  62. package/dist/background-tasks/host.d.ts.map +1 -1
  63. package/dist/background-tasks/host.js +579 -50
  64. package/dist/background-tasks/host.js.map +1 -1
  65. package/dist/background-tasks/index.d.ts +2 -2
  66. package/dist/background-tasks/index.d.ts.map +1 -1
  67. package/dist/background-tasks/index.js +11 -6
  68. package/dist/background-tasks/index.js.map +1 -1
  69. package/dist/background-tasks/routes.d.ts +19 -2
  70. package/dist/background-tasks/routes.d.ts.map +1 -1
  71. package/dist/background-tasks/routes.js +4 -4
  72. package/dist/background-tasks/routes.js.map +1 -1
  73. package/dist/deployment-identity-protocol.d.ts +2 -2
  74. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  75. package/dist/deployment-identity-protocol.js +1 -1
  76. package/dist/deployment-identity-protocol.js.map +1 -1
  77. package/dist/do-runner/cause-chain.d.ts +53 -0
  78. package/dist/do-runner/cause-chain.d.ts.map +1 -0
  79. package/dist/do-runner/cause-chain.js +96 -0
  80. package/dist/do-runner/cause-chain.js.map +1 -0
  81. package/dist/do-runner/constants.d.ts +3 -0
  82. package/dist/do-runner/constants.d.ts.map +1 -0
  83. package/dist/do-runner/constants.js +3 -0
  84. package/dist/do-runner/constants.js.map +1 -0
  85. package/dist/do-runner/d1-storage.d.ts +47 -69
  86. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  87. package/dist/do-runner/d1-storage.js +972 -196
  88. package/dist/do-runner/d1-storage.js.map +1 -1
  89. package/dist/do-runner/deployment-identity.d.ts +29 -5
  90. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  91. package/dist/do-runner/deployment-identity.js +23 -6
  92. package/dist/do-runner/deployment-identity.js.map +1 -1
  93. package/dist/do-runner/do-error-response.d.ts +4 -23
  94. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  95. package/dist/do-runner/do-error-response.js +19 -24
  96. package/dist/do-runner/do-error-response.js.map +1 -1
  97. package/dist/do-runner/do-status-error.d.ts +37 -0
  98. package/dist/do-runner/do-status-error.d.ts.map +1 -0
  99. package/dist/do-runner/do-status-error.js +42 -0
  100. package/dist/do-runner/do-status-error.js.map +1 -0
  101. package/dist/do-runner/durable-object.d.ts +2 -1
  102. package/dist/do-runner/durable-object.d.ts.map +1 -1
  103. package/dist/do-runner/durable-object.js +617 -144
  104. package/dist/do-runner/durable-object.js.map +1 -1
  105. package/dist/do-runner/execution-admission.d.ts +114 -0
  106. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  107. package/dist/do-runner/execution-admission.js +206 -0
  108. package/dist/do-runner/execution-admission.js.map +1 -0
  109. package/dist/do-runner/execution-context.d.ts.map +1 -1
  110. package/dist/do-runner/execution-context.js +1 -0
  111. package/dist/do-runner/execution-context.js.map +1 -1
  112. package/dist/do-runner/execution-fence.d.ts +379 -0
  113. package/dist/do-runner/execution-fence.d.ts.map +1 -0
  114. package/dist/do-runner/execution-fence.js +1098 -0
  115. package/dist/do-runner/execution-fence.js.map +1 -0
  116. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  117. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  118. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  119. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  120. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  121. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  122. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  123. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  124. package/dist/do-runner/index.d.ts +20 -8
  125. package/dist/do-runner/index.d.ts.map +1 -1
  126. package/dist/do-runner/index.js +21 -4
  127. package/dist/do-runner/index.js.map +1 -1
  128. package/dist/do-runner/init.d.ts +82 -1
  129. package/dist/do-runner/init.d.ts.map +1 -1
  130. package/dist/do-runner/init.js +58 -3
  131. package/dist/do-runner/init.js.map +1 -1
  132. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  133. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  134. package/dist/do-runner/initial-admission-refusal.js +41 -0
  135. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  136. package/dist/do-runner/inventory.d.ts +295 -0
  137. package/dist/do-runner/inventory.d.ts.map +1 -0
  138. package/dist/do-runner/inventory.js +800 -0
  139. package/dist/do-runner/inventory.js.map +1 -0
  140. package/dist/do-runner/notification-predicate.d.ts +8 -0
  141. package/dist/do-runner/notification-predicate.d.ts.map +1 -0
  142. package/dist/do-runner/notification-predicate.js +136 -0
  143. package/dist/do-runner/notification-predicate.js.map +1 -0
  144. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  145. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  146. package/dist/do-runner/run-lifecycle.js +67 -13
  147. package/dist/do-runner/run-lifecycle.js.map +1 -1
  148. package/dist/do-runner/run-provenance.d.ts +38 -0
  149. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  150. package/dist/do-runner/run-provenance.js +152 -0
  151. package/dist/do-runner/run-provenance.js.map +1 -0
  152. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  153. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  154. package/dist/do-runner/run-storage-tables.js +4 -0
  155. package/dist/do-runner/run-storage-tables.js.map +1 -0
  156. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  157. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  158. package/dist/do-runner/run-terminal-state.js +105 -0
  159. package/dist/do-runner/run-terminal-state.js.map +1 -0
  160. package/dist/do-runner/runtime.d.ts +191 -46
  161. package/dist/do-runner/runtime.d.ts.map +1 -1
  162. package/dist/do-runner/runtime.js +994 -378
  163. package/dist/do-runner/runtime.js.map +1 -1
  164. package/dist/do-runner/start-idempotency.d.ts +285 -0
  165. package/dist/do-runner/start-idempotency.d.ts.map +1 -0
  166. package/dist/do-runner/start-idempotency.js +994 -0
  167. package/dist/do-runner/start-idempotency.js.map +1 -0
  168. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  169. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  170. package/dist/do-runner/start-reservation-contract.js +338 -0
  171. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  172. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  173. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  174. package/dist/do-runner/suspension-deadline.js +8 -12
  175. package/dist/do-runner/suspension-deadline.js.map +1 -1
  176. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  177. package/dist/do-runner/table-prefix.js +2 -1
  178. package/dist/do-runner/table-prefix.js.map +1 -1
  179. package/dist/do-runner/testing.d.ts +3 -0
  180. package/dist/do-runner/testing.d.ts.map +1 -0
  181. package/dist/do-runner/testing.js +3 -0
  182. package/dist/do-runner/testing.js.map +1 -0
  183. package/dist/do-runner/thread-do.d.ts +2 -1
  184. package/dist/do-runner/thread-do.d.ts.map +1 -1
  185. package/dist/do-runner/thread-do.js +14 -10
  186. package/dist/do-runner/thread-do.js.map +1 -1
  187. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  188. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  189. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  190. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  191. package/dist/goals/objective-routes.d.ts +15 -5
  192. package/dist/goals/objective-routes.d.ts.map +1 -1
  193. package/dist/goals/objective-routes.js +64 -64
  194. package/dist/goals/objective-routes.js.map +1 -1
  195. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  196. package/dist/host-kit/approval-bridge.js +10 -7
  197. package/dist/host-kit/approval-bridge.js.map +1 -1
  198. package/dist/host-kit/do-response.d.ts +16 -0
  199. package/dist/host-kit/do-response.d.ts.map +1 -1
  200. package/dist/host-kit/do-response.js +181 -0
  201. package/dist/host-kit/do-response.js.map +1 -1
  202. package/dist/host-kit/do-run-topology.d.ts +3 -0
  203. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  204. package/dist/host-kit/do-run-topology.js +36 -8
  205. package/dist/host-kit/do-run-topology.js.map +1 -1
  206. package/dist/host-kit/env-vars.d.ts.map +1 -1
  207. package/dist/host-kit/env-vars.js +5 -6
  208. package/dist/host-kit/env-vars.js.map +1 -1
  209. package/dist/host-kit/flowsafe-worker.d.ts +49 -6
  210. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  211. package/dist/host-kit/flowsafe-worker.js +409 -111
  212. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  213. package/dist/host-kit/host-approval-service.d.ts +24 -14
  214. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  215. package/dist/host-kit/host-approval-service.js +29 -40
  216. package/dist/host-kit/host-approval-service.js.map +1 -1
  217. package/dist/host-kit/index.d.ts +9 -3
  218. package/dist/host-kit/index.d.ts.map +1 -1
  219. package/dist/host-kit/index.js +5 -1
  220. package/dist/host-kit/index.js.map +1 -1
  221. package/dist/host-kit/run-route-error.d.ts +8 -4
  222. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  223. package/dist/host-kit/run-route-error.js +14 -11
  224. package/dist/host-kit/run-route-error.js.map +1 -1
  225. package/dist/host-kit/run-router.d.ts +63 -2
  226. package/dist/host-kit/run-router.d.ts.map +1 -1
  227. package/dist/host-kit/run-router.js +167 -45
  228. package/dist/host-kit/run-router.js.map +1 -1
  229. package/dist/host-kit/stream-router.d.ts.map +1 -1
  230. package/dist/host-kit/stream-router.js +18 -9
  231. package/dist/host-kit/stream-router.js.map +1 -1
  232. package/dist/host-kit/thread-topology.d.ts +1 -1
  233. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  234. package/dist/host-kit/thread-topology.js +7 -3
  235. package/dist/host-kit/thread-topology.js.map +1 -1
  236. package/dist/internal-error-response.d.ts.map +1 -1
  237. package/dist/internal-error-response.js +16 -6
  238. package/dist/internal-error-response.js.map +1 -1
  239. package/dist/schedules/index.d.ts +1 -0
  240. package/dist/schedules/index.d.ts.map +1 -1
  241. package/dist/schedules/index.js +1 -7
  242. package/dist/schedules/index.js.map +1 -1
  243. package/dist/schedules/mutation-contract.d.ts +38 -0
  244. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  245. package/dist/schedules/mutation-contract.js +21 -0
  246. package/dist/schedules/mutation-contract.js.map +1 -0
  247. package/dist/schedules/router.d.ts +15 -8
  248. package/dist/schedules/router.d.ts.map +1 -1
  249. package/dist/schedules/router.js +170 -59
  250. package/dist/schedules/router.js.map +1 -1
  251. package/dist/schedules/schedules-d1.d.ts +11 -5
  252. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  253. package/dist/schedules/schedules-d1.js +570 -143
  254. package/dist/schedules/schedules-d1.js.map +1 -1
  255. package/dist/schedules/storage.d.ts +0 -7
  256. package/dist/schedules/storage.d.ts.map +1 -1
  257. package/dist/schedules/storage.js +0 -27
  258. package/dist/schedules/storage.js.map +1 -1
  259. package/dist/schedules/tick.d.ts +13 -0
  260. package/dist/schedules/tick.d.ts.map +1 -1
  261. package/dist/schedules/tick.js +66 -40
  262. package/dist/schedules/tick.js.map +1 -1
  263. package/dist/signal-providers/host-do.d.ts +12 -1
  264. package/dist/signal-providers/host-do.d.ts.map +1 -1
  265. package/dist/signal-providers/host-do.js +28 -3
  266. package/dist/signal-providers/host-do.js.map +1 -1
  267. package/dist/signal-providers/webhook-route.d.ts +15 -1
  268. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  269. package/dist/signal-providers/webhook-route.js +126 -113
  270. package/dist/signal-providers/webhook-route.js.map +1 -1
  271. package/dist/signals/d1-shared.d.ts +11 -8
  272. package/dist/signals/d1-shared.d.ts.map +1 -1
  273. package/dist/signals/d1-shared.js +1 -6
  274. package/dist/signals/d1-shared.js.map +1 -1
  275. package/dist/signals/index.d.ts +1 -1
  276. package/dist/signals/index.d.ts.map +1 -1
  277. package/dist/signals/index.js +1 -1
  278. package/dist/signals/index.js.map +1 -1
  279. package/dist/signals/notification-dispatch.d.ts +109 -5
  280. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  281. package/dist/signals/notification-dispatch.js +430 -46
  282. package/dist/signals/notification-dispatch.js.map +1 -1
  283. package/dist/signals/notifications-d1.d.ts +14 -1
  284. package/dist/signals/notifications-d1.d.ts.map +1 -1
  285. package/dist/signals/notifications-d1.js +229 -18
  286. package/dist/signals/notifications-d1.js.map +1 -1
  287. package/dist/signals/router.d.ts +6 -4
  288. package/dist/signals/router.d.ts.map +1 -1
  289. package/dist/signals/router.js +49 -84
  290. package/dist/signals/router.js.map +1 -1
  291. package/dist/signals/thread-do-routes.d.ts +2 -0
  292. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  293. package/dist/signals/thread-do-routes.js +330 -83
  294. package/dist/signals/thread-do-routes.js.map +1 -1
  295. package/package.json +6 -3
  296. package/patches/@mastra__core@1.53.0.patch +54 -0
  297. package/scripts/seed-deployment-identity.mjs +34 -9
@@ -0,0 +1,994 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // A missing result cannot establish whether a claimed start had effects.
3
+ import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal-identity.js';
4
+ import { missingTableReadsEmpty } from './cause-chain.js';
5
+ import { DoStatusError } from './do-status-error.js';
6
+ import { InvalidExecutionIdentityError, normalizeMutationEpoch, normalizeStartExecutionIdentity, RunAdmissionConflictError, } from './execution-admission.js';
7
+ import { isPathSafeId } from './path-safe-id.js';
8
+ import { admissionReservationFromRow, captureReservation, decodeStartReservationAdmissionResult, isStartTargetKind, ReservationSchemaError, reservationFromRow, reservationResultRows, reservationSchemaStage, START_IDEMPOTENCY_ADDITIONS, START_IDEMPOTENCY_COLUMNS, START_IDEMPOTENCY_DDL, START_IDEMPOTENCY_RUN_INDEX_DDL, START_IDEMPOTENCY_STATE_INDEX_DDL, START_IDEMPOTENCY_TABLE, START_TARGET_KINDS, sameReservationIdentity, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
9
+ export { decodeStartReservationAdmissionResult, START_IDEMPOTENCY_DDL, START_IDEMPOTENCY_RUN_INDEX_DDL, START_IDEMPOTENCY_STATE_INDEX_DDL, START_IDEMPOTENCY_TABLE, START_RESERVATION_STATES, START_TARGET_KINDS, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
10
+ function captureStartRequest(request) {
11
+ const key = assertKey(request.key);
12
+ const owner = assertOwner(request.owner);
13
+ const { targetKind, targetId, threadId, mintRunId } = request;
14
+ if (!isStartTargetKind(targetKind)) {
15
+ throw new InvalidStartIdempotencyRequestError(`target kind must be one of ${START_TARGET_KINDS.join(', ')}`);
16
+ }
17
+ if (!isPathSafeId(targetId)) {
18
+ throw new InvalidStartIdempotencyRequestError('target id must be a URL-path-safe identifier');
19
+ }
20
+ // The thread is the agent run's ADDRESS, so requiring it for agents and
21
+ // rejecting it for workflows is not tidiness: an agent reservation without
22
+ // one is a run a retry can never reach, and a workflow reservation WITH one
23
+ // is a second, silently divergent copy of an address that is already
24
+ // derivable from (workflowId, runId).
25
+ if (targetKind === 'agent') {
26
+ if (!isPathSafeId(threadId)) {
27
+ throw new InvalidStartIdempotencyRequestError('an agent start reservation requires a URL-path-safe threadId');
28
+ }
29
+ }
30
+ else if (threadId !== undefined) {
31
+ throw new InvalidStartIdempotencyRequestError('threadId applies only to agent start reservations');
32
+ }
33
+ if (typeof mintRunId !== 'function') {
34
+ throw new InvalidStartIdempotencyRequestError('mintRunId must be a function');
35
+ }
36
+ return Object.freeze({
37
+ key,
38
+ owner,
39
+ targetKind,
40
+ targetId,
41
+ threadId,
42
+ mintRunId: () => Reflect.apply(mintRunId, request, []),
43
+ });
44
+ }
45
+ /**
46
+ * The key names a reservation owned by a different principal.
47
+ *
48
+ * 403 rather than 404: the caller sent a syntactically valid key it is simply
49
+ * not entitled to, and this is the one refusal whose body deliberately carries
50
+ * nothing else — not the owner, not the target, not the run. A key is guessable
51
+ * by construction (hosts derive them from order ids and request ids), so this
52
+ * response is reachable by probing, and everything it does not say is something
53
+ * a prober does not learn.
54
+ */
55
+ export class StartReservationOwnerMismatchError extends DoStatusError {
56
+ status = 403;
57
+ reason;
58
+ constructor(key) {
59
+ super(`idempotency key '${key}' belongs to another principal`);
60
+ this.name = 'StartReservationOwnerMismatchError';
61
+ this.reason = { code: 'IDEMPOTENT_START_OWNER_MISMATCH' };
62
+ }
63
+ }
64
+ /**
65
+ * The caller's own key, pointed at a different workflow or agent than the one
66
+ * it reserved. 409, and it DOES name the reservation's target: the caller owns
67
+ * this key, so telling it what the key already means is telling it about its
68
+ * own state, and a caller that reused a key by accident needs exactly that to
69
+ * find the bug.
70
+ */
71
+ export class StartReservationTargetMismatchError extends DoStatusError {
72
+ status = 409;
73
+ reason;
74
+ constructor(key, reservation) {
75
+ super(`idempotency key '${key}' already names ${reservation.targetKind} '${reservation.targetId}'`);
76
+ this.name = 'StartReservationTargetMismatchError';
77
+ this.reason = {
78
+ code: 'IDEMPOTENT_START_TARGET_MISMATCH',
79
+ targetKind: reservation.targetKind,
80
+ targetId: reservation.targetId,
81
+ };
82
+ }
83
+ }
84
+ export class IdempotentStartPendingError extends DoStatusError {
85
+ status = 503;
86
+ reason;
87
+ constructor(reservation) {
88
+ super(`run '${reservation.runId}' for this idempotency key is still starting`);
89
+ this.name = 'IdempotentStartPendingError';
90
+ this.reason = {
91
+ code: 'IDEMPOTENT_START_PENDING',
92
+ runId: reservation.runId,
93
+ pendingSince: reservation.updatedAt,
94
+ };
95
+ }
96
+ }
97
+ /**
98
+ * The claim was taken, nothing persisted, and nothing is running.
99
+ *
100
+ * This is the refusal that refuses to guess. The message is written for the
101
+ * human who will read it in a log at 3am, because the decision it asks for is
102
+ * a judgement call this package cannot make: a side effect may or may not have
103
+ * fired before the crash, and only the host knows whether its first step is the
104
+ * kind that charges.
105
+ */
106
+ export class IdempotentStartUnresolvableError extends DoStatusError {
107
+ status = 409;
108
+ reason;
109
+ constructor(reservation) {
110
+ super(`run '${reservation.runId}' for this idempotency key was claimed but never persisted and is not running — investigate whether its first step already took effect before re-running with a fresh key`);
111
+ this.name = 'IdempotentStartUnresolvableError';
112
+ this.reason = {
113
+ code: 'IDEMPOTENT_START_UNRESOLVABLE',
114
+ runId: reservation.runId,
115
+ };
116
+ }
117
+ }
118
+ /**
119
+ * The run finished and its summary has aged out of retention. 409 and never a
120
+ * re-execution: a key whose run completed is spent, and the fact that nobody
121
+ * can still read the OUTCOME does not make the WORK un-done.
122
+ */
123
+ export class IdempotentStartAlreadySettledError extends DoStatusError {
124
+ status = 409;
125
+ reason;
126
+ constructor(reservation) {
127
+ super(`run '${reservation.runId}' for this idempotency key already completed and its summary has expired`);
128
+ this.name = 'IdempotentStartAlreadySettledError';
129
+ this.reason = {
130
+ code: 'IDEMPOTENT_START_ALREADY_SETTLED',
131
+ runId: reservation.runId,
132
+ };
133
+ }
134
+ }
135
+ /** A malformed idempotency key or reservation request — the caller's to fix. */
136
+ export class InvalidStartIdempotencyRequestError extends DoStatusError {
137
+ status = 400;
138
+ reason;
139
+ constructor(message) {
140
+ super(message);
141
+ this.name = 'InvalidStartIdempotencyRequestError';
142
+ this.reason = { code: 'INVALID_START_IDEMPOTENCY_REQUEST' };
143
+ }
144
+ }
145
+ /**
146
+ * A start carried a key onto a deployment whose host never wired the
147
+ * reservation store.
148
+ *
149
+ * 503, and never a silent pass-through. Honouring the request without a
150
+ * reservation would answer an exactly-once REQUEST with at-least-once
151
+ * BEHAVIOUR, which is worse than refusing: the caller would have every reason
152
+ * to believe a retry is safe, and no way to find out it is not. The condition
153
+ * is a wiring fault an operator fixes, so it reads as transient rather than as
154
+ * the caller's mistake.
155
+ */
156
+ export class StartIdempotencyUnsupportedError extends DoStatusError {
157
+ status = 503;
158
+ reason;
159
+ constructor() {
160
+ super('idempotent starts are not configured on this deployment — wire a StartIdempotencyStore before accepting idempotencyKey');
161
+ this.name = 'StartIdempotencyUnsupportedError';
162
+ this.reason = { code: 'IDEMPOTENT_START_UNSUPPORTED' };
163
+ }
164
+ }
165
+ /**
166
+ * Recognize the five reservation-decision refusals:
167
+ *
168
+ * - `IDEMPOTENT_START_OWNER_MISMATCH` (403)
169
+ * - `IDEMPOTENT_START_TARGET_MISMATCH` (409)
170
+ * - `IDEMPOTENT_START_PENDING` (503)
171
+ * - `IDEMPOTENT_START_UNRESOLVABLE` (409)
172
+ * - `IDEMPOTENT_START_ALREADY_SETTLED` (409)
173
+ *
174
+ * The guard also recognizes `IDEMPOTENT_START_UNSUPPORTED` keyed admission
175
+ * (503) and malformed reservation input (400,
176
+ * `INVALID_START_IDEMPOTENCY_REQUEST`).
177
+ *
178
+ * Unsupported wiring remains in this guard because the keyed request is
179
+ * intentionally refused at admission instead of being executed without its
180
+ * exactly-once guarantee. `StartReservationUnreadableError` is deliberately
181
+ * outside it: unreadable storage is an integrity or availability failure, not
182
+ * a reservation decision, and propagates through the shared `DoStatusError`
183
+ * renderer with `IDEMPOTENT_START_UNREADABLE` and its 503 status. A false
184
+ * answer never permits an unkeyed start: a `StartReservationUnreadableError`
185
+ * must still propagate as 503.
186
+ */
187
+ export function isStartReservationRefusal(error) {
188
+ return (error instanceof StartReservationOwnerMismatchError ||
189
+ error instanceof StartReservationTargetMismatchError ||
190
+ error instanceof IdempotentStartPendingError ||
191
+ error instanceof IdempotentStartUnresolvableError ||
192
+ error instanceof IdempotentStartAlreadySettledError ||
193
+ error instanceof StartIdempotencyUnsupportedError ||
194
+ error instanceof InvalidStartIdempotencyRequestError);
195
+ }
196
+ /**
197
+ * Rows affected by a write, read from D1's `{ meta: { changes } }` envelope.
198
+ * Restated here for the same reason execution-fence.ts restates it: every
199
+ * surface that reserves must be able to import this module without dragging
200
+ * the D1 storage adapter (and @mastra/cloudflare-d1 with it) into its bundle.
201
+ *
202
+ * That bundle rule is why the imports at the top of this file are what they
203
+ * are: lightweight identity/error leaves and the execution-fence store, whose
204
+ * dependencies never reach the adapter. Nothing on that graph can cycle
205
+ * back here, which matters more than usual: the eight DoStatusError subclasses
206
+ * in this module are evaluated at module load, so an import edge that came
207
+ * back around would meet a class expression still in its temporal dead zone.
208
+ */
209
+ function changesOf(result) {
210
+ const changes = result?.meta
211
+ ?.changes;
212
+ return typeof changes === 'number' ? changes : 0;
213
+ }
214
+ /**
215
+ * One reservation store per DATABASE, keyed on the BINDING — the same memo, for
216
+ * the same reason, as `executionFenceFor`: the router that reserves, the
217
+ * topology that claims, the runtime that settles, and the purge that reaps must
218
+ * all be looking at one table, and keying on an env object would hand two
219
+ * databases the same store the first time a host mutated env across requests.
220
+ */
221
+ const startIdempotencyStores = new WeakMap();
222
+ export function startIdempotencyFor(db) {
223
+ const existing = startIdempotencyStores.get(db);
224
+ if (existing)
225
+ return existing;
226
+ const store = new StartIdempotencyStore(db);
227
+ startIdempotencyStores.set(db, store);
228
+ return store;
229
+ }
230
+ /**
231
+ * A reservation exists but cannot be understood, or the table could not be
232
+ * read. 503 and never "no reservation": the absent answer is the one that
233
+ * starts a run, so an unreadable store degrades CLOSED exactly as an unreadable
234
+ * fence does.
235
+ */
236
+ export class StartReservationUnreadableError extends DoStatusError {
237
+ status = 503;
238
+ reason;
239
+ constructor(key, options) {
240
+ super(`start reservation '${key}' is not readable`, options);
241
+ this.name = 'StartReservationUnreadableError';
242
+ this.reason = { code: 'IDEMPOTENT_START_UNREADABLE' };
243
+ }
244
+ }
245
+ /**
246
+ * SQLite/D1's "no such table", for THIS store's table: the reservation table is
247
+ * created lazily by the first `reserve()`, so its absence means no key has ever
248
+ * been used here and there is nothing to find.
249
+ *
250
+ * The rule itself — bounded, cycle-safe, and matched at the ROOT of the cause
251
+ * chain only — lives in cause-chain.ts, shared with the fence store. Root-only
252
+ * is the load-bearing half: a missing-table link mentioned part-way down a
253
+ * chain describes a fault that merely PASSED this table on its way out (a
254
+ * failed migration, an adapter reporting the last thing it saw), and concluding
255
+ * "no reservations exist" from that would start a run.
256
+ *
257
+ * Kept local because every consumer is in this store; the drain inventory uses
258
+ * `missingTableReadsEmpty` directly with `START_IDEMPOTENCY_TABLE`.
259
+ */
260
+ function isMissingReservationTable(error) {
261
+ return missingTableReadsEmpty(error, START_IDEMPOTENCY_TABLE);
262
+ }
263
+ function assertKey(key) {
264
+ if (!isPathSafeId(key)) {
265
+ throw new InvalidStartIdempotencyRequestError("idempotencyKey must be a URL-path-safe identifier (letters, digits, '.', '_', '~', '-'; 1-200 chars)");
266
+ }
267
+ return key;
268
+ }
269
+ function assertOwner(owner) {
270
+ if (owner === null || typeof owner !== 'object') {
271
+ throw new InvalidStartIdempotencyRequestError('reservation owner must be an execution principal');
272
+ }
273
+ const { kind, id } = owner;
274
+ if (!isExecutionPrincipalKind(kind) || !isExecutionPrincipalId(id)) {
275
+ throw new InvalidStartIdempotencyRequestError('reservation owner must be an execution principal');
276
+ }
277
+ return { kind, id };
278
+ }
279
+ function assertReservationStartIdentity(reservation, execution) {
280
+ if (reservation.owner.kind !== execution.owner.kind ||
281
+ reservation.owner.id !== execution.owner.id)
282
+ throw new StartReservationOwnerMismatchError(reservation.key);
283
+ if (reservation.targetKind !== execution.target.kind ||
284
+ reservation.targetId !== execution.target.id)
285
+ throw new StartReservationTargetMismatchError(reservation.key, reservation);
286
+ if (reservation.runId !== execution.runId ||
287
+ reservation.threadId !==
288
+ (execution.target.kind === 'agent'
289
+ ? execution.target.threadId
290
+ : undefined) ||
291
+ (execution.target.kind === 'workflow' &&
292
+ execution.workflowId !== execution.target.id))
293
+ throw new InvalidExecutionIdentityError('admission');
294
+ }
295
+ function sameReservationExecution(reservation, execution) {
296
+ return (reservation.runId === execution.runId &&
297
+ reservation.owner.kind === execution.owner.kind &&
298
+ reservation.owner.id === execution.owner.id &&
299
+ reservation.targetKind === execution.target.kind &&
300
+ reservation.targetId === execution.target.id &&
301
+ reservation.threadId ===
302
+ (execution.target.kind === 'agent'
303
+ ? execution.target.threadId
304
+ : undefined) &&
305
+ reservation.binding.kind === 'bound' &&
306
+ reservation.binding.execution.runId === execution.runId &&
307
+ reservation.binding.execution.startToken === execution.startToken &&
308
+ reservation.binding.execution.tablePrefix === execution.tablePrefix &&
309
+ reservation.binding.execution.workflowId === execution.workflowId);
310
+ }
311
+ function reservationMutationResult(result, observed, state, updatedAt, execution) {
312
+ const row = decodeStartReservationAdmissionResult(result);
313
+ if (row !== undefined &&
314
+ (!sameReservationIdentity(row, observed) ||
315
+ row.state !== state ||
316
+ row.updatedAt !== updatedAt ||
317
+ (execution === undefined
318
+ ? row.binding.kind !== 'unbound'
319
+ : !sameReservationExecution(row, execution))))
320
+ throw new Error('reservation mutation returned an unexpected row');
321
+ return row;
322
+ }
323
+ /**
324
+ * The deployment's start reservations, over the SAME D1 database its snapshots,
325
+ * its resource owners, and its execution fence live in — so a reservation
326
+ * cannot be separated from the run it reserves by any binding mistake.
327
+ */
328
+ export class StartIdempotencyStore {
329
+ #db;
330
+ #now;
331
+ #ready;
332
+ constructor(db, options = {}) {
333
+ this.#db = db;
334
+ this.#now = options.now ?? Date.now;
335
+ const ready = options.ready;
336
+ if (ready) {
337
+ this.#ready = async () => {
338
+ await Reflect.apply(ready, this, []);
339
+ if ((await this.#schemaStage()) !== 3)
340
+ throw new ReservationSchemaError('host readiness did not reach the current schema');
341
+ };
342
+ }
343
+ else {
344
+ let ready;
345
+ this.#ready = () => {
346
+ ready ??= this.#createSchema().catch((error) => {
347
+ ready = undefined;
348
+ throw error;
349
+ });
350
+ return ready;
351
+ };
352
+ }
353
+ }
354
+ /**
355
+ * Decide which run this key means, creating the reservation if it is new.
356
+ *
357
+ * INSERT OR IGNORE then READ BACK — the resource-ownership idiom, and the
358
+ * only shape that is correct without a transaction: the insert is the race,
359
+ * the read-back is the result, and every caller that lost the insert reads
360
+ * the winner's row rather than its own intention. Two callers can therefore
361
+ * never both believe they created the reservation, whatever order their
362
+ * statements interleave in, and neither needs to know it raced.
363
+ *
364
+ * This is the ONE method that may create the table. A reservation is the
365
+ * first write anything here makes, so the schema belongs on its path and
366
+ * nowhere else — in particular not on `read`, where lazy DDL would turn the
367
+ * deployment's read-only drain inventory into a write.
368
+ */
369
+ async reserve(request) {
370
+ const { key, owner, targetKind, targetId, threadId, mintRunId } = captureStartRequest(request);
371
+ try {
372
+ await this.#ready();
373
+ }
374
+ catch (error) {
375
+ throw new StartReservationUnreadableError(key, { cause: error });
376
+ }
377
+ const candidateRunId = Reflect.apply(mintRunId, request, []);
378
+ if (!isPathSafeId(candidateRunId)) {
379
+ throw new InvalidStartIdempotencyRequestError('the host minted a runId that is not URL-path-safe');
380
+ }
381
+ const now = this.#now();
382
+ const inserted = changesOf(await this.#db
383
+ .prepare(`INSERT OR IGNORE INTO ${START_IDEMPOTENCY_TABLE}
384
+ (key, owner_kind, owner_id, target_kind, target_id, run_id,
385
+ thread_id, state, created_at, updated_at, start_token, start_table_prefix, start_workflow_id)
386
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'reserved', ?, ?, '', NULL, NULL)`)
387
+ .bind(key, owner.kind, owner.id, targetKind, targetId, candidateRunId, threadId ?? null, now, now)
388
+ .run());
389
+ const stored = await this.read(key);
390
+ if (stored === undefined) {
391
+ // The row was written and is already gone: the purge cannot reach a row
392
+ // this young, so this is a storage fault, not a reservation state.
393
+ throw new StartReservationUnreadableError(key);
394
+ }
395
+ // Owner FIRST, always. A caller that is not the owner must learn nothing
396
+ // about the target, and checking the target first would leak it through the
397
+ // choice of refusal.
398
+ if (stored.owner.kind !== owner.kind || stored.owner.id !== owner.id) {
399
+ throw new StartReservationOwnerMismatchError(key);
400
+ }
401
+ if (stored.targetKind !== targetKind || stored.targetId !== targetId) {
402
+ throw new StartReservationTargetMismatchError(key, stored);
403
+ }
404
+ // Both signals must agree before this caller believes it created the row.
405
+ // `changes` alone would trust the adapter's bookkeeping; the id comparison
406
+ // alone would trust that two mints never collide. Requiring both makes the
407
+ // false answer the SAFE one — a creator misread as a replayer takes the
408
+ // replay path and converges, while the reverse would start a second run.
409
+ return {
410
+ reservation: stored,
411
+ created: inserted > 0 && stored.runId === candidateRunId,
412
+ };
413
+ }
414
+ /** Claim only this observed modern-unbound reservation. */
415
+ async claimReservation(observed) {
416
+ const reservation = captureReservation(observed, 'reserved');
417
+ const next = this.#nextReservationStamp(reservation);
418
+ await this.#requireReservationSchema(reservation.key);
419
+ let result;
420
+ try {
421
+ result = await this.#db
422
+ .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE} SET state = 'started', updated_at = ?
423
+ WHERE key = ? AND run_id = ?
424
+ AND owner_kind = ? AND owner_id = ?
425
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
426
+ AND created_at = ? AND updated_at = ? AND state = ?
427
+ AND state = 'reserved'
428
+ AND start_token = '' AND start_table_prefix IS NULL AND start_workflow_id IS NULL
429
+ RETURNING *`)
430
+ .bind(next, reservation.key, reservation.runId, reservation.owner.kind, reservation.owner.id, reservation.targetKind, reservation.targetId, reservation.threadId ?? null, reservation.createdAt, reservation.updatedAt, reservation.state)
431
+ .all();
432
+ }
433
+ catch (error) {
434
+ throw new StartReservationUnreadableError(reservation.key, {
435
+ cause: error,
436
+ });
437
+ }
438
+ try {
439
+ return reservationMutationResult(result, reservation, 'started', next);
440
+ }
441
+ catch (error) {
442
+ throw new StartReservationUnreadableError(reservation.key, {
443
+ cause: error,
444
+ });
445
+ }
446
+ }
447
+ /** Release only the exact unbound claim, without readback recovery. */
448
+ async releaseReservation(observed) {
449
+ const reservation = captureReservation(observed, 'started');
450
+ const next = this.#nextReservationStamp(reservation);
451
+ await this.#requireReservationSchema(reservation.key);
452
+ let result;
453
+ try {
454
+ result = await this.#db
455
+ .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE} SET state = 'reserved', updated_at = ?
456
+ WHERE key = ? AND run_id = ?
457
+ AND owner_kind = ? AND owner_id = ?
458
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
459
+ AND created_at = ? AND updated_at = ? AND state = ?
460
+ AND state = 'started'
461
+ AND start_token = '' AND start_table_prefix IS NULL AND start_workflow_id IS NULL
462
+ RETURNING *`)
463
+ .bind(next, reservation.key, reservation.runId, reservation.owner.kind, reservation.owner.id, reservation.targetKind, reservation.targetId, reservation.threadId ?? null, reservation.createdAt, reservation.updatedAt, reservation.state)
464
+ .all();
465
+ }
466
+ catch (error) {
467
+ throw new StartReservationUnreadableError(reservation.key, {
468
+ cause: error,
469
+ });
470
+ }
471
+ try {
472
+ return (reservationMutationResult(result, reservation, 'reserved', next) !==
473
+ undefined);
474
+ }
475
+ catch (error) {
476
+ throw new StartReservationUnreadableError(reservation.key, {
477
+ cause: error,
478
+ });
479
+ }
480
+ }
481
+ /** Associate an alias with an already-observed nonpending execution. */
482
+ async associateReservation(observed, execution) {
483
+ const reservation = captureReservation(observed, 'nonterminal');
484
+ const identity = normalizeStartExecutionIdentity(execution);
485
+ assertReservationStartIdentity(reservation, identity);
486
+ await this.#requireReservationSchema(reservation.key);
487
+ let result;
488
+ let failed = false;
489
+ let writeCause;
490
+ try {
491
+ result = await this.#db
492
+ .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE}
493
+ SET start_token = ?, start_table_prefix = ?, start_workflow_id = ?
494
+ WHERE key = ? AND run_id = ?
495
+ AND owner_kind = ? AND owner_id = ?
496
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
497
+ AND created_at = ? AND updated_at = ? AND state = ?
498
+ AND state <> 'terminal'
499
+ AND start_token = '' AND start_table_prefix IS NULL AND start_workflow_id IS NULL
500
+ RETURNING *`)
501
+ .bind(identity.startToken, identity.tablePrefix, identity.workflowId, reservation.key, reservation.runId, reservation.owner.kind, reservation.owner.id, reservation.targetKind, reservation.targetId, reservation.threadId ?? null, reservation.createdAt, reservation.updatedAt, reservation.state)
502
+ .all();
503
+ }
504
+ catch (error) {
505
+ failed = true;
506
+ writeCause = error;
507
+ }
508
+ if (!failed) {
509
+ try {
510
+ const row = reservationMutationResult(result, reservation, reservation.state, reservation.updatedAt, identity);
511
+ if (row)
512
+ return row;
513
+ }
514
+ catch (error) {
515
+ throw new StartReservationUnreadableError(reservation.key, {
516
+ cause: error,
517
+ });
518
+ }
519
+ }
520
+ let current;
521
+ try {
522
+ current = await this.readForAdmission(reservation.key);
523
+ }
524
+ catch (error) {
525
+ if (!failed)
526
+ throw error;
527
+ }
528
+ if (current &&
529
+ sameReservationIdentity(current, reservation) &&
530
+ sameReservationExecution(current, identity))
531
+ return current;
532
+ if (failed)
533
+ throw new StartReservationUnreadableError(reservation.key, {
534
+ cause: writeCause,
535
+ });
536
+ throw new RunAdmissionConflictError('reservation-changed');
537
+ }
538
+ /** Bind a prepared start; only exact lost-write readback can recover. */
539
+ async bindPreparedStart(observed, execution) {
540
+ const reservation = captureReservation(observed, 'started');
541
+ const identity = normalizeStartExecutionIdentity(execution);
542
+ assertReservationStartIdentity(reservation, identity);
543
+ await this.#requireReservationSchema(reservation.key);
544
+ let result;
545
+ try {
546
+ result = await this.#db
547
+ .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE}
548
+ SET start_token = ?, start_table_prefix = ?, start_workflow_id = ?
549
+ WHERE key = ? AND run_id = ?
550
+ AND owner_kind = ? AND owner_id = ?
551
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
552
+ AND created_at = ? AND updated_at = ? AND state = ?
553
+ AND state = 'started'
554
+ AND start_token = '' AND start_table_prefix IS NULL AND start_workflow_id IS NULL
555
+ RETURNING *`)
556
+ .bind(identity.startToken, identity.tablePrefix, identity.workflowId, reservation.key, reservation.runId, reservation.owner.kind, reservation.owner.id, reservation.targetKind, reservation.targetId, reservation.threadId ?? null, reservation.createdAt, reservation.updatedAt, reservation.state)
557
+ .all();
558
+ }
559
+ catch (error) {
560
+ let current;
561
+ try {
562
+ current = await this.readForAdmission(reservation.key);
563
+ }
564
+ catch {
565
+ // Preserve the write uncertainty even when its one readback also fails.
566
+ }
567
+ if (current &&
568
+ sameReservationIdentity(current, reservation) &&
569
+ current.state === reservation.state &&
570
+ current.updatedAt === reservation.updatedAt &&
571
+ sameReservationExecution(current, identity))
572
+ return current;
573
+ throw new StartReservationUnreadableError(reservation.key, {
574
+ cause: error,
575
+ });
576
+ }
577
+ let row;
578
+ try {
579
+ row = reservationMutationResult(result, reservation, reservation.state, reservation.updatedAt, identity);
580
+ }
581
+ catch (error) {
582
+ throw new StartReservationUnreadableError(reservation.key, {
583
+ cause: error,
584
+ });
585
+ }
586
+ if (row)
587
+ return row;
588
+ throw new RunAdmissionConflictError('reservation-changed');
589
+ }
590
+ /** Settle every alias of this complete physical/logical execution. */
591
+ async settleExecution(execution) {
592
+ const identity = normalizeStartExecutionIdentity(execution);
593
+ const clock = this.#reservationClock(identity.runId);
594
+ let result;
595
+ try {
596
+ const stage = await this.#schemaStage();
597
+ if (stage === undefined)
598
+ return 0;
599
+ if (stage !== 3)
600
+ throw new ReservationSchemaError('settlement requires current schema');
601
+ result = await this.#db
602
+ .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE} SET state = 'terminal', updated_at = ?
603
+ WHERE run_id = ? AND start_token = ? AND start_table_prefix IS ?
604
+ AND start_workflow_id = ? AND owner_kind = ? AND owner_id = ?
605
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
606
+ AND state <> 'terminal' RETURNING *`)
607
+ .bind(clock, identity.runId, identity.startToken, identity.tablePrefix, identity.workflowId, identity.owner.kind, identity.owner.id, identity.target.kind, identity.target.id, identity.target.kind === 'agent' ? identity.target.threadId : null)
608
+ .all();
609
+ }
610
+ catch (error) {
611
+ if (isMissingReservationTable(error))
612
+ return 0;
613
+ throw new StartReservationUnreadableError(identity.runId, {
614
+ cause: error,
615
+ });
616
+ }
617
+ try {
618
+ const keys = new Set();
619
+ for (const raw of reservationResultRows(result)) {
620
+ const row = admissionReservationFromRow(raw, 3);
621
+ if (keys.has(row.key) ||
622
+ row.state !== 'terminal' ||
623
+ row.updatedAt !== clock ||
624
+ !sameReservationExecution(row, identity))
625
+ throw new Error('settlement returned an unexpected reservation');
626
+ keys.add(row.key);
627
+ }
628
+ return keys.size;
629
+ }
630
+ catch (error) {
631
+ throw new StartReservationUnreadableError(identity.runId, {
632
+ cause: error,
633
+ });
634
+ }
635
+ }
636
+ #reservationClock(key) {
637
+ try {
638
+ const clock = this.#now();
639
+ if (!Number.isFinite(clock))
640
+ throw new Error('reservation clock is not finite');
641
+ return clock;
642
+ }
643
+ catch (error) {
644
+ throw new StartReservationUnreadableError(key, { cause: error });
645
+ }
646
+ }
647
+ #nextReservationStamp(reservation) {
648
+ const clock = this.#reservationClock(reservation.key);
649
+ const next = Math.max(clock, reservation.updatedAt + 1);
650
+ if (!Number.isFinite(next) || next <= reservation.updatedAt)
651
+ throw new StartReservationUnreadableError(reservation.key, {
652
+ cause: new Error('reservation update stamp is exhausted'),
653
+ });
654
+ return next;
655
+ }
656
+ async #requireReservationSchema(key) {
657
+ try {
658
+ if ((await this.#schemaStage()) !== 3)
659
+ throw new ReservationSchemaError('mutation requires current schema');
660
+ }
661
+ catch (error) {
662
+ throw new StartReservationUnreadableError(key, { cause: error });
663
+ }
664
+ }
665
+ /**
666
+ * Read one reservation. A PURE read: no lazy DDL, no upsert, nothing that
667
+ * would make consulting a key mutate the database — which is what lets a
668
+ * read-only drain inventory and every replay path use it freely, and what
669
+ * keeps a read-only replica or a revoked-write incident a degrade rather than
670
+ * an outage.
671
+ *
672
+ * An absent TABLE reads as an absent reservation, because on a deployment
673
+ * where no key has ever been used those are the same fact.
674
+ */
675
+ async read(key) {
676
+ const safeKey = assertKey(key);
677
+ const rows = await this.#readReservations(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE key = ? LIMIT 2`, [safeKey], safeKey);
678
+ if (rows.length > 1 || (rows[0] !== undefined && rows[0].key !== safeKey)) {
679
+ throw new StartReservationUnreadableError(safeKey, {
680
+ cause: new Error('reservation query did not return the requested singleton key'),
681
+ });
682
+ }
683
+ const row = rows[0];
684
+ return row;
685
+ }
686
+ usesDatabase(binding) {
687
+ return this.#db === binding;
688
+ }
689
+ /** @internal Pure current-stage read, including for an absent key. */
690
+ async readForAdmission(key) {
691
+ const safeKey = assertKey(key);
692
+ try {
693
+ const result = await this.#db
694
+ .prepare(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE key = ? LIMIT 2`)
695
+ .bind(safeKey)
696
+ .all();
697
+ const row = decodeStartReservationAdmissionResult(result);
698
+ validateStartReservationAdmissionSchema(await this.#db
699
+ .prepare(`PRAGMA table_xinfo(${START_IDEMPOTENCY_TABLE})`)
700
+ .all());
701
+ if (row !== undefined && row.key !== safeKey)
702
+ throw new ReservationSchemaError('admission returned another key');
703
+ return row;
704
+ }
705
+ catch (error) {
706
+ throw new StartReservationUnreadableError(safeKey, { cause: error });
707
+ }
708
+ }
709
+ async #schemaStage() {
710
+ return reservationSchemaStage(await this.#db
711
+ .prepare(`PRAGMA table_xinfo(${START_IDEMPOTENCY_TABLE})`)
712
+ .all());
713
+ }
714
+ async #readReservations(sql, bindings, key) {
715
+ try {
716
+ let result;
717
+ try {
718
+ result = await this.#db
719
+ .prepare(sql)
720
+ .bind(...bindings)
721
+ .all();
722
+ }
723
+ catch (error) {
724
+ if (isMissingReservationTable(error))
725
+ return [];
726
+ throw error;
727
+ }
728
+ const rows = reservationResultRows(result);
729
+ const stage = await this.#schemaStage();
730
+ if (stage === undefined)
731
+ throw new ReservationSchemaError('row observation has no schema');
732
+ return rows.map((row) => reservationFromRow(row, stage));
733
+ }
734
+ catch (error) {
735
+ throw new StartReservationUnreadableError(key, { cause: error });
736
+ }
737
+ }
738
+ async #migrationStage() {
739
+ const stage = await this.#schemaStage();
740
+ if (stage === undefined)
741
+ throw new ReservationSchemaError('table is missing during initialization');
742
+ if (stage === 0 || stage === 3)
743
+ return stage;
744
+ const predicate = START_IDEMPOTENCY_COLUMNS.slice(10, 10 + stage)
745
+ .map(([name]) => `${name} IS NOT NULL`)
746
+ .join(' OR ');
747
+ const rows = reservationResultRows(await this.#db
748
+ .prepare(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE ${predicate} LIMIT 1`)
749
+ .all());
750
+ const observed = await this.#schemaStage();
751
+ if (observed === undefined || observed < stage)
752
+ throw new ReservationSchemaError('schema regressed during initialization');
753
+ if (rows.length > 1)
754
+ throw new ReservationSchemaError('partial binding query returned multiple rows');
755
+ for (const row of rows)
756
+ reservationFromRow(row, observed);
757
+ return observed;
758
+ }
759
+ /** Create the table and its two access paths. Only `reserve()` reaches this. */
760
+ async #createSchema() {
761
+ if ((await this.#schemaStage()) === undefined) {
762
+ await this.#db.prepare(START_IDEMPOTENCY_DDL).run();
763
+ }
764
+ for (let index = await this.#migrationStage(); index < START_IDEMPOTENCY_ADDITIONS.length; index += 1) {
765
+ const stage = await this.#migrationStage();
766
+ if (stage < index)
767
+ throw new ReservationSchemaError('schema regressed during initialization');
768
+ if (stage > index)
769
+ continue;
770
+ try {
771
+ await this.#db
772
+ .prepare(`ALTER TABLE ${START_IDEMPOTENCY_TABLE} ADD COLUMN ${START_IDEMPOTENCY_ADDITIONS[index]}`)
773
+ .run();
774
+ }
775
+ catch (error) {
776
+ let observed;
777
+ try {
778
+ observed = await this.#schemaStage();
779
+ }
780
+ catch (readError) {
781
+ if (readError instanceof ReservationSchemaError)
782
+ throw readError;
783
+ throw error;
784
+ }
785
+ if (observed === undefined || observed <= index)
786
+ throw error;
787
+ }
788
+ }
789
+ if ((await this.#schemaStage()) !== 3)
790
+ throw new ReservationSchemaError('initialization did not reach the current schema');
791
+ await this.#db.prepare(START_IDEMPOTENCY_RUN_INDEX_DDL).run();
792
+ await this.#db.prepare(START_IDEMPOTENCY_STATE_INDEX_DDL).run();
793
+ }
794
+ /**
795
+ * Every reservation naming one of these runs, for the purge and the
796
+ * inventory. Chunked by the caller; this method binds exactly what it is
797
+ * given, so a caller must respect D1's 100-parameter statement limit.
798
+ */
799
+ async reservationsForRuns(runIds) {
800
+ const safeRunIds = runIds.filter((runId) => isPathSafeId(runId));
801
+ if (safeRunIds.length === 0)
802
+ return [];
803
+ const placeholders = safeRunIds.map(() => '?').join(', ');
804
+ const rows = await this.#readReservations(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE run_id IN (${placeholders})`, safeRunIds, '(run lookup)');
805
+ const requested = new Set(safeRunIds);
806
+ if (rows.some((row) => !requested.has(row.runId))) {
807
+ throw new StartReservationUnreadableError('(run lookup)', {
808
+ cause: new Error('reservation lookup returned an unrequested run'),
809
+ });
810
+ }
811
+ return rows;
812
+ }
813
+ }
814
+ export async function beginIdempotentStart(store, request, surface, fence, mutationEpoch) {
815
+ const capturedRequest = captureStartRequest(request);
816
+ const epoch = normalizeMutationEpoch(mutationEpoch);
817
+ const { persisted, live } = surface;
818
+ const capturedSurface = {
819
+ persisted: (row) => Reflect.apply(persisted, surface, [row]),
820
+ live: (row) => Reflect.apply(live, surface, [row]),
821
+ };
822
+ let proof;
823
+ if (fence !== undefined && fence !== 'none') {
824
+ try {
825
+ const reading = await fence.read();
826
+ if (reading.state === 'proof-only' &&
827
+ reading.proofKey === capturedRequest.key)
828
+ proof = Object.freeze({
829
+ key: capturedRequest.key,
830
+ mutationEpoch: reading.mutationEpoch,
831
+ transitionRevision: reading.transitionRevision,
832
+ });
833
+ }
834
+ catch {
835
+ /* A failed observation cannot authorize nomination. */
836
+ }
837
+ }
838
+ const { reservation, created } = await store.reserve(capturedRequest);
839
+ let decision;
840
+ // A creator can read back another caller's released reservation.
841
+ if (created &&
842
+ reservation.binding.kind === 'unbound' &&
843
+ reservation.state === 'reserved' &&
844
+ reservation.updatedAt === reservation.createdAt) {
845
+ const claimed = await store.claimReservation(reservation);
846
+ if (claimed !== undefined)
847
+ return { kind: 'start', reservation: claimed };
848
+ decision = await resolveLostClaim(store, reservation, capturedSurface);
849
+ }
850
+ else
851
+ decision = await resolveExistingReservation(store, reservation, capturedSurface, true);
852
+ if (decision.kind === 'replay' &&
853
+ proof !== undefined &&
854
+ fence !== undefined &&
855
+ fence !== 'none') {
856
+ const row = decision.reservation;
857
+ if (row.binding.kind === 'bound' &&
858
+ row.binding.execution.tablePrefix !== null) {
859
+ try {
860
+ if (row.targetKind === 'agent' && row.threadId === undefined)
861
+ throw new InvalidExecutionIdentityError('admission');
862
+ await fence.rebindProofRun({
863
+ reservation: row,
864
+ execution: {
865
+ ...row.binding.execution,
866
+ tablePrefix: row.binding.execution.tablePrefix,
867
+ owner: row.owner,
868
+ target: row.targetKind === 'agent'
869
+ ? {
870
+ kind: 'agent',
871
+ id: row.targetId,
872
+ threadId: row.threadId,
873
+ }
874
+ : { kind: 'workflow', id: row.targetId },
875
+ },
876
+ proof,
877
+ mutationEpoch: epoch,
878
+ reservationStore: store,
879
+ });
880
+ }
881
+ catch (error) {
882
+ console.error(JSON.stringify({
883
+ type: 'start-reservation-proof-rebind-failed',
884
+ key: row.key,
885
+ runId: row.runId,
886
+ error: error instanceof Error ? error.message : String(error),
887
+ }));
888
+ }
889
+ }
890
+ }
891
+ return decision;
892
+ }
893
+ function decodePersistedStart(value, row) {
894
+ try {
895
+ if (value === null ||
896
+ typeof value !== 'object' ||
897
+ Array.isArray(value) ||
898
+ !Object.hasOwn(value, 'kind') ||
899
+ !Object.hasOwn(value, 'execution'))
900
+ throw new Error('persisted start result is malformed');
901
+ const { kind, execution: raw } = value;
902
+ if ((kind !== 'initial' && kind !== 'result') ||
903
+ (kind === 'initial'
904
+ ? Object.hasOwn(value, 'value')
905
+ : !Object.hasOwn(value, 'value')))
906
+ throw new Error('persisted start result is malformed');
907
+ const { tablePrefix, workflowId, runId, startToken, owner, target } = raw;
908
+ const execution = normalizeStartExecutionIdentity({
909
+ tablePrefix,
910
+ workflowId,
911
+ runId,
912
+ startToken,
913
+ owner,
914
+ target,
915
+ });
916
+ if (execution.tablePrefix !== tablePrefix)
917
+ throw new Error('persisted start prefix is not canonical');
918
+ assertReservationStartIdentity(row, execution);
919
+ return kind === 'initial'
920
+ ? { kind, execution }
921
+ : { kind, execution, value: value.value };
922
+ }
923
+ catch (cause) {
924
+ throw new StartReservationUnreadableError(row.key, { cause });
925
+ }
926
+ }
927
+ async function resolveExistingReservation(store, observed, surface, mayClaim) {
928
+ if (observed.binding.kind === 'legacy') {
929
+ if (observed.state === 'terminal')
930
+ throw new IdempotentStartAlreadySettledError(observed);
931
+ throw new IdempotentStartUnresolvableError(observed);
932
+ }
933
+ const value = await surface.persisted(observed);
934
+ if (value !== undefined) {
935
+ const persisted = decodePersistedStart(value, observed);
936
+ if (observed.binding.kind === 'bound' &&
937
+ !sameReservationExecution(observed, persisted.execution)) {
938
+ if (observed.state === 'terminal')
939
+ throw new IdempotentStartAlreadySettledError(observed);
940
+ throw new IdempotentStartUnresolvableError(observed);
941
+ }
942
+ if (persisted.kind === 'result') {
943
+ if (observed.binding.kind === 'bound')
944
+ return {
945
+ kind: 'replay',
946
+ reservation: observed,
947
+ persisted: persisted.value,
948
+ };
949
+ if (observed.state === 'terminal')
950
+ throw new IdempotentStartAlreadySettledError(observed);
951
+ const reservation = await store.associateReservation(observed, persisted.execution);
952
+ return { kind: 'replay', reservation, persisted: persisted.value };
953
+ }
954
+ }
955
+ else if (mayClaim &&
956
+ observed.state === 'reserved' &&
957
+ observed.binding.kind === 'unbound') {
958
+ if (await surface.live(observed))
959
+ throw new IdempotentStartPendingError(observed);
960
+ const claimed = await store.claimReservation(observed);
961
+ if (claimed !== undefined)
962
+ return { kind: 'start', reservation: claimed };
963
+ return resolveLostClaim(store, observed, surface);
964
+ }
965
+ if (observed.state === 'terminal')
966
+ throw new IdempotentStartAlreadySettledError(observed);
967
+ if (await surface.live(observed))
968
+ throw new IdempotentStartPendingError(observed);
969
+ throw new IdempotentStartUnresolvableError(observed);
970
+ }
971
+ async function resolveLostClaim(store, observed, surface) {
972
+ const current = await store.readForAdmission(observed.key);
973
+ if (current === undefined || !sameReservationIdentity(current, observed))
974
+ throw new StartReservationUnreadableError(observed.key);
975
+ return resolveExistingReservation(store, current, surface, false);
976
+ }
977
+ /**
978
+ * Resolve a surface's reservation wiring, refusing a key the host cannot
979
+ * honour.
980
+ *
981
+ * `undefined` is admitted alongside `'none'` for the same reason
982
+ * `readExecutionFence` admits it — a wiring that arrives through an object the
983
+ * host may not have populated — and means the same thing: no store. What it
984
+ * does NOT mean is "ignore the key", which is why this throws rather than
985
+ * returning undefined. A start carrying an idempotency key onto an unwired
986
+ * deployment is a request this host cannot answer truthfully.
987
+ */
988
+ export function requireStartIdempotency(wiring) {
989
+ if (wiring === undefined || wiring === 'none') {
990
+ throw new StartIdempotencyUnsupportedError();
991
+ }
992
+ return wiring;
993
+ }
994
+ //# sourceMappingURL=start-idempotency.js.map