@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
@@ -1,13 +1,13 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // FlowsafeDurableAgent — drive Mastra's durable-agent loop through the ONE
3
- // RunnerRuntime chokepoint (DL-001/DL-010) so every agent leg inherits the
4
- // substrate's invariants: INV-1 server-minted runIds, per-leg
5
- // requestContextForRun grant derivation, snapshot provenance, RunSummary, and
6
- // retention purge — with no second execution path to audit.
3
+ // RunnerRuntime chokepoint so every agent leg inherits the substrate's
4
+ // invariants: server-minted runIds, per-leg requestContextForRun grant
5
+ // derivation, snapshot provenance, RunSummary, and retention purge, with no
6
+ // second execution path to audit.
7
7
  //
8
- // The mechanic (validated against @mastra/core 1.50.0 dist, spike S1 — every
9
- // offset in THIS section is 1.50.0-vintage and deliberately kept as the
10
- // provenance of the original validation; later sections carry their own stamp):
8
+ // The mechanic was validated against @mastra/core 1.50.0 dist. Every offset in
9
+ // THIS section is 1.50.0-vintage and deliberately kept as the provenance of the
10
+ // original validation; later sections carry their own stamp:
11
11
  // DurableAgent compiles the agent loop to the default-engine workflow
12
12
  // 'durable-agentic-loop' (agent/durable index.js: AGENTIC_LOOP :62,
13
13
  // getWorkflow() :5936, agent-agnostic — the agent is resolved per run by the
@@ -30,20 +30,20 @@
30
30
  // #requestContextFor mints per leg — so approvalGrantProvider's
31
31
  // `breakwater.connectorGrants` grant reaches the connector write gate with
32
32
  // zero extra wiring, and a forged/self resume that mints no grant fails closed
33
- // there (the registry copy is read only for the fail-closed, over-require-safe
34
- // approval PRE-check, S5).
33
+ // there. The registry copy is read only for the fail-closed, over-require-safe
34
+ // approval pre-check.
35
35
  //
36
- // INV-1 at the boundary: stream()/generate()/prepare() are the THREE inherited
37
- // minting entry points — each takes an OPTIONAL runId and, when it is absent,
38
- // lets core mint an unowned crypto.randomUUID() upstream
36
+ // Host-owned run ids at the boundary: stream()/generate()/prepare() are the
37
+ // THREE inherited minting entry points. Each takes an OPTIONAL runId and, when
38
+ // it is absent, lets core mint an unowned crypto.randomUUID() upstream
39
39
  // (prepareForDurableExecution, agent/durable index.js:589) that
40
40
  // PATH_SAFE_ID_PATTERN then accepts, slipping past executeWorkflow's guard AND
41
- // RunnerRuntime.start's (the exact fallback INV-1 forbids). All three are
42
- // overridden ONLY to REQUIRE a caller-minted runId before delegating to super —
43
- // and prepare() also REGISTERS the run under that id (index.js:5984), so an
44
- // unguarded prepare() strands an unowned run in the registry. streamUntilIdle()
45
- // needs no override: it drives agent.stream() (index.js:368), so the stream()
46
- // guard already covers it.
41
+ // RunnerRuntime.start's exact fallback, which the host-owned run-id rule
42
+ // forbids. All three are overridden ONLY to require a caller-minted runId
43
+ // before delegating to super. prepare() also REGISTERS the run under that id
44
+ // (index.js:5984), so an unguarded prepare() strands an unowned run in the
45
+ // registry. streamUntilIdle() needs no override: it drives agent.stream()
46
+ // (index.js:368), so the stream() guard already covers it.
47
47
  //
48
48
  // EVERY OTHER inherited entry point that can drive a run — or that hands back
49
49
  // runs the caller may not own — is BLOCKED, overridden to throw before it
@@ -195,19 +195,74 @@
195
195
  // caveat as getWorkflow() returning a startable object, and reaching it takes a
196
196
  // deliberate private cast, which is a first-party act.
197
197
  //
198
- // Corroboration: breakwater's guarded handle reaches the same verdict on seven
199
- // of the eight members blocked here that live on Agent.prototype — network,
200
- // resumeNetwork, approveNetworkToolCall, declineNetworkToolCall,
201
- // generateLegacy, streamLegacy and sendToolApproval are all
202
- // `intentionallyUnavailable` (packages/breakwater/src/agent/agent.test.ts:824).
203
- // It diverges on listSuspendedRuns (:955), which it files under
204
- // `explicitlyNonExecution` — the same divergence as listActiveRuns (:935), and
205
- // for the same reason: a narrowed HANDLE can only omit, so a data-returning
206
- // member is harmless there, while an INSTANCE Mastra calls in-process must
207
- // throw.
198
+ // Corroboration: breakwater's guarded handle reaches the same verdict on the
199
+ // network four (network, resumeNetwork, approveNetworkToolCall,
200
+ // declineNetworkToolCall), the legacy pair (generateLegacy, streamLegacy) and
201
+ // sendToolApproval, which it files `intentionallyUnavailable`
202
+ // (packages/breakwater/src/agent/agent.test.ts). It diverges on
203
+ // listSuspendedRuns, which it files under `explicitlyNonExecution` — the same
204
+ // divergence as listActiveRuns, and for the same reason: a
205
+ // narrowed HANDLE can only omit, so a data-returning member is harmless there,
206
+ // while an INSTANCE Mastra calls in-process must throw. The two members
207
+ // blocked below for newer cores diverge the same way; each entry records it.
208
208
  //
