@proofoftech/flowsafe 0.21.0 → 0.23.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 (77) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +25 -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 +108 -58
  9. package/dist/agent-host/thread-host.js.map +1 -1
  10. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  11. package/dist/agent-host/thread-topology.js +11 -9
  12. package/dist/agent-host/thread-topology.js.map +1 -1
  13. package/dist/agent-runner/durable-agent-runner.d.ts +134 -96
  14. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  15. package/dist/agent-runner/durable-agent-runner.js +424 -282
  16. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  17. package/dist/approval-api/actor-context.js +3 -3
  18. package/dist/approval-api/actor-context.js.map +1 -1
  19. package/dist/approval-api/service.d.ts +6 -9
  20. package/dist/approval-api/service.d.ts.map +1 -1
  21. package/dist/approval-api/service.js +6 -9
  22. package/dist/approval-api/service.js.map +1 -1
  23. package/dist/background-tasks/d1-storage.js +1 -1
  24. package/dist/background-tasks/d1-storage.js.map +1 -1
  25. package/dist/background-tasks/host.d.ts.map +1 -1
  26. package/dist/background-tasks/host.js +3 -2
  27. package/dist/background-tasks/host.js.map +1 -1
  28. package/dist/do-runner/d1-storage.d.ts +4 -2
  29. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  30. package/dist/do-runner/d1-storage.js +4 -2
  31. package/dist/do-runner/d1-storage.js.map +1 -1
  32. package/dist/do-runner/durable-object.d.ts.map +1 -1
  33. package/dist/do-runner/durable-object.js +22 -22
  34. package/dist/do-runner/durable-object.js.map +1 -1
  35. package/dist/do-runner/execution-context.d.ts +5 -1
  36. package/dist/do-runner/execution-context.d.ts.map +1 -1
  37. package/dist/do-runner/execution-context.js +5 -1
  38. package/dist/do-runner/execution-context.js.map +1 -1
  39. package/dist/do-runner/execution-fence.js +2 -2
  40. package/dist/do-runner/execution-fence.js.map +1 -1
  41. package/dist/do-runner/run-lifecycle.js +6 -6
  42. package/dist/do-runner/run-lifecycle.js.map +1 -1
  43. package/dist/do-runner/runtime.d.ts +23 -47
  44. package/dist/do-runner/runtime.d.ts.map +1 -1
  45. package/dist/do-runner/runtime.js +61 -68
  46. package/dist/do-runner/runtime.js.map +1 -1
  47. package/dist/do-runner/start-idempotency.js +4 -4
  48. package/dist/do-runner/start-idempotency.js.map +1 -1
  49. package/dist/host-kit/approval-bridge.d.ts +8 -8
  50. package/dist/host-kit/approval-bridge.js +8 -8
  51. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  52. package/dist/host-kit/flowsafe-worker.js +5 -0
  53. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  54. package/dist/schedules/schedules-d1.js +1 -1
  55. package/dist/schedules/tick.d.ts +1 -8
  56. package/dist/schedules/tick.d.ts.map +1 -1
  57. package/dist/schedules/tick.js +8 -19
  58. package/dist/schedules/tick.js.map +1 -1
  59. package/dist/signals/client.d.ts +7 -4
  60. package/dist/signals/client.d.ts.map +1 -1
  61. package/dist/signals/client.js +9 -7
  62. package/dist/signals/client.js.map +1 -1
  63. package/dist/signals/d1-shared.js +1 -1
  64. package/dist/signals/index.d.ts +1 -1
  65. package/dist/signals/index.d.ts.map +1 -1
  66. package/dist/signals/index.js.map +1 -1
  67. package/dist/signals/notification-dispatch.d.ts +1 -12
  68. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  69. package/dist/signals/notification-dispatch.js +0 -53
  70. package/dist/signals/notification-dispatch.js.map +1 -1
  71. package/dist/signals/thread-do-routes.d.ts +48 -9
  72. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  73. package/dist/signals/thread-do-routes.js +411 -230
  74. package/dist/signals/thread-do-routes.js.map +1 -1
  75. package/package.json +14 -9
  76. package/scripts/seed-deployment-identity.mjs +25 -11
  77. package/patches/@mastra__core@1.53.0.patch +0 -54
@@ -1,13 +1,11 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // FlowsafeDurableAgent — drive Mastra's durable-agent loop through the ONE
3
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.
4
+ // invariants.
7
5
  //
8
6
  // 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:
7
+ // THIS section is 1.50.0-vintage and kept as the provenance of the original
8
+ // validation; later sections carry their own stamp:
11
9
  // DurableAgent compiles the agent loop to the default-engine workflow
12
10
  // 'durable-agentic-loop' (agent/durable index.js: AGENTIC_LOOP :62,
13
11
  // getWorkflow() :5936, agent-agnostic — the agent is resolved per run by the
@@ -33,23 +31,29 @@
33
31
  // there. The registry copy is read only for the fail-closed, over-require-safe
34
32
  // approval pre-check.
35
33
  //
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
34
+ // Host-owned run ids at the boundary: stream()/generate()/prepare() are
35
+ // inherited minting entry points. Each takes an OPTIONAL runId and, when it is
36
+ // absent, lets core mint an unowned crypto.randomUUID() upstream
39
37
  // (prepareForDurableExecution, agent/durable index.js:589) that
40
38
  // PATH_SAFE_ID_PATTERN then accepts, slipping past executeWorkflow's guard AND
41
39
  // 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
40
+ // forbids. They are overridden ONLY to require a caller-minted runId before
41
+ // delegating to super. prepare() also REGISTERS the run under that id
44
42
  // (index.js:5984), so an unguarded prepare() strands an unowned run in the
45
43
  // registry. streamUntilIdle() needs no override: it drives agent.stream()
46
44
  // (index.js:368), so the stream() guard already covers it.
47
45
  //
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.
46
+ // EVERY OTHER inherited entry point whose call can drive a run that would not
47
+ // land on those guarded overrides, or whose call itself discovers run or thread
48
+ // identities without a scope the caller names, is BLOCKED, overridden to throw
49
+ // before it touches storage or the registry. A call that returns the run id of
50
+ // a thread or run the caller names discovers nothing. A call that installs a
51
+ // second execution surface is refused on the fourth ground too. Installing a
52
+ // runtime service after construction is refused on the fifth ground.
53
+ // Direct cancellation outside RunnerRuntime's terminal lifecycle is refused
54
+ // on the sixth.
55
+ // BLOCKED_RUN_ENTRIES below is the single source for which method is refused on
56
+ // which ground; the grounds are enumerated there.
53
57
  //
54
58
  // Provenance for this section: read from the @mastra/core 1.53.0 dist. Chunk
55
59
  // file names are CONTENT-HASHED and move every release, so each offset below is
@@ -68,7 +72,7 @@
68
72
  // reaches it, and the snapshot rows belong to deployment-scoped retention
69
73
  // purge.
70
74
  //
71
- // (2) Unscoped run DISCOVERY, which returns run/thread/resource ids rather
75
+ // (2) Unscoped run or thread identity DISCOVERY returns identities rather
72
76
  // than driving anything. listActiveRuns() (chunk-XMEACVLS.js:6927)
73
77
  // enumerates `listWorkflowRuns({ workflowName: 'durable-agentic-loop',
74
78
  // status: 'running' })`, and the Agent-level listSuspendedRuns()
@@ -79,7 +83,9 @@
79
83
  // (:6962-6981 and :49563-49586). Neither consults the host topology's
80
84
  // per-principal run-ownership checks (resourceAccess().owner('run', …)),
81
85
  // so either one hands a caller ids for runs it does not own. Run listing
82
- // is the topology's job.
86
+ // is the topology's job. discoverThreadPeers()
87
+ // (agent-Dk0N0Nlg.js:38208-38210) likewise enumerates advertised thread
88
+ // identities on the pub/sub without a caller-named thread or principal.
83
89
  //
84
90
  // (3) The resume family, in chunk-XMEACVLS.js: resume() (:6072) and its
85
91
  // funnels resumeStream() (:6650), resumeGenerate() (:6878),
@@ -87,8 +93,7 @@
87
93
  // approveToolCallGenerate() (:6679) / declineToolCallGenerate() (:6683),
88
94
  // plus the new resume(..., { toolCallId }) which only forwards toolCallId
89
95
  // 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,
96
+ // runId from its caller. 1.53.0 changed what they reach: resume() no longer requires a live registry entry,
92
97
  // and on a miss it loads the persisted snapshot (:6075-6076), rehydrates
93
98
  // via prepare() (:6115) with the full application processor chain, then
94
99
  // re-drives with createRun + run.resume (:6281/:6293) below
@@ -97,16 +102,12 @@
97
102
  // call it.
98
103
  //
99
104
  // 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.
