@proofoftech/flowsafe 0.23.0 → 0.25.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 (115) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +59 -9
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +26 -2
  5. package/dist/agent-host/thread-host.js.map +1 -1
  6. package/dist/agent-runner/durable-agent-runner.d.ts +13 -19
  7. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  8. package/dist/agent-runner/durable-agent-runner.js +551 -372
  9. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  10. package/dist/approval-api/retention.d.ts.map +1 -1
  11. package/dist/approval-api/retention.js +6 -5
  12. package/dist/approval-api/retention.js.map +1 -1
  13. package/dist/approval-api/service.js +4 -4
  14. package/dist/approval-api/service.js.map +1 -1
  15. package/dist/approval-ui/use-approval-dashboard.js +6 -6
  16. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  17. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  18. package/dist/background-tasks/d1-storage.js +7 -5
  19. package/dist/background-tasks/d1-storage.js.map +1 -1
  20. package/dist/background-tasks/host.d.ts.map +1 -1
  21. package/dist/background-tasks/host.js +27 -38
  22. package/dist/background-tasks/host.js.map +1 -1
  23. package/dist/do-runner/cause-chain.d.ts +5 -0
  24. package/dist/do-runner/cause-chain.d.ts.map +1 -1
  25. package/dist/do-runner/cause-chain.js +12 -0
  26. package/dist/do-runner/cause-chain.js.map +1 -1
  27. package/dist/do-runner/cf-types.d.ts +3 -0
  28. package/dist/do-runner/cf-types.d.ts.map +1 -1
  29. package/dist/do-runner/cf-types.js.map +1 -1
  30. package/dist/do-runner/constants.d.ts +1 -1
  31. package/dist/do-runner/constants.d.ts.map +1 -1
  32. package/dist/do-runner/constants.js +1 -1
  33. package/dist/do-runner/constants.js.map +1 -1
  34. package/dist/do-runner/core-events-nonce.d.ts +2 -0
  35. package/dist/do-runner/core-events-nonce.d.ts.map +1 -0
  36. package/dist/do-runner/core-events-nonce.js +16 -0
  37. package/dist/do-runner/core-events-nonce.js.map +1 -0
  38. package/dist/do-runner/d1-storage.js +1 -9
  39. package/dist/do-runner/d1-storage.js.map +1 -1
  40. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  41. package/dist/do-runner/do-error-response.js +2 -1
  42. package/dist/do-runner/do-error-response.js.map +1 -1
  43. package/dist/do-runner/durable-object.d.ts +34 -2
  44. package/dist/do-runner/durable-object.d.ts.map +1 -1
  45. package/dist/do-runner/durable-object.js +447 -53
  46. package/dist/do-runner/durable-object.js.map +1 -1
  47. package/dist/do-runner/fenced-workflow-capability.d.ts +51 -0
  48. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  49. package/dist/do-runner/fenced-workflows-d1.d.ts +5 -1
  50. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  51. package/dist/do-runner/fenced-workflows-d1.js +236 -48
  52. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  53. package/dist/do-runner/index.d.ts +2 -2
  54. package/dist/do-runner/index.d.ts.map +1 -1
  55. package/dist/do-runner/index.js +2 -2
  56. package/dist/do-runner/index.js.map +1 -1
  57. package/dist/do-runner/init.d.ts +2 -3
  58. package/dist/do-runner/init.d.ts.map +1 -1
  59. package/dist/do-runner/init.js.map +1 -1
  60. package/dist/do-runner/memory-id.js +1 -1
  61. package/dist/do-runner/memory-id.js.map +1 -1
  62. package/dist/do-runner/pubsub.d.ts +6 -2
  63. package/dist/do-runner/pubsub.d.ts.map +1 -1
  64. package/dist/do-runner/pubsub.js +12 -22
  65. package/dist/do-runner/pubsub.js.map +1 -1
  66. package/dist/do-runner/run-lifecycle.d.ts +42 -2
  67. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  68. package/dist/do-runner/run-lifecycle.js +57 -1
  69. package/dist/do-runner/run-lifecycle.js.map +1 -1
  70. package/dist/do-runner/run-terminal-state.d.ts +2 -0
  71. package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
  72. package/dist/do-runner/run-terminal-state.js +4 -0
  73. package/dist/do-runner/run-terminal-state.js.map +1 -1
  74. package/dist/do-runner/runtime.d.ts +87 -17
  75. package/dist/do-runner/runtime.d.ts.map +1 -1
  76. package/dist/do-runner/runtime.js +455 -155
  77. package/dist/do-runner/runtime.js.map +1 -1
  78. package/dist/do-runner/suspension-deadline.d.ts +25 -17
  79. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  80. package/dist/do-runner/suspension-deadline.js +44 -21
  81. package/dist/do-runner/suspension-deadline.js.map +1 -1
  82. package/dist/do-runner/workflow-snapshot-row.d.ts +6 -0
  83. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  84. package/dist/do-runner/workflow-snapshot-row.js +17 -0
  85. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  86. package/dist/host-kit/approval-bridge.d.ts +25 -9
  87. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  88. package/dist/host-kit/approval-bridge.js +72 -15
  89. package/dist/host-kit/approval-bridge.js.map +1 -1
  90. package/dist/host-kit/do-response.d.ts.map +1 -1
  91. package/dist/host-kit/do-response.js +7 -1
  92. package/dist/host-kit/do-response.js.map +1 -1
  93. package/dist/host-kit/flowsafe-worker.d.ts +2 -1
  94. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  95. package/dist/host-kit/flowsafe-worker.js +4 -2
  96. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  97. package/dist/host-kit/run-router.d.ts +4 -1
  98. package/dist/host-kit/run-router.d.ts.map +1 -1
  99. package/dist/host-kit/run-router.js +3 -2
  100. package/dist/host-kit/run-router.js.map +1 -1
  101. package/dist/schedules/schedules-d1.d.ts +1 -0
  102. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  103. package/dist/schedules/schedules-d1.js +35 -22
  104. package/dist/schedules/schedules-d1.js.map +1 -1
  105. package/dist/schedules/tick.d.ts +17 -2
  106. package/dist/schedules/tick.d.ts.map +1 -1
  107. package/dist/schedules/tick.js +63 -44
  108. package/dist/schedules/tick.js.map +1 -1
  109. package/dist/signals/d1-shared.js +1 -1
  110. package/dist/signals/d1-shared.js.map +1 -1
  111. package/dist/signals/thread-do-routes.d.ts +8 -1
  112. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  113. package/dist/signals/thread-do-routes.js +40 -44
  114. package/dist/signals/thread-do-routes.js.map +1 -1
  115. package/package.json +10 -7
@@ -1,297 +1,71 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // FlowsafeDurableAgent — drive Mastra's durable-agent loop through the ONE
3
- // RunnerRuntime chokepoint so every agent leg inherits the substrate's
4
- // invariants.
2
+ // FlowsafeDurableAgent drives Mastra's durable-agent loop through RunnerRuntime
3
+ // so agent legs inherit its execution and lifecycle invariants.
5
4
  //
6
- // The mechanic was validated against @mastra/core 1.50.0 dist. Every offset in
7
- // THIS section is 1.50.0-vintage and kept as the provenance of the original
8
- // validation; later sections carry their own stamp:
9
- // DurableAgent compiles the agent loop to the default-engine workflow
10
- // 'durable-agentic-loop' (agent/durable index.js: AGENTIC_LOOP :62,
11
- // getWorkflow() :5936, agent-agnostic — the agent is resolved per run by the
12
- // `agentId` in the input, so ONE registered loop serves every durable agent).
13
- // `DurableAgent.stream()` resolves the non-serializable model/tools onto the
14
- // in-process globalRunRegistry (keyed by runId), builds a serializable
15
- // DurableAgenticWorkflowInput, then calls the OVERRIDABLE
16
- // `executeWorkflow(runId, workflowInput)` — the documented subclass seam
17
- // (durable-agent.d.ts: "Subclasses override this method to customize how the
18
- // workflow is executed"; EventedAgent/InngestAgent override it the same way).
19
- // The base runs it via `workflow.createRun() + run.start()`; we route it
20
- // through `runtime.start('durable-agentic-loop', { runId, inputData })` instead.
5
+ // DurableAgent.getWorkflow compiles the agent-agnostic durable-agentic-loop;
6
+ // each run resolves its agent from the input's agentId. DurableAgent.stream
7
+ // registers non-serializable dependencies in globalRunRegistry and calls the
8
+ // overridable executeWorkflow seam, which this class routes to runtime.start.
21
9
  //
22
- // Why this composes the grant-only doctrine for free: the durable tool-call
23
- // step hands `tool.execute` the ENGINE-LEG requestContext from its step params
24
- // (index.js: `const { ..., requestContext } = params` :3138 ->
25
- // `toolOptions = { ..., requestContext }` :3339 ->
26
- // `tool.execute(cleanedArgs, toolOptions)` :3642), NOT the stream()-time
27
- // registry copy. Under runtime drive that engine-leg context is exactly what
28
- // #requestContextFor mints per leg — so approvalGrantProvider's
29
- // `breakwater.connectorGrants` grant reaches the connector write gate with
30
- // 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.
10
+ // createDurableToolCallStep passes the engine leg's requestContext to
11
+ // tool.execute, so #requestContextFor's connector grant reaches the write gate.
12
+ // The registry context serves the approval pre-check; a resume without a
13
+ // runtime-minted grant fails the connector gate.
33
14
  //