209
- // Blocking them keeps A-D2/P8 true by construction: resumeViaRuntime() is the
210
- // ONLY way a run resumes. ApprovalService.decide -> the host's ResumeRunFn ->
209
+ // Two more Agent-level members are blocked for cores NEWER than the pin. Read
210
+ // from the @mastra/core 1.67.0 dist, which the mastra-compat canary installs;
211
+ // offsets here are 1.67.0-vintage, in agent-Dk0N0Nlg.js unless another file is
212
+ // named, and the 1.53.0 offsets above are left as the provenance of that read.
213
+ // The pinned peer exposes neither member, so on 1.53.0 each refusal stands
214
+ // where the base would have raised a TypeError, and shadows a real
215
+ // implementation only once the peer moves.
216
+ //
217
+ // - listActiveThreadRuns() (:38214) is the discovery ground one scope wider
218
+ // than listActiveRuns. It takes no arguments and returns `{ runId,
219
+ // resourceId, threadId }` for every thread on the pubsub instance with a
220
+ // run in flight (storage-MbGlKLkB.js:1011-1023), and that state is keyed
221
+ // by pubsub instance rather than by agent (`#statesByPubSub`, :150, read
222
+ // through #getState :294), so it narrows by neither principal nor agent
223
+ // where the two listings above at least narrow by agentId. The in-process
224
+ // sibling getActiveThreadRunId() stays non-execution because it makes the
225
+ // caller name the (resourceId, threadId) pair: it confirms where this
226
+ // enumerates. Breakwater files it `explicitlyNonExecution`
227
+ // (agent.test.ts) for the reason it files listActiveRuns there: a
228
+ // narrowed HANDLE can only omit, so a data-returning member is harmless
229
+ // there, while an INSTANCE Mastra calls in-process must throw. Cost, stated
230
+ // rather than left to be rediscovered: core's AgentController aggregates
231
+ // this member across its backing agents
232
+ // (agent-controller-CKgKFyMR.js:5722-5725), so that aggregation now throws.
233
+ // It is already unusable over this class — the same controller calls the
234
+ // blocked sendToolApproval() at :4089 and :4118.
235
+ // - __setThreadRuntimeAgent() (:33609) installs another agent as the target
236
+ // the thread-runtime paths resolve through #getThreadRuntimeAgent()
237
+ // (:33612, `this.#threadRuntimeAgent ?? this`); the refusal in
238
+ // BLOCKED_RUN_ENTRIES names those paths, for the core it is written
239
+ // against. That is the fourth ground by installation rather than by call:
240
+ // the containment those inherited members rely on IS virtual dispatch on
241
+ // `this`, so one call moves every run those paths start onto an agent
242
+ // carrying none of these overrides — no caller-minted runId assertion, no
243
+ // executeWorkflow, no #startRequesters backstop. subscribeToThread drives
244
+ // no run of its own; the field moves its replay target all the same. It is
245
+ // public in the type surface (agent.d.ts:229 declares it with no
246
+ // modifier), so unlike getLegacyHandler it takes no private cast.
247
+ // Breakwater files it `explicitlyNonExecution` (agent.test.ts) for the
248
+ // reason it files the listings there: a narrowed HANDLE can only omit, so
249
+ // a setter is harmless there, while an INSTANCE Mastra calls in-process
250
+ // must throw.
251
+ //
252
+ // Neither carries the `override` keyword, and that is load-bearing rather than
253
+ // an oversight: TypeScript rejects `override` on a member the base does not
254
+ // declare, and 1.53.0 declares neither, so the keyword would fail the pinned
255
+ // typecheck that gates every merge. Each signature must still satisfy the base
256
+ // it acquires on newest; the caveat on each member says how. Both re-checks
257
+ // come due together, when the declared peer reaches a core that carries either
258
+ // member: the VERSION_SKEW expiry assertion in durable-agent-surface.test.ts
259
+ // goes red there, because each member's row claims the installed core carries
260
+ // it on neither prototype. That message speaks about the row alone; these two
261
+ // members' keyword and signature move with it.
262
+ //
263
+ // Blocking them keeps the single-resume and no-capability guarantees true by
264
+ // construction: resumeViaRuntime() is the ONLY way a run resumes.
265
+ // ApprovalService.decide -> the host's ResumeRunFn ->
211
266
  // createAgentApprovalResumer, which hands every 'durable-agentic-loop' record to
212
267
  // the thread topology's resume (-> resumeViaRuntime -> runtime.resume) and
213
268
  // refuses one carrying no agent-thread target rather than falling through to the