105
+ // chunk or file is named). The base `Agent` also carries own members
106
+ // DurableAgent does not shadow; durable-agent-surface.test.ts pins their
107
+ // partition by name.
106
108
  //
107
109
  // BLOCKED outright, because each is its own execution path:
108
- // - listSuspendedRuns() (:49532), the one direct data-returning discovery
109
- // member — the discovery ground.
110
+ // - listSuspendedRuns() (:49532) — the discovery ground.
110
111
  // - the network family: network() (:49263) and resumeNetwork() (:49326)
111
112
  // start and resume THE SAME networkLoop (:32496), which compiles its own
112
113
  // workflow and drives it with `mainWorkflow.createRun` (:32968) +
@@ -124,39 +125,34 @@
124
125
  // every supported entry calls (requireAgentExecutionFGA, defined :48798,
125
126
  // called from generate :49420, stream :49858, resumeStream :50002,
126
127
  // 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
128
+ // chunk-XMEACVLS.js:5918/6158/6718 — none of them on the network or
129
+ // legacy path). It touches no persisted workflow run state, so it is
130
+ // convicted on minting plus the skipped gate, not on re-drive.
131
+ // - sendToolApproval() (:50254), whose name suggests a funnel. With
132
+ // `messages && approved` it calls
132
133
  // agentThreadStreamRuntime.continueWithMessages() (:50266), where
133
134
  // `const runId = target.runId ?? randomUUID()` (chunk-P4Y2BJL7.js:6752)
134
135
  // mints and `agent.stream(..., { runId })` (:6720) then starts a run
135
136
  // under that core-minted id — path-safe, so #assertCallerRunId cannot
136
137
  // 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
+ // this.listSuspendedRuns() (:50287), which is blocked. Only its tail
138
139
  // reaches this.resumeStream() (:50338) / this.sendStreamResume()
139
140
  // (:50345). The mint is the conviction.
140
141
  //
141
142
  // LEFT INHERITED as funnellers, because virtual dispatch already lands them
142
143
  // on an override: resumeStreamUntilIdle() (:49954 -> agent.resumeStream) and
143
144
  // 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.
145
+ // resumeStream. The signal senders stay inherited because every outcome they
146
+ // can produce lands on this runner's terminal path; queueMessage keeps the
147
+ // same containment property.
147
148
  //
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
149
+ // Direct sender calls can reach core's minting sites: the idle wake
154
150
  // (:7441), continuation (:6720), completion drain (:6665), and queued-id
155
151
  // drain (:6808), all in chunk-P4Y2BJL7.js.
156
152
  // 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.
153
+ // terminal refusal: it preserves input by the guarded input chain's
154
+ // verdict when memory permits, publishes ERROR, and never calls
155
+ // RunnerRuntime. #persistUnownedInput states the verdict rule.
160
156
  //
161
157
  // Core registers thread state only when stream options carry a memory
162
158
  // thread (chunk-P4Y2BJL7.js:6557-6594). For those runs its completion
@@ -170,9 +166,9 @@
170
166
  // cleanup before a synchronous refusal would be safe there. Upstream note:
171
167
  // DurableAgent does not forward the wrapped Agent's `notifications`
172
168
  // 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.
169
+ // If the runner's publication attempts and core's own fire-and-forget
170
+ // attempt fail, the terminal output never closes and the thread remains
171
+ // active until eviction or a new host start.
176
172
  //
177
173
  // LEFT INHERITED as non-execution, on a read of each: the base delegators
178
174
  // resume/recover/listActiveRuns/recoverActiveRuns/prepare (:50497 onward) are
@@ -180,58 +176,49 @@
180
176
  // this instance; `observe` is likewise shadowed by DurableAgent but is NOT
181
177
  // overridden and must not be — it only reattaches to a run's pubsub replay,
182
178
  // 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.
179
+ // `durable` (:44568) is a field accessor; getActiveThreadRunId() (:49507)
180
+ // reads only the in-process pubsub registry, never storage;
181
+ // genTitle() (:46377) and generateTitleFromUserMessage() (:46296) call
182
+ // `llm.stream`/`llm.__text` with no tools.
189
183
  //
190
- // Two residuals remain outside this class's reach rather than overlooked.
191
- // Mastra.restartAllActiveWorkflowRuns() is Mastra-level, not an agent member —
184
+ // Residuals outside this class's reach include:
185
+ // Mastra.restartAllActiveWorkflowRuns() belongs to Mastra, not an agent —
192
186
  // nothing here calls it, and it would hit core's processor-rebuild fallback if
193
187
  // 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.
188
+ // returns the very handler the legacy entries refuse; that is the same class
189
+ // of caveat as getWorkflow() returning a startable object, and reaching it
190
+ // takes a deliberate private cast, which is a first-party act.
197
191
  //
198
- // Corroboration: breakwater's guarded handle reaches the same verdict on the
199
- // network four (network, resumeNetwork, approveNetworkToolCall,
200
- // declineNetworkToolCall), the legacy pair (generateLegacy, streamLegacy) and
201
- // sendToolApproval, which it files `intentionallyUnavailable`
202
- // (packages/breakwater/src/agent/agent.test.ts). It diverges on
203
- // listSuspendedRuns, which it files under `explicitlyNonExecution` — the same
204
- // divergence as listActiveRuns, and for the same reason: a
205
- // narrowed HANDLE can only omit, so a data-returning member is harmless there,
206
- // while an INSTANCE Mastra calls in-process must throw. The two members
207
- // blocked below for newer cores diverge the same way; each entry records it.
192
+ // Corroboration: breakwater's guarded handle inventory
193
+ // (packages/breakwater/src/agent/agent.test.ts) classifies the same Agent
194
+ // members for a narrowed HANDLE. A handle can only omit, so a data-returning
195
+ // member or a setter is harmless there, while an INSTANCE Mastra calls
196
+ // in-process must throw; the inventories can file a member differently for
197
+ // that reason.
208
198
  //
209
- // Two more Agent-level members are blocked for cores NEWER than the pin. Read
210
- // from the @mastra/core 1.67.0 dist, which the mastra-compat canary installs;
211
- // offsets here are 1.67.0-vintage, in agent-Dk0N0Nlg.js unless another file is
212
- // named, and the 1.53.0 offsets above are left as the provenance of that read.
213
- // The pinned peer exposes neither member, so on 1.53.0 each refusal stands
214
- // where the base would have raised a TypeError, and shadows a real
215
- // implementation only once the peer moves.
199
+ // The Agent-level members below are blocked as well. Read from the
200
+ // @mastra/core 1.67.0 dist, the declared peer; offsets here are 1.67.0-vintage,
201
+ // in agent-Dk0N0Nlg.js unless another file is named, and the 1.53.0 offsets
202
+ // above are left as the provenance of that read. The peer carries each of
203
+ // them, so each refusal shadows a real implementation.
216
204
  //
217
205
  // - listActiveThreadRuns() (:38214) is the discovery ground one scope wider
218
206
  // than listActiveRuns. It takes no arguments and returns `{ runId,
219
- // resourceId, threadId }` for every thread on the pubsub instance with a
220
- // run in flight (storage-MbGlKLkB.js:1011-1023), and that state is keyed
221
- // by pubsub instance rather than by agent (`#statesByPubSub`, :150, read
222
- // through #getState :294), so it narrows by neither principal nor agent
223
- // where the two listings above at least narrow by agentId. The in-process
224
- // sibling getActiveThreadRunId() stays non-execution because it makes the
225
- // caller name the (resourceId, threadId) pair: it confirms where this
226
- // enumerates. Breakwater files it `explicitlyNonExecution`
227
- // (agent.test.ts) for the reason it files listActiveRuns there: a
228
- // narrowed HANDLE can only omit, so a data-returning member is harmless
229
- // there, while an INSTANCE Mastra calls in-process must throw. Cost, stated
230
- // rather than left to be rediscovered: core's AgentController aggregates
231
- // this member across its backing agents
232
- // (agent-controller-CKgKFyMR.js:5722-5725), so that aggregation now throws.
233
- // It is already unusable over this class — the same controller calls the
234
- // blocked sendToolApproval() at :4089 and :4118.
207
+ // resourceId, threadId }` for every thread on the pubsub instance with a run
208
+ // in flight (storage-MbGlKLkB.js:1011-1023), and that state is keyed by
209
+ // pubsub instance rather than by agent (`#statesByPubSub`, :150, read through
210
+ // #getState :294), so it narrows by neither principal nor agent where the
211
+ // listings above at least narrow by agentId. The in-process sibling
212
+ // getActiveThreadRunId() stays non-execution because it makes the caller name
213
+ // the (resourceId, threadId) pair: it confirms where this enumerates.
214
+ // Cost, stated rather than left to be rediscovered: core's AgentController
215
+ // aggregates this member across its backing agents
216
+ // (agent-controller-CKgKFyMR.js:5722-5725), so that aggregation throws. The
217
+ // controller installs configured memory or pub/sub when the agent lacks its
218
+ // own (agent-controller-CKgKFyMR.js:5618-5622), reaching the refused
219
+ // __setMemory() or __setPubSub(). When it installs neither, init() still
220
+ // reaches the refused __setMastra() through Mastra.addAgent(). It also calls
221
+ // the blocked sendToolApproval() at :4089 and :4118.
235
222
  // - __setThreadRuntimeAgent() (:33609) installs another agent as the target
