@proofoftech/flowsafe 0.18.0 → 0.20.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 (196) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +79 -5
  3. package/deployment-identity-protocol.d.mts +62 -1
  4. package/deployment-identity-protocol.mjs +201 -5
  5. package/dist/agent-host/catalog.js +1 -1
  6. package/dist/agent-host/catalog.js.map +1 -1
  7. package/dist/agent-host/index.d.ts +1 -1
  8. package/dist/agent-host/index.d.ts.map +1 -1
  9. package/dist/agent-host/index.js.map +1 -1
  10. package/dist/agent-host/router.d.ts.map +1 -1
  11. package/dist/agent-host/router.js +6 -2
  12. package/dist/agent-host/router.js.map +1 -1
  13. package/dist/agent-host/thread-host.d.ts +11 -0
  14. package/dist/agent-host/thread-host.d.ts.map +1 -1
  15. package/dist/agent-host/thread-host.js +53 -1
  16. package/dist/agent-host/thread-host.js.map +1 -1
  17. package/dist/agent-host/thread-topology.d.ts +35 -1
  18. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  19. package/dist/agent-host/thread-topology.js +103 -7
  20. package/dist/agent-host/thread-topology.js.map +1 -1
  21. package/dist/agent-runner/durable-agent-runner.d.ts +267 -21
  22. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  23. package/dist/agent-runner/durable-agent-runner.js +706 -76
  24. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  25. package/dist/approval-api/d1-store.d.ts.map +1 -1
  26. package/dist/approval-api/d1-store.js +6 -3
  27. package/dist/approval-api/d1-store.js.map +1 -1
  28. package/dist/approval-api/principal-identity.d.ts +32 -0
  29. package/dist/approval-api/principal-identity.d.ts.map +1 -0
  30. package/dist/approval-api/principal-identity.js +69 -0
  31. package/dist/approval-api/principal-identity.js.map +1 -0
  32. package/dist/approval-api/principal.d.ts +9 -12
  33. package/dist/approval-api/principal.d.ts.map +1 -1
  34. package/dist/approval-api/principal.js +9 -45
  35. package/dist/approval-api/principal.js.map +1 -1
  36. package/dist/approval-api/router.d.ts.map +1 -1
  37. package/dist/approval-api/router.js +9 -1
  38. package/dist/approval-api/router.js.map +1 -1
  39. package/dist/approval-api/service.d.ts +19 -0
  40. package/dist/approval-api/service.d.ts.map +1 -1
  41. package/dist/approval-api/service.js +41 -10
  42. package/dist/approval-api/service.js.map +1 -1
  43. package/dist/approval-api/types.d.ts +12 -0
  44. package/dist/approval-api/types.d.ts.map +1 -1
  45. package/dist/approval-api/types.js +12 -0
  46. package/dist/approval-api/types.js.map +1 -1
  47. package/dist/background-tasks/host.d.ts +127 -14
  48. package/dist/background-tasks/host.d.ts.map +1 -1
  49. package/dist/background-tasks/host.js +579 -50
  50. package/dist/background-tasks/host.js.map +1 -1
  51. package/dist/background-tasks/index.d.ts +2 -2
  52. package/dist/background-tasks/index.d.ts.map +1 -1
  53. package/dist/background-tasks/index.js +11 -6
  54. package/dist/background-tasks/index.js.map +1 -1
  55. package/dist/background-tasks/routes.d.ts +19 -2
  56. package/dist/background-tasks/routes.d.ts.map +1 -1
  57. package/dist/background-tasks/routes.js +4 -4
  58. package/dist/background-tasks/routes.js.map +1 -1
  59. package/dist/deployment-identity-protocol.d.ts +2 -2
  60. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  61. package/dist/deployment-identity-protocol.js +1 -1
  62. package/dist/deployment-identity-protocol.js.map +1 -1
  63. package/dist/do-runner/cause-chain.d.ts +53 -0
  64. package/dist/do-runner/cause-chain.d.ts.map +1 -0
  65. package/dist/do-runner/cause-chain.js +96 -0
  66. package/dist/do-runner/cause-chain.js.map +1 -0
  67. package/dist/do-runner/d1-storage.d.ts +109 -5
  68. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  69. package/dist/do-runner/d1-storage.js +289 -44
  70. package/dist/do-runner/d1-storage.js.map +1 -1
  71. package/dist/do-runner/deployment-identity.d.ts +28 -13
  72. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  73. package/dist/do-runner/deployment-identity.js +25 -35
  74. package/dist/do-runner/deployment-identity.js.map +1 -1
  75. package/dist/do-runner/do-error-response.d.ts +4 -23
  76. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  77. package/dist/do-runner/do-error-response.js +19 -24
  78. package/dist/do-runner/do-error-response.js.map +1 -1
  79. package/dist/do-runner/do-status-error.d.ts +37 -0
  80. package/dist/do-runner/do-status-error.d.ts.map +1 -0
  81. package/dist/do-runner/do-status-error.js +42 -0
  82. package/dist/do-runner/do-status-error.js.map +1 -0
  83. package/dist/do-runner/durable-object.d.ts +2 -1
  84. package/dist/do-runner/durable-object.d.ts.map +1 -1
  85. package/dist/do-runner/durable-object.js +205 -19
  86. package/dist/do-runner/durable-object.js.map +1 -1
  87. package/dist/do-runner/execution-fence.d.ts +335 -0
  88. package/dist/do-runner/execution-fence.d.ts.map +1 -0
  89. package/dist/do-runner/execution-fence.js +534 -0
  90. package/dist/do-runner/execution-fence.js.map +1 -0
  91. package/dist/do-runner/index.d.ts +10 -3
  92. package/dist/do-runner/index.d.ts.map +1 -1
  93. package/dist/do-runner/index.js +16 -3
  94. package/dist/do-runner/index.js.map +1 -1
  95. package/dist/do-runner/init.d.ts +82 -1
  96. package/dist/do-runner/init.d.ts.map +1 -1
  97. package/dist/do-runner/init.js +58 -3
  98. package/dist/do-runner/init.js.map +1 -1
  99. package/dist/do-runner/inventory.d.ts +294 -0
  100. package/dist/do-runner/inventory.d.ts.map +1 -0
  101. package/dist/do-runner/inventory.js +811 -0
  102. package/dist/do-runner/inventory.js.map +1 -0
  103. package/dist/do-runner/notification-predicate.d.ts +8 -0
  104. package/dist/do-runner/notification-predicate.d.ts.map +1 -0
  105. package/dist/do-runner/notification-predicate.js +9 -0
  106. package/dist/do-runner/notification-predicate.js.map +1 -0
  107. package/dist/do-runner/runtime.d.ts +83 -0
  108. package/dist/do-runner/runtime.d.ts.map +1 -1
  109. package/dist/do-runner/runtime.js +131 -4
  110. package/dist/do-runner/runtime.js.map +1 -1
  111. package/dist/do-runner/start-idempotency.d.ts +508 -0
  112. package/dist/do-runner/start-idempotency.d.ts.map +1 -0
  113. package/dist/do-runner/start-idempotency.js +886 -0
  114. package/dist/do-runner/start-idempotency.js.map +1 -0
  115. package/dist/do-runner/suspension-deadline.d.ts +3 -2
  116. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  117. package/dist/do-runner/suspension-deadline.js +3 -2
  118. package/dist/do-runner/suspension-deadline.js.map +1 -1
  119. package/dist/goals/objective-routes.d.ts +14 -0
  120. package/dist/goals/objective-routes.d.ts.map +1 -1
  121. package/dist/goals/objective-routes.js +45 -24
  122. package/dist/goals/objective-routes.js.map +1 -1
  123. package/dist/host-kit/do-run-topology.d.ts +15 -0
  124. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  125. package/dist/host-kit/do-run-topology.js +22 -1
  126. package/dist/host-kit/do-run-topology.js.map +1 -1
  127. package/dist/host-kit/flowsafe-worker.d.ts +11 -0
  128. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  129. package/dist/host-kit/flowsafe-worker.js +343 -62
  130. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  131. package/dist/host-kit/host-approval-service.d.ts +20 -0
  132. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  133. package/dist/host-kit/host-approval-service.js +6 -0
  134. package/dist/host-kit/host-approval-service.js.map +1 -1
  135. package/dist/host-kit/index.d.ts +2 -2
  136. package/dist/host-kit/index.d.ts.map +1 -1
  137. package/dist/host-kit/index.js +1 -1
  138. package/dist/host-kit/index.js.map +1 -1
  139. package/dist/host-kit/run-route-error.d.ts +18 -0
  140. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  141. package/dist/host-kit/run-route-error.js +23 -0
  142. package/dist/host-kit/run-route-error.js.map +1 -1
  143. package/dist/host-kit/run-router.d.ts +58 -1
  144. package/dist/host-kit/run-router.d.ts.map +1 -1
  145. package/dist/host-kit/run-router.js +120 -11
  146. package/dist/host-kit/run-router.js.map +1 -1
  147. package/dist/host-kit/stream-router.d.ts.map +1 -1
  148. package/dist/host-kit/stream-router.js +18 -9
  149. package/dist/host-kit/stream-router.js.map +1 -1
  150. package/dist/schedules/router.d.ts +15 -0
  151. package/dist/schedules/router.d.ts.map +1 -1
  152. package/dist/schedules/router.js +47 -17
  153. package/dist/schedules/router.js.map +1 -1
  154. package/dist/schedules/tick.d.ts +13 -0
  155. package/dist/schedules/tick.d.ts.map +1 -1
  156. package/dist/schedules/tick.js +59 -39
  157. package/dist/schedules/tick.js.map +1 -1
  158. package/dist/signal-providers/delivery.d.ts +32 -0
  159. package/dist/signal-providers/delivery.d.ts.map +1 -1
  160. package/dist/signal-providers/delivery.js +45 -0
  161. package/dist/signal-providers/delivery.js.map +1 -1
  162. package/dist/signal-providers/host-do.d.ts +23 -1
  163. package/dist/signal-providers/host-do.d.ts.map +1 -1
  164. package/dist/signal-providers/host-do.js +76 -17
  165. package/dist/signal-providers/host-do.js.map +1 -1
  166. package/dist/signal-providers/provider.d.ts +8 -0
  167. package/dist/signal-providers/provider.d.ts.map +1 -1
  168. package/dist/signal-providers/provider.js.map +1 -1
  169. package/dist/signal-providers/webhook-route.d.ts +20 -0
  170. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  171. package/dist/signal-providers/webhook-route.js +137 -26
  172. package/dist/signal-providers/webhook-route.js.map +1 -1
  173. package/dist/signals/client.d.ts +19 -5
  174. package/dist/signals/client.d.ts.map +1 -1
  175. package/dist/signals/client.js +25 -17
  176. package/dist/signals/client.js.map +1 -1
  177. package/dist/signals/index.d.ts +1 -1
  178. package/dist/signals/index.d.ts.map +1 -1
  179. package/dist/signals/index.js.map +1 -1
  180. package/dist/signals/notification-dispatch.d.ts +15 -0
  181. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  182. package/dist/signals/notification-dispatch.js +23 -1
  183. package/dist/signals/notification-dispatch.js.map +1 -1
  184. package/dist/signals/notifications-d1.d.ts +8 -0
  185. package/dist/signals/notifications-d1.d.ts.map +1 -1
  186. package/dist/signals/notifications-d1.js +15 -9
  187. package/dist/signals/notifications-d1.js.map +1 -1
  188. package/dist/signals/router.d.ts.map +1 -1
  189. package/dist/signals/router.js +3 -2
  190. package/dist/signals/router.js.map +1 -1
  191. package/dist/signals/thread-do-routes.d.ts +48 -10
  192. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  193. package/dist/signals/thread-do-routes.js +710 -136
  194. package/dist/signals/thread-do-routes.js.map +1 -1
  195. package/package.json +8 -6
  196. package/scripts/seed-deployment-identity.mjs +22 -4
