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