236
223
  // the thread-runtime paths resolve through #getThreadRuntimeAgent()
237
224
  // (:33612, `this.#threadRuntimeAgent ?? this`); the refusal in
@@ -240,38 +227,56 @@
240
227
  // the containment those inherited members rely on IS virtual dispatch on
241
228
  // `this`, so one call moves every run those paths start onto an agent
242
229
  // carrying none of these overrides — no caller-minted runId assertion, no
243
- // executeWorkflow, no #startRequesters backstop. subscribeToThread drives
244
- // no run of its own; the field moves its replay target all the same. It is
245
- // public in the type surface (agent.d.ts:229 declares it with no
246
- // modifier), so unlike getLegacyHandler it takes no private cast.
247
- // Breakwater files it `explicitlyNonExecution` (agent.test.ts) for the
248
- // reason it files the listings there: a narrowed HANDLE can only omit, so
249
- // a setter is harmless there, while an INSTANCE Mastra calls in-process
250
- // must throw.
230
+ // executeWorkflow, no #startRequesters backstop. The field also moves
231
+ // subscribeToThread's replay target. It is public in the type surface
232
+ // (agent.d.ts:229 declares it with no modifier), so unlike getLegacyHandler
233
+ // it takes no private cast.
234
+ // The DurableAgent-level members below are blocked too. Read from the
235
+ // @mastra/core 1.67.0 dist; offsets here are 1.67.0-vintage, in
236
+ // create-durable-agent-DFHwqN2K.js unless another file is named.
251
237
  //
252
- // Neither carries the `override` keyword, and that is load-bearing rather than
253
- // an oversight: TypeScript rejects `override` on a member the base does not
254
- // declare, and 1.53.0 declares neither, so the keyword would fail the pinned
255
- // typecheck that gates every merge. Each signature must still satisfy the base
256
- // it acquires on newest; the caveat on each member says how. Both re-checks
257
- // come due together, when the declared peer reaches a core that carries either
258
- // member: the VERSION_SKEW expiry assertion in durable-agent-surface.test.ts
259
- // goes red there, because each member's row claims the installed core carries
260
- // it on neither prototype. That message speaks about the row alone; these two
261
- // members' keyword and signature move with it.
238
+ // - setChannels() (:6408) and __setDeclaredSchedules() (:6240) forward what
239
+ // they are given to the wrapped agent. Channels make that agent their
240
+ // dispatch target (agent-Dk0N0Nlg.js:33791-33796), so a plain AgentChannels
241
+ // delivers inbound messages to its sendMessage, and channel approvals and
242
+ // declines to its approveToolCall and declineToolCall (agent-Dk0N0Nlg.js
243
+ // :21002, :21031, :21045). The schedule worker of a Mastra that registers
244
+ // the wrapped agent and runs startWorkers() (mastra-CCeMcPkn.js:4525-4589)
245
+ // resolves each declared schedule's agent by id and fires it through that
246
+ // agent's sendSignal or generate (worker-CemmWBp9.js:167, :319, :448). Both
247
+ // run the wrapped agent outside RunnerRuntime, so each call is the fourth
248
+ // ground by installation, as __setThreadRuntimeAgent() is.
249
+ // - __setMemory() and __setPubSub() (:6414-6421) install and forward services
250
+ // to the wrapped agent. AgentController reaches them under the conditions
251
+ // above (agent-controller-CKgKFyMR.js:5618-5622); a parent with pub/sub
252
+ // also reaches __setPubSub() when the wrapped agent has no pub/sub of its
253
+ // own (agent-Dk0N0Nlg.js:34105).
254
+ // - abortRunStream() and abortThreadStream() (:6565-6601) cancel outside the
255
+ // terminate route's ownership and settlement checks.
256
+ // - __setMastra() (:7922) forwards to __registerMastra() (:7934), which sets
257
+ // this wrapper's Mastra and the wrapped agent's (:7934-7939). Every later
258
+ // leg is prepared against that Mastra: core hands it to
259
+ // prepareForDurableExecution (:6693, :7362, :7882), and so does
260
+ // #rehydrateRegistry. Mastra.addAgent calls __setMastra()
261
+ // (mastra-CCeMcPkn.js:1674) and then adds getDurableWorkflows() to its own
262
+ // registry (:1689-1692); once the runtime has built its own Mastra, that
263
+ // repoints the runtime's loop workflow, and with it run state, to the
264
+ // other Mastra's storage. Agent.listAgents calls
265
+ // __registerMastra() on each static sub-agent (agent-Dk0N0Nlg.js:34104).
266
+ // A parent with pub/sub also calls __setPubSub() on a static sub-agent
267
+ // without its own pub/sub (:34105), even when it has no Mastra. These are
268
+ // the fifth ground. The refusal throws from addAgent before its registry
269
+ // write and before it repoints the loop.
262
270
  //
263
- // Blocking them keeps the single-resume and no-capability guarantees true by
264
- // construction: resumeViaRuntime() is the ONLY way a run resumes.
265
- // ApprovalService.decide -> the host's ResumeRunFn ->
266
- // createAgentApprovalResumer, which hands every 'durable-agentic-loop' record to
267
- // the thread topology's resume (-> resumeViaRuntime -> runtime.resume) and
268
- // refuses one carrying no agent-thread target rather than falling through to the
269
- // generic resumer; grants are derived on the (suspendedAt, resumeCount)
270
- // fingerprint there. Blocking does not un-brand the agent — DurableAgentLike
271
- // duck-types on `recover`/`recoverActiveRuns` merely BEING functions
272
- // (chunk-3S5BFAEP.js:204), which the overrides still are. The surface tripwire in
273
- // durable-agent-surface.test.ts requires every DurableAgent prototype member to
274
- // stay classified, so a future peer bump surfaces whatever it adds.
271
+ // Each carries the `override` keyword: the declared peer declares the member,
272
+ // so the keyword holds the refusal to a base that exists and fails the
273
+ // typecheck if a future core drops it. Each signature satisfies the base it
274
+ // shadows on that base's own terms.
275
+ //
276
+ // The runner's resume path is resumeViaRuntime(). Blocking does not un-brand
277
+ // the agent — DurableAgentLike duck-types on `recover`/`recoverActiveRuns`
278
+ // merely BEING functions (agent-Dk0N0Nlg.js:272), which the overrides still
279
+ // are.
275
280
  //
276
281
  // Live-isolate scope: the loop resolves the tool's execute closure from the
277
282
  // in-process globalRunRegistry (populated by stream()). A DO holds one run in
@@ -280,7 +285,7 @@
280
285
  // application input processors. resumeViaRuntime() rebuilds the registry with
281
286
  // complete runtime processor lists after invoking only reserved RBAC during
282
287
  // empty-message preparation, then drives runtime.resume().
283
- import { isMastraSignalMessage, MessageList, mastraDBMessageToSignal, } from '@mastra/core/agent';
288
+ import { isCreatedAgentSignal, isDurableAgentLike, isMastraSignalMessage, isTransientSignalMessage, MessageList, mastraDBMessageToSignal, signalToMastraDBMessage, } from '@mastra/core/agent';
284
289
  import { DurableAgent, globalRunRegistry, prepareForDurableExecution, } from '@mastra/core/agent/durable';
285
290
  import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
286
291
  import { normalizeMutationEpoch, normalizeStartIdentity, } from '../do-runner/execution-admission.js';
@@ -304,11 +309,11 @@ const UNOWNED_INPUT_PERSIST_TIMEOUT_MS = 5_000;
304
309
  const UNREGISTERED_RUN_REFUSAL_PREFIX = 'Flowsafe durable-agent runner refused unregistered run: ';
305
310
  /**
306
311
  * @internal Metadata key that prevents a route delivery from being terminally
307
- * persisted. Deliberately deep-imported by `signals/thread-do-routes.ts` and
308
- * kept off `./index.js`.
312
+ * persisted. Kept off `./index.js`.
309
313
  */
310
314
  export const FLOWSAFE_PERSISTENCE_FORBIDDEN = 'flowsafe.persistence-forbidden';
311
315
  const BREAKWATER_GUARDED_AGENT_HOST_PROTOCOL = Symbol.for('@proofoftech/breakwater/guarded-agent-host/v1');