34
- // Host-owned run ids at the boundary: stream()/generate()/prepare() are
35
- // inherited minting entry points. Each takes an OPTIONAL runId and, when it is
36
- // absent, lets core mint an unowned crypto.randomUUID() upstream
37
- // (prepareForDurableExecution, agent/durable index.js:589) that
38
- // PATH_SAFE_ID_PATTERN then accepts, slipping past executeWorkflow's guard AND
39
- // RunnerRuntime.start's exact fallback, which the host-owned run-id rule
40
- // forbids. They are overridden ONLY to require a caller-minted runId before
41
- // delegating to super. prepare() also REGISTERS the run under that id
42
- // (index.js:5984), so an unguarded prepare() strands an unowned run in the
43
- // registry. streamUntilIdle() needs no override: it drives agent.stream()
44
- // (index.js:368), so the stream() guard already covers it.
15
+ // prepareForDurableExecution mints a UUID when stream, generate or prepare has
16
+ // no runId, and prepare also registers that id. The public overrides must
17
+ // reject an absent caller id before that UUID satisfies downstream path checks;
18
+ // streamUntilIdle delegates through the guarded stream override.
45
19
  //
46
- // EVERY OTHER inherited entry point whose call can drive a run that would not
47
- // land on those guarded overrides, or whose call itself discovers run or thread
48
- // identities without a scope the caller names, is BLOCKED, overridden to throw
49
- // before it touches storage or the registry. A call that returns the run id of
50
- // a thread or run the caller names discovers nothing. A call that installs a
51
- // second execution surface is refused on the fourth ground too. Installing a
52
- // runtime service after construction is refused on the fifth ground.
53
- // Direct cancellation outside RunnerRuntime's terminal lifecycle is refused
54
- // on the sixth.
55
- // BLOCKED_RUN_ENTRIES below is the single source for which method is refused on
56
- // which ground; the grounds are enumerated there.
20
+ // BLOCKED_RUN_ENTRIES is the single source for which method is refused on
21
+ // which ground.
22
+ // Core's isDurableAgentLike checks that recover and recoverActiveRuns are
23
+ // functions, so throwing refusals preserve the durable-agent brand.
57
24
  //
58
- // Provenance for this section: read from the @mastra/core 1.53.0 dist. Chunk
59
- // file names are CONTENT-HASHED and move every release, so each offset below is
60
- // qualified by the chunk that carried it at 1.53.0 — re-read, never re-trust,
61
- // on a peer bump.
25
+ // Signal senders and queueMessage stay inherited because their starts reach
26
+ // executeWorkflow's refusal for ids absent from #startRequesters, preserving
27
+ // the input verdict and publishing terminal ERROR.
62
28
  //
63
- // (1) Recovery (new in 1.53.0), in chunk-XMEACVLS.js. recover() (:6385) reads
64
- // the persisted AGENTIC_LOOP snapshot (:6405) and re-drives it with
65
- // `workflow.createRun({ runId }) + run.restart()` (:6587-6588); it also
66
- // rebuilds the registry from the FULL application processor list (:6471)
67
- // rather than #rehydrateRegistry's RBAC-only, fail-closed preparation.
68
- // recoverActiveRuns() (:7027) is listActiveRuns() plus a recover() per
69
- // row. The protected deleteRunSnapshots() (:5877) joins them: its only
70
- // core call sites are the base executeWorkflow (:5834, overridden here),
71
- // resume() (:6308) and recover() (:6593), so no path this class drives
72
- // reaches it, and the snapshot rows belong to deployment-scoped retention
73
- // purge.
29
+ // AgentThreadStreamRuntime's idle wake, continuation and queued-signal drains
30
+ // can start runs with core-minted ids. registerRun's completion watcher removes
31
+ // completed thread records and releases or transfers their leases, while
32
+ // #drainPendingSignals also clears failed-start state and requeues the signal.
74
33
  //
75
- // (2) Unscoped run or thread identity DISCOVERY returns identities rather
76
- // than driving anything. listActiveRuns() (chunk-XMEACVLS.js:6927)
77
- // enumerates `listWorkflowRuns({ workflowName: 'durable-agentic-loop',
78
- // status: 'running' })`, and the Agent-level listSuspendedRuns()
79
- // (chunk-3S5BFAEP.js:49532) enumerates
80
- // `listWorkflowRuns({ workflowName: 'agentic-loop', status:
81
- // 'suspended' })`; both then narrow the rows identically, by the
82
- // snapshot's agentId plus the caller's OWN optional threadId/resourceId
83
- // (:6962-6981 and :49563-49586). Neither consults the host topology's
84
- // per-principal run-ownership checks (resourceAccess().owner('run', …)),
85
- // so either one hands a caller ids for runs it does not own. Run listing
86
- // is the topology's job. discoverThreadPeers()
87
- // (agent-Dk0N0Nlg.js:38208-38210) likewise enumerates advertised thread
88
- // identities on the pub/sub without a caller-named thread or principal.
34
+ // The runner's terminal refusal lets core consume a failed stream result and
35
+ // complete thread cleanup. DurableAgent does not forward the wrapped agent's
36
+ // notifications configuration, and if terminal error publication fails the
37
+ // output can remain open until eviction or a host start.
89
38
  //