@@ -1,11 +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):
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:
9
11
  // DurableAgent compiles the agent loop to the default-engine workflow
10
12
  // 'durable-agentic-loop' (agent/durable index.js: AGENTIC_LOOP :62,
11
13
  // getWorkflow() :5936, agent-agnostic — the agent is resolved per run by the
@@ -28,33 +30,203 @@
28
30
  // #requestContextFor mints per leg — so approvalGrantProvider's
29
31
  // `breakwater.connectorGrants` grant reaches the connector write gate with
30
32
  // zero extra wiring, and a forged/self resume that mints no grant fails closed
31
- // there (the registry copy is read only for the fail-closed, over-require-safe
32
- // approval PRE-check, S5).
33
+ // there. The registry copy is read only for the fail-closed, over-require-safe
34
+ // approval pre-check.
33
35
  //
34
- // INV-1 at the boundary: stream()/generate()/prepare() are the THREE inherited
35
- // minting entry points — each takes an OPTIONAL runId and, when it is absent,
36
- // 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
37
39
  // (prepareForDurableExecution, agent/durable index.js:589) that
38
40
  // PATH_SAFE_ID_PATTERN then accepts, slipping past executeWorkflow's guard AND
39
- // RunnerRuntime.start's (the exact fallback INV-1 forbids). All three are
40
- // overridden ONLY to REQUIRE a caller-minted runId before delegating to super —
41
- // and prepare() also REGISTERS the run under that id (index.js:5984), so an
42
- // unguarded prepare() strands an unowned run in the registry. streamUntilIdle()
43
- // needs no override: it drives agent.stream() (index.js:368), so the stream()
44
- // guard already covers it. resume() is NOT overridden to be client-facing
45
- // (A-D2/P8): resume flows ONLY through the approval-decision path
46
- // (ApprovalService.decide -> resumeViaRuntime -> runtime.resume), which derives
47
- // grants on the (suspendedAt, resumeCount) fingerprint. The inherited
48
- // resume()/approveToolCall()/declineToolCall() still exist and never mint (they
49
- // read the run-registry entry), but no route wires them.
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
+ //
48
+ // EVERY OTHER inherited entry point that can drive a run — or that hands back
49
+ // runs the caller may not own — is BLOCKED, overridden to throw before it
50
+ // touches storage or the registry. BLOCKED_RUN_ENTRIES below is the single
51
+ // source for which method is refused on which ground; the four grounds are
52
+ // enumerated there.
53
+ //
54
+ // Provenance for this section: read from the @mastra/core 1.53.0 dist. Chunk
55
+ // file names are CONTENT-HASHED and move every release, so each offset below is
56
+ // qualified by the chunk that carried it at 1.53.0 — re-read, never re-trust,
57
+ // on a peer bump.
58
+ //
59
+ // (1) Recovery (new in 1.53.0), in chunk-XMEACVLS.js. recover() (:6385) reads
60
+ // the persisted AGENTIC_LOOP snapshot (:6405) and re-drives it with
61
+ // `workflow.createRun({ runId }) + run.restart()` (:6587-6588); it also
62
+ // rebuilds the registry from the FULL application processor list (:6471)
63
+ // rather than #rehydrateRegistry's RBAC-only, fail-closed preparation.
64
+ // recoverActiveRuns() (:7027) is listActiveRuns() plus a recover() per
65
+ // row. The protected deleteRunSnapshots() (:5877) joins them: its only
66
+ // core call sites are the base executeWorkflow (:5834, overridden here),
67
+ // resume() (:6308) and recover() (:6593), so no path this class drives
68
+ // reaches it, and the snapshot rows belong to deployment-scoped retention
69
+ // purge.
70
+ //
71
+ // (2) Unscoped run DISCOVERY, which returns run/thread/resource ids rather
72
+ // than driving anything. listActiveRuns() (chunk-XMEACVLS.js:6927)
73
+ // enumerates `listWorkflowRuns({ workflowName: 'durable-agentic-loop',
74
+ // status: 'running' })`, and the Agent-level listSuspendedRuns()
75
+ // (chunk-3S5BFAEP.js:49532) enumerates
76
+ // `listWorkflowRuns({ workflowName: 'agentic-loop', status:
77
+ // 'suspended' })`; both then narrow the rows identically, by the
78
+ // snapshot's agentId plus the caller's OWN optional threadId/resourceId
79
+ // (:6962-6981 and :49563-49586). Neither consults the host topology's
80
+ // per-principal run-ownership checks (resourceAccess().owner('run', …)),
81
+ // so either one hands a caller ids for runs it does not own. Run listing
82
+ // is the topology's job.
83
+ //
84
+ // (3) The resume family, in chunk-XMEACVLS.js: resume() (:6072) and its
85
+ // funnels resumeStream() (:6650), resumeGenerate() (:6878),
86
+ // approveToolCall() (:6669), declineToolCall() (:6676) and 1.53.0's
87
+ // approveToolCallGenerate() (:6679) / declineToolCallGenerate() (:6683),
88
+ // plus the new resume(..., { toolCallId }) which only forwards toolCallId
89
+ // as run.resume's `label` (:6293). None of them MINTS — each takes the
90
+ // runId from its caller — which is why they were merely unwired before.
91
+ // 1.53.0 changed that: resume() no longer requires a live registry entry,
92
+ // and on a miss it loads the persisted snapshot (:6075-6076), rehydrates
93
+ // via prepare() (:6115) with the full application processor chain, then
94
+ // re-drives with createRun + run.resume (:6281/:6293) below
95
+ // executeWorkflow. That is the same second execution path recovery opens,
96
+ // so it earns the same refusal rather than a comment asking hosts not to
97
+ // call it.
98
+ //
99
+ // Agent-level surface (offsets in chunk-3S5BFAEP.js at 1.53.0 unless another
100
+ // chunk or file is named). The base `Agent` carries 82 own members
101
+ // DurableAgent does not shadow. Every one of them has been read and
102
+ // dispositioned into exactly one of the three buckets below, and
103
+ // durable-agent-surface.test.ts pins that partition by name the same way it
104
+ // pins the 87-member durable one — so the invariant holds over the WHOLE
105
+ // inherited surface, not just the durable half, and stays holding on a bump.
106
+ //
107
+ // BLOCKED outright, because each is its own execution path:
108
+ // - listSuspendedRuns() (:49532), the one direct data-returning discovery
109
+ // member — the discovery ground.
110
+ // - the network family: network() (:49263) and resumeNetwork() (:49326)
111
+ // start and resume THE SAME networkLoop (:32496), which compiles its own
112
+ // workflow and drives it with `mainWorkflow.createRun` (:32968) +
113
+ // `run.stream` (:32990) / `run.resumeStream` (:32985) on the default
114
+ // engine. network() also MINTS: `runId = mergedOptions?.runId ||
115
+ // this.#mastra?.generateId() || randomUUID()` (:49272) — the exact
116
+ // unowned fallback the host-owned run-id rule forbids.
117
+ // approveNetworkToolCall() (:49382) and declineNetworkToolCall()
118
+ // (:49400) are one-line forwards to resumeNetwork(). None of them
119
+ // dispatches through a blocked method, so each needs its own override.
120
+ // - the legacy family: generateLegacy() (:50414) and streamLegacy()
121
+ // (:50417) forward into AgentLegacyHandler (:41721-42751), which converts
122
+ // and RUNS the agent's tools, mints `runId = args.runId ||
123
+ // mastra.generateId() || randomUUID()`, and skips the authorization gate
124
+ // every supported entry calls (requireAgentExecutionFGA, defined :48798,
125
+ // called from generate :49420, stream :49858, resumeStream :50002,
126
+ // resumeGenerate :50105, and durable stream/resume/generate
127
+ // chunk-XMEACVLS.js:5918/6158/6718 — seven sites, none of them on the
128
+ // network or legacy path). It touches no persisted workflow run state, so
129
+ // it is convicted on minting plus the skipped gate, not on re-drive.
130
+ // - sendToolApproval() (:50254), which has four exits and only one of them
131
+ // is the funnel its name suggests. With `messages && approved` it calls
132
+ // agentThreadStreamRuntime.continueWithMessages() (:50266), where
133
+ // `const runId = target.runId ?? randomUUID()` (chunk-P4Y2BJL7.js:6752)
134
+ // mints and `agent.stream(..., { runId })` (:6720) then starts a run
135
+ // under that core-minted id — path-safe, so #assertCallerRunId cannot
136
+ // tell it from a host-minted one. With no active thread run id it calls
137
+ // this.listSuspendedRuns() (:50287), already blocked. Only its tail
138
+ // reaches this.resumeStream() (:50338) / this.sendStreamResume()
139
+ // (:50345). The mint is the conviction.
140
+ //
141
+ // LEFT INHERITED as funnellers, because virtual dispatch already lands them
142
+ // on an override: resumeStreamUntilIdle() (:49954 -> agent.resumeStream) and
143
+ // sendStreamResume() (:50212 -> this.resumeStream) reach the BLOCKED
144
+ // resumeStream. The five signal senders stay inherited because every outcome
145
+ // they can produce lands on this runner's terminal path; queueMessage has no
146
+ // remaining thread-route caller but keeps the same containment property.
147
+ //
148
+ // FlowSafe's queue and state routes, plus persist outcomes from wake routes,
149
+ // require agent memory and answer `memory-unavailable` without it. Owner
150
+ // notifications follow core's policy and treat their memory write as
151
+ // best-effort because the inbox row is already durable. Non-owner
152
+ // notifications are record-only until the trusted dispatcher delivers them.
153
+ // Direct sender calls can still reach core's minting sites: the idle wake
154
+ // (:7441), continuation (:6720), completion drain (:6665), and queued-id
155
+ // drain (:6808), all in chunk-P4Y2BJL7.js.
156
+ // executeWorkflow therefore treats a missing #startRequesters entry as a
157
+ // terminal refusal: it preserves the serialized input when memory permits,
158
+ // except route deliveries marked persistence-forbidden in non-rendered
159
+ // signal metadata, publishes ERROR, and never calls RunnerRuntime.
160
+ //
161
+ // Core registers thread state only when stream options carry a memory
162
+ // thread (chunk-P4Y2BJL7.js:6557-6594). For those runs its completion
163
+ // watcher consumes the failed output, removes the run maps, publishes
164
+ // run-completed, and releases or transfers the lease (:6596-6624).
165
+ // getThreadState heals a non-blocking record (:6235-6246), but neither it
166
+ // nor getActiveThreadRunId heals a record-less active id. This is why the
167
+ // refusal is terminal instead of synchronous: the idle-wake site is
168
+ // wrapped (:7440-7462), while #drainPendingSignals' call at :6665 has no
169
+ // failure cleanup. Upstream note: #drainPendingSignals needs failure
170
+ // cleanup before a synchronous refusal would be safe there. Upstream note:
171
+ // DurableAgent does not forward the wrapped Agent's `notifications`
172
+ // configuration, so the wrapper cannot inject a delivery policy.
173
+ // If both runner publication attempts and core's own fire-and-forget attempt
174
+ // fail, the terminal output never closes and the thread remains active until
175
+ // eviction or a new host start.
176
+ //
177
+ // LEFT INHERITED as non-execution, on a read of each: the base delegators
178
+ // resume/recover/listActiveRuns/recoverActiveRuns/prepare (:50497 onward) are
179
+ // shadowed by DurableAgent and overridden here, so they are unreachable on
180
+ // this instance; `observe` is likewise shadowed by DurableAgent but is NOT
181
+ // overridden and must not be — it only reattaches to a run's pubsub replay,
182
+ // and resumeViaRuntime() calls this.observe() itself after rehydration;
183
+ // `durable` (:44568) is a field accessor; subscribeToThread() (:49500) and
184
+ // getActiveThreadRunId() (:49507) read only the in-process pubsub registry,
185
+ // never storage; abortThreadStream() (:49600) and abortRunStream() (:49603)
186
+ // can stop a stream but not drive one; and genTitle() (:46377) /
187
+ // generateTitleFromUserMessage() (:46296) call `llm.stream`/`llm.__text` with
188
+ // no tools, no run id and no run state.
189
+ //
190
+ // Two residuals remain outside this class's reach rather than overlooked.
191
+ // Mastra.restartAllActiveWorkflowRuns() is Mastra-level, not an agent member —
192
+ // nothing here calls it, and it would hit core's processor-rebuild fallback if
193
+ // a host did. getLegacyHandler() (:45595) is TS-private but runtime-public and
194
+ // returns the very handler the legacy pair refuses; that is the same class of
195
+ // caveat as getWorkflow() returning a startable object, and reaching it takes a
196
+ // deliberate private cast, which is a first-party act.
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.
208
+ //
209
+ // Blocking them keeps the single-resume and no-capability guarantees true by
210
+ // construction: resumeViaRuntime() is the ONLY way a run resumes.
211
+ // ApprovalService.decide -> the host's ResumeRunFn ->
212
+ // createAgentApprovalResumer, which hands every 'durable-agentic-loop' record to
213
+ // the thread topology's resume (-> resumeViaRuntime -> runtime.resume) and
214
+ // refuses one carrying no agent-thread target rather than falling through to the
215
+ // generic resumer; grants are derived on the (suspendedAt, resumeCount)
216
+ // fingerprint there. Blocking does not un-brand the agent — DurableAgentLike
217
+ // duck-types on `recover`/`recoverActiveRuns` merely BEING functions
218
+ // (chunk-3S5BFAEP.js:204), which the overrides still are. The surface tripwire in
219
+ // durable-agent-surface.test.ts requires every DurableAgent prototype member to
220
+ // stay classified, so a future peer bump surfaces whatever it adds.
50
221
  //
