@proofoftech/flowsafe 0.22.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.
@@ -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,55 +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 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.
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. 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.
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.
214
204
  //
215
205
  // - listActiveThreadRuns() (:38214) is the discovery ground one scope wider
216
206
  // than listActiveRuns. It takes no arguments and returns `{ runId,
217
207
  // resourceId, threadId }` for every thread on the pubsub instance with a run
218
208
  // in flight (storage-MbGlKLkB.js:1011-1023), and that state is keyed by
219
209
  // pubsub instance rather than by agent (`#statesByPubSub`, :150, read through
220
- // #getState :294), so it narrows by neither principal nor agent where the two
210
+ // #getState :294), so it narrows by neither principal nor agent where the
221
211
  // listings above at least narrow by agentId. The in-process sibling
222
212
  // getActiveThreadRunId() stays non-execution because it makes the caller name
223
213
  // 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.
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.
232
222
  // - __setThreadRuntimeAgent() (:33609) installs another agent as the target
233
223
  // the thread-runtime paths resolve through #getThreadRuntimeAgent()
234
224
  // (:33612, `this.#threadRuntimeAgent ?? this`); the refusal in
@@ -237,33 +227,56 @@
237
227
  // the containment those inherited members rely on IS virtual dispatch on
238
228
  // `this`, so one call moves every run those paths start onto an agent
239
229
  // 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.
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.
248
237
  //
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.
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.
254
270
  //
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.
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.
267
280
  //
268
281
  // Live-isolate scope: the loop resolves the tool's execute closure from the
269
282
  // in-process globalRunRegistry (populated by stream()). A DO holds one run in
@@ -272,7 +285,7 @@
272
285
  // application input processors. resumeViaRuntime() rebuilds the registry with
273
286
  // complete runtime processor lists after invoking only reserved RBAC during
274
287
  // empty-message preparation, then drives runtime.resume().
275
- import { isMastraSignalMessage, MessageList, mastraDBMessageToSignal, } from '@mastra/core/agent';
288
+ import { isCreatedAgentSignal, isDurableAgentLike, isMastraSignalMessage, isTransientSignalMessage, MessageList, mastraDBMessageToSignal, signalToMastraDBMessage, } from '@mastra/core/agent';
276
289
  import { DurableAgent, globalRunRegistry, prepareForDurableExecution, } from '@mastra/core/agent/durable';
277
290
  import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
278
291
  import { normalizeMutationEpoch, normalizeStartIdentity, } from '../do-runner/execution-admission.js';
@@ -296,11 +309,11 @@ const UNOWNED_INPUT_PERSIST_TIMEOUT_MS = 5_000;
296
309
  const UNREGISTERED_RUN_REFUSAL_PREFIX = 'Flowsafe durable-agent runner refused unregistered run: ';
297
310
  /**
298
311
  * @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`.
312
+ * persisted. Kept off `./index.js`.
301
313
  */
302
314
  export const FLOWSAFE_PERSISTENCE_FORBIDDEN = 'flowsafe.persistence-forbidden';
303
315
  const BREAKWATER_GUARDED_AGENT_HOST_PROTOCOL = Symbol.for('@proofoftech/breakwater/guarded-agent-host/v1');
