@proofoftech/flowsafe 0.22.0 → 0.24.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 (120) hide show
  1. package/CHANGELOG.md +160 -0
  2. package/README.md +77 -12
  3. package/dist/agent-host/catalog.d.ts.map +1 -1
  4. package/dist/agent-host/catalog.js +5 -2
  5. package/dist/agent-host/catalog.js.map +1 -1
  6. package/dist/agent-host/thread-host.d.ts +16 -0
  7. package/dist/agent-host/thread-host.d.ts.map +1 -1
  8. package/dist/agent-host/thread-host.js +81 -27
  9. package/dist/agent-host/thread-host.js.map +1 -1
  10. package/dist/agent-runner/durable-agent-runner.d.ts +121 -80
  11. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  12. package/dist/agent-runner/durable-agent-runner.js +747 -468
  13. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  14. package/dist/approval-ui/use-approval-dashboard.js +6 -6
  15. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  16. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  17. package/dist/background-tasks/d1-storage.js +2 -3
  18. package/dist/background-tasks/d1-storage.js.map +1 -1
  19. package/dist/background-tasks/host.d.ts.map +1 -1
  20. package/dist/background-tasks/host.js +27 -38
  21. package/dist/background-tasks/host.js.map +1 -1
  22. package/dist/do-runner/cause-chain.d.ts +5 -0
  23. package/dist/do-runner/cause-chain.d.ts.map +1 -1
  24. package/dist/do-runner/cause-chain.js +12 -0
  25. package/dist/do-runner/cause-chain.js.map +1 -1
  26. package/dist/do-runner/cf-types.d.ts +3 -0
  27. package/dist/do-runner/cf-types.d.ts.map +1 -1
  28. package/dist/do-runner/cf-types.js.map +1 -1
  29. package/dist/do-runner/constants.d.ts +1 -1
  30. package/dist/do-runner/constants.d.ts.map +1 -1
  31. package/dist/do-runner/constants.js +1 -1
  32. package/dist/do-runner/constants.js.map +1 -1
  33. package/dist/do-runner/core-events-nonce.d.ts +2 -0
  34. package/dist/do-runner/core-events-nonce.d.ts.map +1 -0
  35. package/dist/do-runner/core-events-nonce.js +16 -0
  36. package/dist/do-runner/core-events-nonce.js.map +1 -0
  37. package/dist/do-runner/d1-storage.js +1 -9
  38. package/dist/do-runner/d1-storage.js.map +1 -1
  39. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  40. package/dist/do-runner/do-error-response.js +2 -1
  41. package/dist/do-runner/do-error-response.js.map +1 -1
  42. package/dist/do-runner/durable-object.d.ts +17 -2
  43. package/dist/do-runner/durable-object.d.ts.map +1 -1
  44. package/dist/do-runner/durable-object.js +442 -55
  45. package/dist/do-runner/durable-object.js.map +1 -1
  46. package/dist/do-runner/fenced-workflow-capability.d.ts +24 -0
  47. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  48. package/dist/do-runner/fenced-workflows-d1.d.ts +5 -1
  49. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  50. package/dist/do-runner/fenced-workflows-d1.js +149 -48
  51. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  52. package/dist/do-runner/index.d.ts +2 -2
  53. package/dist/do-runner/index.d.ts.map +1 -1
  54. package/dist/do-runner/index.js +2 -2
  55. package/dist/do-runner/index.js.map +1 -1
  56. package/dist/do-runner/init.d.ts +2 -3
  57. package/dist/do-runner/init.d.ts.map +1 -1
  58. package/dist/do-runner/init.js.map +1 -1
  59. package/dist/do-runner/memory-id.js +1 -1
  60. package/dist/do-runner/memory-id.js.map +1 -1
  61. package/dist/do-runner/pubsub.d.ts +6 -2
  62. package/dist/do-runner/pubsub.d.ts.map +1 -1
  63. package/dist/do-runner/pubsub.js +12 -22
  64. package/dist/do-runner/pubsub.js.map +1 -1
  65. package/dist/do-runner/run-lifecycle.d.ts +42 -2
  66. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  67. package/dist/do-runner/run-lifecycle.js +57 -1
  68. package/dist/do-runner/run-lifecycle.js.map +1 -1
  69. package/dist/do-runner/run-terminal-state.d.ts +2 -0
  70. package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
  71. package/dist/do-runner/run-terminal-state.js +4 -0
  72. package/dist/do-runner/run-terminal-state.js.map +1 -1
  73. package/dist/do-runner/runtime.d.ts +91 -58
  74. package/dist/do-runner/runtime.d.ts.map +1 -1
  75. package/dist/do-runner/runtime.js +351 -191
  76. package/dist/do-runner/runtime.js.map +1 -1
  77. package/dist/do-runner/suspension-deadline.d.ts +25 -17
  78. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  79. package/dist/do-runner/suspension-deadline.js +44 -21
  80. package/dist/do-runner/suspension-deadline.js.map +1 -1
  81. package/dist/do-runner/workflow-snapshot-row.d.ts +7 -0
  82. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  83. package/dist/do-runner/workflow-snapshot-row.js +21 -0
  84. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  85. package/dist/host-kit/approval-bridge.d.ts +11 -8
  86. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  87. package/dist/host-kit/approval-bridge.js +15 -9
  88. package/dist/host-kit/approval-bridge.js.map +1 -1
  89. package/dist/host-kit/do-response.d.ts.map +1 -1
  90. package/dist/host-kit/do-response.js +7 -1
  91. package/dist/host-kit/do-response.js.map +1 -1
  92. package/dist/host-kit/flowsafe-worker.d.ts +2 -1
  93. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  94. package/dist/host-kit/flowsafe-worker.js +4 -2
  95. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  96. package/dist/host-kit/run-router.d.ts.map +1 -1
  97. package/dist/host-kit/run-router.js +3 -2
  98. package/dist/host-kit/run-router.js.map +1 -1
  99. package/dist/schedules/schedules-d1.d.ts +1 -0
  100. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  101. package/dist/schedules/schedules-d1.js +35 -22
  102. package/dist/schedules/schedules-d1.js.map +1 -1
  103. package/dist/schedules/tick.d.ts +17 -2
  104. package/dist/schedules/tick.d.ts.map +1 -1
  105. package/dist/schedules/tick.js +63 -44
  106. package/dist/schedules/tick.js.map +1 -1
  107. package/dist/signals/client.d.ts +7 -4
  108. package/dist/signals/client.d.ts.map +1 -1
  109. package/dist/signals/client.js +9 -7
  110. package/dist/signals/client.js.map +1 -1
  111. package/dist/signals/d1-shared.js +1 -1
  112. package/dist/signals/d1-shared.js.map +1 -1
  113. package/dist/signals/index.d.ts +1 -1
  114. package/dist/signals/index.d.ts.map +1 -1
  115. package/dist/signals/index.js.map +1 -1
  116. package/dist/signals/thread-do-routes.d.ts +56 -10
  117. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  118. package/dist/signals/thread-do-routes.js +434 -247
  119. package/dist/signals/thread-do-routes.js.map +1 -1
  120. package/package.json +18 -9
@@ -1,284 +1,70 @@
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: server-minted runIds, per-leg requestContextForRun grant
5
- // derivation, snapshot provenance, RunSummary, and retention purge, with no
6
- // second execution path to audit.
2
+ // FlowsafeDurableAgent drives Mastra's durable-agent loop through RunnerRuntime
3
+ // so agent legs inherit its execution and lifecycle invariants.
7
4
  //
8
- // The mechanic was validated against @mastra/core 1.50.0 dist. Every offset in
9
- // THIS section is 1.50.0-vintage and deliberately kept as the provenance of the
10
- // original validation; later sections carry their own stamp:
11
- // DurableAgent compiles the agent loop to the default-engine workflow
12
- // 'durable-agentic-loop' (agent/durable index.js: AGENTIC_LOOP :62,
13
- // getWorkflow() :5936, agent-agnostic — the agent is resolved per run by the
14
- // `agentId` in the input, so ONE registered loop serves every durable agent).
15
- // `DurableAgent.stream()` resolves the non-serializable model/tools onto the
16
- // in-process globalRunRegistry (keyed by runId), builds a serializable
17
- // DurableAgenticWorkflowInput, then calls the OVERRIDABLE
18
- // `executeWorkflow(runId, workflowInput)` — the documented subclass seam
19
- // (durable-agent.d.ts: "Subclasses override this method to customize how the
20
- // workflow is executed"; EventedAgent/InngestAgent override it the same way).
21
- // The base runs it via `workflow.createRun() + run.start()`; we route it
22
- // 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.
23
9
  //
24
- // Why this composes the grant-only doctrine for free: the durable tool-call
25
- // step hands `tool.execute` the ENGINE-LEG requestContext from its step params
26
- // (index.js: `const { ..., requestContext } = params` :3138 ->
27
- // `toolOptions = { ..., requestContext }` :3339 ->
28
- // `tool.execute(cleanedArgs, toolOptions)` :3642), NOT the stream()-time
29
- // registry copy. Under runtime drive that engine-leg context is exactly what
30
- // #requestContextFor mints per leg — so approvalGrantProvider's
31
- // `breakwater.connectorGrants` grant reaches the connector write gate with
32
- // zero extra wiring, and a forged/self resume that mints no grant fails closed
33
- // there. The registry copy is read only for the fail-closed, over-require-safe
34
- // approval pre-check.
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.
35
14
  //