90
- // (3) The resume family, in chunk-XMEACVLS.js: resume() (:6072) and its
91
- // funnels resumeStream() (:6650), resumeGenerate() (:6878),
92
- // approveToolCall() (:6669), declineToolCall() (:6676) and 1.53.0's
93
- // approveToolCallGenerate() (:6679) / declineToolCallGenerate() (:6683),
94
- // plus the new resume(..., { toolCallId }) which only forwards toolCallId
95
- // as run.resume's `label` (:6293). None of them MINTS — each takes the
96
- // runId from its caller. 1.53.0 changed what they reach: resume() no longer requires a live registry entry,
97
- // and on a miss it loads the persisted snapshot (:6075-6076), rehydrates
98
- // via prepare() (:6115) with the full application processor chain, then
99
- // re-drives with createRun + run.resume (:6281/:6293) below
100
- // executeWorkflow. That is the same second execution path recovery opens,
101
- // so it earns the same refusal rather than a comment asking hosts not to
102
- // call it.
103
- //
104
- // Agent-level surface (offsets in chunk-3S5BFAEP.js at 1.53.0 unless another
105
- // chunk or file is named). The base `Agent` also carries own members
106
- // DurableAgent does not shadow; durable-agent-surface.test.ts pins their
107
- // partition by name.
108
- //
109
- // BLOCKED outright, because each is its own execution path:
110
- // - listSuspendedRuns() (:49532) — the discovery ground.
111
- // - the network family: network() (:49263) and resumeNetwork() (:49326)
112
- // start and resume THE SAME networkLoop (:32496), which compiles its own
113
- // workflow and drives it with `mainWorkflow.createRun` (:32968) +
114
- // `run.stream` (:32990) / `run.resumeStream` (:32985) on the default
115
- // engine. network() also MINTS: `runId = mergedOptions?.runId ||
116
- // this.#mastra?.generateId() || randomUUID()` (:49272) — the exact
117
- // unowned fallback the host-owned run-id rule forbids.
118
- // approveNetworkToolCall() (:49382) and declineNetworkToolCall()
119
- // (:49400) are one-line forwards to resumeNetwork(). None of them
120
- // dispatches through a blocked method, so each needs its own override.
121
- // - the legacy family: generateLegacy() (:50414) and streamLegacy()
122
- // (:50417) forward into AgentLegacyHandler (:41721-42751), which converts
123
- // and RUNS the agent's tools, mints `runId = args.runId ||
124
- // mastra.generateId() || randomUUID()`, and skips the authorization gate
125
- // every supported entry calls (requireAgentExecutionFGA, defined :48798,
126
- // called from generate :49420, stream :49858, resumeStream :50002,
127
- // resumeGenerate :50105, and durable stream/resume/generate
128
- // chunk-XMEACVLS.js:5918/6158/6718 — none of them on the network or
129
- // legacy path). It touches no persisted workflow run state, so it is
130
- // convicted on minting plus the skipped gate, not on re-drive.
131
- // - sendToolApproval() (:50254), whose name suggests a funnel. With
132
- // `messages && approved` it calls
133
- // agentThreadStreamRuntime.continueWithMessages() (:50266), where
134
- // `const runId = target.runId ?? randomUUID()` (chunk-P4Y2BJL7.js:6752)
135
- // mints and `agent.stream(..., { runId })` (:6720) then starts a run
136
- // under that core-minted id — path-safe, so #assertCallerRunId cannot
137
- // tell it from a host-minted one. With no active thread run id it calls
138
- // this.listSuspendedRuns() (:50287), which is blocked. Only its tail
139
- // reaches this.resumeStream() (:50338) / this.sendStreamResume()
140
- // (:50345). The mint is the conviction.
141
- //
142
- // LEFT INHERITED as funnellers, because virtual dispatch already lands them
143
- // on an override: resumeStreamUntilIdle() (:49954 -> agent.resumeStream) and
144
- // sendStreamResume() (:50212 -> this.resumeStream) reach the BLOCKED
145
- // resumeStream. The signal senders stay inherited because every outcome they
146
- // can produce lands on this runner's terminal path; queueMessage keeps the
147
- // same containment property.
148
- //
149
- // Direct sender calls can reach core's minting sites: the idle wake
150
- // (:7441), continuation (:6720), completion drain (:6665), and queued-id
151
- // drain (:6808), all in chunk-P4Y2BJL7.js.
152
- // executeWorkflow therefore treats a missing #startRequesters entry as a
153
- // terminal refusal: it preserves input by the guarded input chain's
154
- // verdict when memory permits, publishes ERROR, and never calls
155
- // RunnerRuntime. #persistUnownedInput states the verdict rule.
156
- //
157
- // Core registers thread state only when stream options carry a memory
158
- // thread (chunk-P4Y2BJL7.js:6557-6594). For those runs its completion
159
- // watcher consumes the failed output, removes the run maps, publishes
160
- // run-completed, and releases or transfers the lease (:6596-6624).
161
- // getThreadState heals a non-blocking record (:6235-6246), but neither it
162
- // nor getActiveThreadRunId heals a record-less active id. This is why the
163
- // refusal is terminal instead of synchronous: the idle-wake site is
164
- // wrapped (:7440-7462), while #drainPendingSignals' call at :6665 has no
165
- // failure cleanup. Upstream note: #drainPendingSignals needs failure
166
- // cleanup before a synchronous refusal would be safe there. Upstream note:
167
- // DurableAgent does not forward the wrapped Agent's `notifications`
168
- // configuration, so the wrapper cannot inject a delivery policy.
169
- // If the runner's publication attempts and core's own fire-and-forget
170
- // attempt fail, the terminal output never closes and the thread remains
171
- // active until eviction or a new host start.
172
- //
173
- // LEFT INHERITED as non-execution, on a read of each: the base delegators
174
- // resume/recover/listActiveRuns/recoverActiveRuns/prepare (:50497 onward) are
175
- // shadowed by DurableAgent and overridden here, so they are unreachable on
176
- // this instance; `observe` is likewise shadowed by DurableAgent but is NOT
177
- // overridden and must not be — it only reattaches to a run's pubsub replay,
178
- // and resumeViaRuntime() calls this.observe() itself after rehydration;
179
- // `durable` (:44568) is a field accessor; getActiveThreadRunId() (:49507)
180
- // reads only the in-process pubsub registry, never storage;
181
- // genTitle() (:46377) and generateTitleFromUserMessage() (:46296) call
182
- // `llm.stream`/`llm.__text` with no tools.
183
- //
184
- // Residuals outside this class's reach include:
185
- // Mastra.restartAllActiveWorkflowRuns() belongs to Mastra, not an agent —
186
- // nothing here calls it, and it would hit core's processor-rebuild fallback if
187
- // a host did. getLegacyHandler() (:45595) is TS-private but runtime-public and
188
- // returns the very handler the legacy entries refuse; that is the same class
189
- // of caveat as getWorkflow() returning a startable object, and reaching it
190
- // takes a deliberate private cast, which is a first-party act.
191
- //
192
- // Corroboration: breakwater's guarded handle inventory
193
- // (packages/breakwater/src/agent/agent.test.ts) classifies the same Agent
194
- // members for a narrowed HANDLE. A handle can only omit, so a data-returning
195
- // member or a setter is harmless there, while an INSTANCE Mastra calls
196
- // in-process must throw; the inventories can file a member differently for
197
- // that reason.
198
- //
199
- // The Agent-level members below are blocked as well. Read from the
200
- // @mastra/core 1.67.0 dist, the declared peer; offsets here are 1.67.0-vintage,
201
- // in agent-Dk0N0Nlg.js unless another file is named, and the 1.53.0 offsets
202
- // above are left as the provenance of that read. The peer carries each of
203
- // them, so each refusal shadows a real implementation.
204
- //
205
- // - listActiveThreadRuns() (:38214) is the discovery ground one scope wider
206
- // than listActiveRuns. It takes no arguments and returns `{ runId,
207
- // resourceId, threadId }` for every thread on the pubsub instance with a run
208
- // in flight (storage-MbGlKLkB.js:1011-1023), and that state is keyed by
209
- // pubsub instance rather than by agent (`#statesByPubSub`, :150, read through
210
- // #getState :294), so it narrows by neither principal nor agent where the
211
- // listings above at least narrow by agentId. The in-process sibling
212
- // getActiveThreadRunId() stays non-execution because it makes the caller name
213
- // the (resourceId, threadId) pair: it confirms where this enumerates.
214
- // Cost, stated rather than left to be rediscovered: core's AgentController
215
- // aggregates this member across its backing agents
216
- // (agent-controller-CKgKFyMR.js:5722-5725), so that aggregation throws. The
217
- // controller installs configured memory or pub/sub when the agent lacks its
218
- // own (agent-controller-CKgKFyMR.js:5618-5622), reaching the refused
219
- // __setMemory() or __setPubSub(). When it installs neither, init() still
220
- // reaches the refused __setMastra() through Mastra.addAgent(). It also calls
221
- // the blocked sendToolApproval() at :4089 and :4118.
222
- // - __setThreadRuntimeAgent() (:33609) installs another agent as the target
223
- // the thread-runtime paths resolve through #getThreadRuntimeAgent()
224
- // (:33612, `this.#threadRuntimeAgent ?? this`); the refusal in
225
- // BLOCKED_RUN_ENTRIES names those paths, for the core it is written
226
- // against. That is the fourth ground by installation rather than by call:
227
- // the containment those inherited members rely on IS virtual dispatch on
228
- // `this`, so one call moves every run those paths start onto an agent
229
- // carrying none of these overrides — no caller-minted runId assertion, no
230
- // executeWorkflow, no #startRequesters backstop. The field also moves
231
- // subscribeToThread's replay target. It is public in the type surface
232
- // (agent.d.ts:229 declares it with no modifier), so unlike getLegacyHandler
233
- // it takes no private cast.
234
- // The DurableAgent-level members below are blocked too. Read from the
235
- // @mastra/core 1.67.0 dist; offsets here are 1.67.0-vintage, in
236
- // create-durable-agent-DFHwqN2K.js unless another file is named.
237
- //
238
- // - setChannels() (:6408) and __setDeclaredSchedules() (:6240) forward what
239
- // they are given to the wrapped agent. Channels make that agent their
240
- // dispatch target (agent-Dk0N0Nlg.js:33791-33796), so a plain AgentChannels
241
- // delivers inbound messages to its sendMessage, and channel approvals and
242
- // declines to its approveToolCall and declineToolCall (agent-Dk0N0Nlg.js
243
- // :21002, :21031, :21045). The schedule worker of a Mastra that registers
244
- // the wrapped agent and runs startWorkers() (mastra-CCeMcPkn.js:4525-4589)
245
- // resolves each declared schedule's agent by id and fires it through that
246
- // agent's sendSignal or generate (worker-CemmWBp9.js:167, :319, :448). Both
247
- // run the wrapped agent outside RunnerRuntime, so each call is the fourth
248
- // ground by installation, as __setThreadRuntimeAgent() is.
249
- // - __setMemory() and __setPubSub() (:6414-6421) install and forward services
250
- // to the wrapped agent. AgentController reaches them under the conditions
251
- // above (agent-controller-CKgKFyMR.js:5618-5622); a parent with pub/sub
252
- // also reaches __setPubSub() when the wrapped agent has no pub/sub of its
253
- // own (agent-Dk0N0Nlg.js:34105).
254
- // - abortRunStream() and abortThreadStream() (:6565-6601) cancel outside the
255
- // terminate route's ownership and settlement checks.
256
- // - __setMastra() (:7922) forwards to __registerMastra() (:7934), which sets
257
- // this wrapper's Mastra and the wrapped agent's (:7934-7939). Every later
258
- // leg is prepared against that Mastra: core hands it to
259
- // prepareForDurableExecution (:6693, :7362, :7882), and so does
260
- // #rehydrateRegistry. Mastra.addAgent calls __setMastra()
261
- // (mastra-CCeMcPkn.js:1674) and then adds getDurableWorkflows() to its own
262
- // registry (:1689-1692); once the runtime has built its own Mastra, that
263
- // repoints the runtime's loop workflow, and with it run state, to the
264
- // other Mastra's storage. Agent.listAgents calls
265
- // __registerMastra() on each static sub-agent (agent-Dk0N0Nlg.js:34104).
266
- // A parent with pub/sub also calls __setPubSub() on a static sub-agent
267
- // without its own pub/sub (:34105), even when it has no Mastra. These are
268
- // the fifth ground. The refusal throws from addAgent before its registry
269
- // write and before it repoints the loop.
270
- //
271
- // Each carries the `override` keyword: the declared peer declares the member,
272
- // so the keyword holds the refusal to a base that exists and fails the
273
- // typecheck if a future core drops it. Each signature satisfies the base it
274
- // shadows on that base's own terms.
275
- //
276
- // The runner's resume path is resumeViaRuntime(). Blocking does not un-brand
277
- // the agent — DurableAgentLike duck-types on `recover`/`recoverActiveRuns`
278
- // merely BEING functions (agent-Dk0N0Nlg.js:272), which the overrides still
279
- // are.
39
+ // Mastra.restartAllActiveWorkflowRuns is a separate host capability that can
40
+ // reach core's processor-rebuild fallback. Agent.getLegacyHandler is
41
+ // TS-private but runtime-public and returns the legacy execution handler, so
42
+ // accessing it requires the same first-party trust as other live core objects.
280
43
  //
281
44
  // Live-isolate scope: the loop resolves the tool's execute closure from the