316
+ const BREAKWATER_RBAC_PROCESSOR_ID = 'breakwater-rbac';
304
317
  function captureAgentStartAuthority(source, requestedBy, requestedByKind) {
305
318
  if (source === null || typeof source !== 'object' || Array.isArray(source)) {
306
319
  throw new InvalidRunRequestError('agent start authority is required');
@@ -397,7 +410,7 @@ function snapshotDurableCallOptions(options) {
397
410
  }
398
411
  return Object.freeze(snapshot);
399
412
  }
400
- /** @internal Shared with the guarded agent catalog's compatibility check. */
413
+ /** @internal */
401
414
  export function breakwaterGuardedAgentHostProtocol(agent) {
402
415
  if ((typeof agent !== 'object' && typeof agent !== 'function') || !agent) {
403
416
  return undefined;
@@ -415,23 +428,41 @@ export function breakwaterGuardedAgentHostProtocol(agent) {
415
428
  return protocol;
416
429
  }
417
430
  /**
418
- * 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
419
451
  * entry points are one code path (resumeStream/resumeGenerate/the approve and
420
452
  * decline pairs all funnel into resume()), so one sentence must not drift into
421
- * seven.
453
+ * a copy per entry point.
422
454
  */
423
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";
424
456
  /**
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.
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.
429
461
  */
430
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';
431
463
  /**
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.
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.
435
466
  */
436
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)";
437
468
  /**
@@ -441,30 +472,41 @@ const LEGACY_FAMILY_REASON = "the AI SDK v4 legacy handler is a second execution
441
472
  */
442
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';
443
474
  /**
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.
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.
450
492
  *
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:
493
+ * The grounds:
454
494
  * 1. re-drives a persisted run below `executeWorkflow`, where there is no
455
495
  * RunnerRuntime — no run ownership, no per-leg grant, no snapshot
456
496
  * 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;
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;
459
500
  * 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.
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.
465
507
  *
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.
508
+ * NOT re-exported from `./index.js` (a named-exports-only barrel), so this
509
+ * stays off the public `@proofoftech/flowsafe/agent-runner` subpath.
468
510
  */
469
511
  export const BLOCKED_RUN_ENTRIES = {
470
512
  recover: 're-driving a persisted run bypasses run ownership, per-leg grant minting and the fail-closed registry rehydration',
@@ -479,6 +521,7 @@ export const BLOCKED_RUN_ENTRIES = {
479
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",
480
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",
481
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',
482
525
  deleteRunSnapshots: 'durable-agent snapshot rows are retained until deployment-scoped retention purge removes them',
483
526
  network: `${NETWORK_FAMILY_REASON}, and it mints an unowned run id when the caller omits one`,
484
527
  resumeNetwork: NETWORK_FAMILY_REASON,
@@ -488,47 +531,46 @@ export const BLOCKED_RUN_ENTRIES = {
488
531
  streamLegacy: LEGACY_FAMILY_REASON,
489
532
  sendToolApproval: THREAD_TOOL_APPROVAL_REASON,
490
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,
491
542
  };
492
543
  /**
493
- * 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
494
545
  * {@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
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
500
548
  * entries have none to carry, and the others must not echo an id the caller may
501
549
  * not own into its log.
502
550
  */
503
551
  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)`);
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)`);
505
553
  }
506
554
  function bindThreadCompletion(output, completion) {
507
555
  return new Proxy(output, {
508
- 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);
509
559
  if (property === '_waitUntilFinished') {
510
- const wait = Reflect.get(target, property, target);
511
- return () => typeof wait === 'function'
560
+ return () => typeof value === 'function'
512
561
  ? Promise.race([
513
- Promise.resolve(wait.call(target)),
562
+ Promise.resolve(value.call(target)),
514
563
  completion,
515
564
  ])
516
565
  : completion;
517
566
  }
518
- const value = Reflect.get(target, property, receiver);
519
567
  return typeof value === 'function' ? value.bind(target) : value;
520
568
  },
521
569
  });
522
570
  }
523
571
  /**
524
572
  * 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.
573
+ * it before a wake seam may start a run.
532
574
  *
533
575
  * Direct core sender calls that mint a run still reach the durable runner,
534
576
  * which fails them terminally without executing. Structural so a test double
@@ -569,35 +611,45 @@ export class FlowsafeDurableAgent extends DurableAgent {
569
611
  /**
570
612
  * runId -> the reservation key the thread topology took for this start, so
571
613
  * `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.
614
+ * fence's proof-only match.
575
615
  */
576
616
  #startIdempotencyKeys = new Map();
577
617
  #startAuthorities = new Map();
578
618
  #startScheduleDispatches = new Map();
579
619
  // The host's exact options object receives one private, single-use re-entry ticket.
580
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();
581
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
+ }
582
637
  const guardedProtocol = breakwaterGuardedAgentHostProtocol(options.agent);