36
- // Host-owned run ids at the boundary: stream()/generate()/prepare() are the
37
- // THREE inherited minting entry points. Each takes an OPTIONAL runId and, when
38
- // it is absent, lets core mint an unowned crypto.randomUUID() upstream
39
- // (prepareForDurableExecution, agent/durable index.js:589) that
40
- // PATH_SAFE_ID_PATTERN then accepts, slipping past executeWorkflow's guard AND
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.
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.
47
19
  //
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.
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.
53
24
  //
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.
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.
58
28
  //
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.
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.
70
33
  //
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.
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.
83
38
  //
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 the
199
- // network four (network, resumeNetwork, approveNetworkToolCall,
200
- // declineNetworkToolCall), the legacy pair (generateLegacy, streamLegacy) and
201
- // sendToolApproval, which it files `intentionallyUnavailable`
202
- // (packages/breakwater/src/agent/agent.test.ts). It diverges on
203
- // listSuspendedRuns, which it files under `explicitlyNonExecution` — the same
204
- // divergence as listActiveRuns, and for the same reason: a narrowed HANDLE can
205
- // only omit, so a data-returning member is harmless there, while an INSTANCE
206
- // Mastra calls in-process must throw. The two members blocked below diverge the
207
- // same way; each entry records it.
208
- //
209
- // Two more Agent-level members are blocked. Read from the @mastra/core 1.67.0
210
- // dist, the declared peer; offsets here are 1.67.0-vintage, in
211
- // agent-Dk0N0Nlg.js unless another file is named, and the 1.53.0 offsets above
212
- // are left as the provenance of that read. The peer carries both members, so
213
- // each refusal shadows a real implementation.
214
- //
215
- // - listActiveThreadRuns() (:38214) is the discovery ground one scope wider
216
- // than listActiveRuns. It takes no arguments and returns `{ runId,
217
- // resourceId, threadId }` for every thread on the pubsub instance with a run
218
- // in flight (storage-MbGlKLkB.js:1011-1023), and that state is keyed by
219
- // pubsub instance rather than by agent (`#statesByPubSub`, :150, read through
220
- // #getState :294), so it narrows by neither principal nor agent where the two
221
- // listings above at least narrow by agentId. The in-process sibling
222
- // getActiveThreadRunId() stays non-execution because it makes the caller name
223
- // the (resourceId, threadId) pair: it confirms where this enumerates.
224
- // Breakwater files it `explicitlyNonExecution` (agent.test.ts) for the reason
225
- // it files listActiveRuns there: a narrowed HANDLE can only omit, so a
226
- // data-returning member is harmless there, while an INSTANCE Mastra calls
227
- // in-process must throw. Cost, stated rather than left to be rediscovered:
228
- // core's AgentController aggregates this member across its backing agents
229
- // (agent-controller-CKgKFyMR.js:5722-5725), so that aggregation now throws.
230
- // It is already unusable over this class — the same controller calls the
231
- // blocked sendToolApproval() at :4089 and :4118.
232
- // - __setThreadRuntimeAgent() (:33609) installs another agent as the target
233
- // the thread-runtime paths resolve through #getThreadRuntimeAgent()
234
- // (:33612, `this.#threadRuntimeAgent ?? this`); the refusal in
235
- // BLOCKED_RUN_ENTRIES names those paths, for the core it is written
236
- // against. That is the fourth ground by installation rather than by call:
237
- // the containment those inherited members rely on IS virtual dispatch on
238
- // `this`, so one call moves every run those paths start onto an agent
239
- // carrying none of these overrides — no caller-minted runId assertion, no
240
- // executeWorkflow, no #startRequesters backstop. subscribeToThread drives no
241
- // run of its own; the field moves its replay target all the same. It is
242
- // public in the type surface (agent.d.ts:229 declares it with no modifier),
243
- // so unlike getLegacyHandler it takes no private cast.
244
- // Breakwater files it `explicitlyNonExecution` (agent.test.ts) for the
245
- // reason it files the listings there: a narrowed HANDLE can only omit, so
246
- // a setter is harmless there, while an INSTANCE Mastra calls in-process
247
- // must throw.
248
- //
249
- // Both carry the `override` keyword, like every other refusal in this class:
250
- // the declared peer declares both members, so the keyword holds each refusal to
251
- // a base that exists and fails the typecheck if a future core drops one. Each
252
- // signature satisfies the base it shadows on that base's own terms; the caveat
253
- // on each member says how.
254
- //
255
- // Blocking them keeps the single-resume and no-capability guarantees true by
256
- // construction: resumeViaRuntime() is the ONLY way a run resumes.
257
- // ApprovalService.decide -> the host's ResumeRunFn ->
258
- // createAgentApprovalResumer, which hands every 'durable-agentic-loop' record to
259
- // the thread topology's resume (-> resumeViaRuntime -> runtime.resume) and
260
- // refuses one carrying no agent-thread target rather than falling through to the
261
- // generic resumer; grants are derived on the (suspendedAt, resumeCount)
262
- // fingerprint there. Blocking does not un-brand the agent — DurableAgentLike
263
- // duck-types on `recover`/`recoverActiveRuns` merely BEING functions
264
- // (agent-Dk0N0Nlg.js:272), which the overrides still are. The surface tripwire in
265
- // durable-agent-surface.test.ts requires every DurableAgent prototype member to
266
- // stay classified, so a future peer bump surfaces whatever it adds.
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.
267
43
  //
268
44
  // Live-isolate scope: the loop resolves the tool's execute closure from the
269
45
  // in-process globalRunRegistry (populated by stream()). A DO holds one run in
270
46
  // one isolate, so a resume decided before eviction finds it. A resume
271
47
  // AFTER eviction must first rehydrate that registry without replaying
272
48
  // application input processors. resumeViaRuntime() rebuilds the registry with
273
- // complete runtime processor lists after invoking only reserved RBAC during
274
- // empty-message preparation, then drives runtime.resume().
275
- import { isMastraSignalMessage, MessageList, mastraDBMessageToSignal, } from '@mastra/core/agent';
276
- import { DurableAgent, globalRunRegistry, prepareForDurableExecution, } from '@mastra/core/agent/durable';
49
+ // complete runtime processor lists after invoking only Breakwater's reserved
50
+ // processInput steps during empty-message preparation, then drives
51
+ // runtime.resume().
52
+ import { isCreatedAgentSignal, isDurableAgentLike, isMastraSignalMessage, isTransientSignalMessage, MessageList, mastraDBMessageToSignal, signalToMastraDBMessage, } from '@mastra/core/agent';
53
+ import { AGENT_STREAM_TOPIC, DurableAgent, globalRunRegistry, prepareForDurableExecution, } from '@mastra/core/agent/durable';
277
54
  import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
55
+ import { DoStatusError } from '../do-runner/do-status-error.js';
278
56
  import { normalizeMutationEpoch, normalizeStartIdentity, } from '../do-runner/execution-admission.js';
279
57
  import { InvalidRunRequestError, isPathSafeId, RunStateUnreadableError, } from '../do-runner/index.js';
280
58
  import { resourceIdFromKey } from '../do-runner/memory-id.js';
59
+ import { isTerminalRunStatus } from '../do-runner/run-terminal-state.js';
281
60
  import { captureReservation, } from '../do-runner/start-reservation-contract.js';
61
+ class AgentAuthorizationDeniedError extends DoStatusError {
62
+ status = 403;
63
+ constructor() {
64
+ super('agent authorization denied');
65
+ this.name = 'AgentAuthorizationDeniedError';
66
+ }
67
+ }
282
68
  /** @internal A coherent snapshot belongs to another agent or thread. */