282
45
  // in-process globalRunRegistry (populated by stream()). A DO holds one run in
283
46
  // one isolate, so a resume decided before eviction finds it. A resume
284
47
  // AFTER eviction must first rehydrate that registry without replaying
285
48
  // application input processors. resumeViaRuntime() rebuilds the registry with
286
- // complete runtime processor lists after invoking only reserved RBAC during
287
- // empty-message preparation, then drives runtime.resume().
49
+ // complete runtime processor lists after invoking only Breakwater's reserved
50
+ // processInput steps during empty-message preparation, then drives
51
+ // runtime.resume().
288
52
  import { isCreatedAgentSignal, isDurableAgentLike, isMastraSignalMessage, isTransientSignalMessage, MessageList, mastraDBMessageToSignal, signalToMastraDBMessage, } from '@mastra/core/agent';
289
- import { DurableAgent, globalRunRegistry, prepareForDurableExecution, } from '@mastra/core/agent/durable';
53
+ import { AGENT_STREAM_TOPIC, DurableAgent, globalRunRegistry, prepareForDurableExecution, } from '@mastra/core/agent/durable';
54
+ import { MastraTimeoutError } from '@mastra/core/loop';
290
55
  import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
56
+ import { DoStatusError } from '../do-runner/do-status-error.js';
291
57
  import { normalizeMutationEpoch, normalizeStartIdentity, } from '../do-runner/execution-admission.js';
292
58
  import { InvalidRunRequestError, isPathSafeId, RunStateUnreadableError, } from '../do-runner/index.js';
293
59
  import { resourceIdFromKey } from '../do-runner/memory-id.js';
60
+ import { isTerminalRunStatus } from '../do-runner/run-terminal-state.js';
294
61
  import { captureReservation, } from '../do-runner/start-reservation-contract.js';
62
+ class AgentAuthorizationDeniedError extends DoStatusError {
63
+ status = 403;
64
+ constructor() {
65
+ super('agent authorization denied');
66
+ this.name = 'AgentAuthorizationDeniedError';
67
+ }
68
+ }
295
69
  /** @internal A coherent snapshot belongs to another agent or thread. */