51
222
  // Live-isolate scope: the loop resolves the tool's execute closure from the
52
223
  // in-process globalRunRegistry (populated by stream()). A DO holds one run in
53
- // one isolate (P1), so a resume decided before eviction finds it. A resume
224
+ // one isolate, so a resume decided before eviction finds it. A resume
54
225
  // AFTER eviction must first rehydrate that registry without replaying
55
226
  // application input processors. resumeViaRuntime() rebuilds the registry with
56
227
  // complete runtime processor lists after invoking only reserved RBAC during
57
228
  // empty-message preparation, then drives runtime.resume().
229
+ import { isMastraSignalMessage, MessageList, mastraDBMessageToSignal, } from '@mastra/core/agent';
58
230
  import { DurableAgent, globalRunRegistry, prepareForDurableExecution, } from '@mastra/core/agent/durable';
59
231
  import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
60
232
  import { InvalidRunRequestError, isPathSafeId, } from '../do-runner/index.js';
@@ -64,6 +236,14 @@ import { InvalidRunRequestError, isPathSafeId, } from '../do-runner/index.js';
64
236
  * the registered id without a magic string.
65
237
  */
66
238
  export const DURABLE_AGENTIC_LOOP_WORKFLOW_ID = 'durable-agentic-loop';
239
+ const UNOWNED_INPUT_PERSIST_TIMEOUT_MS = 5_000;
240
+ const UNREGISTERED_RUN_REFUSAL_PREFIX = 'Flowsafe durable-agent runner refused unregistered run: ';
241
+ /**
242
+ * @internal Metadata key that prevents a route delivery from being terminally
243
+ * persisted. Deliberately deep-imported by `signals/thread-do-routes.ts` and
244
+ * kept off `./index.js`.
245
+ */
246
+ export const FLOWSAFE_PERSISTENCE_FORBIDDEN = 'flowsafe.persistence-forbidden';
67
247
  const BREAKWATER_GUARDED_AGENT_HOST_PROTOCOL = Symbol.for('@proofoftech/breakwater/guarded-agent-host/v1');