283
69
  export class AgentRunSelectorMismatchError extends RunStateUnreadableError {
284
70
  constructor(workflowId, runId) {
@@ -296,11 +82,14 @@ const UNOWNED_INPUT_PERSIST_TIMEOUT_MS = 5_000;
296
82
  const UNREGISTERED_RUN_REFUSAL_PREFIX = 'Flowsafe durable-agent runner refused unregistered run: ';
297
83
  /**
298
84
  * @internal Metadata key that prevents a route delivery from being terminally
299
- * persisted. Deliberately deep-imported by `signals/thread-do-routes.ts` and
300
- * kept off `./index.js`.
85
+ * persisted. Kept off `./index.js`.
301
86
  */
302
87
  export const FLOWSAFE_PERSISTENCE_FORBIDDEN = 'flowsafe.persistence-forbidden';
303
88
  const BREAKWATER_GUARDED_AGENT_HOST_PROTOCOL = Symbol.for('@proofoftech/breakwater/guarded-agent-host/v1');
89
+ const BREAKWATER_RBAC_PROCESSOR_ID = 'breakwater-rbac';
90
+ // Replaying the reserved failure step for unresolved memory processors refuses
91
+ // rehydration before the resumed step.
92
+ const BREAKWATER_MEMORY_PROCESSOR_ID = 'breakwater-memory';
304
93
  function captureAgentStartAuthority(source, requestedBy, requestedByKind) {
305
94
  if (source === null || typeof source !== 'object' || Array.isArray(source)) {
306
95
  throw new InvalidRunRequestError('agent start authority is required');
@@ -372,7 +161,14 @@ function captureAgentStartAuthority(source, requestedBy, requestedByKind) {
372
161
  startReservation,
373
162
  });
374
163
  }
375
- function snapshotDurableCallOptions(options) {
164
+ function ownDataDescriptor(target, key, path) {
165
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
166
+ if (descriptor && !('value' in descriptor)) {
167
+ throw new TypeError(`FlowsafeDurableAgent: call option '${path}' must be a data property`);
168
+ }
169
+ return descriptor;
170
+ }
171
+ function snapshotDurableCallOptions(options, mapper) {
376
172
  if (options === undefined)
377
173
  return undefined;
378
174
  if (options === null ||
@@ -382,22 +178,19 @@ function snapshotDurableCallOptions(options) {
382
178
  }
383
179
  const snapshot = {};
384
180
  for (const key of Reflect.ownKeys(options)) {
385
- const descriptor = Object.getOwnPropertyDescriptor(options, key);
181
+ const descriptor = ownDataDescriptor(options, key, String(key));
386
182
  if (!descriptor)
387
183
  continue;
388
- if (descriptor.get || descriptor.set) {
389
- throw new TypeError(`FlowsafeDurableAgent: call option '${String(key)}' must be a data property`);
390
- }
391
184
  Object.defineProperty(snapshot, key, {
392
185
  configurable: false,
393
186
  enumerable: descriptor.enumerable,
394
- value: descriptor.value,
187
+ value: mapper ? mapper(key, descriptor.value) : descriptor.value,
395
188
  writable: false,
396
189
  });
397
190
  }
398
191
  return Object.freeze(snapshot);
399
192
  }
400
- /** @internal Shared with the guarded agent catalog's compatibility check. */
193
+ /** @internal */
401
194
  export function breakwaterGuardedAgentHostProtocol(agent) {
402
195
  if ((typeof agent !== 'object' && typeof agent !== 'function') || !agent) {
403
196
  return undefined;
@@ -415,23 +208,41 @@ export function breakwaterGuardedAgentHostProtocol(agent) {
415
208
  return protocol;
416
209
  }
417
210
  /**
418
- * Why every member of the resume family is refused. Homed once: the seven
211
+ * @internal Why the runner refuses to wrap `agent`, or `undefined` when it
212
+ * accepts it.
213
+ */
214
+ export function unwrappableAgentReason(agent) {
215
+ if (agent.durable) {
216
+ return "sets the 'durable' option: a Mastra that registers it wraps it in its own DurableAgent, whose loop, recovery and run listing run outside RunnerRuntime";
217
+ }
218
+ if (isDurableAgentLike(agent)) {
219
+ return 'is already a durable agent: the runtime registers the agent it wraps on its own Mastra, where a Mastra DurableAgent brings recovery and run listing outside RunnerRuntime and a FlowsafeDurableAgent refuses to register; wrap the plain Agent instead';
220
+ }
221
+ if (agent.getChannels() != null) {
222
+ return 'has channels configured: Mastra dispatches their inbound messages and tool approvals to that agent outside RunnerRuntime';
223
+ }
224
+ if (agent.getDeclaredSchedules().length > 0) {
225
+ return 'declares schedules: the schedule worker of a Mastra that registers that agent fires them on it outside RunnerRuntime';
226
+ }
227
+ return undefined;
228
+ }
229
+ /**
230
+ * Why every member of the resume family is refused. Homed once: the family's
419
231
  * entry points are one code path (resumeStream/resumeGenerate/the approve and
420
232
  * decline pairs all funnel into resume()), so one sentence must not drift into
421
- * seven.
233
+ * a copy per entry point.
422
234
  */
423
235
  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";
424
236
  /**
425
- * Why the four network entry points are refused. Homed once: `network()` starts
426
- * and `resumeNetwork()` resumes THE SAME networkLoop, and the approve/decline
427
- * pair are one-line forwards to `resumeNetwork()`, so one sentence must not
428
- * drift into four.
237
+ * Why the network entry points are refused. Homed once: `network()` starts and
238
+ * `resumeNetwork()` resumes THE SAME networkLoop, and the approve/decline pair
239
+ * are one-line forwards to `resumeNetwork()`, so one sentence must not drift
240
+ * into a copy per entry point.
429
241
  */
430
242
  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';
431
243
  /**
432
- * Why both legacy execution entry points are refused. Homed once: each is a
433
- * one-line forward into the SAME AgentLegacyHandler, so they are one code path
434
- * wearing two names.
244
+ * Why the legacy execution entry points are refused. Homed once: each is a
245
+ * one-line forward into the SAME AgentLegacyHandler, so they are one code path.
435
246
  */
436
247
  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)";
437
248
  /**
@@ -439,32 +250,322 @@ const LEGACY_FAMILY_REASON = "the AI SDK v4 legacy handler is a second execution
439
250
  * but its continuation branch STARTS a run under a core-minted id — a mint on
440
251
  * the far side of a method that never asks the caller for one.
441
252
  */
442
- 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';
253
+ 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';
254
+ /**
255
+ * Why binding the wrapper to a Mastra is refused. Homed once: `__setMastra()`
256
+ * forwards to `__registerMastra()`, so the two are one code path.
257
+ */
258
+ const MASTRA_BINDING_REASON = "it binds the runner and its wrapped agent to a Mastra the runtime did not build, so every later leg is prepared against that Mastra; registered through Mastra.addAgent once the runtime has built its own Mastra, it also repoints the runtime's loop workflow, and with it run state, to that Mastra's storage";
259
+ /**
260
+ * Why service setters are refused. Homed once: both install after construction
261
+ * and forward their service to the wrapped agent.
262
+ */
263
+ const INSTALLED_SERVICE_REASON = "it installs memory or pub/sub after construction and forwards it to the wrapped agent; the wrapper's pub/sub is fixed at construction because thread state, signal delivery and the run's drain share it";
264
+ /**
265
+ * Why direct aborts are refused. Homed once: both bypass the terminate route's
266
+ * ownership and disputed-settlement checks.
267
+ */
268
+ 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 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";
270
+ const GUARDED_OBSERVABILITY_REASON = 'observability only';
271
+ const GUARDED_REENTRY_REASON = "Mastra's own re-entry options for its idle loop and background-task wait";
272
+ // The single classification of a guarded agent's durable call options; the
273
+ // host-facing list in docs/durable-agents.md#durable-call-options follows it.
274
+ // Keys the table does not name, and symbol keys, pass unchanged: core re-enters
275
+ // stream() with keys of its own. Absent compared keys pass because core merges
276
+ // the guarded defaults into every run it registers.
277
+ const GUARDED_DURABLE_CALL_OPTIONS = {
278
+ structuredOutput: {
279
+ kind: 'refused',
280
+ why: 'Mastra parses and releases the structured object outside the output policies',
281
+ },
282
+ errorProcessors: {
283
+ kind: 'refused',
284
+ why: 'error processors can change model requests after the guarded input chain',
285
+ },
286
+ clientTools: {
287
+ kind: 'refused',
288
+ why: "Mastra maps a per-call client tool's result after the guarded input policies have read it",
289
+ },
290
+ toolsets: {
291
+ kind: 'refused',
292
+ why: "Mastra adds the call's tools and maps a client tool's result after the guarded input policies have read it",
293
+ },
294
+ outputProcessors: {
295
+ kind: 'refused',
296
+ why: "Mastra replaces the guarded output processors, output policies included, with the call's list",
297
+ },
298
+ inputProcessors: {
299
+ kind: 'refused',
300
+ why: 'Breakwater fixes the guarded input processors at construction',
301
+ },
302
+ instructions: {
303
+ kind: 'refused',
304
+ why: "Mastra replaces the guarded agent's instructions with the call's",
305
+ },
306
+ system: {
307
+ kind: 'refused',
308
+ why: "Mastra adds the call's system messages, which the input policies do not read",
309
+ },
310
+ context: {
311
+ kind: 'refused',
312
+ why: "Mastra adds the call's context messages, which the input policies do not read",
313
+ },
314
+ prepareStep: {
315
+ kind: 'refused',
316
+ why: "Mastra runs the call's step preparation after the guarded input processors on every step",
317
+ },
318
+ hooks: {
319
+ kind: 'refused',
320
+ why: "Mastra runs the call's tool hooks over the guarded agent's own, and a hook can replace a tool call's result",
321
+ },
322
+ scorers: {
323
+ kind: 'refused',
324
+ why: "Mastra replaces the guarded agent's scorers with the call's",
325
+ },
326
+ savePerStep: {
327
+ kind: 'refused',
328
+ why: "Mastra saves each step before the output processors' result phase and before a later refusal",
329
+ },
330
+ versions: {
331
+ kind: 'refused',
332
+ why: "Mastra resolves the guarded agent's sub-agents to the call's versions",
333
+ },
334
+ autoResumeSuspendedTools: {
335
+ kind: 'refused',
336
+ why: 'Mastra adds a system instruction after the guarded input chain and lets model input resume suspended tools',
337
+ },
338
+ includeRawChunks: {
339
+ kind: 'refused',
340
+ why: "the provider's raw chunks reach the stream without passing the output policies",
341
+ },
342
+ onChunk: {
343
+ kind: 'refused',
344
+ why: 'Mastra calls it with each chunk before the output processors run',
345
+ },
346
+ delegation: {
347
+ kind: 'refused',
348
+ why: "Mastra runs the call's delegation hooks, which can change what sub-agents receive and return",
349
+ },
350
+ onIterationComplete: {
351
+ kind: 'refused',
352
+ why: 'its feedback reaches the model and the saved thread without passing the guarded policies',
353
+ },
354
+ isTaskComplete: {
355
+ kind: 'refused',
356
+ why: "Mastra runs the call's completion scorers, and their feedback reaches the model and the saved thread without passing the guarded policies",
357
+ },
358
+ transform: {
359
+ kind: 'refused',
360
+ why: "Mastra replaces the guarded agent's tool-payload transform with the call's",
361
+ },
362
+ experimentalTransform: {
363
+ kind: 'refused',
364
+ why: "it rewrites the thread's shared stream after the output processors",
365
+ },
366
+ requireToolApproval: {
367
+ kind: 'refused',
368
+ 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",
369
+ },
370
+ backgroundTaskPolicy: {
371
+ kind: 'refused',
372
+ why: 'it changes the delegated tools Mastra assembles, and Breakwater disables background tasks at construction',
373
+ },
374
+ maxProcessorRetries: {
375
+ kind: 'refused',
376
+ why: 'Breakwater fixes processor retries at construction',
377
+ },
378
+ eagerToolExecution: {
379
+ kind: 'refused',
380
+ why: "the guarded agent runs no tool eagerly, and Mastra's durable execution does not support eager tool execution",
381
+ },
382
+ maxSteps: { kind: 'compared', comparison: 'guardedMaxSteps' },
383
+ toolChoice: { kind: 'compared', comparison: 'guardedToolChoice' },
384
+ disableBackgroundTasks: {
385
+ kind: 'compared',
386
+ comparison: 'backgroundTasksDisabled',
387
+ },
388
+ memory: { kind: 'memoryBinding' },
389
+ runId: {
390
+ kind: 'allowed',
391
+ why: 'the host mints the run id, and each entry requires a path-safe one',
392
+ },
393
+ requestContext: {
394
+ kind: 'allowed',
395
+ why: 'the host builds it, and Breakwater authorizes the call from it',
396
+ },
397
+ abortSignal: { kind: 'allowed', why: 'it can only stop the run' },
398
+ actor: {
399
+ kind: 'allowed',
400
+ why: "Mastra's authorization signal, which only the host sets; Breakwater authorizes from the request context",
401
+ },
402
+ mcp: {
403
+ kind: 'allowed',
404
+ why: 'an execution context for tools the agent already has; it adds none',
405
+ },
406
+ serverless: {
407
+ kind: 'allowed',
408
+ why: 'it keeps the platform alive for finish work and changes nothing the call does',
409
+ },
410
+ hideSignals: {
411
+ kind: 'allowed',
412
+ why: "it hides signals from the caller's stream only; model context and storage are unchanged",
413
+ },
414
+ closeOnSuspend: {
415
+ kind: 'allowed',
416
+ why: "it closes the caller's stream when the run suspends",
417
+ },
418
+ stopWhen: {
419
+ kind: 'allowed',
420
+ why: 'it can only stop the run earlier, within maxSteps',
421
+ },
422
+ activeTools: {
423
+ kind: 'allowed',
424
+ why: "it selects among the guarded agent's tools and adds none",
425
+ },
426
+ toolCallConcurrency: {
427
+ kind: 'allowed',
428
+ why: "it schedules the guarded agent's tool calls and adds none",
429
+ },
430
+ returnScorerData: {
431
+ kind: 'allowed',
432
+ why: "it returns the guarded agent's own scorers' data",
433
+ },
434
+ modelSettings: {
435
+ kind: 'allowed',
436
+ why: 'host-owned generation settings: headers, stop sequences and timeouts',
437
+ },
438
+ providerOptions: {
439
+ kind: 'allowed',
440
+ why: "the thread host checks it against Breakwater's accepted provider options, and a direct caller must",
441
+ },
442
+ onStepFinish: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
443
+ onFinish: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
444
+ onError: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
445
+ onSuspended: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
446
+ onAbort: { kind: 'allowed', why: GUARDED_CALLBACK_REASON },
447
+ tracingOptions: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
448
+ tracing: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
449
+ loggerVNext: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
450
+ metrics: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
451
+ tracingContext: { kind: 'allowed', why: GUARDED_OBSERVABILITY_REASON },
452
+ untilIdle: { kind: 'allowed', why: GUARDED_REENTRY_REASON },
453
+ _skipBgTaskWait: { kind: 'allowed', why: GUARDED_REENTRY_REASON },
454
+ };
455
+ const GUARDED_MEMORY_REASON = "Mastra applies call-level memory configuration and thread fields outside the input policies; configure them on the agent's Memory";
456
+ function guardedMemoryBinding(memory) {
457
+ if (memory === undefined)
458
+ return memory;
459
+ if (memory === null || typeof memory !== 'object' || Array.isArray(memory)) {
460
+ throw new TypeError('FlowsafeDurableAgent: memory must be an object for a Breakwater guarded agent');
461
+ }
462
+ const binding = {};
463
+ for (const key of Reflect.ownKeys(memory)) {
464
+ if (key !== 'thread' && key !== 'resource') {
465
+ throw new TypeError(`FlowsafeDurableAgent: memory.${String(key)} is not supported for a Breakwater guarded agent because ${GUARDED_MEMORY_REASON}`);
466
+ }
467
+ const descriptor = ownDataDescriptor(memory, key, `memory.${key}`);
468
+ if (!descriptor)
469
+ continue;
470
+ let value = descriptor.value;
471
+ if (key === 'thread' &&
472
+ value !== null &&
473
+ (typeof value === 'object' || typeof value === 'function')) {
474
+ let idDescriptor;
475
+ for (const threadKey of Reflect.ownKeys(value)) {
476
+ if (threadKey !== 'id') {
477
+ throw new TypeError(`FlowsafeDurableAgent: memory.thread.${String(threadKey)} is not supported for a Breakwater guarded agent because ${GUARDED_MEMORY_REASON}`);
478
+ }
479
+ idDescriptor = ownDataDescriptor(value, threadKey, 'memory.thread.id');
480
+ }
481
+ value = Object.freeze({ id: idDescriptor?.value });
482
+ }
483
+ binding[key] = value;
484
+ }
485
+ return Object.freeze(binding);
486
+ }
487
+ function guardedToolChoiceMatches(value, guarded) {
488
+ if (typeof guarded === 'string')
489
+ return value === guarded;
490
+ if (!guarded || value === null || typeof value !== 'object')
491
+ return false;
492
+ if (Reflect.ownKeys(value).some((key) => key !== 'type' && key !== 'toolName')) {
493
+ return false;
494
+ }
495
+ const typeDescriptor = Object.getOwnPropertyDescriptor(value, 'type');
496
+ const toolNameDescriptor = Object.getOwnPropertyDescriptor(value, 'toolName');
497
+ return (typeDescriptor !== undefined &&
498
+ 'value' in typeDescriptor &&
499
+ typeDescriptor.value === guarded.type &&
500
+ toolNameDescriptor !== undefined &&
501
+ 'value' in toolNameDescriptor &&
502
+ toolNameDescriptor.value === guarded.toolName);
503
+ }
504
+ function guardedCallOptionMapper(defaults) {
505
+ const { maxSteps, toolChoice } = defaults;
506
+ return (key, value) => {
507
+ if (key === '__proto__') {
508
+ const why = "Mastra's option merge makes its value the prototype of the options it resolves";
509
+ throw new TypeError(`FlowsafeDurableAgent: __proto__ is not supported for a Breakwater guarded agent because ${why}`);
510
+ }
511
+ if (typeof key !== 'string' ||
512
+ !Object.hasOwn(GUARDED_DURABLE_CALL_OPTIONS, key)) {
513
+ return value;
514
+ }
515
+ const rule = GUARDED_DURABLE_CALL_OPTIONS[key];
516
+ switch (rule.kind) {
517
+ case 'refused':
518
+ throw new TypeError(`FlowsafeDurableAgent: ${key} is not supported for a Breakwater guarded agent because ${rule.why}`);
519
+ case 'memoryBinding':
520
+ return guardedMemoryBinding(value);
521
+ case 'allowed':
522
+ return value;
523
+ case 'compared': {
524
+ let expected;
525
+ let matches;
526
+ switch (rule.comparison) {
527
+ case 'guardedMaxSteps':
528
+ expected = maxSteps;
529
+ matches = value === expected;
530
+ break;
531
+ case 'guardedToolChoice':
532
+ expected = toolChoice;
533
+ matches = guardedToolChoiceMatches(value, toolChoice);
534
+ break;
535
+ case 'backgroundTasksDisabled':
536
+ expected = true;
537
+ matches = value === expected;
538
+ break;
539
+ }
540
+ if (!matches) {
541
+ throw new TypeError(`FlowsafeDurableAgent: ${key} must equal the guarded agent's own value`);
542
+ }
543
+ return expected;
544
+ }
545
+ }
546
+ };
547
+ }
443
548
  /**
444
- * Why each blocked entry point is refused, keyed by method name. The SINGLE
445
- * source: every override throws `unavailableRunEntry(name,
446
- * BLOCKED_RUN_ENTRIES[name])`, and durable-agent-surface.test.ts derives both
447
- * its blocked-member partition and its per-method message assertions from these
448
- * keys — so a new blocked entry cannot ship with an unexercised refusal, and a
449
- * reason cannot drift between the throw and the test.
549
+ * Why each blocked entry point is refused, keyed by method name: the SINGLE
550
+ * source of those reasons.
450
551
  *
451
- * Four grounds. The module comment walks the same members by PROVENANCE
452
- * section (the durable surface, then the Agent surface) rather than by ground,
453
- * so its numbering is not this list's:
552
+ * The grounds:
454
553
  * 1. re-drives a persisted run below `executeWorkflow`, where there is no
455
554
  * RunnerRuntime — no run ownership, no per-leg grant, no snapshot
456
555
  * provenance;
457
- * 2. unscoped run discovery that bypasses the host topology's per-principal
458
- * run-ownership checks and returns ids the caller does not own;
556
+ * 2. unscoped run or thread identity discovery that bypasses the host
557
+ * topology's per-principal ownership checks and returns identities the
558
+ * caller does not own;
459
559
  * 3. snapshot deletion owned by deployment-scoped retention;
460
- * 4. a SECOND execution surface that runs the agent outside RunnerRuntime
461
- * entirely, or that mints a run id below the caller — the network loop's
462
- * own workflow, the legacy handler, the thread runtime's tool-approval
463
- * continuation, and the setter that installs a different agent as the
464
- * thread runtime's execution target.
560
+ * 4. a SECOND execution surface outside RunnerRuntime, whether the call runs
561
+ * it or installs something that later does, or that mints a run id below
562
+ * the caller;
563
+ * 5. installs a runtime service — a Mastra, memory or pub/sub — after
564
+ * construction;
565
+ * 6. cancels a run outside RunnerRuntime's terminal lifecycle.
465
566
  *
466
- * Deliberately NOT re-exported from `./index.js` (a named-exports-only barrel),
467
- * so this stays off the public `@proofoftech/flowsafe/agent-runner` subpath.
567
+ * NOT re-exported from `./index.js` (a named-exports-only barrel), so this
568
+ * stays off the public `@proofoftech/flowsafe/agent-runner` subpath.
468
569
  */
469
570
  export const BLOCKED_RUN_ENTRIES = {
470
571
  recover: 're-driving a persisted run bypasses run ownership, per-leg grant minting and the fail-closed registry rehydration',
@@ -479,6 +580,7 @@ export const BLOCKED_RUN_ENTRIES = {
479
580
  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",
480
581
  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",
481
582
  listActiveThreadRuns: 'core scopes the active thread-run listing by nothing at all: it takes no arguments and returns the run, thread and resource ids of every thread on the pubsub instance with a run in flight, which core keys by pubsub instance rather than by agent, so it enumerates ids across every principal AND every agent that shares the instance',
583
+ discoverThreadPeers: 'it takes no caller-named thread or principal and returns the agent, resource, thread and source identities every peer on the pub/sub advertises',
482
584
  deleteRunSnapshots: 'durable-agent snapshot rows are retained until deployment-scoped retention purge removes them',
483
585
  network: `${NETWORK_FAMILY_REASON}, and it mints an unowned run id when the caller omits one`,
484
586
  resumeNetwork: NETWORK_FAMILY_REASON,
@@ -487,48 +589,54 @@ export const BLOCKED_RUN_ENTRIES = {
487
589
  generateLegacy: LEGACY_FAMILY_REASON,
488
590
  streamLegacy: LEGACY_FAMILY_REASON,
489
591
  sendToolApproval: THREAD_TOOL_APPROVAL_REASON,
490
- __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",
592
+ __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",
593
+ 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",
594
+ __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",
595
+ __setMastra: MASTRA_BINDING_REASON,
596
+ __registerMastra: MASTRA_BINDING_REASON,
597
+ __setMemory: INSTALLED_SERVICE_REASON,
598
+ __setPubSub: INSTALLED_SERVICE_REASON,
599
+ abortRunStream: DIRECT_ABORT_REASON,
600
+ abortThreadStream: DIRECT_ABORT_REASON,
491
601
  };
492
602
  /**
493
- * The refusal every blocked run entry point throws. A plain `Error`, not
603
+ * The refusal for a blocked run entry point. A plain `Error`, not
494
604
  * {@link InvalidRunRequestError}: that class means "the client's run request is
495
- * malformed" (runtime.ts homes the convention — client input is an
496
- * InvalidRunRequestError, a developer-controlled mistake is a plain Error), and
497
- * calling one of these is neither a run request nor recoverable by fixing an
498
- * argument. Same voice as #rehydrateRegistry's fail-closed throw. The message
499
- * names WHAT is refused and WHY, and carries no run data — the discovery
605
+ * malformed", and calling one of these is neither a run request nor
606
+ * recoverable by fixing an argument. The message names WHAT is refused and WHY, and carries no run data — the discovery
500
607
  * entries have none to carry, and the others must not echo an id the caller may
501
608
  * not own into its log.
502
609
  */
503
610
  function unavailableRunEntry(method, why) {
504
- 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)`);
611
+ 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)`);
505
612
  }
506
- function bindThreadCompletion(output, completion) {
613
+ function bindResumedLegLifecycle(output, leg) {
507
614
  return new Proxy(output, {
508
- get(target, property, receiver) {
509
- if (property === '_waitUntilFinished') {
510
- const wait = Reflect.get(target, property, target);
511
- return () => typeof wait === 'function'
512
- ? Promise.race([
513
- Promise.resolve(wait.call(target)),
514
- completion,
515
- ])
516
- : completion;
615
+ get(target, property) {
616
+ if (property === '_waitUntilFinished')
617
+ return () => leg.completion;
618
+ if (property === 'status') {
619
+ if (leg.outcome === 'suspended')
620
+ return 'suspended';
621
+ const status = target.status;
622
+ if (leg.outcome === undefined) {
623
+ return status === 'running' || status === 'suspended'
624
+ ? status
625
+ : 'running';
626
+ }
627
+ return status !== 'running' && status !== 'suspended'
628
+ ? status
629
+ : leg.outcome;
517
630
  }
518
- const value = Reflect.get(target, property, receiver);
631
+ // Core's output getters read private fields, which a proxy receiver lacks.
632
+ const value = Reflect.get(target, property, target);
519
633
  return typeof value === 'function' ? value.bind(target) : value;
520
634
  },
521
635
  });
522
636
  }
523
637
  /**
524
638
  * Brand marking an agent as runtime-driven. The thread Durable Object requires
525
- * it before its message, signal, schedule, or notification-dispatch wake seam
526
- * may start a run. Queue and state persist rather than wake on idle. Non-owner
527
- * notifications are recorded for the trusted dispatcher and never send a
528
- * signal directly. An unbranded agent reports
529
- * `degraded: 'not-runtime-driven'` on state and owner-notification responses
530
- * that reach the sender, regardless of thread state. Skipped state and
531
- * `memory-unavailable` responses return earlier and carry no marker.
639
+ * it before a wake seam may start a run.
532
640
  *
533
641
  * Direct core sender calls that mint a run still reach the durable runner,
534
642
  * which fails them terminally without executing. Structural so a test double
@@ -560,8 +668,10 @@ export class FlowsafeDurableAgent extends DurableAgent {
560
668
  [RUNTIME_DRIVEN_AGENT] = true;
561
669
  #runtime;
562
670
  #wrappedAgent;
563
- #isBreakwaterGuardedAgent;
671
+ #rehydrationInputProcessorIds;
672
+ #guardedCallOptionMapper;
564
673
  #threadRuntime;
674
+ #resumedThreadLegs = new Map();
565
675
  #persistenceWaiters = new Map();
566
676
  #startRequesters = new Map();
567
677
  #startRequesterKinds = new Map();
@@ -569,51 +679,81 @@ export class FlowsafeDurableAgent extends DurableAgent {
569
679
  /**
570
680
  * runId -> the reservation key the thread topology took for this start, so
571
681
  * `executeWorkflow` can hand it to `RunnerRuntime.start` for the execution
572
- * fence's proof-only match. Same lifetime and same cleanup as the attempt
573
- * token beside it: registered by `streamUntilPersisted`, dropped in its
574
- * `finally`, so nothing outlives the start it belongs to.
682
+ * fence's proof-only match.
575
683
  */
576
684
  #startIdempotencyKeys = new Map();
577
685
  #startAuthorities = new Map();
578
686
  #startScheduleDispatches = new Map();
579
687
  // The host's exact options object receives one private, single-use re-entry ticket.
580
688
  #hostStreamTickets = new WeakSet();
689
+ // The created signal of a start with neither a host ticket nor a request
690
+ // context, the options a drain inherits from a run resumeViaRuntime()
691
+ // registered. An RBAC refusal removes that signal from the prepared message
692
+ // list, so executeWorkflow preserves it from this capture.
693
+ #replayedSignals = new Map();
581
694
  constructor(options) {
695
+ const refusal = unwrappableAgentReason(options.agent);
696
+ if (refusal !== undefined) {
697
+ throw new TypeError(`FlowsafeDurableAgent: the wrapped agent ${refusal}`);
698
+ }
699
+ const pubsub = options.pubsub ?? options.runtime.pubsub;
700
+ // The run's drain reads the wrapped agent's pub/sub, where an own pub/sub
701
+ // wins over the one this wrapper installs.
702
+ if (options.agent.hasOwnPubSub() && options.agent.getPubSub() !== pubsub) {
703
+ 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");
704
+ }
582
705
  const guardedProtocol = breakwaterGuardedAgentHostProtocol(options.agent);
706
+ let callOptionMapper;
707
+ if (guardedProtocol !== undefined) {
708
+ const defaults = options.agent.getDefaultOptions();
709
+ if (defaults === null ||
710
+ typeof defaults !== 'object' ||
711
+ typeof defaults.then === 'function') {
712
+ throw new TypeError('FlowsafeDurableAgent: a Breakwater guarded agent must have static default options');
713
+ }
714
+ for (const [key, rule] of Object.entries(GUARDED_DURABLE_CALL_OPTIONS)) {
715
+ if (rule.kind === 'compared' &&
716
+ (!Object.hasOwn(defaults, key) ||
717
+ ownDataDescriptor(defaults, key, key)?.value === undefined)) {
718
+ throw new TypeError(`FlowsafeDurableAgent: a Breakwater guarded agent's default options must carry ${key}`);
719
+ }
720
+ }
721
+ const { maxSteps, toolChoice } = defaults;
722
+ callOptionMapper = guardedCallOptionMapper(Object.freeze({
723
+ maxSteps,
724
+ toolChoice: toolChoice !== null && typeof toolChoice === 'object'
725
+ ? Object.freeze({
726
+ type: toolChoice.type,
727
+ toolName: toolChoice.toolName,
728
+ })
729
+ : toolChoice,
730
+ }));
731
+ // Signal drains replay these defaults, so an unusable one fails before registering a run.
732
+ snapshotDurableCallOptions(defaults, callOptionMapper);
733
+ }
583
734
  super({
584
735
  agent: options.agent,
585
736
  id: options.id,
586
737
  name: options.name,
587
738
  cache: options.cache,
588
- // Default the agent's own stream pubsub to the runtime's identity (ONE
589
- // feed per DO), so a host that configures only init()'s pubsub still
590
- // gets observe()/emitError aligned with the run's events (the run is driven
591
- // through the runtime, which publishes on THAT identity). An explicit
592
- // pubsub wins; both-absent falls to core's per-agent default (poll-only,
593
- // byte-identical to before this seam existed).
594
- pubsub: options.pubsub ?? options.runtime.pubsub,
739
+ pubsub,
595
740
  maxSteps: options.maxSteps,
596
741
  });
597
742
  this.#runtime = options.runtime;
598
743
  this.#wrappedAgent = options.agent;
599
- this.#isBreakwaterGuardedAgent = guardedProtocol !== undefined;
744
+ this.#rehydrationInputProcessorIds = new Set(guardedProtocol !== undefined
745
+ ? [BREAKWATER_RBAC_PROCESSOR_ID, BREAKWATER_MEMORY_PROCESSOR_ID]
746
+ : [BREAKWATER_RBAC_PROCESSOR_ID]);
747
+ this.#guardedCallOptionMapper = callOptionMapper;
600
748
  this.#threadRuntime = options.threadRuntime;
749
+ // Core keys thread state and signal delivery on the agent-level pub/sub;
750
+ // its stream pub/sub option leaves that identity unset for the run's drain.
751
+ super.__setPubSub(pubsub ?? this.pubsub);
601
752
  }
602
753
  /**
603
- * Host-owned run-ID enforcement at the public boundary. The durable-agent entry points (stream /
604
- * generate / prepare) take an OPTIONAL runId, and when it is omitted core's
605
- * `prepareForDurableExecution` mints `crypto.randomUUID()`
606
- * (create-durable-agent-DFHwqN2K.js:1211) — the exact unowned fallback this
607
- * wrapper forbids — and hands it to `executeWorkflow` BELOW this class's own
608
- * guard, where a bare UUID is already indistinguishable from a legitimately
609
- * caller-minted one. So the guard must ALSO fire HERE, before
610
- * `super.stream()/generate()/prepare()`, while "absent" is still visible. Same
611
- * posture as `RunnerRuntime.start`
612
- * (typeof + PATH_SAFE_ID_PATTERN, NO generation fallback); the `typeof` check
613
- * is load-bearing because `RegExp.test` coerces its argument to a string, so a
614
- * numeric runId would pass the pattern yet key a run by the number. Homed once
615
- * and shared by the four call sites below so the rule cannot drift within this
616
- * class.
754
+ * Reject an absent caller runId before prepareForDurableExecution replaces
755
+ * it with a UUID that downstream path checks accept. The string check also
756
+ * prevents RegExp coercion from accepting a numeric registry key.
617
757
  */
618
758
  #assertCallerRunId(runId) {
619
759
  if (!isPathSafeId(runId)) {
@@ -625,8 +765,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
625
765
  * `#startRequesters` alone is insufficient because `streamUntilPersisted()`
626
766
  * removes it after the first summary while a suspended stream stays live.
627
767
  * The internal registry has no TTL, so it also covers long suspensions after
628
- * the global registry's ten-minute TTL expires.
629
- * The one exemption is the host's own first start: `streamUntilPersisted()`
768
+ * the global registry's TTL expires.
769
+ * It exempts the host's own first start: `streamUntilPersisted()`
630
770
  * stamps its exact options object with a single-use ticket that `stream()`
631
771
  * consumes. A private `WeakSet`, a locally constructed object, and first-use
632
772
  * consumption make that exemption unavailable to callers.
@@ -643,13 +783,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
643
783
  globalRunRegistry.has(runId) ||
644
784
  this.runRegistryInternal.has(runId));
645
785
  }
646
- #assertGuardedStructuredOutput(options) {
647
- if (this.#isBreakwaterGuardedAgent &&
648
- options !== null &&
649
- typeof options === 'object' &&
650
- Object.hasOwn(options, 'structuredOutput')) {
651
- throw new TypeError('FlowsafeDurableAgent: structuredOutput is not supported for a Breakwater guarded agent because Mastra durable execution bypasses the narrow guarded handle');
652
- }
786
+ #snapshotCallOptions(options) {
787
+ return snapshotDurableCallOptions(options, this.#guardedCallOptionMapper);
653
788
  }
654
789
  /**
655
790
  * Enforce a caller-minted run ID before the inherited durable
@@ -663,16 +798,25 @@ export class FlowsafeDurableAgent extends DurableAgent {
663
798
  const hostStreamTicket = options !== undefined && this.#hostStreamTickets.has(options);
664
799
  if (hostStreamTicket)
665
800
  this.#hostStreamTickets.delete(options);
666
- const callOptions = snapshotDurableCallOptions(options);
801
+ const callOptions = this.#snapshotCallOptions(options);
667
802
  this.#assertCallerRunId(callOptions?.runId);
668
803
  if (!hostStreamTicket)
669
804
  this.#assertRunIdNotLive(callOptions.runId);
670
- this.#assertGuardedStructuredOutput(callOptions);
671
- const result = await super.stream(messages, callOptions);
672
- if (!callOptions?.untilIdle) {
673
- await this.#threadRuntime?.registerRun(this, result.output, (callOptions ?? {}), this.pubsub);
805
+ let capturedSignal = false;
806
+ if (!hostStreamTicket &&
807
+ callOptions.requestContext === undefined &&
808
+ isCreatedAgentSignal(messages)) {
809
+ this.#replayedSignals.set(callOptions.runId, messages);
810
+ capturedSignal = true;
811
+ }
812
+ try {
813
+ return await super.stream(messages, callOptions);
814
+ }
815
+ catch (error) {
816
+ if (capturedSignal)
817
+ this.#replayedSignals.delete(callOptions.runId);
818
+ throw error;
674
819
  }
675
- return result;
676
820
  }
677
821
  /**
678
822
  * Start a durable stream and wait until RunnerRuntime has persisted the
@@ -691,21 +835,19 @@ export class FlowsafeDurableAgent extends DurableAgent {
691
835
  /**
692
836
  * The idempotency key the thread topology already RESERVED for this run.
693
837
  *
694
- * It travels down here for one job: the execution fence's proof-only state
838
+ * It travels down here because the execution fence's proof-only state
695
839
  * admits exactly the start whose key matches its nominated proof key, and
696
840
  * `RunnerRuntime.start` is where that comparison happens. It buys no
697
841
  * exactly-once property at this layer — the reservation above already did —
698
- * so nothing here validates it beyond passing it on, and a run started
699
- * without one behaves exactly as before.
842
+ * so nothing here validates it beyond passing it on.
700
843
  *
701
844
  * Parked per-runId beside the attempt token rather than threaded through
702
845
  * core, because core owns the call between `stream()` and
703
846
  * `executeWorkflow()` and carries no field this could ride in.
704
847
  */
705
848
  idempotencyKey, authority) {
706
- const callOptions = snapshotDurableCallOptions(options);
849
+ const callOptions = this.#snapshotCallOptions(options);
707
850
  this.#assertCallerRunId(callOptions?.runId);
708
- this.#assertGuardedStructuredOutput(callOptions);
709
851
  if (callOptions.untilIdle) {
710
852
  throw new InvalidRunRequestError('streamUntilPersisted does not support untilIdle');
711
853
  }
@@ -782,10 +924,9 @@ export class FlowsafeDurableAgent extends DurableAgent {
782
924
  * one is not supplied.
783
925
  */
784
926
  async generate(messages, options) {
785
- const callOptions = snapshotDurableCallOptions(options);
927
+ const callOptions = this.#snapshotCallOptions(options);
786
928
  this.#assertCallerRunId(callOptions?.runId);
787
929
  this.#assertRunIdNotLive(callOptions.runId);
788
- this.#assertGuardedStructuredOutput(callOptions);
789
930
  try {
790
931
  return await super.generate(messages, callOptions);
791
932
  }
@@ -804,24 +945,14 @@ export class FlowsafeDurableAgent extends DurableAgent {
804
945
  }
805
946
  }
806
947
  /**
807
- * The same host-owned run-ID guard as {@link FlowsafeDurableAgent.stream}.
808
- * `prepare()`
809
- * is the third inherited minting entry point: it forwards `options?.runId` into
810
- * core's `prepareForDurableExecution` (create-durable-agent-DFHwqN2K.js:7882),
811
- * which mints an unowned `crypto.randomUUID()` when it is absent
812
- * (create-durable-agent-DFHwqN2K.js:1211) AND REGISTERS a run under that id
813
- * (create-durable-agent-DFHwqN2K.js:7890) — so a later
814
- * `resume(runId)`/`executeWorkflow` sees a bare UUID `PATH_SAFE_ID_PATTERN`
815
- * already accepts, past every downstream guard. Enforce the caller-minted ID
816
- * here, while "absent" is still visible. A prepared id remains live until core
817
- * cleans up the run, so later `stream()`, `generate()`, `prepare()`, and
818
- * `streamUntilPersisted()` calls carrying that id are refused.
948
+ * Enforce the caller-owned id before DurableAgent.prepare forwards it to
949
+ * prepareForDurableExecution, which mints an absent id and registers the run.
950
+ * That UUID satisfies downstream path checks and stays live until cleanup.
819
951
  */
820
952
  async prepare(messages, options) {
821
- const callOptions = snapshotDurableCallOptions(options);
953
+ const callOptions = this.#snapshotCallOptions(options);
822
954
  this.#assertCallerRunId(callOptions?.runId);
823
955
  this.#assertRunIdNotLive(callOptions.runId);
824
- this.#assertGuardedStructuredOutput(callOptions);
825
956
  return super.prepare(messages, callOptions);
826
957
  }
827
958
  /**
@@ -839,9 +970,9 @@ export class FlowsafeDurableAgent extends DurableAgent {
839
970
  * Refuse core's bulk recovery. `recoverActiveRuns()` is
840
971
  * {@link FlowsafeDurableAgent.listActiveRuns} plus a `recover()` per row, and
841
972
  * it is what `Mastra.recoverAllDurableAgents()` calls on every registered
842
- * durable agent — so this is the one blocked entry point a host can reach
843
- * without a FlowSafe call site, by opting into `recovery: { durableAgents:
844
- * 'auto' }`. That loop isolates each agent in its own try/catch, so this
973
+ * durable agent — so a host reaches this blocked entry point without a
974
+ * FlowSafe call site by opting into `recovery: { durableAgents: 'auto' }`.
975
+ * That loop isolates each agent in its own try/catch, so this
845
976
  * refusal is logged there rather than failing boot. Refuse with an explicit
846
977
  * `runId` too: a single target is still a re-drive off RunnerRuntime.
847
978
  */
@@ -869,10 +1000,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
869
1000
  * — and narrows by `agentId` plus the optional `threadId`/`resourceId`
870
1001
  * filters the CALLER supplies, the same scoping `listActiveRuns()` applies.
871
1002
  * Same ground too: an unfiltered call returns run, thread and resource ids
872
- * across every principal that shares the agent. It is the one direct
873
- * data-returning discovery member the base `Agent` surface adds; the other
874
- * additions funnel through `this.resumeStream()` and so fail closed on that
875
- * override.
1003
+ * across every principal that shares the agent.
876
1004
  */
877
1005
  async listSuspendedRuns(_options) {
878
1006
  throw unavailableRunEntry('listSuspendedRuns', BLOCKED_RUN_ENTRIES.listSuspendedRuns);
@@ -888,13 +1016,25 @@ export class FlowsafeDurableAgent extends DurableAgent {
888
1016
  * makes the caller name the (resourceId, threadId) pair it confirms.
889
1017
  *
890
1018
  * Signature caveat, and the reason this one is not `async`: the base declares
891
- * it SYNCHRONOUS (`listActiveThreadRuns(): ActiveThreadRun[]`), so the
892
- * `async … Promise<never>` shape every other refusal here carries would not
893
- * be assignable to it. A re-check for a peer bump.
1019
+ * it SYNCHRONOUS (`listActiveThreadRuns(): ActiveThreadRun[]`), so an
1020
+ * `async … Promise<never>` refusal would not be assignable to it. A re-check
1021
+ * for a peer bump.
894
1022
  */
895
1023
  listActiveThreadRuns() {
896
1024
  throw unavailableRunEntry('listActiveThreadRuns', BLOCKED_RUN_ENTRIES.listActiveThreadRuns);
897
1025
  }
1026
+ /** Refuse unscoped thread identity discovery under the second ground. */
1027
+ async discoverThreadPeers(_options) {
1028
+ throw unavailableRunEntry('discoverThreadPeers', BLOCKED_RUN_ENTRIES.discoverThreadPeers);
1029
+ }
1030
+ /** Refuse direct run cancellation under the sixth ground. */
1031
+ abortRunStream(_runId) {
1032
+ throw unavailableRunEntry('abortRunStream', BLOCKED_RUN_ENTRIES.abortRunStream);
1033
+ }
1034
+ /** Refuse direct thread cancellation under the sixth ground. */
1035
+ abortThreadStream(_options) {
1036
+ throw unavailableRunEntry('abortThreadStream', BLOCKED_RUN_ENTRIES.abortThreadStream);
1037
+ }
898
1038
  /**
899
1039
  * Refuse the multi-agent network start. `network()` does not touch the
900
1040
  * durable-agentic-loop at all: it compiles a SEPARATE workflow and drives it
@@ -941,7 +1081,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
941
1081
  * omits one, and skips `requireAgentExecutionFGA` — the authorization gate
942
1082
  * every SUPPORTED entry point calls, so this would run the agent without it.
943
1083
  * (The network family skips that gate too; neither is unique in doing so.) It
944
- * persists no workflow run state, which is why it is refused on those two
1084
+ * persists no workflow run state, which is why it is refused on those
945
1085
  * grounds rather than as a re-drive.
946
1086
  *
947
1087
  * Signature caveat: overloaded and generic in OUTPUT on the base, so this
@@ -990,6 +1130,62 @@ export class FlowsafeDurableAgent extends DurableAgent {
990
1130
  __setThreadRuntimeAgent(_agent) {
991
1131
  throw unavailableRunEntry('__setThreadRuntimeAgent', BLOCKED_RUN_ENTRIES.__setThreadRuntimeAgent);
992
1132
  }
1133
+ /**
1134
+ * Refuse binding channels. The base forwards them to the wrapped agent,
1135
+ * which becomes their dispatch target outside RunnerRuntime: the fourth
1136
+ * ground reached by installation.
1137
+ */
1138
+ setChannels(_agentChannels) {
1139
+ throw unavailableRunEntry('setChannels', BLOCKED_RUN_ENTRIES.setChannels);
1140
+ }
1141
+ /**
1142
+ * Refuse declaring schedules. The base forwards them to the wrapped agent,
1143
+ * which a Mastra schedule worker fires outside RunnerRuntime: the fourth
1144
+ * ground reached by installation.
1145
+ *
1146
+ * Signature caveat: the parameter is `unknown` rather than core's
1147
+ * `DeclaredAgentSchedule[]`, which it satisfies without depending on method
1148
+ * bivariance.
1149
+ */
1150
+ __setDeclaredSchedules(_schedules) {
1151
+ throw unavailableRunEntry('__setDeclaredSchedules', BLOCKED_RUN_ENTRIES.__setDeclaredSchedules);
1152
+ }
1153
+ /**
1154
+ * Refuse memory installation after construction under the fifth ground.
1155
+ *
1156
+ * Signature caveat: `unknown` accepts core's memory parameter without
1157
+ * depending on method bivariance.
1158
+ */
1159
+ __setMemory(_memory) {
1160
+ throw unavailableRunEntry('__setMemory', BLOCKED_RUN_ENTRIES.__setMemory);
1161
+ }
1162
+ /**
1163
+ * Refuse pub/sub installation after construction under the fifth ground.
1164
+ *
1165
+ * Signature caveat: `unknown` accepts core's pub/sub parameter without
1166
+ * depending on method bivariance.
1167
+ */
1168
+ __setPubSub(_pubsub) {
1169
+ throw unavailableRunEntry('__setPubSub', BLOCKED_RUN_ENTRIES.__setPubSub);
1170
+ }
1171
+ /**
1172
+ * Refuse Mastra registration. `Mastra.addAgent` calls this first, so the
1173
+ * refusal throws before the registry write and before the loop workflow is
1174
+ * added to that Mastra.
1175
+ *
1176
+ * Signature caveat: the parameter is `unknown` rather than core's `Mastra`,
1177
+ * which it satisfies without depending on method bivariance.
1178
+ */
1179
+ __setMastra(_mastra) {
1180
+ throw unavailableRunEntry('__setMastra', BLOCKED_RUN_ENTRIES.__setMastra);
1181
+ }
1182
+ /**
1183
+ * The member {@link FlowsafeDurableAgent.__setMastra} forwards to, which
1184
+ * `Agent.listAgents` calls directly on a static sub-agent.
1185
+ */
1186
+ __registerMastra(_mastra) {
1187
+ throw unavailableRunEntry('__registerMastra', BLOCKED_RUN_ENTRIES.__registerMastra);
1188
+ }
993
1189
  /**
994
1190
  * Refuse core's terminal snapshot cleanup. Its only call sites are the base
995
1191
  * `executeWorkflow` (overridden here), the blocked `resume()` and the blocked
@@ -997,24 +1193,19 @@ export class FlowsafeDurableAgent extends DurableAgent {
997
1193
  * snapshot rows — which deployment-scoped retention purge owns — from being
998
1194
  * dropped out from under that owner by a future internal caller.
999
1195
  *
1000
- * Note what this override buys beyond that call-site audit: the member
1001
- * inventory in durable-agent-surface.test.ts sees a NEW member, never a new
1002
- * core call site on an EXISTING one. So the override is the standing guard —
1003
- * it converts core's best-effort cleanup into a throw the moment a future
1004
- * release calls it on a path FlowSafe drives. None does at 1.67.0.
1196
+ * The override keeps core's best-effort deletion from taking ownership of
1197
+ * these rows if an internal execution path reaches the cleanup method.
1005
1198
  */
1006
1199
  async deleteRunSnapshots(_runId) {
1007
1200
  throw unavailableRunEntry('deleteRunSnapshots', BLOCKED_RUN_ENTRIES.deleteRunSnapshots);
1008
1201
  }
1009
1202
  /**
1010
- * Refuse core's durable resume. Until 1.53.0 this merely read the in-process
1011
- * run registry, which is why it was left inherited-but-unwired; now a registry
1012
- * MISS makes it load the persisted `durable-agentic-loop` snapshot, rehydrate
1013
- * through `prepare()` with the full application processor chain, and re-drive
1014
- * the run with `createRun + run.resume` — below `executeWorkflow`, so the leg
1015
- * carries no minted grant and no snapshot provenance.
1016
- * {@link FlowsafeDurableAgent.resumeViaRuntime} is the only resume path, and
1017
- * it is reached from the approval decision, never from a client.
1203
+ * Refuse core's durable resume. From 1.53.0 a registry MISS makes it load the
1204
+ * persisted `durable-agentic-loop` snapshot, rehydrate through `prepare()`
1205
+ * with the full application processor chain, and re-drive the run with
1206
+ * `createRun + run.resume` — below `executeWorkflow`, so the leg carries no
1207
+ * minted grant and no snapshot provenance. The runner's resume path is
1208
+ * {@link FlowsafeDurableAgent.resumeViaRuntime}.
1018
1209
  */
1019
1210
  async resume(_runId, _resumeData, _options) {
1020
1211
  throw unavailableRunEntry('resume', BLOCKED_RUN_ENTRIES.resume);
@@ -1048,11 +1239,11 @@ export class FlowsafeDurableAgent extends DurableAgent {
1048
1239
  throw unavailableRunEntry('declineToolCall', BLOCKED_RUN_ENTRIES.declineToolCall);
1049
1240
  }
1050
1241
  /**
1051
- * The 1.53.0 generate-shaped tool-approval pair. They funnel into
1052
- * `resumeGenerate()` -> `resume()`, so they are the same entry point wearing a
1242
+ * The 1.53.0 generate-shaped tool-approval entries. They funnel into
1243
+ * `resumeGenerate()` -> `resume()`, so they are the same entry point with a
1053
1244
  * different return type.
1054
1245
  *
1055
- * Signature caveat for both halves: the base method is GENERIC in its OUTPUT
1246
+ * Signature caveat for each: the base method is GENERIC in its OUTPUT
1056
1247
  * type, which `Parameters<>` cannot carry, so the parameter type below is
1057
1248
  * hand-written rather than derived. Re-check it against the base on every
1058
1249
  * peer bump — nothing here fails if core changes the shape.
@@ -1072,17 +1263,16 @@ export class FlowsafeDurableAgent extends DurableAgent {
1072
1263
  let inputProcessors = [];
1073
1264
  let llmRequestInputProcessors = [];
1074
1265
  const rehydrationAgent = new Proxy(wrappedAgent, {
1075
- get(target, property) {
1266
+ get: (target, property) => {
1076
1267
  if (property === 'listInputProcessors') {
1077
1268
  return async (requestContext) => {
1078
1269
  inputProcessors = await target.listInputProcessors(requestContext);
1079
- return inputProcessors.filter((processor) => processor.id === 'breakwater-rbac');
1270
+ return inputProcessors.filter((processor) => this.#rehydrationInputProcessorIds.has(processor.id));
1080
1271
  };
1081
1272
  }
1082
1273
  if (property === '__listLLMRequestProcessors') {
1083
- return async (requestContext) => {
1084
- llmRequestInputProcessors =
1085
- await target.__listLLMRequestProcessors(requestContext);
1274
+ return async (...args) => {
1275
+ llmRequestInputProcessors = await target.__listLLMRequestProcessors(...args);
1086
1276
  return [];
1087
1277
  };
1088
1278
  }
@@ -1137,12 +1327,19 @@ export class FlowsafeDurableAgent extends DurableAgent {
1137
1327
  * Rehydrate a suspended durable-agent run after isolate eviction, restore its
1138
1328
  * active thread registration, then resume through RunnerRuntime so approval
1139
1329
  * grant derivation and snapshot provenance remain authoritative.
1330
+ * A resumed leg observes from the current run stream position. Its thread
1331
+ * registration completes on the run's terminal outcome or a resume failure
1332
+ * after rehydration, when the wrapper publishes a terminal error. Another
1333
+ * suspension keeps blocking the thread until the next resume, as a first leg does.
1140
1334
  * Hosts expose this only from their trusted approval-decision topology.
1141
1335
  */
1142
1336
  async resumeViaRuntime(options) {
1143
1337
  this.#assertCallerRunId(options.runId);
1338
+ const memory = this.#guardedCallOptionMapper
1339
+ ? this.#guardedCallOptionMapper('memory', options.memory)
1340
+ : options.memory;
1144
1341
  let rehydrated = false;
1145
- let finishThreadRegistration;
1342
+ let leg;
1146
1343
  try {
1147
1344
  const summary = await this.#runtime.resume(this.getWorkflow().id, options.runId, {
1148
1345
  ...(options.step !== undefined ? { step: options.step } : {}),
@@ -1152,24 +1349,21 @@ export class FlowsafeDurableAgent extends DurableAgent {
1152
1349
  requestedBy: options.requestedBy,
1153
1350
  requestedByKind: 'human',
1154
1351
  prepareExecution: async (requestContext) => {
1352
+ const offset = (await this.pubsub.getHistory(AGENT_STREAM_TOPIC(options.runId))).length;
1155
1353
  await this.#rehydrateRegistry({
1156
1354
  runId: options.runId,
1157
1355
  requestContext,
1158
- ...(options.memory !== undefined
1159
- ? { memory: options.memory }
1160
- : {}),
1356
+ ...(memory !== undefined ? { memory } : {}),
1161
1357
  });
1162
1358
  rehydrated = true;
1163
- const observed = await this.observe(options.runId);
1164
- const completion = new Promise((resolve) => {
1165
- finishThreadRegistration = resolve;
1166
- });
1167
- await this.#threadRuntime?.registerRun(this, bindThreadCompletion(observed.output, completion), {
1168
- runId: options.runId,
1169
- ...(options.memory !== undefined
1170
- ? { memory: options.memory }
1171
- : {}),
1172
- }, this.pubsub);
1359
+ const observed = await this.observe(options.runId, { offset });
1360
+ if (this.#threadRuntime) {
1361
+ leg = this.#trackResumedLeg(options.runId);
1362
+ await this.#threadRuntime.registerRun(this, bindResumedLegLifecycle(observed.output, leg), {
1363
+ runId: options.runId,
1364
+ ...(memory !== undefined ? { memory } : {}),
1365
+ }, this.getPubSub());
1366
+ }
1173
1367
  },
1174
1368
  });
1175
1369
  if (summary.status === 'failed') {
@@ -1177,6 +1371,16 @@ export class FlowsafeDurableAgent extends DurableAgent {
1177
1371
  this.runRegistryInternal.cleanup(options.runId);
1178
1372
  globalRunRegistry.delete(options.runId);
1179
1373
  }
1374
+ if (isTerminalRunStatus(summary.status)) {
1375
+ this.#completeResumedThreadLegs(options.runId, summary.status === 'success'
1376
+ ? 'success'
1377
+ : summary.status === 'canceled' || summary.status === 'cancelled'
1378
+ ? 'canceled'
1379
+ : 'failed');
1380
+ }
1381
+ else if (leg) {
1382
+ leg.outcome = 'suspended';
1383
+ }
1180
1384
  return summary;
1181
1385
  }
1182
1386
  catch (error) {
@@ -1184,19 +1388,54 @@ export class FlowsafeDurableAgent extends DurableAgent {
1184
1388
  await this.#publishTerminalError(options.runId, error);
1185
1389
  this.runRegistryInternal.cleanup(options.runId);
1186
1390
  globalRunRegistry.delete(options.runId);
1391
+ this.#completeResumedThreadLegs(options.runId, 'failed');
1187
1392
  }
1188
1393
  throw error;
1189
1394
  }
1395
+ }
1396
+ #trackResumedLeg(runId) {
1397
+ let complete;
1398
+ const completion = new Promise((resolve) => {
1399
+ complete = resolve;
1400
+ });
1401
+ const leg = { completion, complete };
1402
+ let legs = this.#resumedThreadLegs.get(runId);
1403
+ if (!legs) {
1404
+ legs = new Set();
1405
+ this.#resumedThreadLegs.set(runId, legs);
1406
+ }
1407
+ legs.add(leg);
1408
+ return leg;
1409
+ }
1410
+ #completeResumedThreadLegs(runId, outcome) {
1411
+ const legs = this.#resumedThreadLegs.get(runId);
1412
+ if (!legs)
1413
+ return;
1414
+ this.#resumedThreadLegs.delete(runId);
1415
+ for (const leg of legs) {
1416
+ leg.outcome = outcome;
1417
+ leg.complete();
1418
+ }
1419
+ }
1420
+ async #settleRefusedStart(runId, refusal) {
1421
+ let published = false;
1422
+ try {
1423
+ published =
1424
+ (await this.#publishTerminalError(runId, refusal)) ||
1425
+ (await this.#publishTerminalError(runId, refusal));
1426
+ }
1190
1427
  finally {
1191
- finishThreadRegistration?.();
1428
+ this.#replayedSignals.delete(runId);
1429
+ this.runRegistryInternal.cleanup(runId);
1430
+ globalRunRegistry.delete(runId);
1192
1431
  }
1432
+ if (!published)
1433
+ throw refusal;
1193
1434
  }
1194
1435
  /**
1195
- * Publish one terminal ERROR attempt without throwing. The unregistered-run
1196
- * terminal path retries once and throws its refusal only after registry
1197
- * cleanup; resume publishes best-effort and preserves its summary or original
1198
- * error. Both call sites publish before cleanup because `emitError()` closes
1199
- * spans through the live global registry entry.
1436
+ * Publish one terminal ERROR attempt without throwing. Call sites publish
1437
+ * before cleanup because `emitError()` closes spans through the live global
1438
+ * registry entry.
1200
1439
  */
1201
1440
  async #publishTerminalError(runId, error) {
1202
1441
  const terminalError = error instanceof Error ? error : new Error(String(error));
@@ -1213,10 +1452,29 @@ export class FlowsafeDurableAgent extends DurableAgent {
1213
1452
  }
1214
1453
  }
1215
1454
  /**
1216
- * Preserve unowned input before terminal refusal. A bounded best-effort write
1217
- * prevents hung memory from blocking the ERROR that heals thread state.
1455
+ * Preserve unowned input before terminal refusal, by the guarded input
1456
+ * chain's verdict on the call:
1457
+ * - no tripwire: the prepared input;
1458
+ * - a tripwire from Breakwater's RBAC gate on a call whose created signal
1459
+ * `stream()` captured: that signal;
1460
+ * - any other tripwire, an RBAC one on a call with no capture included:
1461
+ * nothing.
1462
+ *
1463
+ * `stream()` captures a created signal only on a start that carries neither
1464
+ * a host ticket nor a request context: a drain after a run
1465
+ * `resumeViaRuntime()` registered, which the gate refuses for its missing
1466
+ * actor without reading content. On a guarded agent such a call has no
1467
+ * actor, so the gate refuses it before any application input processor
1468
+ * runs. Host code that calls `stream()` the same way, with a created signal
1469
+ * or an object carrying the signal brand as input, has that input kept when
1470
+ * the gate refuses it.
1471
+ *
1472
+ * The verdict comes from the tripwire rather than from the prepared list, so
1473
+ * it holds whether or not the guard removes refused input from the list. A
1474
+ * bounded best-effort write prevents hung memory from blocking the ERROR
1475
+ * that heals thread state.
1218
1476
  */
1219
- async #persistUnownedInput(runId, workflowInput) {
1477
+ async #persistUnownedInput(runId, workflowInput, replayedSignal) {
1220
1478
  let timeout;
1221
1479
  try {
1222
1480
  await Promise.race([
@@ -1228,19 +1486,39 @@ export class FlowsafeDurableAgent extends DurableAgent {
1228
1486
  // Explicit read-only memory forbids preserving denied input.
1229
1487
  if (state.memoryConfig?.readOnly === true)
1230
1488
  return;
1489
+ const registryEntry = this.runRegistryInternal.get(runId);
1490
+ const tripwire = registryEntry?.tripwire;
1231
1491
  const memory = await this.getMemory({
1232
- requestContext: globalRunRegistry.get(runId)?.requestContext,
1492
+ requestContext: registryEntry?.requestContext,
1233
1493
  });
1234
1494
  if (!memory)
1235
1495
  return;
1236
- const list = new MessageList({
1237
- threadId,
1238
- resourceId: state.resourceId,
1239
- }).deserialize(workflowInput.messageListState);
1240
- const inputIds = list.makeMessageSourceChecker().input;
1241
- const messages = list.get.all
1242
- .db()
1243
- .filter((message) => inputIds.has(message.id))
1496
+ let candidates;
1497
+ if (tripwire === undefined) {
1498
+ const list = new MessageList({
1499
+ threadId,
1500
+ resourceId: state.resourceId,
1501
+ }).deserialize(workflowInput.messageListState);
1502
+ const inputIds = list.makeMessageSourceChecker().input;
1503
+ candidates = list.get.all
1504
+ .db()
1505
+ .filter((message) => inputIds.has(message.id));
1506
+ }
1507
+ else if (tripwire.processorId === BREAKWATER_RBAC_PROCESSOR_ID &&
1508
+ replayedSignal !== undefined) {
1509
+ candidates = [
1510
+ signalToMastraDBMessage(replayedSignal, {
1511
+ threadId,
1512
+ resourceId: state.resourceId,
1513
+ }),
1514
+ ];
1515
+ }
1516
+ else {
1517
+ return;
1518
+ }
1519
+ const messages = candidates
1520
+ // Mastra's own persist lane stores no transient signal either.
1521
+ .filter((message) => !isTransientSignalMessage(message))
1244
1522
  // Honor markPersistenceForbidden's route-to-runner metadata contract.
1245
1523
  .filter((message) => !isMastraSignalMessage(message) ||
1246
1524
  mastraDBMessageToSignal(message).metadata?.[FLOWSAFE_PERSISTENCE_FORBIDDEN] !== true);
@@ -1419,23 +1697,15 @@ export class FlowsafeDurableAgent extends DurableAgent {
1419
1697
  }
1420
1698
  // No #startRequesters entry means the host start seam never registered
1421
1699
  // this id, so core minted it below our boundary. Such a run has no
1422
- // ownership record or trusted engine-leg context. Preserve its input
1423
- // when allowed, then close the stream so core can clean up its maps and
1700
+ // ownership record or trusted engine-leg context. Preserve what the
1701
+ // input chain's verdict allows, including a signal stream() captured
1702
+ // for this id, then close the stream so core can clean up its maps and
1424
1703
  // release the lease transferred to this id.
1425
- await this.#persistUnownedInput(runId, workflowInput);
1704
+ const replayedSignal = this.#replayedSignals.get(runId);
1705
+ this.#replayedSignals.delete(runId);
1706
+ await this.#persistUnownedInput(runId, workflowInput, replayedSignal);
1426
1707
  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`);
1427
- let published = false;
1428
- try {
1429
- published =
1430
- (await this.#publishTerminalError(runId, refusal)) ||
1431
- (await this.#publishTerminalError(runId, refusal));
1432
- }
1433
- finally {
1434
- this.runRegistryInternal.cleanup(runId);
1435
- globalRunRegistry.delete(runId);
1436
- }
1437
- if (!published)
1438
- throw refusal;
1708
+ await this.#settleRefusedStart(runId, refusal);
1439
1709
  return;
1440
1710
  }
1441
1711
  const { runId: coreRunId, agentId: coreAgentId, ...payload } = workflowInput;
@@ -1447,6 +1717,17 @@ export class FlowsafeDurableAgent extends DurableAgent {
1447
1717
  coreAgentId !== authority.startIdentity.target.id) {
1448
1718
  throw new InvalidRunRequestError('Core input does not match agent start authority');
1449
1719
  }
1720
+ // The agent registry retains the preparation refusal when the isolate-wide
1721
+ // registry evicts its entry before the first step.
1722
+ if (this.runRegistryInternal.get(runId)?.tripwire?.processorId ===
1723
+ BREAKWATER_RBAC_PROCESSOR_ID) {
1724
+ const refusal = new AgentAuthorizationDeniedError();
1725
+ // The waiter's first rejection wins; publishing ERROR first supplies a
1726
+ // plain Error that doErrorResponse maps to 500.
1727
+ waiter?.reject(refusal);
1728
+ await this.#settleRefusedStart(runId, refusal);
1729
+ return;
1730
+ }
1450
1731
  const workflow = this.getWorkflow();
1451
1732
  summary = await this.#runtime.start(workflow.id, {
1452
1733
  runId,
@@ -1505,9 +1786,7 @@ export function createFlowsafeDurableAgent(options) {
1505
1786
  const workflow = durableAgent.getWorkflow();
1506
1787
  if (!options.runtime.workflowIds().includes(workflow.id)) {
1507
1788
  // getWorkflow()'s concrete engine generics are not single-cast-assignable to
1508
- // AnyWorkflow, so the double cast through `unknown` is required (init.ts gets
1509
- // away with a single cast because coreCreateWorkflow's return already lines
1510
- // up). The runtime only ever reads id / getWorkflowRunById / createRun off it.
1789
+ // AnyWorkflow, so the double cast through `unknown` is required.
1511
1790
  options.runtime.register(workflow);
1512
1791
  }
1513
1792
  return durableAgent;