@@ -220,7 +275,7 @@
220
275
  //
221
276
  // Live-isolate scope: the loop resolves the tool's execute closure from the
222
277
  // in-process globalRunRegistry (populated by stream()). A DO holds one run in
223
- // one isolate (P1), so a resume decided before eviction finds it. A resume
278
+ // one isolate, so a resume decided before eviction finds it. A resume
224
279
  // AFTER eviction must first rehydrate that registry without replaying
225
280
  // application input processors. resumeViaRuntime() rebuilds the registry with
226
281
  // complete runtime processor lists after invoking only reserved RBAC during
@@ -228,7 +283,17 @@
228
283
  import { isMastraSignalMessage, MessageList, mastraDBMessageToSignal, } from '@mastra/core/agent';
229
284
  import { DurableAgent, globalRunRegistry, prepareForDurableExecution, } from '@mastra/core/agent/durable';
230
285
  import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
231
- import { InvalidRunRequestError, isPathSafeId, } from '../do-runner/index.js';
286
+ import { normalizeMutationEpoch, normalizeStartIdentity, } from '../do-runner/execution-admission.js';
287
+ import { InvalidRunRequestError, isPathSafeId, RunStateUnreadableError, } from '../do-runner/index.js';
288
+ import { resourceIdFromKey } from '../do-runner/memory-id.js';
289
+ import { captureReservation, } from '../do-runner/start-reservation-contract.js';
290
+ /** @internal A coherent snapshot belongs to another agent or thread. */
291
+ export class AgentRunSelectorMismatchError extends RunStateUnreadableError {
292
+ constructor(workflowId, runId) {
293
+ super(workflowId, runId);
294
+ this.name = 'AgentRunSelectorMismatchError';
295
+ }
296
+ }
232
297
  /**
233
298
  * The shared workflow id every durable-agent loop compiles to (core's
234
299
  * DurableAgentDefaults.AGENTIC_LOOP). Exposed so hosts and tests can reference
@@ -244,6 +309,77 @@ const UNREGISTERED_RUN_REFUSAL_PREFIX = 'Flowsafe durable-agent runner refused u
244
309
  */
245
310
  export const FLOWSAFE_PERSISTENCE_FORBIDDEN = 'flowsafe.persistence-forbidden';
246
311
  const BREAKWATER_GUARDED_AGENT_HOST_PROTOCOL = Symbol.for('@proofoftech/breakwater/guarded-agent-host/v1');