296
70
  export class AgentRunSelectorMismatchError extends RunStateUnreadableError {
297
71
  constructor(workflowId, runId) {
@@ -314,6 +88,9 @@ const UNREGISTERED_RUN_REFUSAL_PREFIX = 'Flowsafe durable-agent runner refused u
314
88
  export const FLOWSAFE_PERSISTENCE_FORBIDDEN = 'flowsafe.persistence-forbidden';
315
89
  const BREAKWATER_GUARDED_AGENT_HOST_PROTOCOL = Symbol.for('@proofoftech/breakwater/guarded-agent-host/v1');
316
90
  const BREAKWATER_RBAC_PROCESSOR_ID = 'breakwater-rbac';
91
+ // Replaying the reserved failure step for unresolved memory processors refuses
92
+ // rehydration before the resumed step.
93
+ const BREAKWATER_MEMORY_PROCESSOR_ID = 'breakwater-memory';
317
94
  function captureAgentStartAuthority(source, requestedBy, requestedByKind) {
318
95
  if (source === null || typeof source !== 'object' || Array.isArray(source)) {
319
96
  throw new InvalidRunRequestError('agent start authority is required');
@@ -385,7 +162,14 @@ function captureAgentStartAuthority(source, requestedBy, requestedByKind) {
385
162
  startReservation,
386
163
  });
387
164
  }
388
- function snapshotDurableCallOptions(options) {
165
+ function ownDataDescriptor(target, key, path) {
166
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
167
+ if (descriptor && !('value' in descriptor)) {
168
+ throw new TypeError(`FlowsafeDurableAgent: call option '${path}' must be a data property`);
169
+ }
170
+ return descriptor;
171
+ }
172
+ function snapshotDurableCallOptions(options, mapper) {
389
173
  if (options === undefined)
390
174
  return undefined;
391
175
  if (options === null ||
@@ -395,16 +179,13 @@ function snapshotDurableCallOptions(options) {
395
179
  }
396
180
  const snapshot = {};
397
181
  for (const key of Reflect.ownKeys(options)) {
398
- const descriptor = Object.getOwnPropertyDescriptor(options, key);
182
+ const descriptor = ownDataDescriptor(options, key, String(key));
399
183
  if (!descriptor)
400
184
  continue;
401
- if (descriptor.get || descriptor.set) {
402
- throw new TypeError(`FlowsafeDurableAgent: call option '${String(key)}' must be a data property`);
403
- }
404
185
  Object.defineProperty(snapshot, key, {
405
186
  configurable: false,
406
187
  enumerable: descriptor.enumerable,
407
- value: descriptor.value,
188
+ value: mapper ? mapper(key, descriptor.value) : descriptor.value,
408
189
  writable: false,
409
190
  });
410
191
  }
@@ -470,7 +251,7 @@ const LEGACY_FAMILY_REASON = "the AI SDK v4 legacy handler is a second execution
470
251
  * but its continuation branch STARTS a run under a core-minted id — a mint on
471
252
  * the far side of a method that never asks the caller for one.
472
253
  */
473
- 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';
254
+ 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 when neither an explicit run id nor an active thread run is available, it reaches the equally unscoped suspended-run discovery';
474
255
  /**
475
256
  * Why binding the wrapper to a Mastra is refused. Homed once: `__setMastra()`
476
257
  * forwards to `__registerMastra()`, so the two are one code path.
@@ -485,7 +266,286 @@ const INSTALLED_SERVICE_REASON = "it installs memory or pub/sub after constructi
485
266
  * Why direct aborts are refused. Homed once: both bypass the terminate route's
486
267
  * ownership and disputed-settlement checks.
487
268
  */
488
- const DIRECT_ABORT_REASON = "a direct abort bypasses the terminate route's ownership check and disputed-settlement refusal, stops running tools, and can reach another thread's run in the isolate through core's global run registry; cancel through the terminate route";
269
+ const DIRECT_ABORT_REASON = "a direct abort bypasses the terminate route's ownership check and disputed-settlement refusal, and can reach another thread's run in the isolate through core's global run registry; cancel through the terminate route";
270
+ const GUARDED_CALLBACK_REASON = "it receives what the call's stream delivers; on the durable loop the saved message and the returned result are not filtered by the output policies";
271
+ const GUARDED_OBSERVABILITY_REASON = 'observability only';
272
+ const GUARDED_REENTRY_REASON = "Mastra's own re-entry options for its idle loop and background-task wait";
273
+ // The single classification of a guarded agent's durable call options; the
274
+ // host-facing list in docs/durable-agents.md#durable-call-options follows it.
275
+ // Keys the table does not name, and symbol keys, pass unchanged: core re-enters
276
+ // stream() with keys of its own. Absent compared keys pass because core merges
277
+ // the guarded defaults into every run it registers.
278
+ const GUARDED_DURABLE_CALL_OPTIONS = {
279
+ structuredOutput: {
280
+ kind: 'refused',
281
+ why: 'Mastra parses and releases the structured object outside the output policies',
282
+ },
283
+ errorProcessors: {
284
+ kind: 'refused',
285
+ why: 'error processors can change model requests after the guarded input chain',
286
+ },
287
+ clientTools: {
288
+ kind: 'refused',
289
+ why: "Mastra maps a per-call client tool's result after the guarded input policies have read it",
290
+ },
291
+ toolsets: {
292
+ kind: 'refused',
293
+ why: "Mastra adds the call's tools and maps a client tool's result after the guarded input policies have read it",
294
+ },
295
+ outputProcessors: {
296
+ kind: 'refused',
297
+ why: "Mastra replaces the guarded output processors, output policies included, with the call's list",
298
+ },
299
+ inputProcessors: {
300
+ kind: 'refused',
301
+ why: 'Breakwater fixes the guarded input processors at construction',
302
+ },
303
+ instructions: {
304
+ kind: 'refused',
305
+ why: "Mastra replaces the guarded agent's instructions with the call's",
306
+ },
307
+ system: {
308
+ kind: 'refused',
309
+ why: "Mastra adds the call's system messages, which the input policies do not read",
310
+ },
311
+ context: {
312
+ kind: 'refused',
313
+ why: "Mastra adds the call's context messages, which the input policies do not read",
314
+ },
315
+ prepareStep: {
316
+ kind: 'refused',
317
+ why: "Mastra runs the call's step preparation after the guarded input processors on every step",
318
+ },
319
+ hooks: {
320
+ kind: 'refused',
321
+ why: "Mastra runs the call's tool hooks over the guarded agent's own, and a hook can replace a tool call's result",
322
+ },
323
+ scorers: {
324
+ kind: 'refused',
325
+ why: "Mastra replaces the guarded agent's scorers with the call's",
326
+ },
327
+ savePerStep: {
328
+ kind: 'refused',
329
+ why: "Mastra saves each step before the output processors' result phase and before a later refusal",
330
+ },
331
+ versions: {
332
+ kind: 'refused',
333
+ why: "Mastra resolves the guarded agent's sub-agents to the call's versions",
334
+ },
335
+ autoResumeSuspendedTools: {
336
+ kind: 'refused',
337
+ why: 'Mastra adds a system instruction after the guarded input chain and lets model input resume suspended tools',
338
+ },
339
+ includeRawChunks: {
340
+ kind: 'refused',
341
+ why: "the provider's raw chunks reach the stream without passing the output policies",
342
+ },
343
+ onChunk: {
344
+ kind: 'refused',
345
+ why: 'Mastra calls it with each chunk before the output processors run',
346
+ },
347
+ delegation: {
348
+ kind: 'refused',
349
+ why: "Mastra runs the call's delegation hooks, which can change what sub-agents receive and return",
350
+ },
351
+ onIterationComplete: {
352
+ kind: 'refused',
353
+ why: 'its feedback reaches the model and the saved thread without passing the guarded policies',
354
+ },
355
+ isTaskComplete: {
356
+ kind: 'refused',
357
+ why: "Mastra runs the call's completion scorers, and their feedback reaches the model and the saved thread without passing the guarded policies",
358
+ },
359
+ transform: {
360
+ kind: 'refused',
361
+ why: "Mastra replaces the guarded agent's tool-payload transform with the call's",
362
+ },
363
+ experimentalTransform: {
364
+ kind: 'refused',
365
+ why: "it rewrites the thread's shared stream after the output processors",
366
+ },
367
+ requireToolApproval: {
368
+ kind: 'refused',
369
+ why: "Mastra runs a call-level approval function with the tool's arguments, and a tool's own approval rule replaces the call's setting",
370
+ },
371
+ backgroundTaskPolicy: {
372
+ kind: 'refused',
373
+ why: 'it changes the delegated tools Mastra assembles, and Breakwater disables background tasks at construction',
374
+ },
375
+ maxProcessorRetries: {
376
+ kind: 'refused',
377
+ why: 'Breakwater fixes processor retries at construction',
378
+ },
379
+ eagerToolExecution: {
380
+ kind: 'refused',
381
+ why: "the guarded agent runs no tool eagerly, and Mastra's durable execution does not support eager tool execution",
382
+ },
383
+ maxSteps: { kind: 'compared', comparison: 'guardedMaxSteps' },
384
+ toolChoice: { kind: 'compared', comparison: 'guardedToolChoice' },
385
+ disableBackgroundTasks: {
386
+ kind: 'compared',
387
+ comparison: 'backgroundTasksDisabled',
388
+ },
389
+ memory: { kind: 'memoryBinding' },
390
+ runId: {
391
+ kind: 'allowed',
392
+ why: 'the host mints the run id, and each entry requires a path-safe one',
393
+ },
394
+ requestContext: {
395
+ kind: 'allowed',
396
+ why: 'the host builds it, and Breakwater authorizes the call from it',
397
+ },
398
+ abortSignal: { kind: 'allowed', why: 'it can only stop the run' },
399
+ actor: {
400
+ kind: 'allowed',
401
+ why: "Mastra's authorization signal, which only the host sets; Breakwater authorizes from the request context",
402
+ },
403
+ mcp: {
404
+ kind: 'allowed',
405
+ why: 'an execution context for tools the agent already has; it adds none',
406
+ },
407
+ serverless: {
408
+ kind: 'allowed',
409
+ why: 'it keeps the platform alive for finish work and changes nothing the call does',
410
+ },
411
+ hideSignals: {
412
+ kind: 'allowed',
413
+ why: "it hides signals from the caller's stream only; model context and storage are unchanged",
414
+ },
415
+ closeOnSuspend: {
416
+ kind: 'allowed',
417
+ why: "it closes the caller's stream when the run suspends",
418
+ },
419
+ stopWhen: {
420
+ kind: 'allowed',
421
+ why: 'it can only stop the run earlier, within maxSteps',
422
+ },
423
+ activeTools: {
424
+ kind: 'allowed',
425
+ why: "it selects among the guarded agent's tools and adds none",
426
+ },
427
+ toolCallConcurrency: {
428
+ kind: 'allowed',
429
+ why: "it schedules the guarded agent's tool calls and adds none",
430
+ },
431
+ returnScorerData: {
432
+ kind: 'allowed',
433
+ why: "it returns the guarded agent's own scorers' data",
434
+ },
435
+ modelSettings: {
436
+ kind: 'allowed',
437
+ why: 'host-owned generation settings: headers, stop sequences and timeouts',
438
+ },
439
+ providerOptions: {
440
+ kind: 'allowed',
441
+ why: "the thread host checks it against Breakwater's accepted provider options, and a direct caller must",
442
+ },
443
+ onStepFinish: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
444
+ onFinish: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
445
+ onError: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
446
+ onSuspended: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
447
+ onAbort: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
448
+ tracingOptions: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
449
+ tracing: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
450
+ loggerVNext: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
451
+ metrics: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
452
+ tracingContext: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
453
+ untilIdle: { kind: 'allowed', why: GUARDED_REENTRY_REASON },
454
+ _skipBgTaskWait: { kind: 'allowed', why: GUARDED_REENTRY_REASON },
455
+ };
456
+ const GUARDED_MEMORY_REASON = "Mastra applies call-level memory configuration and thread fields outside the input policies; configure them on the agent's Memory";
457
+ function guardedMemoryBinding(memory) {
458
+ if (memory === undefined)
459
+ return memory;
460
+ if (memory === null || typeof memory !== 'object' || Array.isArray(memory)) {
461
+ throw new TypeError('FlowsafeDurableAgent: memory must be an object for a Breakwater guarded agent');
462
+ }
463
+ const binding = {};
464
+ for (const key of Reflect.ownKeys(memory)) {
465
+ if (key !== 'thread' && key !== 'resource') {
466
+ throw new TypeError(`FlowsafeDurableAgent: memory.${String(key)} is not supported for a Breakwater guarded agent because ${GUARDED_MEMORY_REASON}`);
467
+ }
468
+ const descriptor = ownDataDescriptor(memory, key, `memory.${key}`);
469
+ if (!descriptor)
470
+ continue;
471
+ let value = descriptor.value;
472
+ if (key === 'thread' &&
473
+ value !== null &&
474
+ (typeof value === 'object' || typeof value === 'function')) {
475
+ let idDescriptor;
476
+ for (const threadKey of Reflect.ownKeys(value)) {
477
+ if (threadKey !== 'id') {
478
+ throw new TypeError(`FlowsafeDurableAgent: memory.thread.${String(threadKey)} is not supported for a Breakwater guarded agent because ${GUARDED_MEMORY_REASON}`);
479
+ }
480
+ idDescriptor = ownDataDescriptor(value, threadKey, 'memory.thread.id');
481
+ }
482
+ value = Object.freeze({ id: idDescriptor?.value });
483
+ }
484
+ binding[key] = value;
485
+ }
486
+ return Object.freeze(binding);
487
+ }
488
+ function guardedToolChoiceMatches(value, guarded) {
489
+ if (typeof guarded === 'string')
490
+ return value === guarded;
491
+ if (!guarded || value === null || typeof value !== 'object')
492
+ return false;
493
+ if (Reflect.ownKeys(value).some((key) => key !== 'type' && key !== 'toolName')) {
494
+ return false;
495
+ }
496
+ const typeDescriptor = Object.getOwnPropertyDescriptor(value, 'type');
497
+ const toolNameDescriptor = Object.getOwnPropertyDescriptor(value, 'toolName');
498
+ return (typeDescriptor !== undefined &&
499
+ 'value' in typeDescriptor &&
500
+ typeDescriptor.value === guarded.type &&
501
+ toolNameDescriptor !== undefined &&
502
+ 'value' in toolNameDescriptor &&
503
+ toolNameDescriptor.value === guarded.toolName);
504
+ }
505
+ function guardedCallOptionMapper(defaults) {
506
+ const { maxSteps, toolChoice } = defaults;
507
+ return (key, value) => {
508
+ if (key === '__proto__') {
509
+ const why = "Mastra's option merge makes its value the prototype of the options it resolves";
510
+ throw new TypeError(`FlowsafeDurableAgent: __proto__ is not supported for a Breakwater guarded agent because ${why}`);
511
+ }
512
+ if (typeof key !== 'string' ||
513
+ !Object.hasOwn(GUARDED_DURABLE_CALL_OPTIONS, key)) {
514
+ return value;
515
+ }
516
+ const rule = GUARDED_DURABLE_CALL_OPTIONS[key];
517
+ switch (rule.kind) {
518
+ case 'refused':
519
+ throw new TypeError(`FlowsafeDurableAgent: ${key} is not supported for a Breakwater guarded agent because ${rule.why}`);
520
+ case 'memoryBinding':
521
+ return guardedMemoryBinding(value);
522
+ case 'allowed':
523
+ return value;
524
+ case 'compared': {
525
+ let expected;
526
+ let matches;
527
+ switch (rule.comparison) {
528
+ case 'guardedMaxSteps':
529
+ expected = maxSteps;
530
+ matches = value === expected;
531
+ break;
532
+ case 'guardedToolChoice':
533
+ expected = toolChoice;
534
+ matches = guardedToolChoiceMatches(value, toolChoice);
535
+ break;
536
+ case 'backgroundTasksDisabled':
537
+ expected = true;
538
+ matches = value === expected;
539
+ break;
540
+ }
541
+ if (!matches) {
542
+ throw new TypeError(`FlowsafeDurableAgent: ${key} must equal the guarded agent's own value`);
543
+ }
544
+ return expected;
545
+ }
546
+ }
547
+ };
548
+ }
489
549
  /**
490
550
  * Why each blocked entry point is refused, keyed by method name: the SINGLE
491
551
  * source of those reasons.
@@ -530,7 +590,7 @@ export const BLOCKED_RUN_ENTRIES = {
530
590
  generateLegacy: LEGACY_FAMILY_REASON,
531
591
  streamLegacy: LEGACY_FAMILY_REASON,
532
592
  sendToolApproval: THREAD_TOOL_APPROVAL_REASON,
533
- __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",
593
+ __setThreadRuntimeAgent: "it installs the target subscribeToThread, claimThreadOwnership, sendMessage, queueMessage, sendStateSignal, sendNotificationSignal and sendSignal resolve through the thread-runtime agent field; discoverThreadPeers also resolves that target and listSuspendedRuns reads its durable loop workflow name — redirecting execution and subscription replay 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",
534
594
  setChannels: "it forwards the channels it is given to the wrapped agent, which becomes their dispatch target, so a plain AgentChannels delivers inbound messages to the wrapped agent's sendMessage, and channel approvals and declines to its approveToolCall and declineToolCall, outside RunnerRuntime; an AgentControllerChannels dispatches through its controller instead, and is refused as well because a controller over this class cannot install its runtime services or register this wrapper on its Mastra",
535
595
  __setDeclaredSchedules: "it forwards the schedules it is given to the wrapped agent, and the schedule worker of a Mastra that registers that agent and runs startWorkers() fires each of them through the wrapped agent's sendSignal or generate, outside RunnerRuntime",
536
596
  __setMastra: MASTRA_BINDING_REASON,
@@ -551,23 +611,68 @@ export const BLOCKED_RUN_ENTRIES = {
551
611
  function unavailableRunEntry(method, why) {
552
612
  return new Error(`FlowsafeDurableAgent.${method}() is unavailable: ${why} — this wrapper starts runs through RunnerRuntime from the host start seam (streamUntilPersisted) and resumes them through the approval-decision path (resumeViaRuntime)`);
553
613
  }
554
- function bindThreadCompletion(output, completion) {
614
+ function bindResumedLegLifecycle(output, leg) {
555
615
  return new Proxy(output, {
556
616
  get(target, property) {
617
+ if (property === '_waitUntilFinished')
618
+ return () => leg.completion;
619
+ if (property === 'status') {
620
+ if (leg.outcome === 'suspended')
621
+ return 'suspended';
622
+ const status = target.status;
623
+ if (leg.outcome === undefined) {
624
+ return status === 'running' || status === 'suspended'
625
+ ? status
626
+ : 'running';
627
+ }
628
+ return status !== 'running' && status !== 'suspended'
629
+ ? status
630
+ : leg.outcome;
631
+ }
557
632
  // Core's output getters read private fields, which a proxy receiver lacks.
558
633
  const value = Reflect.get(target, property, target);
559
- if (property === '_waitUntilFinished') {
560
- return () => typeof value === 'function'
561
- ? Promise.race([
562
- Promise.resolve(value.call(target)),
563
- completion,
564
- ])
565
- : completion;
566
- }
567
634
  return typeof value === 'function' ? value.bind(target) : value;
568
635
  },
569
636
  });
570
637
  }
638
+ // The rehydrated registry entry bypasses core's private budget installer, so a
639
+ // resumed leg composes `modelSettings.timeout.totalMs` with its abort signal
640
+ // here, with the same pass-through rule and timeout reason as core's
641
+ // createTimeoutAbortSignal. The parent listener stays attached after cleanup,
642
+ // which also runs when core evicts the entry mid-leg and must not unlink the
643
+ // leg's own abort.
644
+ function composeTotalBudget(parent, totalMs) {
645
+ if (typeof totalMs !== 'number' ||
646
+ !Number.isFinite(totalMs) ||
647
+ totalMs <= 0) {
648
+ return { signal: parent, cleanup: () => undefined };
649
+ }
650
+ const controller = new AbortController();
651
+ const timer = setTimeout(() => {
652
+ controller.abort(new MastraTimeoutError({ timeoutType: 'total', timeoutMs: totalMs }));
653
+ }, totalMs);
654
+ // Node's timer handle has unref; the Workers runtime returns a number.
655
+ timer.unref?.();
656
+ const onParentAbort = () => controller.abort(parent.reason);
657
+ if (parent.aborted)
658
+ onParentAbort();
659
+ else
660
+ parent.addEventListener('abort', onParentAbort, { once: true });
661
+ return {
662
+ signal: controller.signal,
663
+ cleanup: () => clearTimeout(timer),
664
+ };
665
+ }
666
+ function isRecord(value) {
667
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
668
+ }
669
+ function persistedModelSettings(workflowInput) {
670
+ if (!isRecord(workflowInput) || !isRecord(workflowInput.options)) {
671
+ return undefined;
672
+ }
673
+ const { modelSettings } = workflowInput.options;
674
+ return isRecord(modelSettings) ? modelSettings : undefined;
675
+ }
571
676
  /**
572
677
  * Brand marking an agent as runtime-driven. The thread Durable Object requires
573
678
  * it before a wake seam may start a run.
@@ -602,8 +707,10 @@ export class FlowsafeDurableAgent extends DurableAgent {
602
707
  [RUNTIME_DRIVEN_AGENT] = true;
603
708
  #runtime;
604
709
  #wrappedAgent;
605
- #isBreakwaterGuardedAgent;
710
+ #rehydrationInputProcessorIds;
711
+ #guardedCallOptionMapper;
606
712
  #threadRuntime;
713
+ #resumedThreadLegs = new Map();
607
714
  #persistenceWaiters = new Map();
608
715
  #startRequesters = new Map();
609
716
  #startRequesterKinds = new Map();
@@ -635,6 +742,34 @@ export class FlowsafeDurableAgent extends DurableAgent {
635
742
  throw new TypeError("FlowsafeDurableAgent: the wrapped agent has its own pub/sub, which differs from the one the wrapper uses; signal delivery and the run's drain must read the same pub/sub");
636
743
  }
637
744
  const guardedProtocol = breakwaterGuardedAgentHostProtocol(options.agent);
745
+ let callOptionMapper;
746
+ if (guardedProtocol !== undefined) {
747
+ const defaults = options.agent.getDefaultOptions();
748
+ if (defaults === null ||
749
+ typeof defaults !== 'object' ||
750
+ typeof defaults.then === 'function') {
751
+ throw new TypeError('FlowsafeDurableAgent: a Breakwater guarded agent must have static default options');
752
+ }
753
+ for (const [key, rule] of Object.entries(GUARDED_DURABLE_CALL_OPTIONS)) {
754
+ if (rule.kind === 'compared' &&
755
+ (!Object.hasOwn(defaults, key) ||
756
+ ownDataDescriptor(defaults, key, key)?.value === undefined)) {
757
+ throw new TypeError(`FlowsafeDurableAgent: a Breakwater guarded agent's default options must carry ${key}`);
758
+ }
759
+ }
760
+ const { maxSteps, toolChoice } = defaults;
761
+ callOptionMapper = guardedCallOptionMapper(Object.freeze({
762
+ maxSteps,
763
+ toolChoice: toolChoice !== null && typeof toolChoice === 'object'
764
+ ? Object.freeze({
765
+ type: toolChoice.type,
766
+ toolName: toolChoice.toolName,
767
+ })
768
+ : toolChoice,
769
+ }));
770
+ // Signal drains replay these defaults, so an unusable one fails before registering a run.
771
+ snapshotDurableCallOptions(defaults, callOptionMapper);
772
+ }
638
773
  super({
639
774
  agent: options.agent,
640
775
  id: options.id,
@@ -645,25 +780,19 @@ export class FlowsafeDurableAgent extends DurableAgent {
645
780
  });
646
781
  this.#runtime = options.runtime;
647
782
  this.#wrappedAgent = options.agent;
648
- this.#isBreakwaterGuardedAgent = guardedProtocol !== undefined;
783
+ this.#rehydrationInputProcessorIds = new Set(guardedProtocol !== undefined
784
+ ? [BREAKWATER_RBAC_PROCESSOR_ID, BREAKWATER_MEMORY_PROCESSOR_ID]
785
+ : [BREAKWATER_RBAC_PROCESSOR_ID]);
786
+ this.#guardedCallOptionMapper = callOptionMapper;
649
787
  this.#threadRuntime = options.threadRuntime;
650
788
  // Core keys thread state and signal delivery on the agent-level pub/sub;
651
789
  // its stream pub/sub option leaves that identity unset for the run's drain.
652
790
  super.__setPubSub(pubsub ?? this.pubsub);
653
791
  }
654
792
  /**
655
- * Host-owned run-ID enforcement at the public boundary. The durable-agent entry points (stream /
656
- * generate / prepare) take an OPTIONAL runId, and when it is omitted core's
657
- * `prepareForDurableExecution` mints `crypto.randomUUID()`
658
- * (create-durable-agent-DFHwqN2K.js:1211) — the exact unowned fallback this
659
- * wrapper forbids — and hands it to `executeWorkflow` BELOW this class's own
660
- * guard, where a bare UUID is already indistinguishable from a legitimately
661
- * caller-minted one. So the guard must ALSO fire HERE, before
662
- * `super.stream()/generate()/prepare()`, while "absent" is still visible. The
663
- * `typeof` check is load-bearing because `RegExp.test` coerces its argument to a string, so a
664
- * numeric runId would pass the pattern yet key a run by the number. Homed once
665
- * and shared by the call sites below so the rule cannot drift within this
666
- * class.
793
+ * Reject an absent caller runId before prepareForDurableExecution replaces
794
+ * it with a UUID that downstream path checks accept. The string check also
795
+ * prevents RegExp coercion from accepting a numeric registry key.
667
796
  */
668
797
  #assertCallerRunId(runId) {
669
798
  if (!isPathSafeId(runId)) {
@@ -693,13 +822,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
693
822
  globalRunRegistry.has(runId) ||
694
823
  this.runRegistryInternal.has(runId));
695
824
  }
696
- #assertGuardedStructuredOutput(options) {
697
- if (this.#isBreakwaterGuardedAgent &&
698
- options !== null &&
699
- typeof options === 'object' &&
700
- Object.hasOwn(options, 'structuredOutput')) {
701
- throw new TypeError('FlowsafeDurableAgent: structuredOutput is not supported for a Breakwater guarded agent because Mastra durable execution bypasses the narrow guarded handle');
702
- }
825
+ #snapshotCallOptions(options) {
826
+ return snapshotDurableCallOptions(options, this.#guardedCallOptionMapper);
703
827
  }
704
828
  /**
705
829
  * Enforce a caller-minted run ID before the inherited durable
@@ -713,11 +837,10 @@ export class FlowsafeDurableAgent extends DurableAgent {
713
837
  const hostStreamTicket = options !== undefined && this.#hostStreamTickets.has(options);
714
838
  if (hostStreamTicket)
715
839
  this.#hostStreamTickets.delete(options);
716
- const callOptions = snapshotDurableCallOptions(options);
840
+ const callOptions = this.#snapshotCallOptions(options);
717
841
  this.#assertCallerRunId(callOptions?.runId);
718
842
  if (!hostStreamTicket)
719
843
  this.#assertRunIdNotLive(callOptions.runId);
720
- this.#assertGuardedStructuredOutput(callOptions);
721
844
  let capturedSignal = false;
722
845
  if (!hostStreamTicket &&
723
846
  callOptions.requestContext === undefined &&
@@ -762,9 +885,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
762
885
  * `executeWorkflow()` and carries no field this could ride in.
763
886
  */
764
887
  idempotencyKey, authority) {
765
- const callOptions = snapshotDurableCallOptions(options);
888
+ const callOptions = this.#snapshotCallOptions(options);
766
889
  this.#assertCallerRunId(callOptions?.runId);
767
- this.#assertGuardedStructuredOutput(callOptions);
768
890
  if (callOptions.untilIdle) {
769
891
  throw new InvalidRunRequestError('streamUntilPersisted does not support untilIdle');
770
892
  }
@@ -841,10 +963,9 @@ export class FlowsafeDurableAgent extends DurableAgent {
841
963
  * one is not supplied.
842
964
  */
843
965
  async generate(messages, options) {
844
- const callOptions = snapshotDurableCallOptions(options);
966
+ const callOptions = this.#snapshotCallOptions(options);
845
967
  this.#assertCallerRunId(callOptions?.runId);
846
968
  this.#assertRunIdNotLive(callOptions.runId);
847
- this.#assertGuardedStructuredOutput(callOptions);
848
969
  try {
849
970
  return await super.generate(messages, callOptions);
850
971
  }
@@ -863,23 +984,14 @@ export class FlowsafeDurableAgent extends DurableAgent {
863
984
  }
864
985
  }
865
986
  /**
866
- * The same host-owned run-ID guard as {@link FlowsafeDurableAgent.stream}.
867
- * `prepare()`
868
- * is an inherited minting entry point: it forwards `options?.runId` into
869
- * core's `prepareForDurableExecution` (create-durable-agent-DFHwqN2K.js:7882),
870
- * which mints an unowned `crypto.randomUUID()` when it is absent
871
- * (create-durable-agent-DFHwqN2K.js:1211) AND REGISTERS a run under that id
872
- * (create-durable-agent-DFHwqN2K.js:7890) — so a later
873
- * `resume(runId)`/`executeWorkflow` sees a bare UUID `PATH_SAFE_ID_PATTERN`
874
- * already accepts, past every downstream guard. Enforce the caller-minted ID
875
- * here, while "absent" is still visible. A prepared id remains live until core
876
- * cleans up the run.
987
+ * Enforce the caller-owned id before DurableAgent.prepare forwards it to
988
+ * prepareForDurableExecution, which mints an absent id and registers the run.
989
+ * That UUID satisfies downstream path checks and stays live until cleanup.
877
990
  */
878
991
  async prepare(messages, options) {
879
- const callOptions = snapshotDurableCallOptions(options);
992
+ const callOptions = this.#snapshotCallOptions(options);
880
993
  this.#assertCallerRunId(callOptions?.runId);
881
994
  this.#assertRunIdNotLive(callOptions.runId);
882
- this.#assertGuardedStructuredOutput(callOptions);
883
995
  return super.prepare(messages, callOptions);
884
996
  }
885
997
  /**
@@ -1120,10 +1232,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
1120
1232
  * snapshot rows — which deployment-scoped retention purge owns — from being
1121
1233
  * dropped out from under that owner by a future internal caller.
1122
1234
  *
1123
- * Note what this override buys beyond that call-site audit: the override is
1124
- * the standing guard —
1125
- * it converts core's best-effort cleanup into a throw the moment a future
1126
- * release calls it on a path FlowSafe drives. None does at 1.67.0.
1235
+ * The override keeps core's best-effort deletion from taking ownership of
1236
+ * these rows if an internal execution path reaches the cleanup method.
1127
1237
  */
1128
1238
  async deleteRunSnapshots(_runId) {
1129
1239
  throw unavailableRunEntry('deleteRunSnapshots', BLOCKED_RUN_ENTRIES.deleteRunSnapshots);
@@ -1192,17 +1302,16 @@ export class FlowsafeDurableAgent extends DurableAgent {
1192
1302
  let inputProcessors = [];
1193
1303
  let llmRequestInputProcessors = [];
1194
1304
  const rehydrationAgent = new Proxy(wrappedAgent, {
1195
- get(target, property) {
1305
+ get: (target, property) => {
1196
1306
  if (property === 'listInputProcessors') {
1197
1307
  return async (requestContext) => {
1198
1308
  inputProcessors = await target.listInputProcessors(requestContext);
1199
- return inputProcessors.filter((processor) => processor.id === BREAKWATER_RBAC_PROCESSOR_ID);
1309
+ return inputProcessors.filter((processor) => this.#rehydrationInputProcessorIds.has(processor.id));
1200
1310
  };
1201
1311
  }
1202
1312
  if (property === '__listLLMRequestProcessors') {
1203
- return async (requestContext) => {
1204
- llmRequestInputProcessors =
1205
- await target.__listLLMRequestProcessors(requestContext);
1313
+ return async (...args) => {
1314
+ llmRequestInputProcessors = await target.__listLLMRequestProcessors(...args);
1206
1315
  return [];
1207
1316
  };
1208
1317
  }
@@ -1210,9 +1319,12 @@ export class FlowsafeDurableAgent extends DurableAgent {
1210
1319
  return typeof value === 'function' ? value.bind(target) : value;
1211
1320
  },
1212
1321
  });
1213
- const preparationOptions = options.memory !== undefined
1322
+ const preparationOptions = options.memory !== undefined || options.modelSettings !== undefined
1214
1323
  ? {
1215
- memory: options.memory,
1324
+ ...(options.memory !== undefined ? { memory: options.memory } : {}),
1325
+ ...(options.modelSettings !== undefined
1326
+ ? { modelSettings: options.modelSettings }
1327
+ : {}),
1216
1328
  }
1217
1329
  : undefined;
1218
1330
  const preparation = await prepareForDurableExecution({
@@ -1233,15 +1345,19 @@ export class FlowsafeDurableAgent extends DurableAgent {
1233
1345
  preparation.registryEntry.inputProcessors = inputProcessors;
1234
1346
  preparation.registryEntry.llmRequestInputProcessors =
1235
1347
  llmRequestInputProcessors;
1348
+ const budget = composeTotalBudget(options.abortController.signal, preparation.registryEntry.timeoutTotalMs);
1236
1349
  let cleaned = false;
1237
1350
  const cleanup = () => {
1238
1351
  if (cleaned)
1239
1352
  return;
1240
1353
  cleaned = true;
1354
+ budget.cleanup();
1241
1355
  preparation.registryEntry.cleanup?.();
1242
1356
  };
1243
1357
  const registryEntry = {
1244
1358
  ...preparation.registryEntry,
1359
+ abortController: options.abortController,
1360
+ abortSignal: budget.signal,
1245
1361
  cleanup,
1246
1362
  };
1247
1363
  this.runRegistryInternal.registerWithMessageList(options.runId, registryEntry, preparation.messageList, {
@@ -1257,12 +1373,20 @@ export class FlowsafeDurableAgent extends DurableAgent {
1257
1373
  * Rehydrate a suspended durable-agent run after isolate eviction, restore its
1258
1374
  * active thread registration, then resume through RunnerRuntime so approval
1259
1375
  * grant derivation and snapshot provenance remain authoritative.
1376
+ * A resumed leg observes from the current run stream position. Its thread
1377
+ * registration completes on the run's terminal outcome or a resume failure
1378
+ * after rehydration, when the wrapper publishes a terminal error. Another
1379
+ * suspension keeps blocking the thread until the next resume, as a first leg does.
1260
1380
  * Hosts expose this only from their trusted approval-decision topology.
1261
1381
  */
1262
1382
  async resumeViaRuntime(options) {
1263
1383
  this.#assertCallerRunId(options.runId);
1384
+ const memory = this.#guardedCallOptionMapper
1385
+ ? this.#guardedCallOptionMapper('memory', options.memory)
1386
+ : options.memory;
1264
1387
  let rehydrated = false;
1265
- let finishThreadRegistration;
1388
+ let leg;
1389
+ const legAbort = new AbortController();
1266
1390
  try {
1267
1391
  const summary = await this.#runtime.resume(this.getWorkflow().id, options.runId, {
1268
1392
  ...(options.step !== undefined ? { step: options.step } : {}),
@@ -1271,25 +1395,26 @@ export class FlowsafeDurableAgent extends DurableAgent {
1271
1395
  : {}),
1272
1396
  requestedBy: options.requestedBy,
1273
1397
  requestedByKind: 'human',
1274
- prepareExecution: async (requestContext) => {
1398
+ legAbort,
1399
+ prepareExecution: async (requestContext, workflowInput) => {
1400
+ const offset = (await this.pubsub.getHistory(AGENT_STREAM_TOPIC(options.runId))).length;
1401
+ const modelSettings = persistedModelSettings(workflowInput);
1275
1402
  await this.#rehydrateRegistry({
1276
1403
  runId: options.runId,
1277
1404
  requestContext,
1278
- ...(options.memory !== undefined
1279
- ? { memory: options.memory }
1280
- : {}),
1405
+ abortController: legAbort,
1406
+ ...(memory !== undefined ? { memory } : {}),
1407
+ ...(modelSettings !== undefined ? { modelSettings } : {}),
1281
1408
  });
1282
1409
  rehydrated = true;
1283
- const observed = await this.observe(options.runId);
1284
- const completion = new Promise((resolve) => {
1285
- finishThreadRegistration = resolve;
1286
- });
1287
- await this.#threadRuntime?.registerRun(this, bindThreadCompletion(observed.output, completion), {
1288
- runId: options.runId,
1289
- ...(options.memory !== undefined
1290
- ? { memory: options.memory }
1291
- : {}),
1292
- }, this.getPubSub());
1410
+ const observed = await this.observe(options.runId, { offset });
1411
+ if (this.#threadRuntime) {
1412
+ leg = this.#trackResumedLeg(options.runId);
1413
+ await this.#threadRuntime.registerRun(this, bindResumedLegLifecycle(observed.output, leg), {
1414
+ runId: options.runId,
1415
+ ...(memory !== undefined ? { memory } : {}),
1416
+ }, this.getPubSub());
1417
+ }
1293
1418
  },
1294
1419
  });
1295
1420
  if (summary.status === 'failed') {
@@ -1297,6 +1422,16 @@ export class FlowsafeDurableAgent extends DurableAgent {
1297
1422
  this.runRegistryInternal.cleanup(options.runId);
1298
1423
  globalRunRegistry.delete(options.runId);
1299
1424
  }
1425
+ if (isTerminalRunStatus(summary.status)) {
1426
+ this.#completeResumedThreadLegs(options.runId, summary.status === 'success'
1427
+ ? 'success'
1428
+ : summary.status === 'canceled' || summary.status === 'cancelled'
1429
+ ? 'canceled'
1430
+ : 'failed');
1431
+ }
1432
+ else if (leg) {
1433
+ leg.outcome = 'suspended';
1434
+ }
1300
1435
  return summary;
1301
1436
  }
1302
1437
  catch (error) {
@@ -1304,12 +1439,49 @@ export class FlowsafeDurableAgent extends DurableAgent {
1304
1439
  await this.#publishTerminalError(options.runId, error);
1305
1440
  this.runRegistryInternal.cleanup(options.runId);
1306
1441
  globalRunRegistry.delete(options.runId);
1442
+ this.#completeResumedThreadLegs(options.runId, 'failed');
1307
1443
  }
1308
1444
  throw error;
1309
1445
  }
1446
+ }
1447
+ #trackResumedLeg(runId) {
1448
+ let complete;
1449
+ const completion = new Promise((resolve) => {
1450
+ complete = resolve;
1451
+ });
1452
+ const leg = { completion, complete };
1453
+ let legs = this.#resumedThreadLegs.get(runId);
1454
+ if (!legs) {
1455
+ legs = new Set();
1456
+ this.#resumedThreadLegs.set(runId, legs);
1457
+ }
1458
+ legs.add(leg);
1459
+ return leg;
1460
+ }
1461
+ #completeResumedThreadLegs(runId, outcome) {
1462
+ const legs = this.#resumedThreadLegs.get(runId);
1463
+ if (!legs)
1464
+ return;
1465
+ this.#resumedThreadLegs.delete(runId);
1466
+ for (const leg of legs) {
1467
+ leg.outcome = outcome;
1468
+ leg.complete();
1469
+ }
1470
+ }
1471
+ async #settleRefusedStart(runId, refusal) {
1472
+ let published = false;
1473
+ try {
1474
+ published =
1475
+ (await this.#publishTerminalError(runId, refusal)) ||
1476
+ (await this.#publishTerminalError(runId, refusal));
1477
+ }
1310
1478
  finally {
1311
- finishThreadRegistration?.();
1479
+ this.#replayedSignals.delete(runId);
1480
+ this.runRegistryInternal.cleanup(runId);
1481
+ globalRunRegistry.delete(runId);
1312
1482
  }
1483
+ if (!published)
1484
+ throw refusal;
1313
1485
  }
1314
1486
  /**
1315
1487
  * Publish one terminal ERROR attempt without throwing. Call sites publish
@@ -1365,7 +1537,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1365
1537
  // Explicit read-only memory forbids preserving denied input.
1366
1538
  if (state.memoryConfig?.readOnly === true)
1367
1539
  return;
1368
- const registryEntry = globalRunRegistry.get(runId);
1540
+ const registryEntry = this.runRegistryInternal.get(runId);
1369
1541
  const tripwire = registryEntry?.tripwire;
1370
1542
  const memory = await this.getMemory({
1371
1543
  requestContext: registryEntry?.requestContext,
@@ -1570,6 +1742,10 @@ export class FlowsafeDurableAgent extends DurableAgent {
1570
1742
  const scheduleDispatch = this.#startScheduleDispatches.get(runId);
1571
1743
  const idempotencyKey = this.#startIdempotencyKeys.get(runId);
1572
1744
  const authority = this.#startAuthorities.get(runId);
1745
+ // stream() composes a caller's abortSignal into this controller and
1746
+ // registers it before this method runs; every model and tool call of the
1747
+ // leg reads a signal derived from it.
1748
+ const legAbort = this.runRegistryInternal.get(runId)?.abortController;
1573
1749
  if (requestedBy === undefined || requestedByKind === undefined) {
1574
1750
  if (requestedBy !== undefined || requestedByKind !== undefined) {
1575
1751
  throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
@@ -1584,19 +1760,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1584
1760
  this.#replayedSignals.delete(runId);
1585
1761
  await this.#persistUnownedInput(runId, workflowInput, replayedSignal);
1586
1762
  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`);
1587
- let published = false;
1588
- try {
1589
- published =
1590
- (await this.#publishTerminalError(runId, refusal)) ||
1591
- (await this.#publishTerminalError(runId, refusal));
1592
- }
1593
- finally {
1594
- this.#replayedSignals.delete(runId);
1595
- this.runRegistryInternal.cleanup(runId);
1596
- globalRunRegistry.delete(runId);
1597
- }
1598
- if (!published)
1599
- throw refusal;
1763
+ await this.#settleRefusedStart(runId, refusal);
1600
1764
  return;
1601
1765
  }
1602
1766
  const { runId: coreRunId, agentId: coreAgentId, ...payload } = workflowInput;
@@ -1608,6 +1772,20 @@ export class FlowsafeDurableAgent extends DurableAgent {
1608
1772
  coreAgentId !== authority.startIdentity.target.id) {
1609
1773
  throw new InvalidRunRequestError('Core input does not match agent start authority');
1610
1774
  }
1775
+ // The agent registry retains the preparation refusal when the isolate-wide
1776
+ // registry evicts its entry before the first step.
1777
+ if (this.runRegistryInternal.get(runId)?.tripwire?.processorId ===
1778
+ BREAKWATER_RBAC_PROCESSOR_ID) {
1779
+ const refusal = new AgentAuthorizationDeniedError();
1780
+ // The waiter's first rejection wins; publishing ERROR first supplies a
1781
+ // plain Error that doErrorResponse maps to 500.
1782
+ waiter?.reject(refusal);
1783
+ await this.#settleRefusedStart(runId, refusal);
1784
+ return;
1785
+ }
1786
+ if (legAbort === undefined) {
1787
+ console.error(JSON.stringify({ type: 'agent-leg-abort-unavailable', runId }));
1788
+ }
1611
1789
  const workflow = this.getWorkflow();
1612
1790
  summary = await this.#runtime.start(workflow.id, {
1613
1791
  runId,
@@ -1623,6 +1801,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1623
1801
  onPreparedStartIdentity: authority.onPreparedStartIdentity,
1624
1802
  runOwnerGuard: authority.runOwnerGuard,
1625
1803
  startReservation: authority.startReservation,
1804
+ ...(legAbort === undefined ? {} : { legAbort }),
1626
1805
  });
1627
1806
  waiter?.resolve();
1628
1807
  }