68
248
  function snapshotDurableCallOptions(options) {
69
249
  if (options === undefined)
@@ -107,6 +287,92 @@ export function breakwaterGuardedAgentHostProtocol(agent) {
107
287
  }
108
288
  return protocol;
109
289
  }
290
+ /**
291
+ * Why every member of the resume family is refused. Homed once: the seven
292
+ * entry points are one code path (resumeStream/resumeGenerate/the approve and
293
+ * decline pairs all funnel into resume()), so one sentence must not drift into
294
+ * seven.
295
+ */
296
+ const RESUME_FAMILY_REASON = "on a run-registry miss the inherited path rehydrates from persisted snapshot storage and re-drives with createRun + run.resume outside RunnerRuntime, bypassing the approval-decision path's grant derivation and the fail-closed registry rehydration";
297
+ /**
298
+ * Why the four network entry points are refused. Homed once: `network()` starts
299
+ * and `resumeNetwork()` resumes THE SAME networkLoop, and the approve/decline
300
+ * pair are one-line forwards to `resumeNetwork()`, so one sentence must not
301
+ * drift into four.
302
+ */
303
+ const NETWORK_FAMILY_REASON = 'the multi-agent network loop compiles its own workflow and drives it with createRun plus run.stream/run.resumeStream on the default engine, outside RunnerRuntime, so no leg is run-owned, grant-derived or snapshot-provenanced — and under autoResumeSuspendedTools it additionally recovers a suspended run id from thread memory and re-drives that run';
304
+ /**
305
+ * Why both legacy execution entry points are refused. Homed once: each is a
306
+ * one-line forward into the SAME AgentLegacyHandler, so they are one code path
307
+ * wearing two names.
308
+ */
309
+ const LEGACY_FAMILY_REASON = "the AI SDK v4 legacy handler is a second execution surface that converts and runs the agent's tools outside RunnerRuntime, mints its own run id when the caller omits one, and skips the authorization gate every supported entry calls (requireAgentExecutionFGA)";
310
+ /**
311
+ * Why the thread-level tool approval is refused. Its name promises a resume,
312
+ * but its continuation branch STARTS a run under a core-minted id — a mint on
313
+ * the far side of a method that never asks the caller for one.
314
+ */
315
+ const THREAD_TOOL_APPROVAL_REASON = 'the messages-plus-approved branch does not resume at all: it hands the thread runtime a continuation whose run id falls back to randomUUID() when the caller names none, then starts a run under that id — path-safe, so the host-owned run-id guard cannot tell it from a caller-minted one — and its no-active-run branch reaches the equally unscoped suspended-run discovery';
316
+ /**
317
+ * Why each blocked entry point is refused, keyed by method name. The SINGLE
318
+ * source: every override throws `unavailableRunEntry(name,
319
+ * BLOCKED_RUN_ENTRIES[name])`, and durable-agent-surface.test.ts derives both
320
+ * its blocked-member partition and its per-method message assertions from these
321
+ * keys — so a new blocked entry cannot ship with an unexercised refusal, and a
322
+ * reason cannot drift between the throw and the test.
323
+ *
324
+ * Four grounds. The module comment walks the same members by PROVENANCE
325
+ * section (the durable surface, then the Agent surface) rather than by ground,
326
+ * so its numbering is not this list's:
327
+ * 1. re-drives a persisted run below `executeWorkflow`, where there is no
328
+ * RunnerRuntime — no run ownership, no per-leg grant, no snapshot
329
+ * provenance;
330
+ * 2. unscoped run discovery that bypasses the host topology's per-principal
331
+ * run-ownership checks and returns ids the caller does not own;
332
+ * 3. snapshot deletion owned by deployment-scoped retention;
333
+ * 4. a SECOND execution surface that runs the agent outside RunnerRuntime
334
+ * entirely, or that mints a run id below the caller — the network loop's
335
+ * own workflow, the legacy handler, and the thread runtime's tool-approval
336
+ * continuation.
337
+ *
338
+ * Deliberately NOT re-exported from `./index.js` (a named-exports-only barrel),
339
+ * so this stays off the public `@proofoftech/flowsafe/agent-runner` subpath.
340
+ */
341
+ export const BLOCKED_RUN_ENTRIES = {
342
+ recover: 're-driving a persisted run bypasses run ownership, per-leg grant minting and the fail-closed registry rehydration',
343
+ recoverActiveRuns: 'bulk re-driving persisted runs bypasses run ownership and per-leg grant minting',
344
+ resume: RESUME_FAMILY_REASON,
345
+ resumeStream: RESUME_FAMILY_REASON,
346
+ resumeGenerate: RESUME_FAMILY_REASON,
347
+ approveToolCall: RESUME_FAMILY_REASON,
348
+ declineToolCall: RESUME_FAMILY_REASON,
349
+ approveToolCallGenerate: RESUME_FAMILY_REASON,
350
+ declineToolCallGenerate: RESUME_FAMILY_REASON,
351
+ 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",
352
+ 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",
353
+ deleteRunSnapshots: 'durable-agent snapshot rows are retained until deployment-scoped retention purge removes them',
354
+ network: `${NETWORK_FAMILY_REASON}, and it mints an unowned run id when the caller omits one`,
355
+ resumeNetwork: NETWORK_FAMILY_REASON,
356
+ approveNetworkToolCall: NETWORK_FAMILY_REASON,
357
+ declineNetworkToolCall: NETWORK_FAMILY_REASON,
358
+ generateLegacy: LEGACY_FAMILY_REASON,
359
+ streamLegacy: LEGACY_FAMILY_REASON,
360
+ sendToolApproval: THREAD_TOOL_APPROVAL_REASON,
361
+ };
362
+ /**
363
+ * The refusal every blocked run entry point throws. A plain `Error`, not
364
+ * {@link InvalidRunRequestError}: that class means "the client's run request is
365
+ * malformed" (runtime.ts homes the convention — client input is an
366
+ * InvalidRunRequestError, a developer-controlled mistake is a plain Error), and
367
+ * calling one of these is neither a run request nor recoverable by fixing an
368
+ * argument. Same voice as #rehydrateRegistry's fail-closed throw. The message
369
+ * names WHAT is refused and WHY, and carries no run data — the discovery
370
+ * entries have none to carry, and the others must not echo an id the caller may
371
+ * not own into its log.
372
+ */
373
+ function unavailableRunEntry(method, why) {
374
+ return new Error(`FlowsafeDurableAgent.${method}() is unavailable: ${why} — the durable-agentic-loop runs only through RunnerRuntime (executeWorkflow), and resume flows only through the approval-decision path (resumeViaRuntime)`);
375
+ }
110
376
  function bindThreadCompletion(output, completion) {
111
377
  return new Proxy(output, {
112
378
  get(target, property, receiver) {
@@ -125,22 +391,18 @@ function bindThreadCompletion(output, completion) {
125
391
  });
126
392
  }
127
393
  /**
128
- * Brand marking an agent as RUNTIME-DRIVEN: its inherited signal wake
129
- * (`agent.stream` under `ifIdle:'wake'`) re-enters the host-owned-run-ID guard in
130
- * {@link FlowsafeDurableAgent.executeWorkflow}, which drives
131
- * `runtime.start('durable-agentic-loop', …)` rather than the base
132
- * `createRun + run.start` on the default engine. The thread-Durable-Object signal
133
- * routes require this brand before honoring an idle wake, because the wake is the
134
- * one signal path that starts a run: a plain core `Agent` (or a STOCK
135
- * `DurableAgent`, whose `stream()` mints an unowned UUID and whose
136
- * `executeWorkflow` runs on the default engine) would start a run OUTSIDE
137
- * RunnerRuntime — an unsafe second execution path that is unscoped and
138
- * grant-underivable. Structural (a `unique symbol`-keyed truthy field) so a test
139
- * double can opt in without constructing a real durable agent.
394
+ * Brand marking an agent as runtime-driven. The thread Durable Object requires
395
+ * it before its message, signal, schedule, or notification-dispatch wake seam
396
+ * may start a run. Queue and state persist rather than wake on idle. Non-owner
397
+ * notifications are recorded for the trusted dispatcher and never send a
398
+ * signal directly. An unbranded agent reports
399
+ * `degraded: 'not-runtime-driven'` on state and owner-notification responses
400
+ * that reach the sender, regardless of thread state. Skipped state and
401
+ * `memory-unavailable` responses return earlier and carry no marker.
140
402
  *
141
- * The brand is paired with the host-owned idle-start seam: the thread Durable Object
142
- * mints the run id and invokes the wrapper directly, avoiding core's unowned
143
- * idle-wake id generation.
403
+ * Direct core sender calls that mint a run still reach the durable runner,
404
+ * which fails them terminally without executing. Structural so a test double
405
+ * can opt in without constructing a real durable agent.
144
406
  */
145
407
  export const RUNTIME_DRIVEN_AGENT = Symbol('flowsafe.runtimeDrivenAgent');
146
408
  /**
@@ -174,7 +436,17 @@ export class FlowsafeDurableAgent extends DurableAgent {
174
436
  #startRequesters = new Map();
175
437
  #startRequesterKinds = new Map();
176
438
  #startAttemptTokens = new Map();
439
+ /**
440
+ * runId -> the reservation key the thread topology took for this start, so
441
+ * `executeWorkflow` can hand it to `RunnerRuntime.start` for the execution
442
+ * fence's proof-only match. Same lifetime and same cleanup as the attempt
443
+ * token beside it: registered by `streamUntilPersisted`, dropped in its
444
+ * `finally`, so nothing outlives the start it belongs to.
445
+ */
446
+ #startIdempotencyKeys = new Map();
177
447
  #startScheduleDispatches = new Map();
448
+ // The host's exact options object receives one private, single-use re-entry ticket.
449
+ #hostStreamTickets = new WeakSet();
178
450
  constructor(options) {
179
451
  const guardedProtocol = breakwaterGuardedAgentHostProtocol(options.agent);
180
452
  super({
@@ -182,8 +454,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
182
454
  id: options.id,
183
455
  name: options.name,
184
456
  cache: options.cache,
185
- // Default the agent's own stream pubsub to the runtime's identity (DL-001:
186
- // ONE feed per DO), so a host that configures only init()'s pubsub still
457
+ // Default the agent's own stream pubsub to the runtime's identity (ONE
458
+ // feed per DO), so a host that configures only init()'s pubsub still
187
459
  // gets observe()/emitError aligned with the run's events (the run is driven
188
460
  // through the runtime, which publishes on THAT identity). An explicit
189
461
  // pubsub wins; both-absent falls to core's per-agent default (poll-only,
@@ -200,7 +472,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
200
472
  * Host-owned run-ID enforcement at the public boundary. The durable-agent entry points (stream /
201
473
  * generate / prepare) take an OPTIONAL runId, and when it is omitted core's
202
474
  * `prepareForDurableExecution` mints `crypto.randomUUID()`
203
- * (agent/durable/index.js:589) — the exact unowned fallback this wrapper forbids —
475
+ * (agent/durable/index.js:589 — a 1.50.0-vintage offset, since that file is a
476
+ * re-export shim from 1.53.0) — the exact unowned fallback this wrapper forbids —
204
477
  * and hands it to `executeWorkflow` BELOW this class's own guard, where a bare
205
478
  * UUID is already indistinguishable from a legitimately caller-minted one. So
206
479
  * the guard must ALSO fire HERE, before `super.stream()/generate()/prepare()`,
@@ -213,7 +486,26 @@ export class FlowsafeDurableAgent extends DurableAgent {
213
486
  */
214
487
  #assertCallerRunId(runId) {
215
488
  if (!isPathSafeId(runId)) {
216
- 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');
489
+ 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');
490
+ }
491
+ }
492
+ /**
493
+ * Refuse every run id that is still registered on any start or core seam.
494
+ * `#startRequesters` alone is insufficient because `streamUntilPersisted()`
495
+ * removes it after the first summary while a suspended stream stays live.
496
+ * The internal registry has no TTL, so it also covers long suspensions after
497
+ * the global registry's ten-minute TTL expires.
498
+ * The one exemption is the host's own first start: `streamUntilPersisted()`
499
+ * stamps its exact options object with a single-use ticket that `stream()`
500
+ * consumes. A private `WeakSet`, a locally constructed object, and first-use
501
+ * consumption make that exemption unavailable to callers.
502
+ */
503
+ #assertRunIdNotLive(runId) {
504
+ if (this.#startRequesters.has(runId) ||
505
+ this.#persistenceWaiters.has(runId) ||
506
+ globalRunRegistry.has(runId) ||
507
+ this.runRegistryInternal.has(runId)) {
508
+ throw new InvalidRunRequestError('run id is live in the run registry — a registered run cannot be re-entered');
217
509
  }
218
510
  }
219
511
  #assertGuardedStructuredOutput(options) {
@@ -233,8 +525,13 @@ export class FlowsafeDurableAgent extends DurableAgent {
233
525
  * A host mints an opaque path-safe id and passes it as `options.runId`.
234
526
  */
235
527
  async stream(messages, options) {
528
+ const hostStreamTicket = options !== undefined && this.#hostStreamTickets.has(options);
529
+ if (hostStreamTicket)
530
+ this.#hostStreamTickets.delete(options);
236
531
  const callOptions = snapshotDurableCallOptions(options);
237
532
  this.#assertCallerRunId(callOptions?.runId);
533
+ if (!hostStreamTicket)
534
+ this.#assertRunIdNotLive(callOptions.runId);
238
535
  this.#assertGuardedStructuredOutput(callOptions);
239
536
  const result = await super.stream(messages, callOptions);
240
537
  if (!callOptions?.untilIdle) {
@@ -250,13 +547,33 @@ export class FlowsafeDurableAgent extends DurableAgent {
250
547
  * workflow starts asynchronously. Agent hosts need an authoritative summary
251
548
  * before answering a start request, but must keep the stream subscription
252
549
  * and replay cache intact for later HTTP observation.
550
+ * It stamps the locally constructed stream options with the private,
551
+ * single-use host ticket that permits only this first call through `stream()`.
253
552
  *
254
553
  * @internal
255
554
  */
256
- async streamUntilPersisted(messages, options, requestedBy, requestedByKind, attemptToken = crypto.randomUUID(), scheduleDispatch) {
555
+ async streamUntilPersisted(messages, options, requestedBy, requestedByKind, attemptToken = crypto.randomUUID(), scheduleDispatch,
556
+ /**
557
+ * The idempotency key the thread topology already RESERVED for this run.
558
+ *
559
+ * It travels down here for one job: the execution fence's proof-only state
560
+ * admits exactly the start whose key matches its nominated proof key, and
561
+ * `RunnerRuntime.start` is where that comparison happens. It buys no
562
+ * exactly-once property at this layer — the reservation above already did —
563
+ * so nothing here validates it beyond passing it on, and a run started
564
+ * without one behaves exactly as before.
565
+ *
566
+ * Parked per-runId beside the attempt token rather than threaded through
567
+ * core, because core owns the call between `stream()` and
568
+ * `executeWorkflow()` and carries no field this could ride in.
569
+ */
570
+ idempotencyKey) {
257
571
  const callOptions = snapshotDurableCallOptions(options);
258
572
  this.#assertCallerRunId(callOptions?.runId);
259
573
  this.#assertGuardedStructuredOutput(callOptions);
574
+ if (callOptions.untilIdle) {
575
+ throw new InvalidRunRequestError('streamUntilPersisted does not support untilIdle');
576
+ }
260
577
  if (!isExecutionPrincipalId(requestedBy)) {
261
578
  throw new InvalidRunRequestError('requestedBy is malformed');
262
579
  }
@@ -264,9 +581,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
264
581
  throw new InvalidRunRequestError('requestedByKind is malformed');
265
582
  }
266
583
  const runId = callOptions.runId;
267
- if (this.#persistenceWaiters.has(runId)) {
268
- throw new InvalidRunRequestError(`run '${runId}' already has a pending durable start`);
269
- }
584
+ this.#assertRunIdNotLive(runId);
270
585
  let resolve;
271
586
  let reject;
272
587
  const persisted = new Promise((resolvePromise, rejectPromise) => {
@@ -281,9 +596,12 @@ export class FlowsafeDurableAgent extends DurableAgent {
281
596
  if (scheduleDispatch) {
282
597
  this.#startScheduleDispatches.set(runId, scheduleDispatch);
283
598
  }
599
+ if (idempotencyKey !== undefined) {
600
+ this.#startIdempotencyKeys.set(runId, idempotencyKey);
601
+ }
284
602
  const onError = callOptions.onError;
285
603
  try {
286
- const result = await this.stream(messages, {
604
+ const hostCallOptions = {
287
605
  ...callOptions,
288
606
  onError: async (data) => {
289
607
  reject(data.error instanceof Error
@@ -291,7 +609,9 @@ export class FlowsafeDurableAgent extends DurableAgent {
291
609
  : new Error(String(data.error)));
292
610
  await onError?.(data);
293
611
  },
294
- });
612
+ };
613
+ this.#hostStreamTickets.add(hostCallOptions);
614
+ const result = await this.stream(messages, hostCallOptions);
295
615
  await persisted;
296
616
  return result;
297
617
  }
@@ -301,6 +621,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
301
621
  this.#startRequesterKinds.delete(runId);
302
622
  this.#startAttemptTokens.delete(runId);
303
623
  this.#startScheduleDispatches.delete(runId);
624
+ this.#startIdempotencyKeys.delete(runId);
304
625
  }
305
626
  }
306
627
  /**
@@ -312,26 +633,256 @@ export class FlowsafeDurableAgent extends DurableAgent {
312
633
  async generate(messages, options) {
313
634
  const callOptions = snapshotDurableCallOptions(options);
314
635
  this.#assertCallerRunId(callOptions?.runId);
636
+ this.#assertRunIdNotLive(callOptions.runId);
315
637
  this.#assertGuardedStructuredOutput(callOptions);
316
- return super.generate(messages, callOptions);
638
+ try {
639
+ return await super.generate(messages, callOptions);
640
+ }
641
+ catch (error) {
642
+ // Core reconstructs an ERROR chunk with `new Error(message)` plus `name`,
643
+ // which loses the InvalidRunRequestError prototype before generate sees it.
644
+ if (error instanceof Error &&
645
+ error.name === 'InvalidRunRequestError' &&
646
+ error.message.startsWith(UNREGISTERED_RUN_REFUSAL_PREFIX) &&
647
+ !(error instanceof InvalidRunRequestError)) {
648
+ const wrapped = new InvalidRunRequestError(error.message);
649
+ Object.defineProperty(wrapped, 'cause', { value: error });
650
+ throw wrapped;
651
+ }
652
+ throw error;
653
+ }
317
654
  }
318
655
  /**
319
656
  * The same host-owned run-ID guard as {@link FlowsafeDurableAgent.stream}.
320
657
  * `prepare()`
321
658
  * is the third inherited minting entry point: it forwards `options?.runId` into
322
659
  * core's `prepareForDurableExecution` (agent/durable/index.js:5980), which mints
323
- * an unowned `crypto.randomUUID()` when it is absent (index.js:589) AND
324
- * REGISTERS a run under that id (index.js:5984) — so a later
660
+ * an unowned `crypto.randomUUID()` when it is absent
661
+ * (agent/durable/index.js:589) AND REGISTERS a run under that id
662
+ * (agent/durable/index.js:5984 — all three are 1.50.0-vintage offsets, since
663
+ * that file is a re-export shim from 1.53.0) — so a later
325
664
  * `resume(runId)`/`executeWorkflow` sees a bare UUID `PATH_SAFE_ID_PATTERN`
326
- * already accepts, past every downstream guard. Enforce the caller-minted ID here, while
327
- * "absent" is still visible.
665
+ * already accepts, past every downstream guard. Enforce the caller-minted ID
666
+ * here, while "absent" is still visible. A prepared id remains live until core
667
+ * cleans up the run, so later `stream()`, `generate()`, `prepare()`, and
668
+ * `streamUntilPersisted()` calls carrying that id are refused.
328
669
  */
329
670
  async prepare(messages, options) {
330
671
  const callOptions = snapshotDurableCallOptions(options);
331
672
  this.#assertCallerRunId(callOptions?.runId);
673
+ this.#assertRunIdNotLive(callOptions.runId);
332
674
  this.#assertGuardedStructuredOutput(callOptions);
333
675
  return super.prepare(messages, callOptions);
334
676
  }
677
+ /**
678
+ * Refuse core's single-run recovery. `DurableAgent.recover()` loads the
679
+ * persisted `durable-agentic-loop` snapshot, rebuilds model/memory/processors
680
+ * from it and re-drives the run with `createRun + run.restart()` — a second
681
+ * execution path that never enters `executeWorkflow`, so no leg of it is
682
+ * grant-derived, run-owned or snapshot-provenanced. Throw BEFORE the storage
683
+ * read, so a mistaken call cannot even enumerate a run.
684
+ */
685
+ async recover(_runId, _options) {
686
+ throw unavailableRunEntry('recover', BLOCKED_RUN_ENTRIES.recover);
687
+ }
688
+ /**
689
+ * Refuse core's bulk recovery. `recoverActiveRuns()` is
690
+ * {@link FlowsafeDurableAgent.listActiveRuns} plus a `recover()` per row, and
691
+ * it is what `Mastra.recoverAllDurableAgents()` calls on every registered
692
+ * durable agent — so this is the one blocked entry point a host can reach
693
+ * without a FlowSafe call site, by opting into `recovery: { durableAgents:
694
+ * 'auto' }`. That loop isolates each agent in its own try/catch, so this
695
+ * refusal is logged there rather than failing boot. Refuse with an explicit
696
+ * `runId` too: a single target is still a re-drive off RunnerRuntime.
697
+ */
698
+ async recoverActiveRuns(_options) {
699
+ throw unavailableRunEntry('recoverActiveRuns', BLOCKED_RUN_ENTRIES.recoverActiveRuns);
700
+ }
701
+ /**
702
+ * Refuse core's recovery discovery API. `listActiveRuns()` enumerates
703
+ * `listWorkflowRuns({ workflowName: 'durable-agentic-loop', status:
704
+ * 'running' })` narrowed by `agentId` plus the optional
705
+ * `threadId`/`resourceId` filters the CALLER supplies, so it never consults
706
+ * the host topology's per-principal run-ownership checks
707
+ * (`resourceAccess().owner('run', …)`) and hands the caller run ids, thread
708
+ * ids and resource ids for runs it does not own. Host run listing is the
709
+ * topology's job, where ownership is checked.
710
+ */
711
+ async listActiveRuns(_options) {
712
+ throw unavailableRunEntry('listActiveRuns', BLOCKED_RUN_ENTRIES.listActiveRuns);
713
+ }
714
+ /**
715
+ * Refuse the Agent-level analogue of
716
+ * {@link FlowsafeDurableAgent.listActiveRuns}. `listSuspendedRuns()` reads
717
+ * the workflows store directly —
718
+ * `listWorkflowRuns({ workflowName: 'agentic-loop', status: 'suspended' })`
719
+ * — and narrows by `agentId` plus the optional `threadId`/`resourceId`
720
+ * filters the CALLER supplies, the same scoping `listActiveRuns()` applies.
721
+ * Same ground too: an unfiltered call returns run, thread and resource ids
722
+ * across every principal that shares the agent. It is the one direct
723
+ * data-returning discovery member the base `Agent` surface adds; the other
724
+ * additions funnel through `this.resumeStream()` and so fail closed on that
725
+ * override.
726
+ */
727
+ async listSuspendedRuns(_options) {
728
+ throw unavailableRunEntry('listSuspendedRuns', BLOCKED_RUN_ENTRIES.listSuspendedRuns);
729
+ }
730
+ /**
731
+ * Refuse the multi-agent network start. `network()` does not touch the
732
+ * durable-agentic-loop at all: it compiles a SEPARATE workflow and drives it
733
+ * with `createRun + run.stream` on the default engine, so the whole
734
+ * collaboration — every sub-agent leg and every tool call inside it — runs
735
+ * with no per-leg grant context, no snapshot provenance and no RunSummary.
736
+ * It also mints `options.runId || mastra.generateId() || randomUUID()`, the
737
+ * exact unowned fallback this runner forbids: the host mints every run id.
738
+ *
739
+ * Signature caveat: the base method is OVERLOADED and generic in OUTPUT, so
740
+ * `Parameters<>` sees only the LAST overload and is too narrow to satisfy the
741
+ * first. The options parameter is therefore widened to `unknown` — the one
742
+ * supertype that satisfies every overload at once. Re-check on every peer
743
+ * bump; nothing here fails if core changes the shape.
744
+ */
745
+ async network(_messages, _options) {
746
+ throw unavailableRunEntry('network', BLOCKED_RUN_ENTRIES.network);
747
+ }
748
+ /**
749
+ * Refuse the network resume — same loop and same ground as
750
+ * {@link FlowsafeDurableAgent.network}, plus one fact of its own: under
751
+ * `autoResumeSuspendedTools` it RECOVERS a suspended run id out of thread
752
+ * memory, so a caller need not even name the run it re-drives.
753
+ */
754
+ async resumeNetwork(_resumeData, _options) {
755
+ throw unavailableRunEntry('resumeNetwork', BLOCKED_RUN_ENTRIES.resumeNetwork);
756
+ }
757
+ /**
758
+ * Refuse the network tool-approval resume. It is a one-line forward to
759
+ * {@link FlowsafeDurableAgent.resumeNetwork}; blocking it here closes the
760
+ * same door from the side a tool-approval caller reaches for.
761
+ */
762
+ async approveNetworkToolCall(_options) {
763
+ throw unavailableRunEntry('approveNetworkToolCall', BLOCKED_RUN_ENTRIES.approveNetworkToolCall);
764
+ }
765
+ /** The decline half of {@link FlowsafeDurableAgent.approveNetworkToolCall}. */
766
+ async declineNetworkToolCall(_options) {
767
+ throw unavailableRunEntry('declineNetworkToolCall', BLOCKED_RUN_ENTRIES.declineNetworkToolCall);
768
+ }
769
+ /**
770
+ * Refuse the AI SDK v4 legacy execution path. `generateLegacy()` forwards
771
+ * into AgentLegacyHandler, which converts and RUNS the agent's tools while
772
+ * bypassing RunnerRuntime entirely, mints its own run id when the caller
773
+ * omits one, and skips `requireAgentExecutionFGA` — the authorization gate
774
+ * every SUPPORTED entry point calls, so this would run the agent without it.
775
+ * (The network family skips that gate too; neither is unique in doing so.) It
776
+ * persists no workflow run state, which is why it is refused on those two
777
+ * grounds rather than as a re-drive.
778
+ *
779
+ * Signature caveat: overloaded and generic in OUTPUT on the base, so this
780
+ * signature is hand-derived and must be re-checked on every peer bump.
781
+ */
782
+ async generateLegacy(_messages, _args) {
783
+ throw unavailableRunEntry('generateLegacy', BLOCKED_RUN_ENTRIES.generateLegacy);
784
+ }
785
+ /** The streaming half of {@link FlowsafeDurableAgent.generateLegacy}. */
786
+ async streamLegacy(_messages, _args) {
787
+ throw unavailableRunEntry('streamLegacy', BLOCKED_RUN_ENTRIES.streamLegacy);
788
+ }
789
+ /**
790
+ * Refuse the thread-level tool approval. The name reads like a resume, but
791
+ * only its tail is one. Called with `messages` and `approved`, it routes to
792
+ * the thread runtime's continuation, which falls back to `randomUUID()` when
793
+ * the caller named no run id and then STARTS a run under it — an unowned id
794
+ * the host-owned run-id guard cannot distinguish from a real one, because it
795
+ * is path-safe. Called with no active thread run, it reaches the blocked
796
+ * suspended-run discovery instead. FlowSafe's own tool approval is a decided
797
+ * ApprovalRecord resumed through the approval-decision path, which mints the
798
+ * leg's grant; this mints nothing and owns nothing.
799
+ *
800
+ * Signature caveat: the base method is generic in OUTPUT, which
801
+ * `Parameters<>` instantiates to its `undefined` default and so types too
802
+ * narrowly to satisfy the base. The options parameter is widened to
803
+ * `unknown` — the one supertype that fits every instantiation. Re-check on
804
+ * every peer bump.
805
+ */
806
+ async sendToolApproval(_options) {
807
+ throw unavailableRunEntry('sendToolApproval', BLOCKED_RUN_ENTRIES.sendToolApproval);
808
+ }
809
+ /**
810
+ * Refuse core's terminal snapshot cleanup. Its only call sites are the base
811
+ * `executeWorkflow` (overridden here), the blocked `resume()` and the blocked
812
+ * `recover()`, so nothing this class drives reaches it; blocking keeps the
813
+ * snapshot rows — which deployment-scoped retention purge owns — from being
814
+ * dropped out from under that owner by a future internal caller.
815
+ *
816
+ * Note what this override buys beyond that call-site audit: the member
817
+ * inventory in durable-agent-surface.test.ts sees a NEW member, never a new
818
+ * core call site on an EXISTING one. So the override is the standing guard —
819
+ * it converts core's best-effort cleanup into a throw the moment a future
820
+ * release calls it on a path FlowSafe drives. None does at 1.53.0.
821
+ */
822
+ async deleteRunSnapshots(_runId) {
823
+ throw unavailableRunEntry('deleteRunSnapshots', BLOCKED_RUN_ENTRIES.deleteRunSnapshots);
824
+ }
825
+ /**
826
+ * Refuse core's durable resume. Until 1.53.0 this merely read the in-process
827
+ * run registry, which is why it was left inherited-but-unwired; now a registry
828
+ * MISS makes it load the persisted `durable-agentic-loop` snapshot, rehydrate
829
+ * through `prepare()` with the full application processor chain, and re-drive
830
+ * the run with `createRun + run.resume` — below `executeWorkflow`, so the leg
831
+ * carries no minted grant and no snapshot provenance.
832
+ * {@link FlowsafeDurableAgent.resumeViaRuntime} is the only resume path, and
833
+ * it is reached from the approval decision, never from a client.
834
+ */
835
+ async resume(_runId, _resumeData, _options) {
836
+ throw unavailableRunEntry('resume', BLOCKED_RUN_ENTRIES.resume);
837
+ }
838
+ /**
839
+ * Refuse the base-`Agent`-shaped resume. Core overrides `resumeStream()` on
840
+ * DurableAgent precisely so an `Agent`-API caller lands on the durable
841
+ * `resume()`; blocking it here closes that same door from the other side.
842
+ */
843
+ async resumeStream(_resumeData, _streamOptions) {
844
+ throw unavailableRunEntry('resumeStream', BLOCKED_RUN_ENTRIES.resumeStream);
845
+ }
846
+ /**
847
+ * Refuse the drain-to-completion resume. `resumeGenerate()` forwards straight
848
+ * to `resume()`, so it inherits the same below-the-seam re-drive.
849
+ */
850
+ async resumeGenerate(_runId, _resumeData, _options) {
851
+ throw unavailableRunEntry('resumeGenerate', BLOCKED_RUN_ENTRIES.resumeGenerate);
852
+ }
853
+ /**
854
+ * Refuse Mastra's own tool-approval resume. Tool approval in FlowSafe is a
855
+ * decided ApprovalRecord resumed through the approval-decision path, which
856
+ * mints the leg's connector grant; `approveToolCall()` funnels into
857
+ * `resumeStream()` -> `resume()` and mints nothing.
858
+ */
859
+ async approveToolCall(_options) {
860
+ throw unavailableRunEntry('approveToolCall', BLOCKED_RUN_ENTRIES.approveToolCall);
861
+ }
862
+ /** The decline half of {@link FlowsafeDurableAgent.approveToolCall}. */
863
+ async declineToolCall(_options) {
864
+ throw unavailableRunEntry('declineToolCall', BLOCKED_RUN_ENTRIES.declineToolCall);
865
+ }
866
+ /**
867
+ * The 1.53.0 generate-shaped tool-approval pair. They funnel into
868
+ * `resumeGenerate()` -> `resume()`, so they are the same entry point wearing a
869
+ * different return type.
870
+ *
871
+ * Signature caveat for both halves: the base method is GENERIC in its OUTPUT
872
+ * type, which `Parameters<>` cannot carry, so the parameter type below is
873
+ * hand-written rather than derived. Re-check it against the base on every
874
+ * peer bump — nothing here fails if core changes the shape.
875
+ */
876
+ async approveToolCallGenerate(_options) {
877
+ throw unavailableRunEntry('approveToolCallGenerate', BLOCKED_RUN_ENTRIES.approveToolCallGenerate);
878
+ }
879
+ /**
880
+ * The decline half of {@link FlowsafeDurableAgent.approveToolCallGenerate},
881
+ * including its hand-written-signature caveat.
882
+ */
883
+ async declineToolCallGenerate(_options) {
884
+ throw unavailableRunEntry('declineToolCallGenerate', BLOCKED_RUN_ENTRIES.declineToolCallGenerate);
885
+ }
335
886
  async #rehydrateRegistry(options) {
336
887
  const wrappedAgent = this.#wrappedAgent;
337
888
  let inputProcessors = [];
@@ -408,20 +959,6 @@ export class FlowsafeDurableAgent extends DurableAgent {
408
959
  this.#assertCallerRunId(options.runId);
409
960
  let rehydrated = false;
410
961
  let finishThreadRegistration;
411
- const emitTerminalError = async (error) => {
412
- try {
413
- await this.emitError(options.runId, error instanceof Error ? error : new Error(String(error)));
414
- }
415
- catch (publicationError) {
416
- console.error(JSON.stringify({
417
- type: 'durable-agent-resume-error-publication-failed',
418
- runId: options.runId,
419
- error: publicationError instanceof Error
420
- ? publicationError.message
421
- : String(publicationError),
422
- }));
423
- }
424
- };
425
962
  try {
426
963
  const summary = await this.#runtime.resume(this.getWorkflow().id, options.runId, {
427
964
  ...(options.step !== undefined ? { step: options.step } : {}),
@@ -452,13 +989,15 @@ export class FlowsafeDurableAgent extends DurableAgent {
452
989
  },
453
990
  });
454
991
  if (summary.status === 'failed') {
455
- await emitTerminalError(new Error(summary.error ?? 'Durable agent workflow resume failed'));
992
+ await this.#publishTerminalError(options.runId, new Error(summary.error ?? 'Durable agent workflow resume failed'));
993
+ this.runRegistryInternal.cleanup(options.runId);
994
+ globalRunRegistry.delete(options.runId);
456
995
  }
457
996
  return summary;
458
997
  }
459
998
  catch (error) {
460
999
  if (rehydrated) {
461
- await emitTerminalError(error);
1000
+ await this.#publishTerminalError(options.runId, error);
462
1001
  this.runRegistryInternal.cleanup(options.runId);
463
1002
  globalRunRegistry.delete(options.runId);
464
1003
  }
@@ -468,6 +1007,78 @@ export class FlowsafeDurableAgent extends DurableAgent {
468
1007
  finishThreadRegistration?.();
469
1008
  }
470
1009
  }
1010
+ /**
1011
+ * Publish one terminal ERROR attempt without throwing. The unregistered-run
1012
+ * terminal path retries once and throws its refusal only after registry
1013
+ * cleanup; resume publishes best-effort and preserves its summary or original
1014
+ * error. Both call sites publish before cleanup because `emitError()` closes
1015
+ * spans through the live global registry entry.
1016
+ */
1017
+ async #publishTerminalError(runId, error) {
1018
+ const terminalError = error instanceof Error ? error : new Error(String(error));
1019
+ try {
1020
+ await this.emitError(runId, terminalError);
1021
+ return true;
1022
+ }
1023
+ catch {
1024
+ console.error(JSON.stringify({
1025
+ type: 'durable-agent-terminal-error-publication-failed',
1026
+ runId,
1027
+ }));
1028
+ return false;
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Preserve unowned input before terminal refusal. A bounded best-effort write
1033
+ * prevents hung memory from blocking the ERROR that heals thread state.
1034
+ */
1035
+ async #persistUnownedInput(runId, workflowInput) {
1036
+ let timeout;
1037
+ try {
1038
+ await Promise.race([
1039
+ (async () => {
1040
+ const state = workflowInput.state;
1041
+ const threadId = state?.threadId;
1042
+ if (!threadId || state?.threadExists !== true)
1043
+ return;
1044
+ // Explicit read-only memory forbids preserving denied input.
1045
+ if (state.memoryConfig?.readOnly === true)
1046
+ return;
1047
+ const memory = await this.getMemory({
1048
+ requestContext: globalRunRegistry.get(runId)?.requestContext,
1049
+ });
1050
+ if (!memory)
1051
+ return;
1052
+ const list = new MessageList({
1053
+ threadId,
1054
+ resourceId: state.resourceId,
1055
+ }).deserialize(workflowInput.messageListState);
1056
+ const inputIds = list.makeMessageSourceChecker().input;
1057
+ const messages = list.get.all
1058
+ .db()
1059
+ .filter((message) => inputIds.has(message.id))
1060
+ // Honor markPersistenceForbidden's route-to-runner metadata contract.
1061
+ .filter((message) => !isMastraSignalMessage(message) ||
1062
+ mastraDBMessageToSignal(message).metadata?.[FLOWSAFE_PERSISTENCE_FORBIDDEN] !== true);
1063
+ if (messages.length)
1064
+ await memory.saveMessages({ messages });
1065
+ })(),
1066
+ new Promise((_resolve, reject) => {
1067
+ timeout = setTimeout(() => reject(new Error(`unowned input persistence timed out after ${UNOWNED_INPUT_PERSIST_TIMEOUT_MS} ms`)), UNOWNED_INPUT_PERSIST_TIMEOUT_MS);
1068
+ }),
1069
+ ]);
1070
+ }
1071
+ catch {
1072
+ console.error(JSON.stringify({
1073
+ type: 'durable-agent-unowned-input-persistence-failed',
1074
+ runId,
1075
+ }));
1076
+ }
1077
+ finally {
1078
+ if (timeout !== undefined)
1079
+ clearTimeout(timeout);
1080
+ }
1081
+ }
471
1082
  /**
472
1083
  * Drive the durable-agentic-loop through RunnerRuntime instead of the base
473
1084
  * `createRun + run.start`. stream()/generate() have already parked the
@@ -489,25 +1100,44 @@ export class FlowsafeDurableAgent extends DurableAgent {
489
1100
  const requestedByKind = this.#startRequesterKinds.get(runId);
490
1101
  const attemptToken = this.#startAttemptTokens.get(runId);
491
1102
  const scheduleDispatch = this.#startScheduleDispatches.get(runId);
1103
+ const idempotencyKey = this.#startIdempotencyKeys.get(runId);
492
1104
  const startOptions = {
493
1105
  runId,
494
1106
  inputData: workflowInput,
495
1107
  ...(attemptToken === undefined ? {} : { attemptToken }),
496
1108
  ...(scheduleDispatch === undefined ? {} : { scheduleDispatch }),
1109
+ ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
497
1110
  };
498
1111
  if (requestedBy === undefined || requestedByKind === undefined) {
499
1112
  if (requestedBy !== undefined || requestedByKind !== undefined) {
500
1113
  throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
501
1114
  }
502
- summary = await this.#runtime.start(this.getWorkflow().id, startOptions);
503
- }
504
- else {
505
- summary = await this.#runtime.start(this.getWorkflow().id, {
506
- ...startOptions,
507
- requestedBy,
508
- requestedByKind,
509
- });
1115
+ // No #startRequesters entry means the host start seam never registered
1116
+ // this id, so core minted it below our boundary. Such a run has no
1117
+ // ownership record or trusted engine-leg context. Preserve its input
1118
+ // when allowed, then close the stream so core can clean up its maps and
1119
+ // release the lease transferred to this id.
1120
+ await this.#persistUnownedInput(runId, workflowInput);
1121
+ const refusal = new InvalidRunRequestError(`${UNREGISTERED_RUN_REFUSAL_PREFIX}run '${runId}' was not registered by the host start seam — the durable-agent runner never executes a run it does not own`);
1122
+ let published = false;
1123
+ try {
1124
+ published =
1125
+ (await this.#publishTerminalError(runId, refusal)) ||
1126
+ (await this.#publishTerminalError(runId, refusal));
1127
+ }
1128
+ finally {
1129
+ this.runRegistryInternal.cleanup(runId);
1130
+ globalRunRegistry.delete(runId);
1131
+ }
1132
+ if (!published)
1133
+ throw refusal;
1134
+ return;
510
1135
  }
1136
+ summary = await this.#runtime.start(this.getWorkflow().id, {
1137
+ ...startOptions,
1138
+ requestedBy,
1139
+ requestedByKind,
1140
+ });
511
1141
  waiter?.resolve();
512
1142
  }
513
1143
  catch (error) {