312
+ function captureAgentStartAuthority(source, requestedBy, requestedByKind) {
313
+ if (source === null || typeof source !== 'object' || Array.isArray(source)) {
314
+ throw new InvalidRunRequestError('agent start authority is required');
315
+ }
316
+ const { mutationEpoch: rawEpoch, startIdentity: rawIdentity, agentStart: rawAgentStart, onPreparedStartIdentity, runOwnerGuard: rawGuard, startReservation: rawReservation, } = source;
317
+ if (rawIdentity === undefined ||
318
+ rawAgentStart === undefined ||
319
+ !Object.hasOwn(source, 'onPreparedStartIdentity')) {
320
+ throw new InvalidRunRequestError('agent start authority is incomplete');
321
+ }
322
+ const startReservation = rawReservation === undefined
323
+ ? undefined
324
+ : captureReservation(rawReservation, 'started');
325
+ const mutationEpoch = normalizeMutationEpoch(rawEpoch);
326
+ const identity = normalizeStartIdentity(rawIdentity);
327
+ if (identity.target.kind !== 'agent') {
328
+ throw new InvalidRunRequestError('agent start authority requires an agent target');
329
+ }
330
+ if (identity.owner.id !== requestedBy ||
331
+ identity.owner.kind !== requestedByKind) {
332
+ throw new InvalidRunRequestError('startIdentity owner does not match requester');
333
+ }
334
+ if (rawAgentStart === null ||
335
+ typeof rawAgentStart !== 'object' ||
336
+ Array.isArray(rawAgentStart)) {
337
+ throw new InvalidRunRequestError('agentStart is malformed');
338
+ }
339
+ const { threaded } = rawAgentStart;
340
+ if (typeof threaded !== 'boolean') {
341
+ throw new InvalidRunRequestError('agentStart is malformed');
342
+ }
343
+ if (onPreparedStartIdentity !== undefined &&
344
+ typeof onPreparedStartIdentity !== 'function') {
345
+ throw new InvalidRunRequestError('onPreparedStartIdentity is malformed');
346
+ }
347
+ let runOwnerGuard;
348
+ if (rawGuard !== undefined) {
349
+ if (rawGuard === null ||
350
+ typeof rawGuard !== 'object' ||
351
+ Array.isArray(rawGuard)) {
352
+ throw new InvalidRunRequestError('runOwnerGuard is malformed');
353
+ }
354
+ const { owner: rawOwner, reservationToken } = rawGuard;
355
+ if (rawOwner === null ||
356
+ typeof rawOwner !== 'object' ||
357
+ Array.isArray(rawOwner)) {
358
+ throw new InvalidRunRequestError('runOwnerGuard is malformed');
359
+ }
360
+ const { kind, id } = rawOwner;
361
+ if (!isExecutionPrincipalKind(kind) ||
362
+ !isExecutionPrincipalId(id) ||
363
+ !isPathSafeId(reservationToken)) {
364
+ throw new InvalidRunRequestError('runOwnerGuard is malformed');
365
+ }
366
+ runOwnerGuard = Object.freeze({
367
+ owner: Object.freeze({ kind, id }),
368
+ reservationToken,
369
+ });
370
+ }
371
+ return Object.freeze({
372
+ mutationEpoch,
373
+ startIdentity: Object.freeze({
374
+ owner: identity.owner,
375
+ target: identity.target,
376
+ }),
377
+ agentStart: Object.freeze({ threaded }),
378
+ onPreparedStartIdentity,
379
+ runOwnerGuard,
380
+ startReservation,
381
+ });
382
+ }
247
383
  function snapshotDurableCallOptions(options) {
248
384
  if (options === undefined)
249
385
  return undefined;
@@ -331,15 +467,16 @@ const THREAD_TOOL_APPROVAL_REASON = 'the messages-plus-approved branch does not
331
467
  * 3. snapshot deletion owned by deployment-scoped retention;
332
468
  * 4. a SECOND execution surface that runs the agent outside RunnerRuntime
333
469
  * entirely, or that mints a run id below the caller — the network loop's
334
- * own workflow, the legacy handler, and the thread runtime's tool-approval
335
- * continuation.
470
+ * own workflow, the legacy handler, the thread runtime's tool-approval
471
+ * continuation, and the setter that installs a different agent as the
472
+ * thread runtime's execution target.
336
473
  *
337
474
  * Deliberately NOT re-exported from `./index.js` (a named-exports-only barrel),
338
475
  * so this stays off the public `@proofoftech/flowsafe/agent-runner` subpath.
339
476
  */
340
477
  export const BLOCKED_RUN_ENTRIES = {
341
- recover: 're-driving a persisted run bypasses run ownership (INV-1), per-leg grant minting and the fail-closed registry rehydration',
342
- recoverActiveRuns: 'bulk re-driving persisted runs bypasses run ownership (INV-1) and per-leg grant minting',
478
+ recover: 're-driving a persisted run bypasses run ownership, per-leg grant minting and the fail-closed registry rehydration',
479
+ recoverActiveRuns: 'bulk re-driving persisted runs bypasses run ownership and per-leg grant minting',
343
480
  resume: RESUME_FAMILY_REASON,
344
481
  resumeStream: RESUME_FAMILY_REASON,
345
482
  resumeGenerate: RESUME_FAMILY_REASON,
@@ -349,14 +486,16 @@ export const BLOCKED_RUN_ENTRIES = {
349
486
  declineToolCallGenerate: RESUME_FAMILY_REASON,
350
487
  listActiveRuns: "core scopes the running-run listing by agentId plus the caller's own optional thread and resource ids, never by per-principal ownership, so it bypasses the host topology's run-ownership checks and returns run, thread and resource ids the caller does not own",
351
488
  listSuspendedRuns: "core scopes the suspended-run listing by agentId plus the caller's own optional thread and resource ids, never by per-principal ownership, so it bypasses the host topology's run-ownership checks and returns run, thread and resource ids the caller does not own",
489
+ listActiveThreadRuns: 'core scopes the active thread-run listing by nothing at all: it takes no arguments and returns the run, thread and resource ids of every thread on the pubsub instance with a run in flight, which core keys by pubsub instance rather than by agent, so it enumerates ids across every principal AND every agent that shares the instance',
352
490
  deleteRunSnapshots: 'durable-agent snapshot rows are retained until deployment-scoped retention purge removes them',
353
- network: `${NETWORK_FAMILY_REASON}, and it mints an unowned run id when the caller omits one (INV-1)`,
491
+ network: `${NETWORK_FAMILY_REASON}, and it mints an unowned run id when the caller omits one`,
354
492
  resumeNetwork: NETWORK_FAMILY_REASON,
355
493
  approveNetworkToolCall: NETWORK_FAMILY_REASON,
356
494
  declineNetworkToolCall: NETWORK_FAMILY_REASON,
357
495
  generateLegacy: LEGACY_FAMILY_REASON,
358
496
  streamLegacy: LEGACY_FAMILY_REASON,
359
497
  sendToolApproval: THREAD_TOOL_APPROVAL_REASON,
498
+ __setThreadRuntimeAgent: "it installs the agent the thread-runtime paths resolve their target through — on @mastra/core 1.67.0 these are subscribeToThread, claimThreadOwnership, sendMessage, queueMessage, sendStateSignal, sendNotificationSignal and sendSignal, which read the field it writes — so one call moves every run those paths start, and subscribeToThread's replay target with them, onto an agent that carries none of this class's overrides: no caller-minted run id, no executeWorkflow, and no terminal refusal for a run the host start seam never registered",
360
499
  };
361
500
  /**
362
501
  * The refusal every blocked run entry point throws. A plain `Error`, not
@@ -435,6 +574,15 @@ export class FlowsafeDurableAgent extends DurableAgent {
435
574
  #startRequesters = new Map();
436
575
  #startRequesterKinds = new Map();
437
576
  #startAttemptTokens = new Map();
577
+ /**
578
+ * runId -> the reservation key the thread topology took for this start, so
579
+ * `executeWorkflow` can hand it to `RunnerRuntime.start` for the execution
580
+ * fence's proof-only match. Same lifetime and same cleanup as the attempt
581
+ * token beside it: registered by `streamUntilPersisted`, dropped in its
582
+ * `finally`, so nothing outlives the start it belongs to.
583
+ */
584
+ #startIdempotencyKeys = new Map();
585
+ #startAuthorities = new Map();
438
586
  #startScheduleDispatches = new Map();
439
587
  // The host's exact options object receives one private, single-use re-entry ticket.
440
588
  #hostStreamTickets = new WeakSet();
@@ -445,8 +593,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
445
593
  id: options.id,
446
594
  name: options.name,
447
595
  cache: options.cache,
448
- // Default the agent's own stream pubsub to the runtime's identity (DL-001:
449
- // ONE feed per DO), so a host that configures only init()'s pubsub still
596
+ // Default the agent's own stream pubsub to the runtime's identity (ONE
597
+ // feed per DO), so a host that configures only init()'s pubsub still
450
598
  // gets observe()/emitError aligned with the run's events (the run is driven
451
599
  // through the runtime, which publishes on THAT identity). An explicit
452
600
  // pubsub wins; both-absent falls to core's per-agent default (poll-only,
@@ -477,7 +625,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
477
625
  */
478
626
  #assertCallerRunId(runId) {
479
627
  if (!isPathSafeId(runId)) {
480
- throw new InvalidRunRequestError('a caller-minted runId is required and must be URL-path-safe (INV-1: the host owns run ids) — the durable-agent runner never generates one');
628
+ throw new InvalidRunRequestError('a caller-minted runId is required and must be URL-path-safe (the host owns run ids) — the durable-agent runner never generates one');
481
629
  }
482
630
  }
483
631
  /**
@@ -492,13 +640,17 @@ export class FlowsafeDurableAgent extends DurableAgent {
492
640
  * consumption make that exemption unavailable to callers.
493
641
  */
494
642
  #assertRunIdNotLive(runId) {
495
- if (this.#startRequesters.has(runId) ||
496
- this.#persistenceWaiters.has(runId) ||
497
- globalRunRegistry.has(runId) ||
498
- this.runRegistryInternal.has(runId)) {
643
+ if (this.isRunLive(runId)) {
499
644
  throw new InvalidRunRequestError('run id is live in the run registry — a registered run cannot be re-entered');
500
645
  }
501
646
  }
647
+ /** @internal */
648
+ isRunLive(runId) {
649
+ return (this.#startRequesters.has(runId) ||
650
+ this.#persistenceWaiters.has(runId) ||
651
+ globalRunRegistry.has(runId) ||
652
+ this.runRegistryInternal.has(runId));
653
+ }
502
654
  #assertGuardedStructuredOutput(options) {
503
655
  if (this.#isBreakwaterGuardedAgent &&
504
656
  options !== null &&
@@ -543,7 +695,22 @@ export class FlowsafeDurableAgent extends DurableAgent {
543
695
  *
544
696
  * @internal
545
697
  */
546
- async streamUntilPersisted(messages, options, requestedBy, requestedByKind, attemptToken = crypto.randomUUID(), scheduleDispatch) {
698
+ async streamUntilPersisted(messages, options, requestedBy, requestedByKind, attemptToken = crypto.randomUUID(), scheduleDispatch,
699
+ /**
700
+ * The idempotency key the thread topology already RESERVED for this run.
701
+ *
702
+ * It travels down here for one job: the execution fence's proof-only state
703
+ * admits exactly the start whose key matches its nominated proof key, and
704
+ * `RunnerRuntime.start` is where that comparison happens. It buys no
705
+ * exactly-once property at this layer — the reservation above already did —
706
+ * so nothing here validates it beyond passing it on, and a run started
707
+ * without one behaves exactly as before.
708
+ *
709
+ * Parked per-runId beside the attempt token rather than threaded through
710
+ * core, because core owns the call between `stream()` and
711
+ * `executeWorkflow()` and carries no field this could ride in.
712
+ */
713
+ idempotencyKey, authority) {
547
714
  const callOptions = snapshotDurableCallOptions(options);
548
715
  this.#assertCallerRunId(callOptions?.runId);
549
716
  this.#assertGuardedStructuredOutput(callOptions);
@@ -556,6 +723,20 @@ export class FlowsafeDurableAgent extends DurableAgent {
556
723
  if (!isExecutionPrincipalKind(requestedByKind)) {
557
724
  throw new InvalidRunRequestError('requestedByKind is malformed');
558
725
  }
726
+ const capturedAuthority = captureAgentStartAuthority(authority, requestedBy, requestedByKind);
727
+ let capturedScheduleDispatch;
728
+ if (scheduleDispatch !== undefined) {
729
+ if (scheduleDispatch === null ||
730
+ typeof scheduleDispatch !== 'object' ||
731
+ Array.isArray(scheduleDispatch)) {
732
+ throw new Error('stored run lifecycle is malformed');
733
+ }
734
+ const { scheduleId, dispatchId } = scheduleDispatch;
735
+ if (!isPathSafeId(scheduleId) || !isPathSafeId(dispatchId)) {
736
+ throw new Error('stored run lifecycle is malformed');
737
+ }
738
+ capturedScheduleDispatch = Object.freeze({ scheduleId, dispatchId });
739
+ }
559
740
  const runId = callOptions.runId;
560
741
  this.#assertRunIdNotLive(runId);
561
742
  let resolve;
@@ -569,8 +750,12 @@ export class FlowsafeDurableAgent extends DurableAgent {
569
750
  this.#startRequesters.set(runId, requestedBy);
570
751
  this.#startRequesterKinds.set(runId, requestedByKind);
571
752
  this.#startAttemptTokens.set(runId, attemptToken);
572
- if (scheduleDispatch) {
573
- this.#startScheduleDispatches.set(runId, scheduleDispatch);
753
+ this.#startAuthorities.set(runId, capturedAuthority);
754
+ if (capturedScheduleDispatch) {
755
+ this.#startScheduleDispatches.set(runId, capturedScheduleDispatch);
756
+ }
757
+ if (idempotencyKey !== undefined) {
758
+ this.#startIdempotencyKeys.set(runId, idempotencyKey);
574
759
  }
575
760
  const onError = callOptions.onError;
576
761
  try {
@@ -594,6 +779,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
594
779
  this.#startRequesterKinds.delete(runId);
595
780
  this.#startAttemptTokens.delete(runId);
596
781
  this.#startScheduleDispatches.delete(runId);
782
+ this.#startIdempotencyKeys.delete(runId);
783
+ this.#startAuthorities.delete(runId);
597
784
  }
598
785
  }
599
786
  /**
@@ -699,6 +886,26 @@ export class FlowsafeDurableAgent extends DurableAgent {
699
886
  async listSuspendedRuns(_options) {
700
887
  throw unavailableRunEntry('listSuspendedRuns', BLOCKED_RUN_ENTRIES.listSuspendedRuns);
701
888
  }
889
+ /**
890
+ * Refuse the thread-level run enumerator newer cores add.
891
+ * `listActiveThreadRuns()` takes no arguments and returns a runId plus the
892
+ * resourceId and threadId parsed out of the key for every thread on the
893
+ * pubsub instance with a run in flight, and core keys that state by pubsub
894
+ * instance rather than by agent — so it is the same discovery ground as
895
+ * {@link FlowsafeDurableAgent.listActiveRuns} with the last scoping gone.
896
+ * The in-process sibling `getActiveThreadRunId()` stays inherited because it
897
+ * makes the caller name the (resourceId, threadId) pair it confirms.
898
+ *
899
+ * Signature caveat, and the reason this one is not `async`: the base declares
900
+ * it SYNCHRONOUS (`listActiveThreadRuns(): ActiveThreadRun[]`), so the
901
+ * `async … Promise<never>` shape every other refusal here carries would not
902
+ * be assignable to it. No `override` keyword either — the pinned 1.53.0
903
+ * declares no such member, and `override` on a member the base lacks is a
904
+ * type error. Both are re-checks for a peer bump.
905
+ */
906
+ listActiveThreadRuns() {
907
+ throw unavailableRunEntry('listActiveThreadRuns', BLOCKED_RUN_ENTRIES.listActiveThreadRuns);
908
+ }
702
909
  /**
703
910
  * Refuse the multi-agent network start. `network()` does not touch the
704
911
  * durable-agentic-loop at all: it compiles a SEPARATE workflow and drives it
@@ -778,6 +985,28 @@ export class FlowsafeDurableAgent extends DurableAgent {
778
985
  async sendToolApproval(_options) {
779
986
  throw unavailableRunEntry('sendToolApproval', BLOCKED_RUN_ENTRIES.sendToolApproval);
780
987
  }
988
+ /**
989
+ * Refuse the thread-runtime target swap newer cores add. It sets one private
990
+ * field that the thread-runtime paths resolve their target through, falling
991
+ * back to `this`; the refusal in `BLOCKED_RUN_ENTRIES` names those paths,
992
+ * for the core it is written against. So the containment those inherited
993
+ * members rely on is virtual dispatch on `this`, and one call to this setter
994
+ * moves every run they start, and their replay targets with them, onto an
995
+ * agent with none of these overrides in the chain. That is the fourth ground
996
+ * reached by installing a second execution surface rather than by calling
997
+ * one.
998
+ *
999
+ * Signature caveat: the parameter is `unknown` rather than core's
1000
+ * `Agent<any, any, any, any>` because the pinned 1.53.0 declares no such
1001
+ * member at all, while newest 1.x does — `unknown` is the one supertype of
1002
+ * core's parameter, so it satisfies that base without depending on method
1003
+ * bivariance, and it constrains nothing on the pin, where there is no base
1004
+ * member to satisfy. No `override` keyword, for the same reason as
1005
+ * {@link FlowsafeDurableAgent.listActiveThreadRuns}.
1006
+ */
1007
+ __setThreadRuntimeAgent(_agent) {
1008
+ throw unavailableRunEntry('__setThreadRuntimeAgent', BLOCKED_RUN_ENTRIES.__setThreadRuntimeAgent);
1009
+ }
781
1010
  /**
782
1011
  * Refuse core's terminal snapshot cleanup. Its only call sites are the base
783
1012
  * `executeWorkflow` (overridden here), the blocked `resume()` and the blocked
@@ -1051,6 +1280,133 @@ export class FlowsafeDurableAgent extends DurableAgent {
1051
1280
  clearTimeout(timeout);
1052
1281
  }
1053
1282
  }
1283
+ async authoritativeAgentStartState(expectedRuntime, threadId, runId, options) {
1284
+ const includeLegacy = options?.includeLegacy === true;
1285
+ const runtime = this.#runtime;
1286
+ const workflowId = this.getWorkflow().id;
1287
+ const agentId = this.#wrappedAgent.id;
1288
+ try {
1289
+ if (expectedRuntime !== runtime ||
1290
+ !isPathSafeId(threadId) ||
1291
+ !isPathSafeId(runId))
1292
+ throw new Error('agent observation selector is invalid');
1293
+ const state = includeLegacy
1294
+ ? await runtime.authoritativeStartState(workflowId, runId, {
1295
+ includeLegacy: true,
1296
+ })
1297
+ : await runtime.authoritativeStartState(workflowId, runId);
1298
+ if (state === null)
1299
+ return null;
1300
+ if (state.kind === 'legacy') {
1301
+ if (!includeLegacy)
1302
+ throw new Error('legacy agent observation requires explicit opt-in');
1303
+ const context = state.snapshot.requestContext;
1304
+ const input = state.snapshot.context?.input;
1305
+ const correlation = context?.['breakwater.auditContext'];
1306
+ const memory = input?.messageListState?.memoryInfo;
1307
+ const observedAgentId = input?.agentId;
1308
+ const observedThreadId = context?.threadId;
1309
+ if (!isPathSafeId(observedAgentId) || !isPathSafeId(observedThreadId))
1310
+ throw new Error('legacy agent observation identity is malformed');
1311
+ const observedResourceId = resourceIdFromKey(observedThreadId);
1312
+ if (state.address.workflowId !== workflowId ||
1313
+ state.address.runId !== runId ||
1314
+ (input?.runId !== undefined && input.runId !== runId) ||
1315
+ context?.runId !== runId ||
1316
+ context.resourceId !== observedResourceId ||
1317
+ correlation?.agentId !== observedAgentId ||
1318
+ correlation.threadId !== observedThreadId ||
1319
+ correlation.resourceId !== observedResourceId ||
1320
+ (memory !== null &&
1321
+ (memory?.threadId !== observedThreadId ||
1322
+ memory.resourceId !== observedResourceId)))
1323
+ throw new Error('legacy agent observation context contradicts identity');
1324
+ if (observedAgentId !== agentId || observedThreadId !== threadId)
1325
+ throw new AgentRunSelectorMismatchError(workflowId, runId);
1326
+ return { ...state, threaded: memory !== null };
1327
+ }
1328
+ const identity = state.provenance.startIdentity;
1329
+ const threaded = state.provenance.agentStart?.threaded;
1330
+ if (identity?.target.kind !== 'agent' ||
1331
+ typeof threaded !== 'boolean' ||
1332
+ state.execution.workflowId !== workflowId ||
1333
+ state.execution.runId !== runId)
1334
+ throw new Error('agent observation identity is malformed');
1335
+ const observedAgentId = identity.target.id;
1336
+ const observedThreadId = identity.target.threadId;
1337
+ const observedResourceId = resourceIdFromKey(observedThreadId);
1338
+ const context = state.snapshot.requestContext;
1339
+ const record = (value) => {
1340
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
1341
+ throw new Error('agent observation context is malformed');
1342
+ return value;
1343
+ };
1344
+ const check = (value, selectors) => {
1345
+ if (value === undefined)
1346
+ return;
1347
+ const values = record(value);
1348
+ for (const [key, expected] of Object.entries(selectors))
1349
+ if (Object.hasOwn(values, key) && values[key] !== expected)
1350
+ throw new Error('agent observation context contradicts identity');
1351
+ };
1352
+ check(context, {
1353
+ runId,
1354
+ threadId: observedThreadId,
1355
+ resourceId: observedResourceId,
1356
+ });
1357
+ check(context?.['breakwater.auditContext'], {
1358
+ agentId: observedAgentId,
1359
+ threadId: observedThreadId,
1360
+ resourceId: observedResourceId,
1361
+ });
1362
+ const input = state.snapshot.context?.input;
1363
+ if (input !== undefined) {
1364
+ check(input, { agentId: observedAgentId, runId });
1365
+ const messageList = record(input).messageListState;
1366
+ if (messageList !== undefined) {
1367
+ const values = record(messageList);
1368
+ if (Object.hasOwn(values, 'memoryInfo')) {
1369
+ const memory = values.memoryInfo;
1370
+ if (memory === null) {
1371
+ if (threaded)
1372
+ throw new Error('agent mode contradicts memory');
1373
+ }
1374
+ else {
1375
+ const selected = record(memory);
1376
+ if (!threaded ||
1377
+ selected.threadId !== observedThreadId ||
1378
+ selected.resourceId !== observedResourceId)
1379
+ throw new Error('agent mode contradicts memory');
1380
+ }
1381
+ }
1382
+ }
1383
+ }
1384
+ if (observedAgentId !== agentId || observedThreadId !== threadId)
1385
+ throw new AgentRunSelectorMismatchError(workflowId, runId);
1386
+ return {
1387
+ ...state,
1388
+ execution: { ...state.execution, ...identity },
1389
+ threaded,
1390
+ };
1391
+ }
1392
+ catch (cause) {
1393
+ if (cause instanceof RunStateUnreadableError)
1394
+ throw cause;
1395
+ throw new RunStateUnreadableError(workflowId, runId, { cause });
1396
+ }
1397
+ }
1398
+ /** @internal Initial identity can correlate proof without granting replay success. */
1399
+ async proofExecutionFor(expectedRuntime, threadId, runId) {
1400
+ const state = await this.authoritativeAgentStartState(expectedRuntime, threadId, runId);
1401
+ if (state?.storage !== 'd1')
1402
+ return undefined;
1403
+ return {
1404
+ tablePrefix: state.execution.tablePrefix,
1405
+ workflowId: state.execution.workflowId,
1406
+ runId: state.execution.runId,
1407
+ startToken: state.execution.startToken,
1408
+ };
1409
+ }
1054
1410
  /**
1055
1411
  * Drive the durable-agentic-loop through RunnerRuntime instead of the base
1056
1412
  * `createRun + run.start`. stream()/generate() have already parked the
@@ -1072,12 +1428,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
1072
1428
  const requestedByKind = this.#startRequesterKinds.get(runId);
1073
1429
  const attemptToken = this.#startAttemptTokens.get(runId);
1074
1430
  const scheduleDispatch = this.#startScheduleDispatches.get(runId);
1075
- const startOptions = {
1076
- runId,
1077
- inputData: workflowInput,
1078
- ...(attemptToken === undefined ? {} : { attemptToken }),
1079
- ...(scheduleDispatch === undefined ? {} : { scheduleDispatch }),
1080
- };
1431
+ const idempotencyKey = this.#startIdempotencyKeys.get(runId);
1432
+ const authority = this.#startAuthorities.get(runId);
1081
1433
  if (requestedBy === undefined || requestedByKind === undefined) {
1082
1434
  if (requestedBy !== undefined || requestedByKind !== undefined) {
1083
1435
  throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
@@ -1103,10 +1455,30 @@ export class FlowsafeDurableAgent extends DurableAgent {
1103
1455
  throw refusal;
1104
1456
  return;
1105
1457
  }
1106
- summary = await this.#runtime.start(this.getWorkflow().id, {
1107
- ...startOptions,
1458
+ const { runId: coreRunId, agentId: coreAgentId, ...payload } = workflowInput;
1459
+ if (!authority) {
1460
+ throw new InvalidRunRequestError('registered run is missing agent start authority');
1461
+ }
1462
+ if (coreRunId !== runId ||
1463
+ authority.startIdentity.target.id !== this.#wrappedAgent.id ||
1464
+ coreAgentId !== authority.startIdentity.target.id) {
1465
+ throw new InvalidRunRequestError('Core input does not match agent start authority');
1466
+ }
1467
+ const workflow = this.getWorkflow();
1468
+ summary = await this.#runtime.start(workflow.id, {
1469
+ runId,
1470
+ inputData: { ...payload, runId: coreRunId, agentId: coreAgentId },
1471
+ ...(attemptToken === undefined ? {} : { attemptToken }),
1472
+ ...(scheduleDispatch === undefined ? {} : { scheduleDispatch }),
1473
+ ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
1108
1474
  requestedBy,
1109
1475
  requestedByKind,
1476
+ mutationEpoch: authority.mutationEpoch,
1477
+ startIdentity: authority.startIdentity,
1478
+ agentStart: authority.agentStart,
1479
+ onPreparedStartIdentity: authority.onPreparedStartIdentity,
1480
+ runOwnerGuard: authority.runOwnerGuard,
1481
+ startReservation: authority.startReservation,
1110
1482
  });
1111
1483
  waiter?.resolve();
1112
1484
  }