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