316
+ const BREAKWATER_RBAC_PROCESSOR_ID = 'breakwater-rbac';
312
317
  function captureAgentStartAuthority(source, requestedBy, requestedByKind) {
313
318
  if (source === null || typeof source !== 'object' || Array.isArray(source)) {
314
319
  throw new InvalidRunRequestError('agent start authority is required');
@@ -405,7 +410,7 @@ function snapshotDurableCallOptions(options) {
405
410
  }
406
411
  return Object.freeze(snapshot);
407
412
  }
408
- /** @internal Shared with the guarded agent catalog's compatibility check. */
413
+ /** @internal */
409
414
  export function breakwaterGuardedAgentHostProtocol(agent) {
410
415
  if ((typeof agent !== 'object' && typeof agent !== 'function') || !agent) {
411
416
  return undefined;
@@ -423,23 +428,41 @@ export function breakwaterGuardedAgentHostProtocol(agent) {
423
428
  return protocol;
424
429
  }
425
430
  /**
426
- * Why every member of the resume family is refused. Homed once: the seven
431
+ * @internal Why the runner refuses to wrap `agent`, or `undefined` when it
432
+ * accepts it.
433
+ */
434
+ export function unwrappableAgentReason(agent) {
435
+ if (agent.durable) {
436
+ 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";
437
+ }
438
+ if (isDurableAgentLike(agent)) {
439
+ 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';
440
+ }
441
+ if (agent.getChannels() != null) {
442
+ return 'has channels configured: Mastra dispatches their inbound messages and tool approvals to that agent outside RunnerRuntime';
443
+ }
444
+ if (agent.getDeclaredSchedules().length > 0) {
445
+ return 'declares schedules: the schedule worker of a Mastra that registers that agent fires them on it outside RunnerRuntime';
446
+ }
447
+ return undefined;
448
+ }
449
+ /**
450
+ * Why every member of the resume family is refused. Homed once: the family's
427
451
  * entry points are one code path (resumeStream/resumeGenerate/the approve and
428
452
  * decline pairs all funnel into resume()), so one sentence must not drift into
429
- * seven.
453
+ * a copy per entry point.
430
454
  */
431
455
  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";
432
456
  /**
433
- * Why the four network entry points are refused. Homed once: `network()` starts
434
- * and `resumeNetwork()` resumes THE SAME networkLoop, and the approve/decline
435
- * pair are one-line forwards to `resumeNetwork()`, so one sentence must not
436
- * drift into four.
457
+ * Why the network entry points are refused. Homed once: `network()` starts and
458
+ * `resumeNetwork()` resumes THE SAME networkLoop, and the approve/decline pair
459
+ * are one-line forwards to `resumeNetwork()`, so one sentence must not drift
460
+ * into a copy per entry point.
437
461
  */
438
462
  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';
439
463
  /**
440
- * Why both legacy execution entry points are refused. Homed once: each is a
441
- * one-line forward into the SAME AgentLegacyHandler, so they are one code path
442
- * wearing two names.
464
+ * Why the legacy execution entry points are refused. Homed once: each is a
465
+ * one-line forward into the SAME AgentLegacyHandler, so they are one code path.
443
466
  */
444
467
  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)";
445
468
  /**
@@ -449,30 +472,41 @@ const LEGACY_FAMILY_REASON = "the AI SDK v4 legacy handler is a second execution
449
472
  */
450
473
  const THREAD_TOOL_APPROVAL_REASON = 'the messages-plus-approved branch does not resume at all: it hands the thread runtime a continuation whose run id falls back to randomUUID() when the caller names none, then starts a run under that id — path-safe, so the host-owned run-id guard cannot tell it from a caller-minted one — and its no-active-run branch reaches the equally unscoped suspended-run discovery';
451
474
  /**
452
- * Why each blocked entry point is refused, keyed by method name. The SINGLE
453
- * source: every override throws `unavailableRunEntry(name,
454
- * BLOCKED_RUN_ENTRIES[name])`, and durable-agent-surface.test.ts derives both
455
- * its blocked-member partition and its per-method message assertions from these
456
- * keys — so a new blocked entry cannot ship with an unexercised refusal, and a
457
- * reason cannot drift between the throw and the test.
475
+ * Why binding the wrapper to a Mastra is refused. Homed once: `__setMastra()`
476
+ * forwards to `__registerMastra()`, so the two are one code path.
477
+ */
478
+ 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";
479
+ /**
480
+ * Why service setters are refused. Homed once: both install after construction
481
+ * and forward their service to the wrapped agent.
482
+ */
483
+ 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";
484
+ /**
485
+ * Why direct aborts are refused. Homed once: both bypass the terminate route's
486
+ * ownership and disputed-settlement checks.
487
+ */
488
+ const DIRECT_ABORT_REASON = "a direct abort bypasses the terminate route's ownership check and disputed-settlement refusal, stops running tools, and can reach another thread's run in the isolate through core's global run registry; cancel through the terminate route";
489
+ /**
490
+ * Why each blocked entry point is refused, keyed by method name: the SINGLE
491
+ * source of those reasons.
458
492
  *
459
- * Four grounds. The module comment walks the same members by PROVENANCE
460
- * section (the durable surface, then the Agent surface) rather than by ground,
461
- * so its numbering is not this list's:
493
+ * The grounds:
462
494
  * 1. re-drives a persisted run below `executeWorkflow`, where there is no
463
495
  * RunnerRuntime — no run ownership, no per-leg grant, no snapshot
464
496
  * provenance;
465
- * 2. unscoped run discovery that bypasses the host topology's per-principal
466
- * run-ownership checks and returns ids the caller does not own;
497
+ * 2. unscoped run or thread identity discovery that bypasses the host
498
+ * topology's per-principal ownership checks and returns identities the
499
+ * caller does not own;
467
500
  * 3. snapshot deletion owned by deployment-scoped retention;
468
- * 4. a SECOND execution surface that runs the agent outside RunnerRuntime
469
- * entirely, or that mints a run id below the caller — the network loop's
470
- * own workflow, the legacy handler, the thread runtime's tool-approval
471
- * continuation, and the setter that installs a different agent as the
472
- * thread runtime's execution target.
501
+ * 4. a SECOND execution surface outside RunnerRuntime, whether the call runs
502
+ * it or installs something that later does, or that mints a run id below
503
+ * the caller;
504
+ * 5. installs a runtime service — a Mastra, memory or pub/sub — after
505
+ * construction;
506
+ * 6. cancels a run outside RunnerRuntime's terminal lifecycle.
473
507
  *
474
- * Deliberately NOT re-exported from `./index.js` (a named-exports-only barrel),
475
- * so this stays off the public `@proofoftech/flowsafe/agent-runner` subpath.
508
+ * NOT re-exported from `./index.js` (a named-exports-only barrel), so this
509
+ * stays off the public `@proofoftech/flowsafe/agent-runner` subpath.
476
510
  */
477
511
  export const BLOCKED_RUN_ENTRIES = {
478
512
  recover: 're-driving a persisted run bypasses run ownership, per-leg grant minting and the fail-closed registry rehydration',
@@ -487,6 +521,7 @@ export const BLOCKED_RUN_ENTRIES = {
487
521
  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",
488
522
  listSuspendedRuns: "core scopes the suspended-run listing by agentId plus the caller's own optional thread and resource ids, never by per-principal ownership, so it bypasses the host topology's run-ownership checks and returns run, thread and resource ids the caller does not own",
489
523
  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',
524
+ 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',
490
525
  deleteRunSnapshots: 'durable-agent snapshot rows are retained until deployment-scoped retention purge removes them',
491
526
  network: `${NETWORK_FAMILY_REASON}, and it mints an unowned run id when the caller omits one`,
492
527
  resumeNetwork: NETWORK_FAMILY_REASON,
@@ -496,47 +531,46 @@ export const BLOCKED_RUN_ENTRIES = {
496
531
  streamLegacy: LEGACY_FAMILY_REASON,
497
532
  sendToolApproval: THREAD_TOOL_APPROVAL_REASON,
498
533
  __setThreadRuntimeAgent: "it installs the agent the thread-runtime paths resolve their target through — on @mastra/core 1.67.0 these are subscribeToThread, claimThreadOwnership, sendMessage, queueMessage, sendStateSignal, sendNotificationSignal and sendSignal, which read the field it writes — so one call moves every run those paths start, and subscribeToThread's replay target with them, onto an agent that carries none of this class's overrides: no caller-minted run id, no executeWorkflow, and no terminal refusal for a run the host start seam never registered",
534
+ setChannels: "it forwards the channels it is given to the wrapped agent, which becomes their dispatch target, so a plain AgentChannels delivers inbound messages to the wrapped agent's sendMessage, and channel approvals and declines to its approveToolCall and declineToolCall, outside RunnerRuntime; an AgentControllerChannels dispatches through its controller instead, and is refused as well because a controller over this class cannot install its runtime services or register this wrapper on its Mastra",
535
+ __setDeclaredSchedules: "it forwards the schedules it is given to the wrapped agent, and the schedule worker of a Mastra that registers that agent and runs startWorkers() fires each of them through the wrapped agent's sendSignal or generate, outside RunnerRuntime",
536
+ __setMastra: MASTRA_BINDING_REASON,
537
+ __registerMastra: MASTRA_BINDING_REASON,
538
+ __setMemory: INSTALLED_SERVICE_REASON,
539
+ __setPubSub: INSTALLED_SERVICE_REASON,
540
+ abortRunStream: DIRECT_ABORT_REASON,
541
+ abortThreadStream: DIRECT_ABORT_REASON,
499
542
  };
500
543
  /**
501
- * The refusal every blocked run entry point throws. A plain `Error`, not
544
+ * The refusal for a blocked run entry point. A plain `Error`, not
502
545
  * {@link InvalidRunRequestError}: that class means "the client's run request is
503
- * malformed" (runtime.ts homes the convention — client input is an
504
- * InvalidRunRequestError, a developer-controlled mistake is a plain Error), and
505
- * calling one of these is neither a run request nor recoverable by fixing an
506
- * argument. Same voice as #rehydrateRegistry's fail-closed throw. The message
507
- * names WHAT is refused and WHY, and carries no run data — the discovery
546
+ * malformed", and calling one of these is neither a run request nor
547
+ * recoverable by fixing an argument. The message names WHAT is refused and WHY, and carries no run data — the discovery
508
548
  * entries have none to carry, and the others must not echo an id the caller may
509
549
  * not own into its log.
510
550
  */
511
551
  function unavailableRunEntry(method, why) {
512
- 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)`);
552
+ 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)`);
513
553
  }
514
554
  function bindThreadCompletion(output, completion) {
515
555
  return new Proxy(output, {
516
- get(target, property, receiver) {
556
+ get(target, property) {
557
+ // Core's output getters read private fields, which a proxy receiver lacks.
558
+ const value = Reflect.get(target, property, target);
517
559
  if (property === '_waitUntilFinished') {
518
- const wait = Reflect.get(target, property, target);
519
- return () => typeof wait === 'function'
560
+ return () => typeof value === 'function'
520
561
  ? Promise.race([
521
- Promise.resolve(wait.call(target)),
562
+ Promise.resolve(value.call(target)),
522
563
  completion,
523
564
  ])
524
565
  : completion;
525
566
  }
526
- const value = Reflect.get(target, property, receiver);
527
567
  return typeof value === 'function' ? value.bind(target) : value;
528
568
  },
529
569
  });
530
570
  }
531
571
  /**
532
572
  * Brand marking an agent as runtime-driven. The thread Durable Object requires
533
- * it before its message, signal, schedule, or notification-dispatch wake seam
534
- * may start a run. Queue and state persist rather than wake on idle. Non-owner
535
- * notifications are recorded for the trusted dispatcher and never send a
536
- * signal directly. An unbranded agent reports
537
- * `degraded: 'not-runtime-driven'` on state and owner-notification responses
538
- * that reach the sender, regardless of thread state. Skipped state and
539
- * `memory-unavailable` responses return earlier and carry no marker.
573
+ * it before a wake seam may start a run.
540
574
  *
541
575
  * Direct core sender calls that mint a run still reach the durable runner,
542
576
  * which fails them terminally without executing. Structural so a test double
@@ -577,50 +611,58 @@ export class FlowsafeDurableAgent extends DurableAgent {
577
611
  /**
578
612
  * runId -> the reservation key the thread topology took for this start, so
579
613
  * `executeWorkflow` can hand it to `RunnerRuntime.start` for the execution
580
- * fence's proof-only match. Same lifetime and same cleanup as the attempt
581
- * token beside it: registered by `streamUntilPersisted`, dropped in its
582
- * `finally`, so nothing outlives the start it belongs to.
614
+ * fence's proof-only match.
583
615
  */
584
616
  #startIdempotencyKeys = new Map();
585
617
  #startAuthorities = new Map();
586
618
  #startScheduleDispatches = new Map();
587
619
  // The host's exact options object receives one private, single-use re-entry ticket.
588
620
  #hostStreamTickets = new WeakSet();
621
+ // The created signal of a start with neither a host ticket nor a request
622
+ // context, the options a drain inherits from a run resumeViaRuntime()
623
+ // registered. An RBAC refusal removes that signal from the prepared message
624
+ // list, so executeWorkflow preserves it from this capture.
625
+ #replayedSignals = new Map();
589
626
  constructor(options) {
627
+ const refusal = unwrappableAgentReason(options.agent);
628
+ if (refusal !== undefined) {
629
+ throw new TypeError(`FlowsafeDurableAgent: the wrapped agent ${refusal}`);
630
+ }
631
+ const pubsub = options.pubsub ?? options.runtime.pubsub;
632
+ // The run's drain reads the wrapped agent's pub/sub, where an own pub/sub
633
+ // wins over the one this wrapper installs.
634
+ if (options.agent.hasOwnPubSub() && options.agent.getPubSub() !== pubsub) {
635
+ throw new TypeError("FlowsafeDurableAgent: the wrapped agent has its own pub/sub, which differs from the one the wrapper uses; signal delivery and the run's drain must read the same pub/sub");
636
+ }
590
637
  const guardedProtocol = breakwaterGuardedAgentHostProtocol(options.agent);
591
638
  super({
592
639
  agent: options.agent,
593
640
  id: options.id,
594
641
  name: options.name,
595
642
  cache: options.cache,
596
- // Default the agent's own stream pubsub to the runtime's identity (ONE
597
- // feed per DO), so a host that configures only init()'s pubsub still
598
- // gets observe()/emitError aligned with the run's events (the run is driven
599
- // through the runtime, which publishes on THAT identity). An explicit
600
- // pubsub wins; both-absent falls to core's per-agent default (poll-only,
601
- // byte-identical to before this seam existed).
602
- pubsub: options.pubsub ?? options.runtime.pubsub,
643
+ pubsub,
603
644
  maxSteps: options.maxSteps,
604
645
  });
605
646
  this.#runtime = options.runtime;
606
647
  this.#wrappedAgent = options.agent;
607
648
  this.#isBreakwaterGuardedAgent = guardedProtocol !== undefined;
608
649
  this.#threadRuntime = options.threadRuntime;
650
+ // Core keys thread state and signal delivery on the agent-level pub/sub;
651
+ // its stream pub/sub option leaves that identity unset for the run's drain.
652
+ super.__setPubSub(pubsub ?? this.pubsub);
609
653
  }
610
654
  /**
611
655
  * Host-owned run-ID enforcement at the public boundary. The durable-agent entry points (stream /
612
656
  * generate / prepare) take an OPTIONAL runId, and when it is omitted core's
613
657
  * `prepareForDurableExecution` mints `crypto.randomUUID()`
614
- * (agent/durable/index.js:589 — a 1.50.0-vintage offset, since that file is a
615
- * re-export shim from 1.53.0) — the exact unowned fallback this wrapper forbids —
616
- * and hands it to `executeWorkflow` BELOW this class's own guard, where a bare
617
- * UUID is already indistinguishable from a legitimately caller-minted one. So
618
- * the guard must ALSO fire HERE, before `super.stream()/generate()/prepare()`,
619
- * while "absent" is still visible. Same posture as `RunnerRuntime.start`
620
- * (typeof + PATH_SAFE_ID_PATTERN, NO generation fallback); the `typeof` check
621
- * is load-bearing because `RegExp.test` coerces its argument to a string, so a
658
+ * (create-durable-agent-DFHwqN2K.js:1211) — the exact unowned fallback this
659
+ * wrapper forbids — and hands it to `executeWorkflow` BELOW this class's own
660
+ * guard, where a bare UUID is already indistinguishable from a legitimately
661
+ * caller-minted one. So the guard must ALSO fire HERE, before
662
+ * `super.stream()/generate()/prepare()`, while "absent" is still visible. The
663
+ * `typeof` check is load-bearing because `RegExp.test` coerces its argument to a string, so a
622
664
  * numeric runId would pass the pattern yet key a run by the number. Homed once
623
- * and shared by the four call sites below so the rule cannot drift within this
665
+ * and shared by the call sites below so the rule cannot drift within this
624
666
  * class.
625
667
  */
626
668
  #assertCallerRunId(runId) {
@@ -633,8 +675,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
633
675
  * `#startRequesters` alone is insufficient because `streamUntilPersisted()`
634
676
  * removes it after the first summary while a suspended stream stays live.
635
677
  * The internal registry has no TTL, so it also covers long suspensions after
636
- * the global registry's ten-minute TTL expires.
637
- * The one exemption is the host's own first start: `streamUntilPersisted()`
678
+ * the global registry's TTL expires.
679
+ * It exempts the host's own first start: `streamUntilPersisted()`
638
680
  * stamps its exact options object with a single-use ticket that `stream()`
639
681
  * consumes. A private `WeakSet`, a locally constructed object, and first-use
640
682
  * consumption make that exemption unavailable to callers.
@@ -676,11 +718,21 @@ export class FlowsafeDurableAgent extends DurableAgent {
676
718
  if (!hostStreamTicket)
677
719
  this.#assertRunIdNotLive(callOptions.runId);
678
720
  this.#assertGuardedStructuredOutput(callOptions);
679
- const result = await super.stream(messages, callOptions);
680
- if (!callOptions?.untilIdle) {
681
- await this.#threadRuntime?.registerRun(this, result.output, (callOptions ?? {}), this.pubsub);
721
+ let capturedSignal = false;
722
+ if (!hostStreamTicket &&
723
+ callOptions.requestContext === undefined &&
724
+ isCreatedAgentSignal(messages)) {
725
+ this.#replayedSignals.set(callOptions.runId, messages);
726
+ capturedSignal = true;
727
+ }
728
+ try {
729
+ return await super.stream(messages, callOptions);
730
+ }
731
+ catch (error) {
732
+ if (capturedSignal)
733
+ this.#replayedSignals.delete(callOptions.runId);
734
+ throw error;
682
735
  }
683
- return result;
684
736
  }
685
737
  /**
686
738
  * Start a durable stream and wait until RunnerRuntime has persisted the
@@ -699,12 +751,11 @@ export class FlowsafeDurableAgent extends DurableAgent {
699
751
  /**
700
752
  * The idempotency key the thread topology already RESERVED for this run.
701
753
  *
702
- * It travels down here for one job: the execution fence's proof-only state
754
+ * It travels down here because the execution fence's proof-only state
703
755
  * admits exactly the start whose key matches its nominated proof key, and
704
756
  * `RunnerRuntime.start` is where that comparison happens. It buys no
705
757
  * exactly-once property at this layer — the reservation above already did —
706
- * so nothing here validates it beyond passing it on, and a run started
707
- * without one behaves exactly as before.
758
+ * so nothing here validates it beyond passing it on.
708
759
  *
709
760
  * Parked per-runId beside the attempt token rather than threaded through
710
761
  * core, because core owns the call between `stream()` and
@@ -814,17 +865,15 @@ export class FlowsafeDurableAgent extends DurableAgent {
814
865
  /**
815
866
  * The same host-owned run-ID guard as {@link FlowsafeDurableAgent.stream}.
816
867
  * `prepare()`
817
- * is the third inherited minting entry point: it forwards `options?.runId` into
818
- * core's `prepareForDurableExecution` (agent/durable/index.js:5980), which mints
819
- * an unowned `crypto.randomUUID()` when it is absent
820
- * (agent/durable/index.js:589) AND REGISTERS a run under that id
821
- * (agent/durable/index.js:5984 — all three are 1.50.0-vintage offsets, since
822
- * that file is a re-export shim from 1.53.0) — so a later
868
+ * is an inherited minting entry point: it forwards `options?.runId` into
869
+ * core's `prepareForDurableExecution` (create-durable-agent-DFHwqN2K.js:7882),
870
+ * which mints an unowned `crypto.randomUUID()` when it is absent
871
+ * (create-durable-agent-DFHwqN2K.js:1211) AND REGISTERS a run under that id
872
+ * (create-durable-agent-DFHwqN2K.js:7890) — so a later
823
873
  * `resume(runId)`/`executeWorkflow` sees a bare UUID `PATH_SAFE_ID_PATTERN`
824
874
  * already accepts, past every downstream guard. Enforce the caller-minted ID
825
875
  * here, while "absent" is still visible. A prepared id remains live until core
826
- * cleans up the run, so later `stream()`, `generate()`, `prepare()`, and
827
- * `streamUntilPersisted()` calls carrying that id are refused.
876
+ * cleans up the run.
828
877
  */
829
878
  async prepare(messages, options) {
830
879
  const callOptions = snapshotDurableCallOptions(options);
@@ -848,9 +897,9 @@ export class FlowsafeDurableAgent extends DurableAgent {
848
897
  * Refuse core's bulk recovery. `recoverActiveRuns()` is
849
898
  * {@link FlowsafeDurableAgent.listActiveRuns} plus a `recover()` per row, and
850
899
  * it is what `Mastra.recoverAllDurableAgents()` calls on every registered
851
- * durable agent — so this is the one blocked entry point a host can reach
852
- * without a FlowSafe call site, by opting into `recovery: { durableAgents:
853
- * 'auto' }`. That loop isolates each agent in its own try/catch, so this
900
+ * durable agent — so a host reaches this blocked entry point without a
901
+ * FlowSafe call site by opting into `recovery: { durableAgents: 'auto' }`.
902
+ * That loop isolates each agent in its own try/catch, so this
854
903
  * refusal is logged there rather than failing boot. Refuse with an explicit
855
904
  * `runId` too: a single target is still a re-drive off RunnerRuntime.
856
905
  */
@@ -878,34 +927,41 @@ export class FlowsafeDurableAgent extends DurableAgent {
878
927
  * — and narrows by `agentId` plus the optional `threadId`/`resourceId`
879
928
  * filters the CALLER supplies, the same scoping `listActiveRuns()` applies.
880
929
  * Same ground too: an unfiltered call returns run, thread and resource ids
881
- * across every principal that shares the agent. It is the one direct
882
- * data-returning discovery member the base `Agent` surface adds; the other
883
- * additions funnel through `this.resumeStream()` and so fail closed on that
884
- * override.
930
+ * across every principal that shares the agent.
885
931
  */
886
932
  async listSuspendedRuns(_options) {
887
933
  throw unavailableRunEntry('listSuspendedRuns', BLOCKED_RUN_ENTRIES.listSuspendedRuns);
888
934
  }
889
935
  /**
890
- * Refuse the thread-level run enumerator newer cores add.
936
+ * Refuse the thread-level run enumerator.
891
937
  * `listActiveThreadRuns()` takes no arguments and returns a runId plus the
892
- * resourceId and threadId parsed out of the key for every thread on the
893
- * pubsub instance with a run in flight, and core keys that state by pubsub
894
- * instance rather than by agent — so it is the same discovery ground as
938
+ * resourceId and threadId parsed out of the key for every thread on the pubsub
939
+ * instance with a run in flight, and core keys that state by pubsub instance
940
+ * rather than by agent — so it is the same discovery ground as
895
941
  * {@link FlowsafeDurableAgent.listActiveRuns} with the last scoping gone.
896
942
  * The in-process sibling `getActiveThreadRunId()` stays inherited because it
897
943
  * makes the caller name the (resourceId, threadId) pair it confirms.
898
944
  *
899
945
  * Signature caveat, and the reason this one is not `async`: the base declares
900
- * it SYNCHRONOUS (`listActiveThreadRuns(): ActiveThreadRun[]`), so the
901
- * `async … Promise<never>` shape every other refusal here carries would not
902
- * be assignable to it. No `override` keyword either — the pinned 1.53.0
903
- * declares no such member, and `override` on a member the base lacks is a
904
- * type error. Both are re-checks for a peer bump.
946
+ * it SYNCHRONOUS (`listActiveThreadRuns(): ActiveThreadRun[]`), so an
947
+ * `async … Promise<never>` refusal would not be assignable to it. A re-check
948
+ * for a peer bump.
905
949
  */
906
950
  listActiveThreadRuns() {
907
951
  throw unavailableRunEntry('listActiveThreadRuns', BLOCKED_RUN_ENTRIES.listActiveThreadRuns);
908
952
  }
953
+ /** Refuse unscoped thread identity discovery under the second ground. */
954
+ async discoverThreadPeers(_options) {
955
+ throw unavailableRunEntry('discoverThreadPeers', BLOCKED_RUN_ENTRIES.discoverThreadPeers);
956
+ }
957
+ /** Refuse direct run cancellation under the sixth ground. */
958
+ abortRunStream(_runId) {
959
+ throw unavailableRunEntry('abortRunStream', BLOCKED_RUN_ENTRIES.abortRunStream);
960
+ }
961
+ /** Refuse direct thread cancellation under the sixth ground. */
962
+ abortThreadStream(_options) {
963
+ throw unavailableRunEntry('abortThreadStream', BLOCKED_RUN_ENTRIES.abortThreadStream);
964
+ }
909
965
  /**
910
966
  * Refuse the multi-agent network start. `network()` does not touch the
911
967
  * durable-agentic-loop at all: it compiles a SEPARATE workflow and drives it
@@ -952,7 +1008,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
952
1008
  * omits one, and skips `requireAgentExecutionFGA` — the authorization gate
953
1009
  * every SUPPORTED entry point calls, so this would run the agent without it.
954
1010
  * (The network family skips that gate too; neither is unique in doing so.) It
955
- * persists no workflow run state, which is why it is refused on those two
1011
+ * persists no workflow run state, which is why it is refused on those
956
1012
  * grounds rather than as a re-drive.
957
1013
  *
958
1014
  * Signature caveat: overloaded and generic in OUTPUT on the base, so this
@@ -979,34 +1035,84 @@ export class FlowsafeDurableAgent extends DurableAgent {
979
1035
  * Signature caveat: the base method is generic in OUTPUT, which
980
1036
  * `Parameters<>` instantiates to its `undefined` default and so types too
981
1037
  * narrowly to satisfy the base. The options parameter is widened to
982
- * `unknown` — the one supertype that fits every instantiation. Re-check on
983
- * every peer bump.
1038
+ * `unknown` so it fits each instantiation. Re-check on a peer bump.
984
1039
  */
985
1040
  async sendToolApproval(_options) {
986
1041
  throw unavailableRunEntry('sendToolApproval', BLOCKED_RUN_ENTRIES.sendToolApproval);
987
1042
  }
988
1043
  /**
989
- * Refuse the thread-runtime target swap newer cores add. It sets one private
990
- * field that the thread-runtime paths resolve their target through, falling
991
- * back to `this`; the refusal in `BLOCKED_RUN_ENTRIES` names those paths,
992
- * for the core it is written against. So the containment those inherited
993
- * members rely on is virtual dispatch on `this`, and one call to this setter
994
- * moves every run they start, and their replay targets with them, onto an
995
- * agent with none of these overrides in the chain. That is the fourth ground
996
- * reached by installing a second execution surface rather than by calling
997
- * one.
1044
+ * Refuse the thread-runtime target swap. It sets one private field that the
1045
+ * thread-runtime paths resolve their target through, falling back to `this`;
1046
+ * the refusal in `BLOCKED_RUN_ENTRIES` names those paths, for the core it is
1047
+ * written against. So the containment those inherited members rely on is
1048
+ * virtual dispatch on `this`, and one call to this setter moves every run they
1049
+ * start, and their replay targets with them, onto an agent with none of these
1050
+ * overrides in the chain. That is the fourth ground reached by installing a
1051
+ * second execution surface rather than by calling one.
998
1052
  *
999
1053
  * Signature caveat: the parameter is `unknown` rather than core's
1000
- * `Agent<any, any, any, any>` because the pinned 1.53.0 declares no such
1001
- * member at all, while newest 1.x does — `unknown` is the one supertype of
1002
- * core's parameter, so it satisfies that base without depending on method
1003
- * bivariance, and it constrains nothing on the pin, where there is no base
1004
- * member to satisfy. No `override` keyword, for the same reason as
1005
- * {@link FlowsafeDurableAgent.listActiveThreadRuns}.
1054
+ * `Agent<any, any, any, any>`. `unknown` satisfies that base without
1055
+ * depending on method bivariance.
1006
1056
  */
1007
1057
  __setThreadRuntimeAgent(_agent) {
1008
1058
  throw unavailableRunEntry('__setThreadRuntimeAgent', BLOCKED_RUN_ENTRIES.__setThreadRuntimeAgent);
1009
1059
  }
1060
+ /**
1061
+ * Refuse binding channels. The base forwards them to the wrapped agent,
1062
+ * which becomes their dispatch target outside RunnerRuntime: the fourth
1063
+ * ground reached by installation.
1064
+ */
1065
+ setChannels(_agentChannels) {
1066
+ throw unavailableRunEntry('setChannels', BLOCKED_RUN_ENTRIES.setChannels);
1067
+ }
1068
+ /**
1069
+ * Refuse declaring schedules. The base forwards them to the wrapped agent,
1070
+ * which a Mastra schedule worker fires outside RunnerRuntime: the fourth
1071
+ * ground reached by installation.
1072
+ *
1073
+ * Signature caveat: the parameter is `unknown` rather than core's
1074
+ * `DeclaredAgentSchedule[]`, which it satisfies without depending on method
1075
+ * bivariance.
1076
+ */
1077
+ __setDeclaredSchedules(_schedules) {
1078
+ throw unavailableRunEntry('__setDeclaredSchedules', BLOCKED_RUN_ENTRIES.__setDeclaredSchedules);
1079
+ }
1080
+ /**
1081
+ * Refuse memory installation after construction under the fifth ground.
1082
+ *
1083
+ * Signature caveat: `unknown` accepts core's memory parameter without
1084
+ * depending on method bivariance.
1085
+ */
1086
+ __setMemory(_memory) {
1087
+ throw unavailableRunEntry('__setMemory', BLOCKED_RUN_ENTRIES.__setMemory);
1088
+ }
1089
+ /**
1090
+ * Refuse pub/sub installation after construction under the fifth ground.
1091
+ *
1092
+ * Signature caveat: `unknown` accepts core's pub/sub parameter without
1093
+ * depending on method bivariance.
1094
+ */
1095
+ __setPubSub(_pubsub) {
1096
+ throw unavailableRunEntry('__setPubSub', BLOCKED_RUN_ENTRIES.__setPubSub);
1097
+ }
1098
+ /**
1099
+ * Refuse Mastra registration. `Mastra.addAgent` calls this first, so the
1100
+ * refusal throws before the registry write and before the loop workflow is
1101
+ * added to that Mastra.
1102
+ *
1103
+ * Signature caveat: the parameter is `unknown` rather than core's `Mastra`,
1104
+ * which it satisfies without depending on method bivariance.
1105
+ */
1106
+ __setMastra(_mastra) {
1107
+ throw unavailableRunEntry('__setMastra', BLOCKED_RUN_ENTRIES.__setMastra);
1108
+ }
1109
+ /**
1110
+ * The member {@link FlowsafeDurableAgent.__setMastra} forwards to, which
1111
+ * `Agent.listAgents` calls directly on a static sub-agent.
1112
+ */
1113
+ __registerMastra(_mastra) {
1114
+ throw unavailableRunEntry('__registerMastra', BLOCKED_RUN_ENTRIES.__registerMastra);
1115
+ }
1010
1116
  /**
1011
1117
  * Refuse core's terminal snapshot cleanup. Its only call sites are the base
1012
1118
  * `executeWorkflow` (overridden here), the blocked `resume()` and the blocked
@@ -1014,24 +1120,21 @@ export class FlowsafeDurableAgent extends DurableAgent {
1014
1120
  * snapshot rows — which deployment-scoped retention purge owns — from being
1015
1121
  * dropped out from under that owner by a future internal caller.
1016
1122
  *
1017
- * Note what this override buys beyond that call-site audit: the member
1018
- * inventory in durable-agent-surface.test.ts sees a NEW member, never a new
1019
- * core call site on an EXISTING one. So the override is the standing guard —
1123
+ * Note what this override buys beyond that call-site audit: the override is
1124
+ * the standing guard —
1020
1125
  * it converts core's best-effort cleanup into a throw the moment a future
1021
- * release calls it on a path FlowSafe drives. None does at 1.53.0.
1126
+ * release calls it on a path FlowSafe drives. None does at 1.67.0.
1022
1127
  */
1023
1128
  async deleteRunSnapshots(_runId) {
1024
1129
  throw unavailableRunEntry('deleteRunSnapshots', BLOCKED_RUN_ENTRIES.deleteRunSnapshots);
1025
1130
  }
1026
1131
  /**
1027
- * Refuse core's durable resume. Until 1.53.0 this merely read the in-process
1028
- * run registry, which is why it was left inherited-but-unwired; now a registry
1029
- * MISS makes it load the persisted `durable-agentic-loop` snapshot, rehydrate
1030
- * through `prepare()` with the full application processor chain, and re-drive
1031
- * the run with `createRun + run.resume` — below `executeWorkflow`, so the leg
1032
- * carries no minted grant and no snapshot provenance.
1033
- * {@link FlowsafeDurableAgent.resumeViaRuntime} is the only resume path, and
1034
- * it is reached from the approval decision, never from a client.
1132
+ * Refuse core's durable resume. From 1.53.0 a registry MISS makes it load the
1133
+ * persisted `durable-agentic-loop` snapshot, rehydrate through `prepare()`
1134
+ * with the full application processor chain, and re-drive the run with
1135
+ * `createRun + run.resume` — below `executeWorkflow`, so the leg carries no
1136
+ * minted grant and no snapshot provenance. The runner's resume path is
1137
+ * {@link FlowsafeDurableAgent.resumeViaRuntime}.
1035
1138
  */
1036
1139
  async resume(_runId, _resumeData, _options) {
1037
1140
  throw unavailableRunEntry('resume', BLOCKED_RUN_ENTRIES.resume);
@@ -1065,11 +1168,11 @@ export class FlowsafeDurableAgent extends DurableAgent {
1065
1168
  throw unavailableRunEntry('declineToolCall', BLOCKED_RUN_ENTRIES.declineToolCall);
1066
1169
  }
1067
1170
  /**
1068
- * The 1.53.0 generate-shaped tool-approval pair. They funnel into
1069
- * `resumeGenerate()` -> `resume()`, so they are the same entry point wearing a
1171
+ * The 1.53.0 generate-shaped tool-approval entries. They funnel into
1172
+ * `resumeGenerate()` -> `resume()`, so they are the same entry point with a
1070
1173
  * different return type.
1071
1174
  *
1072
- * Signature caveat for both halves: the base method is GENERIC in its OUTPUT
1175
+ * Signature caveat for each: the base method is GENERIC in its OUTPUT
1073
1176
  * type, which `Parameters<>` cannot carry, so the parameter type below is
1074
1177
  * hand-written rather than derived. Re-check it against the base on every
1075
1178
  * peer bump — nothing here fails if core changes the shape.
@@ -1093,7 +1196,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1093
1196
  if (property === 'listInputProcessors') {
1094
1197
  return async (requestContext) => {
1095
1198
  inputProcessors = await target.listInputProcessors(requestContext);
1096
- return inputProcessors.filter((processor) => processor.id === 'breakwater-rbac');
1199
+ return inputProcessors.filter((processor) => processor.id === BREAKWATER_RBAC_PROCESSOR_ID);
1097
1200
  };
1098
1201
  }
1099
1202
  if (property === '__listLLMRequestProcessors') {
@@ -1186,7 +1289,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1186
1289
  ...(options.memory !== undefined
1187
1290
  ? { memory: options.memory }
1188
1291
  : {}),
1189
- }, this.pubsub);
1292
+ }, this.getPubSub());
1190
1293
  },
1191
1294
  });
1192
1295
  if (summary.status === 'failed') {
@@ -1209,11 +1312,9 @@ export class FlowsafeDurableAgent extends DurableAgent {
1209
1312
  }
1210
1313
  }
1211
1314
  /**
1212
- * Publish one terminal ERROR attempt without throwing. The unregistered-run
1213
- * terminal path retries once and throws its refusal only after registry
1214
- * cleanup; resume publishes best-effort and preserves its summary or original
1215
- * error. Both call sites publish before cleanup because `emitError()` closes
1216
- * spans through the live global registry entry.
1315
+ * Publish one terminal ERROR attempt without throwing. Call sites publish
1316
+ * before cleanup because `emitError()` closes spans through the live global
1317
+ * registry entry.
1217
1318
  */
1218
1319
  async #publishTerminalError(runId, error) {
1219
1320
  const terminalError = error instanceof Error ? error : new Error(String(error));
@@ -1230,10 +1331,29 @@ export class FlowsafeDurableAgent extends DurableAgent {
1230
1331
  }
1231
1332
  }
1232
1333
  /**
1233
- * Preserve unowned input before terminal refusal. A bounded best-effort write
1234
- * prevents hung memory from blocking the ERROR that heals thread state.
1334
+ * Preserve unowned input before terminal refusal, by the guarded input
1335
+ * chain's verdict on the call:
1336
+ * - no tripwire: the prepared input;
1337
+ * - a tripwire from Breakwater's RBAC gate on a call whose created signal
1338
+ * `stream()` captured: that signal;
1339
+ * - any other tripwire, an RBAC one on a call with no capture included:
1340
+ * nothing.
1341
+ *
1342
+ * `stream()` captures a created signal only on a start that carries neither
1343
+ * a host ticket nor a request context: a drain after a run
1344
+ * `resumeViaRuntime()` registered, which the gate refuses for its missing
1345
+ * actor without reading content. On a guarded agent such a call has no
1346
+ * actor, so the gate refuses it before any application input processor
1347
+ * runs. Host code that calls `stream()` the same way, with a created signal
1348
+ * or an object carrying the signal brand as input, has that input kept when
1349
+ * the gate refuses it.
1350
+ *
1351
+ * The verdict comes from the tripwire rather than from the prepared list, so
1352
+ * it holds whether or not the guard removes refused input from the list. A
1353
+ * bounded best-effort write prevents hung memory from blocking the ERROR
1354
+ * that heals thread state.
1235
1355
  */
1236
- async #persistUnownedInput(runId, workflowInput) {
1356
+ async #persistUnownedInput(runId, workflowInput, replayedSignal) {
1237
1357
  let timeout;
1238
1358
  try {
1239
1359
  await Promise.race([
@@ -1245,19 +1365,39 @@ export class FlowsafeDurableAgent extends DurableAgent {
1245
1365
  // Explicit read-only memory forbids preserving denied input.
1246
1366
  if (state.memoryConfig?.readOnly === true)
1247
1367
  return;
1368
+ const registryEntry = globalRunRegistry.get(runId);
1369
+ const tripwire = registryEntry?.tripwire;
1248
1370
  const memory = await this.getMemory({
1249
- requestContext: globalRunRegistry.get(runId)?.requestContext,
1371
+ requestContext: registryEntry?.requestContext,
1250
1372
  });
1251
1373
  if (!memory)
1252
1374
  return;
1253
- const list = new MessageList({
1254
- threadId,
1255
- resourceId: state.resourceId,
1256
- }).deserialize(workflowInput.messageListState);
1257
- const inputIds = list.makeMessageSourceChecker().input;
1258
- const messages = list.get.all
1259
- .db()
1260
- .filter((message) => inputIds.has(message.id))
1375
+ let candidates;
1376
+ if (tripwire === undefined) {
1377
+ const list = new MessageList({
1378
+ threadId,
1379
+ resourceId: state.resourceId,
1380
+ }).deserialize(workflowInput.messageListState);
1381
+ const inputIds = list.makeMessageSourceChecker().input;
1382
+ candidates = list.get.all
1383
+ .db()
1384
+ .filter((message) => inputIds.has(message.id));
1385
+ }
1386
+ else if (tripwire.processorId === BREAKWATER_RBAC_PROCESSOR_ID &&
1387
+ replayedSignal !== undefined) {
1388
+ candidates = [
1389
+ signalToMastraDBMessage(replayedSignal, {
1390
+ threadId,
1391
+ resourceId: state.resourceId,
1392
+ }),
1393
+ ];
1394
+ }
1395
+ else {
1396
+ return;
1397
+ }
1398
+ const messages = candidates
1399
+ // Mastra's own persist lane stores no transient signal either.
1400
+ .filter((message) => !isTransientSignalMessage(message))
1261
1401
  // Honor markPersistenceForbidden's route-to-runner metadata contract.
1262
1402
  .filter((message) => !isMastraSignalMessage(message) ||
1263
1403
  mastraDBMessageToSignal(message).metadata?.[FLOWSAFE_PERSISTENCE_FORBIDDEN] !== true);
@@ -1436,10 +1576,13 @@ export class FlowsafeDurableAgent extends DurableAgent {
1436
1576
  }
1437
1577
  // No #startRequesters entry means the host start seam never registered
1438
1578
  // this id, so core minted it below our boundary. Such a run has no
1439
- // ownership record or trusted engine-leg context. Preserve its input
1440
- // when allowed, then close the stream so core can clean up its maps and
1579
+ // ownership record or trusted engine-leg context. Preserve what the
1580
+ // input chain's verdict allows, including a signal stream() captured
1581
+ // for this id, then close the stream so core can clean up its maps and
1441
1582
  // release the lease transferred to this id.
1442
- await this.#persistUnownedInput(runId, workflowInput);
1583
+ const replayedSignal = this.#replayedSignals.get(runId);
1584
+ this.#replayedSignals.delete(runId);
1585
+ await this.#persistUnownedInput(runId, workflowInput, replayedSignal);
1443
1586
  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`);
1444
1587
  let published = false;
1445
1588
  try {
@@ -1448,6 +1591,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1448
1591
  (await this.#publishTerminalError(runId, refusal));
1449
1592
  }
1450
1593
  finally {
1594
+ this.#replayedSignals.delete(runId);
1451
1595
  this.runRegistryInternal.cleanup(runId);
1452
1596
  globalRunRegistry.delete(runId);
1453
1597
  }
@@ -1522,9 +1666,7 @@ export function createFlowsafeDurableAgent(options) {
1522
1666
  const workflow = durableAgent.getWorkflow();
1523
1667
  if (!options.runtime.workflowIds().includes(workflow.id)) {
1524
1668
  // getWorkflow()'s concrete engine generics are not single-cast-assignable to
1525
- // AnyWorkflow, so the double cast through `unknown` is required (init.ts gets
1526
- // away with a single cast because coreCreateWorkflow's return already lines
1527
- // up). The runtime only ever reads id / getWorkflowRunById / createRun off it.
1669
+ // AnyWorkflow, so the double cast through `unknown` is required.
1528
1670
  options.runtime.register(workflow);
1529
1671
  }
1530
1672
  return durableAgent;