583
638
  super({
584
639
  agent: options.agent,
585
640
  id: options.id,
586
641
  name: options.name,
587
642
  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,
643
+ pubsub,
595
644
  maxSteps: options.maxSteps,
596
645
  });
597
646
  this.#runtime = options.runtime;
598
647
  this.#wrappedAgent = options.agent;
599
648
  this.#isBreakwaterGuardedAgent = guardedProtocol !== undefined;
600
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);
601
653
  }
602
654
  /**
603
655
  * Host-owned run-ID enforcement at the public boundary. The durable-agent entry points (stream /
@@ -607,12 +659,10 @@ export class FlowsafeDurableAgent extends DurableAgent {
607
659
  * wrapper forbids — and hands it to `executeWorkflow` BELOW this class's own
608
660
  * guard, where a bare UUID is already indistinguishable from a legitimately
609
661
  * 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
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
614
664
  * 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
665
+ * and shared by the call sites below so the rule cannot drift within this
616
666
  * class.
617
667
  */
618
668
  #assertCallerRunId(runId) {
@@ -625,8 +675,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
625
675
  * `#startRequesters` alone is insufficient because `streamUntilPersisted()`
626
676
  * removes it after the first summary while a suspended stream stays live.
627
677
  * 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()`
678
+ * the global registry's TTL expires.
679
+ * It exempts the host's own first start: `streamUntilPersisted()`
630
680
  * stamps its exact options object with a single-use ticket that `stream()`
631
681
  * consumes. A private `WeakSet`, a locally constructed object, and first-use
632
682
  * consumption make that exemption unavailable to callers.
@@ -668,11 +718,21 @@ export class FlowsafeDurableAgent extends DurableAgent {
668
718
  if (!hostStreamTicket)
669
719
  this.#assertRunIdNotLive(callOptions.runId);
670
720
  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);
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;
674
735
  }
675
- return result;
676
736
  }
677
737
  /**
678
738
  * Start a durable stream and wait until RunnerRuntime has persisted the
@@ -691,12 +751,11 @@ export class FlowsafeDurableAgent extends DurableAgent {
691
751
  /**
692
752
  * The idempotency key the thread topology already RESERVED for this run.
693
753
  *
694
- * 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
695
755
  * admits exactly the start whose key matches its nominated proof key, and
696
756
  * `RunnerRuntime.start` is where that comparison happens. It buys no
697
757
  * 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.
758
+ * so nothing here validates it beyond passing it on.
700
759
  *
701
760
  * Parked per-runId beside the attempt token rather than threaded through
702
761
  * core, because core owns the call between `stream()` and
@@ -806,7 +865,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
806
865
  /**
807
866
  * The same host-owned run-ID guard as {@link FlowsafeDurableAgent.stream}.
808
867
  * `prepare()`
809
- * is the third inherited minting entry point: it forwards `options?.runId` into
868
+ * is an inherited minting entry point: it forwards `options?.runId` into
810
869
  * core's `prepareForDurableExecution` (create-durable-agent-DFHwqN2K.js:7882),
811
870
  * which mints an unowned `crypto.randomUUID()` when it is absent
812
871
  * (create-durable-agent-DFHwqN2K.js:1211) AND REGISTERS a run under that id
@@ -814,8 +873,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
814
873
  * `resume(runId)`/`executeWorkflow` sees a bare UUID `PATH_SAFE_ID_PATTERN`
815
874
  * already accepts, past every downstream guard. Enforce the caller-minted ID
816
875
  * 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.
876
+ * cleans up the run.
819
877
  */
820
878
  async prepare(messages, options) {
821
879
  const callOptions = snapshotDurableCallOptions(options);
@@ -839,9 +897,9 @@ export class FlowsafeDurableAgent extends DurableAgent {
839
897
  * Refuse core's bulk recovery. `recoverActiveRuns()` is
840
898
  * {@link FlowsafeDurableAgent.listActiveRuns} plus a `recover()` per row, and
841
899
  * 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
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
845
903
  * refusal is logged there rather than failing boot. Refuse with an explicit
846
904
  * `runId` too: a single target is still a re-drive off RunnerRuntime.
847
905
  */
@@ -869,10 +927,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
869
927
  * — and narrows by `agentId` plus the optional `threadId`/`resourceId`
870
928
  * filters the CALLER supplies, the same scoping `listActiveRuns()` applies.
871
929
  * 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.
930
+ * across every principal that shares the agent.
876
931
  */
877
932
  async listSuspendedRuns(_options) {
878
933
  throw unavailableRunEntry('listSuspendedRuns', BLOCKED_RUN_ENTRIES.listSuspendedRuns);
@@ -888,13 +943,25 @@ export class FlowsafeDurableAgent extends DurableAgent {
888
943
  * makes the caller name the (resourceId, threadId) pair it confirms.
889
944
  *
890
945
  * 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.
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.
894
949
  */
895
950
  listActiveThreadRuns() {
896
951
  throw unavailableRunEntry('listActiveThreadRuns', BLOCKED_RUN_ENTRIES.listActiveThreadRuns);
897
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
+ }
898
965
  /**
899
966
  * Refuse the multi-agent network start. `network()` does not touch the
900
967
  * durable-agentic-loop at all: it compiles a SEPARATE workflow and drives it
@@ -941,7 +1008,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
941
1008
  * omits one, and skips `requireAgentExecutionFGA` — the authorization gate
942
1009
  * every SUPPORTED entry point calls, so this would run the agent without it.
943
1010
  * (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
1011
+ * persists no workflow run state, which is why it is refused on those
945
1012
  * grounds rather than as a re-drive.
946
1013
  *
947
1014
  * Signature caveat: overloaded and generic in OUTPUT on the base, so this
@@ -990,6 +1057,62 @@ export class FlowsafeDurableAgent extends DurableAgent {
990
1057
  __setThreadRuntimeAgent(_agent) {
991
1058
  throw unavailableRunEntry('__setThreadRuntimeAgent', BLOCKED_RUN_ENTRIES.__setThreadRuntimeAgent);
992
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
+ }
993
1116
  /**
994
1117
  * Refuse core's terminal snapshot cleanup. Its only call sites are the base
995
1118
  * `executeWorkflow` (overridden here), the blocked `resume()` and the blocked
@@ -997,9 +1120,8 @@ export class FlowsafeDurableAgent extends DurableAgent {
997
1120
  * snapshot rows — which deployment-scoped retention purge owns — from being
998
1121
  * dropped out from under that owner by a future internal caller.
999
1122
  *
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 —
1123
+ * Note what this override buys beyond that call-site audit: the override is
1124
+ * the standing guard —
1003
1125
  * it converts core's best-effort cleanup into a throw the moment a future
1004
1126
  * release calls it on a path FlowSafe drives. None does at 1.67.0.
1005
1127
  */
@@ -1007,14 +1129,12 @@ export class FlowsafeDurableAgent extends DurableAgent {
1007
1129
  throw unavailableRunEntry('deleteRunSnapshots', BLOCKED_RUN_ENTRIES.deleteRunSnapshots);
1008
1130
  }
1009
1131
  /**
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.
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}.
1018
1138
  */
1019
1139
  async resume(_runId, _resumeData, _options) {
1020
1140
  throw unavailableRunEntry('resume', BLOCKED_RUN_ENTRIES.resume);
@@ -1048,11 +1168,11 @@ export class FlowsafeDurableAgent extends DurableAgent {
1048
1168
  throw unavailableRunEntry('declineToolCall', BLOCKED_RUN_ENTRIES.declineToolCall);
1049
1169
  }
1050
1170
  /**
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
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
1053
1173
  * different return type.
1054
1174
  *
1055
- * 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
1056
1176
  * type, which `Parameters<>` cannot carry, so the parameter type below is
1057
1177
  * hand-written rather than derived. Re-check it against the base on every
1058
1178
  * peer bump — nothing here fails if core changes the shape.
@@ -1076,7 +1196,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1076
1196
  if (property === 'listInputProcessors') {
1077
1197
  return async (requestContext) => {
1078
1198
  inputProcessors = await target.listInputProcessors(requestContext);
1079
- return inputProcessors.filter((processor) => processor.id === 'breakwater-rbac');
1199
+ return inputProcessors.filter((processor) => processor.id === BREAKWATER_RBAC_PROCESSOR_ID);
1080
1200
  };
1081
1201
  }
1082
1202
  if (property === '__listLLMRequestProcessors') {
@@ -1169,7 +1289,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1169
1289
  ...(options.memory !== undefined
1170
1290
  ? { memory: options.memory }
1171
1291
  : {}),
1172
- }, this.pubsub);
1292
+ }, this.getPubSub());
1173
1293
  },
1174
1294
  });
1175
1295
  if (summary.status === 'failed') {
@@ -1192,11 +1312,9 @@ export class FlowsafeDurableAgent extends DurableAgent {
1192
1312
  }
1193
1313
  }
1194
1314
  /**
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.
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.
1200
1318
  */
1201
1319
  async #publishTerminalError(runId, error) {
1202
1320
  const terminalError = error instanceof Error ? error : new Error(String(error));
@@ -1213,10 +1331,29 @@ export class FlowsafeDurableAgent extends DurableAgent {
1213
1331
  }
1214
1332
  }
1215
1333
  /**
1216
- * Preserve unowned input before terminal refusal. A bounded best-effort write
1217
- * 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.
1218
1355
  */
1219
- async #persistUnownedInput(runId, workflowInput) {
1356
+ async #persistUnownedInput(runId, workflowInput, replayedSignal) {
1220
1357
  let timeout;
1221
1358
  try {
1222
1359
  await Promise.race([
@@ -1228,19 +1365,39 @@ export class FlowsafeDurableAgent extends DurableAgent {
1228
1365
  // Explicit read-only memory forbids preserving denied input.
1229
1366
  if (state.memoryConfig?.readOnly === true)
1230
1367
  return;
1368
+ const registryEntry = globalRunRegistry.get(runId);
1369
+ const tripwire = registryEntry?.tripwire;
1231
1370
  const memory = await this.getMemory({
1232
- requestContext: globalRunRegistry.get(runId)?.requestContext,
1371
+ requestContext: registryEntry?.requestContext,
1233
1372
  });
1234
1373
  if (!memory)
1235
1374
  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))
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))
1244
1401
  // Honor markPersistenceForbidden's route-to-runner metadata contract.
1245
1402
  .filter((message) => !isMastraSignalMessage(message) ||
1246
1403
  mastraDBMessageToSignal(message).metadata?.[FLOWSAFE_PERSISTENCE_FORBIDDEN] !== true);
@@ -1419,10 +1576,13 @@ export class FlowsafeDurableAgent extends DurableAgent {
1419
1576
  }
1420
1577
  // No #startRequesters entry means the host start seam never registered
1421
1578
  // 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
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
1424
1582
  // release the lease transferred to this id.
1425
- await this.#persistUnownedInput(runId, workflowInput);
1583
+ const replayedSignal = this.#replayedSignals.get(runId);
1584
+ this.#replayedSignals.delete(runId);
1585
+ await this.#persistUnownedInput(runId, workflowInput, replayedSignal);
1426
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`);
1427
1587
  let published = false;
1428
1588
  try {
@@ -1431,6 +1591,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1431
1591
  (await this.#publishTerminalError(runId, refusal));
1432
1592
  }
1433
1593
  finally {
1594
+ this.#replayedSignals.delete(runId);
1434
1595
  this.runRegistryInternal.cleanup(runId);
1435
1596
  globalRunRegistry.delete(runId);
1436
1597
  }
@@ -1505,9 +1666,7 @@ export function createFlowsafeDurableAgent(options) {
1505
1666
  const workflow = durableAgent.getWorkflow();
1506
1667
  if (!options.runtime.workflowIds().includes(workflow.id)) {
1507
1668
  // 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.
1669
+ // AnyWorkflow, so the double cast through `unknown` is required.
1511
1670
  options.runtime.register(workflow);
1512
1671
  }
1513
1672
  return durableAgent;