@proofoftech/flowsafe 0.18.0 → 0.20.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 +114 -0
- package/README.md +79 -5
- package/deployment-identity-protocol.d.mts +62 -1
- package/deployment-identity-protocol.mjs +201 -5
- package/dist/agent-host/catalog.js +1 -1
- package/dist/agent-host/catalog.js.map +1 -1
- package/dist/agent-host/index.d.ts +1 -1
- package/dist/agent-host/index.d.ts.map +1 -1
- package/dist/agent-host/index.js.map +1 -1
- package/dist/agent-host/router.d.ts.map +1 -1
- package/dist/agent-host/router.js +6 -2
- package/dist/agent-host/router.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +11 -0
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +53 -1
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts +35 -1
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +103 -7
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +267 -21
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +706 -76
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +6 -3
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/principal-identity.d.ts +32 -0
- package/dist/approval-api/principal-identity.d.ts.map +1 -0
- package/dist/approval-api/principal-identity.js +69 -0
- package/dist/approval-api/principal-identity.js.map +1 -0
- package/dist/approval-api/principal.d.ts +9 -12
- package/dist/approval-api/principal.d.ts.map +1 -1
- package/dist/approval-api/principal.js +9 -45
- package/dist/approval-api/principal.js.map +1 -1
- package/dist/approval-api/router.d.ts.map +1 -1
- package/dist/approval-api/router.js +9 -1
- package/dist/approval-api/router.js.map +1 -1
- package/dist/approval-api/service.d.ts +19 -0
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +41 -10
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/types.d.ts +12 -0
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js +12 -0
- package/dist/approval-api/types.js.map +1 -1
- package/dist/background-tasks/host.d.ts +127 -14
- package/dist/background-tasks/host.d.ts.map +1 -1
- package/dist/background-tasks/host.js +579 -50
- package/dist/background-tasks/host.js.map +1 -1
- package/dist/background-tasks/index.d.ts +2 -2
- package/dist/background-tasks/index.d.ts.map +1 -1
- package/dist/background-tasks/index.js +11 -6
- package/dist/background-tasks/index.js.map +1 -1
- package/dist/background-tasks/routes.d.ts +19 -2
- package/dist/background-tasks/routes.d.ts.map +1 -1
- package/dist/background-tasks/routes.js +4 -4
- package/dist/background-tasks/routes.js.map +1 -1
- package/dist/deployment-identity-protocol.d.ts +2 -2
- 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/cause-chain.d.ts +53 -0
- package/dist/do-runner/cause-chain.d.ts.map +1 -0
- package/dist/do-runner/cause-chain.js +96 -0
- package/dist/do-runner/cause-chain.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +109 -5
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +289 -44
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/deployment-identity.d.ts +28 -13
- package/dist/do-runner/deployment-identity.d.ts.map +1 -1
- package/dist/do-runner/deployment-identity.js +25 -35
- package/dist/do-runner/deployment-identity.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts +4 -23
- package/dist/do-runner/do-error-response.d.ts.map +1 -1
- package/dist/do-runner/do-error-response.js +19 -24
- package/dist/do-runner/do-error-response.js.map +1 -1
- package/dist/do-runner/do-status-error.d.ts +37 -0
- package/dist/do-runner/do-status-error.d.ts.map +1 -0
- package/dist/do-runner/do-status-error.js +42 -0
- package/dist/do-runner/do-status-error.js.map +1 -0
- package/dist/do-runner/durable-object.d.ts +2 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +205 -19
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-fence.d.ts +335 -0
- package/dist/do-runner/execution-fence.d.ts.map +1 -0
- package/dist/do-runner/execution-fence.js +534 -0
- package/dist/do-runner/execution-fence.js.map +1 -0
- package/dist/do-runner/index.d.ts +10 -3
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +16 -3
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +82 -1
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js +58 -3
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/inventory.d.ts +294 -0
- package/dist/do-runner/inventory.d.ts.map +1 -0
- package/dist/do-runner/inventory.js +811 -0
- package/dist/do-runner/inventory.js.map +1 -0
- package/dist/do-runner/notification-predicate.d.ts +8 -0
- package/dist/do-runner/notification-predicate.d.ts.map +1 -0
- package/dist/do-runner/notification-predicate.js +9 -0
- package/dist/do-runner/notification-predicate.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +83 -0
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +131 -4
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/start-idempotency.d.ts +508 -0
- package/dist/do-runner/start-idempotency.d.ts.map +1 -0
- package/dist/do-runner/start-idempotency.js +886 -0
- package/dist/do-runner/start-idempotency.js.map +1 -0
- package/dist/do-runner/suspension-deadline.d.ts +3 -2
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
- package/dist/do-runner/suspension-deadline.js +3 -2
- package/dist/do-runner/suspension-deadline.js.map +1 -1
- package/dist/goals/objective-routes.d.ts +14 -0
- package/dist/goals/objective-routes.d.ts.map +1 -1
- package/dist/goals/objective-routes.js +45 -24
- package/dist/goals/objective-routes.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +15 -0
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +22 -1
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +11 -0
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +343 -62
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +20 -0
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +6 -0
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/index.d.ts +2 -2
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +1 -1
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/run-route-error.d.ts +18 -0
- package/dist/host-kit/run-route-error.d.ts.map +1 -1
- package/dist/host-kit/run-route-error.js +23 -0
- package/dist/host-kit/run-route-error.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +58 -1
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +120 -11
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/stream-router.d.ts.map +1 -1
- package/dist/host-kit/stream-router.js +18 -9
- package/dist/host-kit/stream-router.js.map +1 -1
- package/dist/schedules/router.d.ts +15 -0
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +47 -17
- package/dist/schedules/router.js.map +1 -1
- package/dist/schedules/tick.d.ts +13 -0
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +59 -39
- package/dist/schedules/tick.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 +23 -1
- package/dist/signal-providers/host-do.d.ts.map +1 -1
- package/dist/signal-providers/host-do.js +76 -17
- 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 +20 -0
- package/dist/signal-providers/webhook-route.d.ts.map +1 -1
- package/dist/signal-providers/webhook-route.js +137 -26
- 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 +15 -0
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +23 -1
- package/dist/signals/notification-dispatch.js.map +1 -1
- package/dist/signals/notifications-d1.d.ts +8 -0
- package/dist/signals/notifications-d1.d.ts.map +1 -1
- package/dist/signals/notifications-d1.js +15 -9
- package/dist/signals/notifications-d1.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 +710 -136
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +8 -6
- package/scripts/seed-deployment-identity.mjs +22 -4
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
// `scope.principal` are trusted here; the P6 ingestion gate (allowlist / size
|
|
2
|
+
// The signal routes hosted ON the thread DO. A thread's agent loop and every
|
|
3
|
+
// signal both address `idFromName(threadId)`, so the platform serializes them
|
|
4
|
+
// onto ONE isolate. The DO IS the serialization lease Mastra otherwise wants
|
|
5
|
+
// Redis for. These routes run AFTER ThreadDurableObject.fetch verifies the
|
|
6
|
+
// deployment identity and decodes the server-stamped principal. The scope's
|
|
7
|
+
// threadId and principal are trusted here; the ingestion gate (allowlist / size
|
|
9
8
|
// cap / rate cap / audit) is the Worker-side createSignalRouter's job, the same
|
|
10
9
|
// split createRunRouter (Worker gate) → DurableObjectRunner (execution) uses.
|
|
11
10
|
//
|
|
@@ -14,32 +13,55 @@
|
|
|
14
13
|
// module-level `defaultAgentThreadPubSub`), so a send only drains into an active
|
|
15
14
|
// loop when BOTH run in one isolate (the DO gives this) AND both use the SAME
|
|
16
15
|
// pubsub. The agent resolves its pubsub from `agent.getPubSub()`, so these routes
|
|
17
|
-
// stamp the DO's ONE identity (`scope.init.pubsub
|
|
18
|
-
//
|
|
19
|
-
//
|
|
16
|
+
// stamp the DO's ONE identity (`scope.init.pubsub`) onto the agent before every
|
|
17
|
+
// call — the exact reason durable-agent execution threads that identity into
|
|
18
|
+
// createRun. Absent (host opted out) ⇒ core's module default, still one per
|
|
20
19
|
// isolate, so affinity holds either way; a wired pubsub additionally makes
|
|
21
20
|
// observe()/replay align (pubsub.ts).
|
|
22
21
|
//
|
|
23
22
|
// core's `agentThreadStreamRuntime` is NOT on the package exports map, so these
|
|
24
|
-
// routes drive the PUBLIC Agent methods
|
|
23
|
+
// routes drive only the PUBLIC Agent methods, never a deep dist import across
|
|
24
|
+
// the export boundary.
|
|
25
|
+
import { createMessageSignal, createSignal, resolveDeliveryAttributes, signalToXmlMarkup, } from '@mastra/core/agent';
|
|
25
26
|
import { createNotificationSignal, createNotificationSummarySignal, summarizeNotifications, } from '@mastra/core/notifications';
|
|
26
27
|
import { RequestContext } from '@mastra/core/request-context';
|
|
28
|
+
import { FLOWSAFE_PERSISTENCE_FORBIDDEN } from '../agent-runner/durable-agent-runner.js';
|
|
27
29
|
import { isRuntimeDrivenAgent, } from '../agent-runner/index.js';
|
|
28
30
|
import { samePrincipal, } from '../approval-api/index.js';
|
|
29
|
-
import { DoStatusError, isPathSafeId, } from '../do-runner/index.js';
|
|
31
|
+
import { admitsExistingRun, DoStatusError, executionFencedResponse, isExecutionFenceRefusal, isPathSafeId, readExecutionFence, } from '../do-runner/index.js';
|
|
30
32
|
import { internalErrorResponse } from '../internal-error-response.js';
|
|
31
33
|
import { createScheduleAgentDispatchReceipt, } from '../schedules/schedules-d1.js';
|
|
32
34
|
import { deferNotificationAfterFailure, MAX_NOTIFICATION_DISPATCH_IDS, planNotificationDispatch, } from './notification-dispatch.js';
|
|
33
35
|
/**
|
|
34
36
|
* The idle-thread delivery behavior a send may ask for. `wake` starts a run
|
|
35
37
|
* after consulting the run cap; `persist` writes the signal to the durable
|
|
36
|
-
* inbox for the next turn; `discard` drops it. Mirrors core
|
|
38
|
+
* inbox for the next host-started turn; `discard` drops it. Mirrors core
|
|
37
39
|
* `AgentSignalIdleBehavior`, re-declared so the route body validates the wire
|
|
38
40
|
* value rather than trusting an `as`.
|
|
39
41
|
*/
|
|
40
42
|
export const IDLE_BEHAVIORS = ['wake', 'persist', 'discard'];
|
|
41
43
|
/** The active-thread delivery behavior. Mirrors core `AgentSignalActiveBehavior`. */
|
|
42
44
|
export const ACTIVE_BEHAVIORS = ['deliver', 'persist', 'discard'];
|
|
45
|
+
/**
|
|
46
|
+
* Put the persistence prohibition in signal metadata so core preserves it
|
|
47
|
+
* through the database round trip without showing it to the model. Attributes
|
|
48
|
+
* are rendered into model-visible markup by `signalToXmlMarkup`; metadata is
|
|
49
|
+
* not.
|
|
50
|
+
*/
|
|
51
|
+
function markPersistenceForbidden(input) {
|
|
52
|
+
return {
|
|
53
|
+
...input,
|
|
54
|
+
metadata: {
|
|
55
|
+
...input.metadata,
|
|
56
|
+
[FLOWSAFE_PERSISTENCE_FORBIDDEN]: true,
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function activeThreadRunIdOf(agent, threadId, resourceId) {
|
|
61
|
+
return typeof agent.getActiveThreadRunId === 'function'
|
|
62
|
+
? agent.getActiveThreadRunId({ threadId, resourceId })
|
|
63
|
+
: undefined;
|
|
64
|
+
}
|
|
43
65
|
function entryPathForSignalRoute(path) {
|
|
44
66
|
switch (path) {
|
|
45
67
|
case '/signal/message':
|
|
@@ -91,26 +113,84 @@ function isContents(value) {
|
|
|
91
113
|
* (and attribute names) inside `signalToXmlMarkup` — MIRRORED here, not
|
|
92
114
|
* deep-imported: `XML_NAME_PATTERN` / `assertXmlName` are not on core's exports
|
|
93
115
|
* map. Validating the caller-supplied `tagName` at INGEST turns an invalid one
|
|
94
|
-
* into a 400 at the route
|
|
116
|
+
* into a 400 at the route, and an invalid attribute name into a dropped
|
|
117
|
+
* attributes object (`isAttributes`), rather than a
|
|
95
118
|
* throw at render time inside the agent turn. Kept byte-identical to core
|
|
96
119
|
* (chunk `signalToXmlMarkup`: `/^[A-Za-z_][A-Za-z0-9_.-]*$/`); the render test
|
|
97
120
|
* pins core's own neutralization of contents/attribute values so this
|
|
98
121
|
* mirror and that layer are checked together.
|
|
99
122
|
*/
|
|
100
123
|
const XML_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
|
|
101
|
-
/**
|
|
124
|
+
/**
|
|
125
|
+
* Attributes must be a flat record of primitives (core `AgentSignalAttributes`)
|
|
126
|
+
* whose rendered KEYS are XML names. Core's `signalAttributesToXml` drops
|
|
127
|
+
* null/undefined entries and then asserts the name of every remaining key, so
|
|
128
|
+
* an unrenderable key would otherwise throw at render time — inside the agent
|
|
129
|
+
* turn, or here at the content gate — long after the route accepted it. A
|
|
130
|
+
* malformed attributes object is dropped whole, exactly as a malformed
|
|
131
|
+
* attribute VALUE already is.
|
|
132
|
+
*/
|
|
102
133
|
function isAttributes(value) {
|
|
103
134
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
104
135
|
return false;
|
|
105
136
|
}
|
|
106
|
-
return Object.
|
|
137
|
+
return Object.entries(value).every(([key, v]) => v === null ||
|
|
107
138
|
v === undefined ||
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
139
|
+
(XML_NAME_PATTERN.test(key) &&
|
|
140
|
+
(typeof v === 'string' ||
|
|
141
|
+
typeof v === 'number' ||
|
|
142
|
+
typeof v === 'boolean')));
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Whether already-typed attributes can be rendered — the key half of the
|
|
146
|
+
* `isAttributes` rule, for server-owned records that arrive typed and so need
|
|
147
|
+
* no value check. Absent attributes render fine.
|
|
148
|
+
*/
|
|
149
|
+
function renderableAttributes(attributes) {
|
|
150
|
+
if (attributes === undefined)
|
|
151
|
+
return true;
|
|
152
|
+
return Object.entries(attributes).every(([key, value]) => value === null || value === undefined || XML_NAME_PATTERN.test(key));
|
|
153
|
+
}
|
|
154
|
+
async function inspectSignalContent(policy, input, signal, runId) {
|
|
155
|
+
if (typeof signal.contents !== 'string')
|
|
156
|
+
return 'error';
|
|
157
|
+
let text;
|
|
158
|
+
try {
|
|
159
|
+
text = signalToXmlMarkup({
|
|
160
|
+
type: signal.type,
|
|
161
|
+
tagName: signal.tagName,
|
|
162
|
+
attributes: signal.attributes,
|
|
163
|
+
contents: signal.contents,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return 'error';
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const result = await policy({
|
|
171
|
+
...input,
|
|
172
|
+
text,
|
|
173
|
+
...(runId !== undefined ? { runId } : {}),
|
|
174
|
+
});
|
|
175
|
+
if (result?.allowed === true)
|
|
176
|
+
return 'allowed';
|
|
177
|
+
if (result?.allowed === false &&
|
|
178
|
+
(result.outcome === 'denied' || result.outcome === 'error')) {
|
|
179
|
+
return result.outcome;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
return 'error';
|
|
184
|
+
}
|
|
185
|
+
return 'error';
|
|
186
|
+
}
|
|
187
|
+
function signalContentPolicyResponse(inspection) {
|
|
188
|
+
return inspection === 'denied'
|
|
189
|
+
? json({ error: 'signal content denied' }, 422)
|
|
190
|
+
: json({ error: 'signal content policy unavailable' }, 503);
|
|
111
191
|
}
|
|
112
192
|
export function createThreadSignalRoutes(options) {
|
|
113
|
-
const { resolveAgent, resolveResourceId, consultRunCap, startIdleRun, resolveBlockingRun, serializeDispatch, resolveScheduleRunStatus, resolveScheduleTarget, canPersist, canPersistSchedule, resolveNotificationsStorage, resolveScheduleDispatchStore, } = options;
|
|
193
|
+
const { resolveAgent, resolveResourceId, consultRunCap, startIdleRun, resolveBlockingRun, serializeDispatch, resolveScheduleRunStatus, resolveScheduleTarget, canPersist, canPersistSchedule, resolveNotificationsStorage, resolveScheduleDispatchStore, contentPolicy, } = options;
|
|
114
194
|
if (resolveBlockingRun && !serializeDispatch) {
|
|
115
195
|
throw new Error('signal routes require serializeDispatch with resolveBlockingRun');
|
|
116
196
|
}
|
|
@@ -141,6 +221,18 @@ export function createThreadSignalRoutes(options) {
|
|
|
141
221
|
if (!body)
|
|
142
222
|
return json({ error: 'a JSON body is required' }, 400);
|
|
143
223
|
try {
|
|
224
|
+
// The execution fence, read ONCE for this request and before any store
|
|
225
|
+
// lookup. `migration-locked` refuses every signal route outright — the
|
|
226
|
+
// persist lanes included, because their thread-state write is part of
|
|
227
|
+
// what the migration is copying. `proof-only` is decided further down,
|
|
228
|
+
// once the thread's active run is knowable.
|
|
229
|
+
//
|
|
230
|
+
// A read that fails throws ExecutionFenceUnreadableError, which the
|
|
231
|
+
// catch below answers as a 503 — degrade closed, never a silent open.
|
|
232
|
+
const executionFence = await readExecutionFence(scope.init.executionFence);
|
|
233
|
+
if (executionFence.state === 'migration-locked') {
|
|
234
|
+
return executionFencedResponse(executionFence.state, entryPath);
|
|
235
|
+
}
|
|
144
236
|
let scheduleTarget;
|
|
145
237
|
if (path === '/signal/schedule') {
|
|
146
238
|
if (!resolveScheduleTarget) {
|
|
@@ -186,6 +278,35 @@ export function createThreadSignalRoutes(options) {
|
|
|
186
278
|
agent.__setPubSub(pubsub);
|
|
187
279
|
const resourceId = resolveResourceId?.(scope);
|
|
188
280
|
const threadId = scope.threadId;
|
|
281
|
+
// proof-only admits work on ONE run, so the gate lives here — the first
|
|
282
|
+
// point where the run a signal would reach is knowable, and the only one
|
|
283
|
+
// every route passes through. Deciding it inside handleWake would leave
|
|
284
|
+
// the lanes that never reach it (the persist routes, and a default
|
|
285
|
+
// non-wake delivery) ungated; handleWake keeps its own check for the
|
|
286
|
+
// wake path it owns.
|
|
287
|
+
if (executionFence.state === 'proof-only') {
|
|
288
|
+
const activeRunId = activeThreadRunIdOf(agent, threadId, resourceId ?? '');
|
|
289
|
+
if (!admitsExistingRun(executionFence, activeRunId)) {
|
|
290
|
+
return executionFencedResponse(executionFence.state, entryPath);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
let memoryResolution;
|
|
294
|
+
const memoryAvailable = () => {
|
|
295
|
+
memoryResolution ??= (async () => {
|
|
296
|
+
try {
|
|
297
|
+
return (typeof agent.getMemory === 'function' &&
|
|
298
|
+
Boolean(await agent.getMemory()));
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
console.error(JSON.stringify({
|
|
302
|
+
type: 'signal-memory-resolution-failed',
|
|
303
|
+
threadId,
|
|
304
|
+
}));
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
})();
|
|
308
|
+
return memoryResolution;
|
|
309
|
+
};
|
|
189
310
|
const deliveredResourceId = url.searchParams.get('resourceId');
|
|
190
311
|
if (path === '/signal/notification' &&
|
|
191
312
|
deliveredResourceId !== null &&
|
|
@@ -196,18 +317,53 @@ export function createThreadSignalRoutes(options) {
|
|
|
196
317
|
? () => resolveBlockingRun(scope)
|
|
197
318
|
: undefined;
|
|
198
319
|
const persistenceAllowed = canPersist ? await canPersist(scope) : true;
|
|
320
|
+
const inspectContent = contentPolicy
|
|
321
|
+
? (signal, runId) => inspectSignalContent(contentPolicy, {
|
|
322
|
+
agentId: agent.id,
|
|
323
|
+
threadId,
|
|
324
|
+
...(resourceId !== undefined ? { resourceId } : {}),
|
|
325
|
+
...(scope.deploymentTag !== undefined
|
|
326
|
+
? { deploymentTag: scope.deploymentTag }
|
|
327
|
+
: {}),
|
|
328
|
+
entryPath,
|
|
329
|
+
principal: scope.principal,
|
|
330
|
+
}, signal, runId)
|
|
331
|
+
: undefined;
|
|
199
332
|
// POST /signal/message — immediate user message (joins the active loop or,
|
|
200
333
|
// idle, wakes/persists per ifIdle).
|
|
201
334
|
if (path === '/signal/message') {
|
|
202
|
-
return await handleMessage(agent, body, threadId, resourceId, consultRunCap, scope.deploymentTag,
|
|
335
|
+
return await handleMessage(agent, body, threadId, resourceId, consultRunCap, scope.deploymentTag, entryPath, startIdleRun, serializeWake, {
|
|
336
|
+
runtimeDriven,
|
|
337
|
+
principal: scope.principal,
|
|
338
|
+
blockingRun,
|
|
339
|
+
persistenceAllowed,
|
|
340
|
+
memoryAvailable,
|
|
341
|
+
inspectContent,
|
|
342
|
+
executionFence,
|
|
343
|
+
});
|
|
203
344
|
}
|
|
204
|
-
// POST /signal/queue —
|
|
345
|
+
// POST /signal/queue — persisted for the next host-started turn; never
|
|
346
|
+
// wakes, in either state.
|
|
205
347
|
if (path === '/signal/queue') {
|
|
206
|
-
return await handleQueue(agent, body, threadId, resourceId,
|
|
348
|
+
return await handleQueue(agent, body, threadId, resourceId, {
|
|
349
|
+
principal: scope.principal,
|
|
350
|
+
blockingRun,
|
|
351
|
+
persistenceAllowed,
|
|
352
|
+
memoryAvailable,
|
|
353
|
+
inspectContent,
|
|
354
|
+
});
|
|
207
355
|
}
|
|
208
356
|
// POST /signal — a system signal (ifActive/ifIdle deliver/persist/discard/wake).
|
|
209
357
|
if (path === '/signal') {
|
|
210
|
-
return await handleSignal(agent, body, threadId, resourceId, consultRunCap, scope.deploymentTag,
|
|
358
|
+
return await handleSignal(agent, body, threadId, resourceId, consultRunCap, scope.deploymentTag, entryPath, startIdleRun, serializeWake, {
|
|
359
|
+
runtimeDriven,
|
|
360
|
+
principal: scope.principal,
|
|
361
|
+
blockingRun,
|
|
362
|
+
persistenceAllowed,
|
|
363
|
+
memoryAvailable,
|
|
364
|
+
inspectContent,
|
|
365
|
+
executionFence,
|
|
366
|
+
});
|
|
211
367
|
}
|
|
212
368
|
if (path === '/signal/schedule') {
|
|
213
369
|
if (!resolveScheduleDispatchStore) {
|
|
@@ -219,6 +375,7 @@ export function createThreadSignalRoutes(options) {
|
|
|
219
375
|
return await handleScheduleSignal({
|
|
220
376
|
agent,
|
|
221
377
|
body,
|
|
378
|
+
executionFence,
|
|
222
379
|
target: scheduleTarget,
|
|
223
380
|
threadId,
|
|
224
381
|
resourceId,
|
|
@@ -230,6 +387,7 @@ export function createThreadSignalRoutes(options) {
|
|
|
230
387
|
serializeWake,
|
|
231
388
|
blockingRun,
|
|
232
389
|
persistenceAllowed,
|
|
390
|
+
memoryAvailable,
|
|
233
391
|
schedulePersistenceAllowed: canPersistSchedule
|
|
234
392
|
? (input) => canPersistSchedule(scope, input)
|
|
235
393
|
: undefined,
|
|
@@ -238,11 +396,19 @@ export function createThreadSignalRoutes(options) {
|
|
|
238
396
|
: undefined,
|
|
239
397
|
store: await resolveScheduleDispatchStore(scope),
|
|
240
398
|
completed: completedScheduleDispatches,
|
|
399
|
+
inspectContent,
|
|
241
400
|
});
|
|
242
401
|
}
|
|
243
402
|
// POST /signal/state — a durable thread-state lane (snapshot/delta).
|
|
244
403
|
if (path === '/signal/state') {
|
|
245
|
-
return await handleState(agent, body, threadId, resourceId
|
|
404
|
+
return await handleState(agent, body, threadId, resourceId, {
|
|
405
|
+
principal: scope.principal,
|
|
406
|
+
blockingRun,
|
|
407
|
+
persistenceAllowed,
|
|
408
|
+
runtimeDriven,
|
|
409
|
+
memoryAvailable,
|
|
410
|
+
inspectContent,
|
|
411
|
+
});
|
|
246
412
|
}
|
|
247
413
|
if (requestedAgentId !== undefined) {
|
|
248
414
|
if (!resolveNotificationsStorage) {
|
|
@@ -251,6 +417,7 @@ export function createThreadSignalRoutes(options) {
|
|
|
251
417
|
return await serializeNotification(async () => handleNotificationDispatch({
|
|
252
418
|
agent,
|
|
253
419
|
body,
|
|
420
|
+
executionFence,
|
|
254
421
|
threadId,
|
|
255
422
|
resourceId,
|
|
256
423
|
deploymentTag: scope.deploymentTag,
|
|
@@ -262,17 +429,28 @@ export function createThreadSignalRoutes(options) {
|
|
|
262
429
|
serializeWake,
|
|
263
430
|
blockingRun,
|
|
264
431
|
persistenceAllowed,
|
|
432
|
+
memoryAvailable,
|
|
265
433
|
storage: await resolveNotificationsStorage(scope),
|
|
266
434
|
agentId: requestedAgentId,
|
|
435
|
+
inspectContent,
|
|
267
436
|
}));
|
|
268
437
|
}
|
|
269
438
|
// POST /signal/notification — the durable AGENT inbox (mastra_notifications).
|
|
270
439
|
if (path === '/signal/notification') {
|
|
271
|
-
return await serializeNotification(() => handleNotification(agent, body, threadId, resourceId
|
|
440
|
+
return await serializeNotification(async () => handleNotification(agent, body, threadId, resourceId, resolveNotificationsStorage
|
|
441
|
+
? () => resolveNotificationsStorage(scope)
|
|
442
|
+
: undefined, { persistenceAllowed, runtimeDriven, inspectContent }));
|
|
272
443
|
}
|
|
273
444
|
return json({ error: 'not found' }, 404);
|
|
274
445
|
}
|
|
275
446
|
catch (error) {
|
|
447
|
+
// The fence refusing, or failing to answer. Surfaced with its own 503 and
|
|
448
|
+
// reason rather than the 502 below: a caller must be able to tell "this
|
|
449
|
+
// deployment is deliberately not executing" (retry after the migration)
|
|
450
|
+
// from "the model or a route is broken".
|
|
451
|
+
if (isExecutionFenceRefusal(error)) {
|
|
452
|
+
return json({ error: error.message, reason: error.reason }, error.status);
|
|
453
|
+
}
|
|
276
454
|
if (error instanceof DoStatusError &&
|
|
277
455
|
(error.status === 403 || error.status === 404 || error.status === 409)) {
|
|
278
456
|
const message = error.status === 403
|
|
@@ -367,20 +545,44 @@ async function handleNotificationDispatch(options) {
|
|
|
367
545
|
requestedBatchThreadState === 'idle'
|
|
368
546
|
? requestedBatchThreadState
|
|
369
547
|
: durableBlockingRun ||
|
|
370
|
-
(
|
|
371
|
-
options.agent.getActiveThreadRunId({
|
|
372
|
-
threadId: options.threadId,
|
|
373
|
-
resourceId,
|
|
374
|
-
}))
|
|
548
|
+
activeThreadRunIdOf(options.agent, options.threadId, resourceId)
|
|
375
549
|
? 'active'
|
|
376
550
|
: 'idle';
|
|
377
551
|
let delivered = 0;
|
|
378
552
|
let failed = 0;
|
|
553
|
+
let discarded = 0;
|
|
554
|
+
// Records whose terminal discard is already durable. A later throw in the
|
|
555
|
+
// same group funnels the group into `updateFailure`; without this, an
|
|
556
|
+
// already-discarded record would be counted twice and have its
|
|
557
|
+
// content-policy reason overwritten by an unrelated storage error.
|
|
558
|
+
const settledDiscards = new Set();
|
|
379
559
|
const updateFailure = async (record, error) => {
|
|
560
|
+
if (settledDiscards.has(record.id))
|
|
561
|
+
return;
|
|
380
562
|
failed += 1;
|
|
381
563
|
await deferNotificationAfterFailure(options.storage, record, now, error);
|
|
382
564
|
};
|
|
565
|
+
const discardAfterDenial = async (record) => {
|
|
566
|
+
await options.storage.updateNotification({
|
|
567
|
+
id: record.id,
|
|
568
|
+
threadId: record.threadId,
|
|
569
|
+
status: 'discarded',
|
|
570
|
+
deliveryReason: 'content-policy-denied',
|
|
571
|
+
lastDeliveryAttemptAt: now,
|
|
572
|
+
});
|
|
573
|
+
settledDiscards.add(record.id);
|
|
574
|
+
discarded += 1;
|
|
575
|
+
};
|
|
576
|
+
const inspect = async (signal) => {
|
|
577
|
+
if (!options.inspectContent)
|
|
578
|
+
return 'allowed';
|
|
579
|
+
return options.inspectContent(signal, durableBlockingRun?.runId ??
|
|
580
|
+
activeThreadRunIdOf(options.agent, options.threadId, resourceId));
|
|
581
|
+
};
|
|
383
582
|
const send = async (signal) => {
|
|
583
|
+
const deliverableSignal = options.persistenceAllowed
|
|
584
|
+
? signal
|
|
585
|
+
: markPersistenceForbidden(signal);
|
|
384
586
|
const response = await handleWake({
|
|
385
587
|
agent: options.agent,
|
|
386
588
|
deploymentTag: options.deploymentTag,
|
|
@@ -392,18 +594,25 @@ async function handleNotificationDispatch(options) {
|
|
|
392
594
|
consultRunCap: options.consultRunCap,
|
|
393
595
|
startIdleRun: options.startIdleRun,
|
|
394
596
|
serializeWake: options.serializeWake,
|
|
597
|
+
executionFence: options.executionFence,
|
|
395
598
|
blockingRun: durableBlockingRun
|
|
396
599
|
? () => durableBlockingRun
|
|
397
600
|
: options.blockingRun,
|
|
398
601
|
persistenceAllowed: options.persistenceAllowed,
|
|
399
|
-
|
|
400
|
-
|
|
602
|
+
memoryAvailable: options.memoryAvailable,
|
|
603
|
+
signal: deliverableSignal,
|
|
604
|
+
deliverActive: (runId, memoryAvailable) => options.agent.sendSignal(deliverableSignal, {
|
|
401
605
|
runId,
|
|
402
606
|
threadId: options.threadId,
|
|
403
607
|
resourceId,
|
|
404
608
|
ifActive: { behavior: 'deliver' },
|
|
609
|
+
ifIdle: {
|
|
610
|
+
behavior: memoryAvailable && options.persistenceAllowed
|
|
611
|
+
? 'persist'
|
|
612
|
+
: 'discard',
|
|
613
|
+
},
|
|
405
614
|
}),
|
|
406
|
-
persist: () => options.agent.sendSignal(
|
|
615
|
+
persist: () => options.agent.sendSignal(deliverableSignal, {
|
|
407
616
|
threadId: options.threadId,
|
|
408
617
|
resourceId,
|
|
409
618
|
ifIdle: { behavior: 'persist' },
|
|
@@ -413,6 +622,8 @@ async function handleNotificationDispatch(options) {
|
|
|
413
622
|
throw new Error(`notification signal returned ${response.status}`);
|
|
414
623
|
const result = (await response.json());
|
|
415
624
|
const action = recordValue(result.decision)?.action;
|
|
625
|
+
// A stale active id can fall through to idle. Persistence-forbidden and
|
|
626
|
+
// memory-unavailable discards are failed delivery, never a fresh wake.
|
|
416
627
|
if (action !== 'wake' &&
|
|
417
628
|
action !== 'deliver' &&
|
|
418
629
|
!(action === 'persist' && options.persistenceAllowed)) {
|
|
@@ -426,6 +637,9 @@ async function handleNotificationDispatch(options) {
|
|
|
426
637
|
if (!options.persistenceAllowed) {
|
|
427
638
|
throw new Error('signal persistence is forbidden for this principal');
|
|
428
639
|
}
|
|
640
|
+
if (!(await options.memoryAvailable())) {
|
|
641
|
+
throw new Error('signal persistence requires agent memory');
|
|
642
|
+
}
|
|
429
643
|
const result = options.agent.sendSignal(signal, {
|
|
430
644
|
threadId: options.threadId,
|
|
431
645
|
resourceId,
|
|
@@ -439,8 +653,24 @@ async function handleNotificationDispatch(options) {
|
|
|
439
653
|
};
|
|
440
654
|
for (const item of planNotificationDispatch(records, now)) {
|
|
441
655
|
if (item.type === 'summary') {
|
|
656
|
+
// Everything from rendering onward stays inside this try: a storage
|
|
657
|
+
// failure in the discard/failure bookkeeping below must be contained to
|
|
658
|
+
// this group, exactly as the individual branch contains its own, rather
|
|
659
|
+
// than escaping and abandoning the rest of the plan.
|
|
442
660
|
try {
|
|
443
661
|
const signal = createNotificationSummarySignal(summarizeNotifications(item.records));
|
|
662
|
+
const inspection = await inspect(signal);
|
|
663
|
+
if (inspection === 'denied') {
|
|
664
|
+
for (const record of item.records)
|
|
665
|
+
await discardAfterDenial(record);
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
if (inspection === 'error') {
|
|
669
|
+
for (const record of item.records) {
|
|
670
|
+
await updateFailure(record, new Error('signal content policy failed'));
|
|
671
|
+
}
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
444
674
|
const lowPriority = item.records.every((record) => record.priority === 'low');
|
|
445
675
|
const signalId = lowPriority && options.persistenceAllowed
|
|
446
676
|
? await persistWithoutWake(signal)
|
|
@@ -485,11 +715,21 @@ async function handleNotificationDispatch(options) {
|
|
|
485
715
|
skipped += 1;
|
|
486
716
|
continue;
|
|
487
717
|
}
|
|
488
|
-
const
|
|
718
|
+
const signal = createNotificationSignal({
|
|
489
719
|
...record,
|
|
490
720
|
status: 'delivered',
|
|
491
721
|
deliveredAt: now,
|
|
492
|
-
})
|
|
722
|
+
});
|
|
723
|
+
const inspection = await inspect(signal);
|
|
724
|
+
if (inspection === 'denied') {
|
|
725
|
+
await discardAfterDenial(record);
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
if (inspection === 'error') {
|
|
729
|
+
await updateFailure(record, new Error('signal content policy failed'));
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
const signalId = await send(signal);
|
|
493
733
|
await options.storage.updateNotification({
|
|
494
734
|
id: record.id,
|
|
495
735
|
threadId: record.threadId,
|
|
@@ -506,14 +746,17 @@ async function handleNotificationDispatch(options) {
|
|
|
506
746
|
return json({
|
|
507
747
|
delivered,
|
|
508
748
|
failed,
|
|
749
|
+
...(discarded > 0 ? { discarded } : {}),
|
|
509
750
|
...(skipped > 0 ? { skipped } : {}),
|
|
510
751
|
...(carriesBatchThreadState ? { batchThreadState } : {}),
|
|
511
752
|
});
|
|
512
753
|
}
|
|
513
754
|
/**
|
|
514
755
|
* Resolve the idle behavior a body asked for. A `wake` STARTS a run, so it is
|
|
515
|
-
* gated twice
|
|
516
|
-
*
|
|
756
|
+
* gated twice. A refused or capped wake degrades to a durable persist when the
|
|
757
|
+
* principal may persist and the agent has memory; otherwise the route answers
|
|
758
|
+
* `persistence-forbidden` or `memory-unavailable` instead of silently dropping
|
|
759
|
+
* the signal:
|
|
517
760
|
* - the agent must be RUNTIME-DRIVEN (its stream re-enters RunnerRuntime, not
|
|
518
761
|
* the default engine) — else `wakeRefused:'not-runtime-driven'`;
|
|
519
762
|
* - the deployment run cap must allow it — otherwise `capped:true`.
|
|
@@ -535,19 +778,62 @@ function principalMismatchResponse(runId) {
|
|
|
535
778
|
capped: false,
|
|
536
779
|
});
|
|
537
780
|
}
|
|
781
|
+
/**
|
|
782
|
+
* Report a lazily computed missing-memory gate after content inspection, only
|
|
783
|
+
* where a memory write would otherwise disappear. Wake-start and notification
|
|
784
|
+
* inbox recording never use this response. On an active thread it is returned
|
|
785
|
+
* for a persist outcome that would otherwise be silently dropped — an explicit
|
|
786
|
+
* `ifActive: 'persist'`, or the stale-active-id idle fall-through — and by
|
|
787
|
+
* `/state`, whose pre-send gate replaces core's hard memory requirement rather
|
|
788
|
+
* than covering a dropped write. A default or `ifIdle: 'persist'` request to
|
|
789
|
+
* `/signal/message` or `/signal` still delivers into an active run without
|
|
790
|
+
* memory; the memory gate responds only when core's outcome for the request
|
|
791
|
+
* replaced a persist (an idle discard substituted for a requested persist, or
|
|
792
|
+
* an active persist that no memory could write).
|
|
793
|
+
*/
|
|
794
|
+
function memoryUnavailableResponse() {
|
|
795
|
+
return json({
|
|
796
|
+
decision: { action: 'discard', reason: 'memory-unavailable' },
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Report route-specific persistence authorization failures.
|
|
801
|
+
* `/queue` and `/state` refuse every non-owner request before sending.
|
|
802
|
+
* `/signal/message` and `/signal` refuse a default or requested `ifIdle: 'persist'`;
|
|
803
|
+
* `/signal` also degrades a requested `ifActive: 'persist'`.
|
|
804
|
+
* `/notification` never refuses because a non-owner is record-only for the
|
|
805
|
+
* dispatcher.
|
|
806
|
+
* Wake handling for `/signal/message`, `/signal`, `/signal/schedule`, and the
|
|
807
|
+
* notification dispatch lane returns this response from `handleWake` when a
|
|
808
|
+
* refused or capped wake, or a stale-active-id fall-through, would otherwise
|
|
809
|
+
* persist for a non-owner.
|
|
810
|
+
*/
|
|
811
|
+
function persistenceForbiddenResponse(options) {
|
|
812
|
+
return json({
|
|
813
|
+
decision: { action: 'discard', reason: 'persistence-forbidden' },
|
|
814
|
+
...(options?.capped !== undefined ? { capped: options.capped } : {}),
|
|
815
|
+
...(options?.wakeRefused !== undefined
|
|
816
|
+
? { wakeRefused: options.wakeRefused }
|
|
817
|
+
: {}),
|
|
818
|
+
...(options?.signalId !== undefined ? { signalId: options.signalId } : {}),
|
|
819
|
+
});
|
|
820
|
+
}
|
|
538
821
|
async function handleWake(options) {
|
|
539
822
|
return options.serializeWake(async () => {
|
|
823
|
+
const fence = options.executionFence;
|
|
540
824
|
const durableBlockingRun = await options.blockingRun?.();
|
|
541
|
-
const activeRunId =
|
|
542
|
-
? options.agent.getActiveThreadRunId({
|
|
543
|
-
threadId: options.threadId,
|
|
544
|
-
resourceId: options.resourceId,
|
|
545
|
-
})
|
|
546
|
-
: undefined;
|
|
825
|
+
const activeRunId = activeThreadRunIdOf(options.agent, options.threadId, options.resourceId);
|
|
547
826
|
if (durableBlockingRun &&
|
|
548
827
|
!samePrincipal(durableBlockingRun.principal, options.principal)) {
|
|
549
828
|
return principalMismatchResponse(durableBlockingRun.runId);
|
|
550
829
|
}
|
|
830
|
+
// Delivery into a run that ALREADY exists survives a drain — the run is
|
|
831
|
+
// what the drain is waiting for — and in proof-only it is admitted only
|
|
832
|
+
// for the nominated run. The check sits after the principal gate so a
|
|
833
|
+
// fenced deployment leaks nothing a permitted caller could not see.
|
|
834
|
+
if (activeRunId && !admitsExistingRun(fence, activeRunId)) {
|
|
835
|
+
return executionFencedResponse(fence.state, 'signal delivery');
|
|
836
|
+
}
|
|
551
837
|
if (activeRunId) {
|
|
552
838
|
if (durableBlockingRun && durableBlockingRun.runId !== activeRunId) {
|
|
553
839
|
return json({
|
|
@@ -559,9 +845,22 @@ async function handleWake(options) {
|
|
|
559
845
|
capped: false,
|
|
560
846
|
});
|
|
561
847
|
}
|
|
562
|
-
const
|
|
848
|
+
const memoryAvailable = await options.memoryAvailable();
|
|
849
|
+
const delivered = options.deliverActive(activeRunId, memoryAvailable);
|
|
850
|
+
const decision = await delivered.accepted;
|
|
851
|
+
if (delivered.persisted)
|
|
852
|
+
await delivered.persisted;
|
|
853
|
+
const action = recordValue(decision)?.action;
|
|
854
|
+
if (action === 'discard' && !options.activeDiscardAllowed) {
|
|
855
|
+
return options.persistenceAllowed
|
|
856
|
+
? memoryUnavailableResponse()
|
|
857
|
+
: persistenceForbiddenResponse({ capped: false });
|
|
858
|
+
}
|
|
859
|
+
if (action === 'persist' && !memoryAvailable) {
|
|
860
|
+
return memoryUnavailableResponse();
|
|
861
|
+
}
|
|
563
862
|
return json({
|
|
564
|
-
decision
|
|
863
|
+
decision,
|
|
565
864
|
capped: false,
|
|
566
865
|
signalId: delivered.signal.id,
|
|
567
866
|
});
|
|
@@ -579,22 +878,39 @@ async function handleWake(options) {
|
|
|
579
878
|
: {}),
|
|
580
879
|
});
|
|
581
880
|
}
|
|
881
|
+
// An idle thread has no run to deliver into, so from here on the only way
|
|
882
|
+
// to serve the signal is to MINT one. `migration-locked` and `proof-only`
|
|
883
|
+
// forbid that outright and have no lossless alternative to offer (the
|
|
884
|
+
// proof run is a specific run, not this thread's next one), so they refuse
|
|
885
|
+
// and the caller retries after the migration. `draining` degrades to the
|
|
886
|
+
// persist branch below instead — see WakeRefusal.
|
|
887
|
+
if (fence.state === 'migration-locked' || fence.state === 'proof-only') {
|
|
888
|
+
return executionFencedResponse(fence.state, 'signal wake');
|
|
889
|
+
}
|
|
582
890
|
const startIdleRun = options.startIdleRun;
|
|
583
|
-
const refusal =
|
|
584
|
-
? '
|
|
585
|
-
: !
|
|
586
|
-
? '
|
|
587
|
-
:
|
|
891
|
+
const refusal = fence.state === 'draining'
|
|
892
|
+
? 'execution-draining'
|
|
893
|
+
: !options.runtimeDriven
|
|
894
|
+
? 'not-runtime-driven'
|
|
895
|
+
: !startIdleRun
|
|
896
|
+
? 'no-start-idle-run'
|
|
897
|
+
: undefined;
|
|
588
898
|
const capped = options.runtimeDriven && options.consultRunCap
|
|
589
899
|
? !(await options.consultRunCap())
|
|
590
900
|
: false;
|
|
591
901
|
if (refusal || capped) {
|
|
902
|
+
// The one place a drain can lose a signal, and it is the CALLER'S choice,
|
|
903
|
+
// not the fence's. `execution-draining` degrades a wake into a persist so
|
|
904
|
+
// nothing is lost while a deployment finishes its work — but a caller who
|
|
905
|
+
// said persistence is forbidden has already declared it does not want its
|
|
906
|
+
// signal parked, and honouring the fence by parking it anyway would
|
|
907
|
+
// override an authorization decision with an operational one. So it is
|
|
908
|
+
// discarded, deliberately, and the response SAYS SO: `wakeRefused:
|
|
909
|
+
// 'execution-draining'` alongside `action: 'discard'` tells the caller
|
|
910
|
+
// exactly which condition dropped it, so a sender that would rather wait
|
|
911
|
+
// out the migration can retry instead of assuming delivery.
|
|
592
912
|
if (!options.persistenceAllowed) {
|
|
593
|
-
return
|
|
594
|
-
decision: {
|
|
595
|
-
action: 'discard',
|
|
596
|
-
reason: 'persistence-forbidden',
|
|
597
|
-
},
|
|
913
|
+
return persistenceForbiddenResponse({
|
|
598
914
|
capped,
|
|
599
915
|
...(refusal ? { wakeRefused: refusal } : {}),
|
|
600
916
|
...(options.signal?.id !== undefined
|
|
@@ -602,6 +918,8 @@ async function handleWake(options) {
|
|
|
602
918
|
: {}),
|
|
603
919
|
});
|
|
604
920
|
}
|
|
921
|
+
if (!(await options.memoryAvailable()))
|
|
922
|
+
return memoryUnavailableResponse();
|
|
605
923
|
const persisted = options.persist();
|
|
606
924
|
const decision = await persisted.accepted;
|
|
607
925
|
if (persisted.persisted)
|
|
@@ -700,9 +1018,19 @@ async function handleScheduleSignal(options) {
|
|
|
700
1018
|
return json({ error: 'invalid schedule signal dispatch' }, 400);
|
|
701
1019
|
}
|
|
702
1020
|
const resourceId = options.resourceId;
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
1021
|
+
// Every terminal "this fire will not be delivered" outcome settles the same
|
|
1022
|
+
// canonical receipt, so a replay of the dispatch returns it instead of
|
|
1023
|
+
// re-deciding. Settling is what lets the schedule advance; leaving the lease
|
|
1024
|
+
// unsettled is reserved for outcomes a later tick could still resolve.
|
|
1025
|
+
const settleDiscard = async () => {
|
|
1026
|
+
const receipt = createScheduleAgentDispatchReceipt('discard', {
|
|
1027
|
+
signalId: dispatchId,
|
|
1028
|
+
});
|
|
1029
|
+
options.completed.set(dispatchId, receipt);
|
|
1030
|
+
await options.store.settle(scheduleId, dispatchId, receipt);
|
|
1031
|
+
options.completed.delete(dispatchId);
|
|
1032
|
+
return json({ receipt });
|
|
1033
|
+
};
|
|
706
1034
|
const completed = options.completed.get(dispatchId);
|
|
707
1035
|
if (completed) {
|
|
708
1036
|
await options.store.settle(scheduleId, dispatchId, completed);
|
|
@@ -750,12 +1078,33 @@ async function handleScheduleSignal(options) {
|
|
|
750
1078
|
options.completed.delete(dispatchId);
|
|
751
1079
|
return json({ receipt });
|
|
752
1080
|
}
|
|
1081
|
+
// A stored target that cannot be rendered as XML can never be delivered: core
|
|
1082
|
+
// asserts the tag name and every surviving attribute name inside
|
|
1083
|
+
// signalToXmlMarkup, and a schedule's attributes never pass through
|
|
1084
|
+
// `isAttributes` (core types them as a bare string record). Returning an error
|
|
1085
|
+
// would leave the lease unsettled and hand the same permanently broken target
|
|
1086
|
+
// to every later tick, so settle it terminally and let the schedule advance.
|
|
1087
|
+
const effectiveTagName = target.tagName ?? 'schedule';
|
|
1088
|
+
if (!XML_NAME_PATTERN.test(effectiveTagName) ||
|
|
1089
|
+
!renderableAttributes(target.attributes) ||
|
|
1090
|
+
!renderableAttributes(target.ifActive?.attributes) ||
|
|
1091
|
+
!renderableAttributes(target.ifIdle?.attributes)) {
|
|
1092
|
+
// The operator has to be able to find the broken schedule; the offending
|
|
1093
|
+
// name itself stays out of the log.
|
|
1094
|
+
console.error(JSON.stringify({
|
|
1095
|
+
type: 'schedule-target-unrenderable',
|
|
1096
|
+
scheduleId,
|
|
1097
|
+
dispatchId,
|
|
1098
|
+
agentId: target.agentId,
|
|
1099
|
+
}));
|
|
1100
|
+
return await settleDiscard();
|
|
1101
|
+
}
|
|
753
1102
|
const baseProviderOptions = target.providerOptions ?? {};
|
|
754
1103
|
const baseMastra = recordValue(baseProviderOptions.mastra) ?? {};
|
|
755
1104
|
const signal = {
|
|
756
1105
|
id: dispatchId,
|
|
757
1106
|
type: target.signalType ?? 'notification',
|
|
758
|
-
tagName:
|
|
1107
|
+
tagName: effectiveTagName,
|
|
759
1108
|
contents: target.prompt,
|
|
760
1109
|
...(target.attributes !== undefined
|
|
761
1110
|
? { attributes: target.attributes }
|
|
@@ -773,12 +1122,7 @@ async function handleScheduleSignal(options) {
|
|
|
773
1122
|
};
|
|
774
1123
|
const ifActive = target.ifActive ?? { behavior: 'deliver' };
|
|
775
1124
|
const ifIdle = target.ifIdle ?? { behavior: 'wake' };
|
|
776
|
-
const localActiveRunId =
|
|
777
|
-
? options.agent.getActiveThreadRunId({
|
|
778
|
-
threadId: options.threadId,
|
|
779
|
-
resourceId,
|
|
780
|
-
})
|
|
781
|
-
: undefined;
|
|
1125
|
+
const localActiveRunId = activeThreadRunIdOf(options.agent, options.threadId, resourceId);
|
|
782
1126
|
const persistenceRequested = localActiveRunId
|
|
783
1127
|
? (ifActive.behavior ?? 'deliver') === 'persist'
|
|
784
1128
|
: (ifIdle.behavior ?? 'wake') === 'persist';
|
|
@@ -793,15 +1137,39 @@ async function handleScheduleSignal(options) {
|
|
|
793
1137
|
})
|
|
794
1138
|
: options.persistenceAllowed;
|
|
795
1139
|
if (persistenceRequested && !persistenceAllowed) {
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
1140
|
+
return await settleDiscard();
|
|
1141
|
+
}
|
|
1142
|
+
const deliverableSignal = persistenceAllowed
|
|
1143
|
+
? signal
|
|
1144
|
+
: markPersistenceForbidden(signal);
|
|
1145
|
+
if (options.inspectContent) {
|
|
1146
|
+
// Mastra chooses the active or idle branch after an async boundary, so both
|
|
1147
|
+
// renderings are inspected. `resolveDeliveryAttributes` returns the SAME
|
|
1148
|
+
// object when a branch declares no attributes — the default — so the common
|
|
1149
|
+
// case is one inspection, not two identical ones (a host policy backed by a
|
|
1150
|
+
// classifier would otherwise pay twice per fire and audit twice).
|
|
1151
|
+
const createdSignal = createSignal(deliverableSignal);
|
|
1152
|
+
const activeSignal = resolveDeliveryAttributes(createdSignal, ifActive.attributes);
|
|
1153
|
+
const idleSignal = resolveDeliveryAttributes(createdSignal, ifIdle.attributes);
|
|
1154
|
+
const executingRunId = localActiveRunId ?? durableBlockingRun?.runId;
|
|
1155
|
+
const [activeInspection, idleInspection] = activeSignal === idleSignal
|
|
1156
|
+
? [
|
|
1157
|
+
await options.inspectContent(activeSignal, executingRunId ?? runId),
|
|
1158
|
+
undefined,
|
|
1159
|
+
]
|
|
1160
|
+
: await Promise.all([
|
|
1161
|
+
options.inspectContent(activeSignal, executingRunId),
|
|
1162
|
+
options.inspectContent(idleSignal, runId),
|
|
1163
|
+
]);
|
|
1164
|
+
// Denial wins over an evaluator failure on the other branch: only one branch
|
|
1165
|
+
// ever delivers, but which one is not known here, so refusing terminally is
|
|
1166
|
+
// the fail-closed answer.
|
|
1167
|
+
if (activeInspection === 'denied' || idleInspection === 'denied') {
|
|
1168
|
+
return await settleDiscard();
|
|
1169
|
+
}
|
|
1170
|
+
if (activeInspection === 'error' || idleInspection === 'error') {
|
|
1171
|
+
return signalContentPolicyResponse('error');
|
|
1172
|
+
}
|
|
805
1173
|
}
|
|
806
1174
|
const idleRequestContext = ifIdle.streamOptions?.requestContext ?? streamRequestContext;
|
|
807
1175
|
const signalIfIdle = {
|
|
@@ -830,9 +1198,14 @@ async function handleScheduleSignal(options) {
|
|
|
830
1198
|
let signalId;
|
|
831
1199
|
if ((ifIdle.behavior ?? 'wake') === 'wake') {
|
|
832
1200
|
const idleSignal = {
|
|
833
|
-
...
|
|
1201
|
+
...deliverableSignal,
|
|
834
1202
|
...(ifIdle.attributes !== undefined
|
|
835
|
-
? {
|
|
1203
|
+
? {
|
|
1204
|
+
attributes: {
|
|
1205
|
+
...deliverableSignal.attributes,
|
|
1206
|
+
...ifIdle.attributes,
|
|
1207
|
+
},
|
|
1208
|
+
}
|
|
836
1209
|
: {}),
|
|
837
1210
|
};
|
|
838
1211
|
const response = await handleWake({
|
|
@@ -846,22 +1219,28 @@ async function handleScheduleSignal(options) {
|
|
|
846
1219
|
consultRunCap: options.consultRunCap,
|
|
847
1220
|
startIdleRun: options.startIdleRun,
|
|
848
1221
|
serializeWake: options.serializeWake,
|
|
1222
|
+
executionFence: options.executionFence,
|
|
849
1223
|
blockingRun: durableBlockingRun
|
|
850
1224
|
? () => durableBlockingRun
|
|
851
1225
|
: options.blockingRun,
|
|
852
1226
|
persistenceAllowed,
|
|
1227
|
+
memoryAvailable: options.memoryAvailable,
|
|
853
1228
|
signal: idleSignal,
|
|
854
1229
|
runId,
|
|
855
1230
|
scheduleId,
|
|
856
1231
|
dispatchId,
|
|
857
1232
|
safeContext: { ...requestContext, ...idleRequestContext },
|
|
858
|
-
|
|
1233
|
+
activeDiscardAllowed: ifActive.behavior === 'discard',
|
|
1234
|
+
deliverActive: (activeRunId, memoryAvailable) => options.agent.sendSignal(deliverableSignal, {
|
|
859
1235
|
runId: activeRunId,
|
|
860
1236
|
threadId: options.threadId,
|
|
861
1237
|
resourceId,
|
|
862
1238
|
ifActive,
|
|
1239
|
+
ifIdle: {
|
|
1240
|
+
behavior: memoryAvailable && persistenceAllowed ? 'persist' : 'discard',
|
|
1241
|
+
},
|
|
863
1242
|
}),
|
|
864
|
-
persist: () => options.agent.sendSignal(
|
|
1243
|
+
persist: () => options.agent.sendSignal(deliverableSignal, {
|
|
865
1244
|
threadId: options.threadId,
|
|
866
1245
|
resourceId,
|
|
867
1246
|
ifActive,
|
|
@@ -876,9 +1255,17 @@ async function handleScheduleSignal(options) {
|
|
|
876
1255
|
typeof payload.signalId === 'string' ? payload.signalId : undefined;
|
|
877
1256
|
}
|
|
878
1257
|
else {
|
|
879
|
-
const sent = options.agent.sendSignal(
|
|
1258
|
+
const sent = options.agent.sendSignal(deliverableSignal, signalTarget);
|
|
880
1259
|
decision = await sent.accepted;
|
|
881
|
-
|
|
1260
|
+
const action = recordValue(decision)?.action;
|
|
1261
|
+
if (action === 'persist' && !(await options.memoryAvailable())) {
|
|
1262
|
+
if (sent.persisted)
|
|
1263
|
+
await sent.persisted;
|
|
1264
|
+
// A memory-less host cannot persist this fire; an unsettled lease would
|
|
1265
|
+
// replay it every tick.
|
|
1266
|
+
return await settleDiscard();
|
|
1267
|
+
}
|
|
1268
|
+
if (action === 'persist' && sent.persisted) {
|
|
882
1269
|
await sent.persisted;
|
|
883
1270
|
}
|
|
884
1271
|
signalId = sent.signal.id;
|
|
@@ -892,14 +1279,25 @@ async function handleScheduleSignal(options) {
|
|
|
892
1279
|
options.completed.delete(dispatchId);
|
|
893
1280
|
return json({ receipt });
|
|
894
1281
|
}
|
|
895
|
-
async function
|
|
1282
|
+
async function contentPolicyRefusal(inspectContent, signal, runId) {
|
|
1283
|
+
if (!inspectContent)
|
|
1284
|
+
return undefined;
|
|
1285
|
+
const inspection = await inspectContent(signal, runId);
|
|
1286
|
+
return inspection === 'allowed'
|
|
1287
|
+
? undefined
|
|
1288
|
+
: signalContentPolicyResponse(inspection);
|
|
1289
|
+
}
|
|
1290
|
+
async function handleMessage(agent, body, threadId, resourceId, consultRunCap, deploymentTag, entryPath, startIdleRun, serializeWake, options) {
|
|
896
1291
|
if (!isContents(body.contents)) {
|
|
897
1292
|
return json({ error: 'contents (string) is required' }, 400);
|
|
898
1293
|
}
|
|
899
|
-
const
|
|
1294
|
+
const baseMessage = {
|
|
900
1295
|
contents: body.contents,
|
|
901
1296
|
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
902
1297
|
};
|
|
1298
|
+
const message = options.persistenceAllowed
|
|
1299
|
+
? baseMessage
|
|
1300
|
+
: markPersistenceForbidden(baseMessage);
|
|
903
1301
|
// sendMessage requires a resourceId+threadId target for its idle branch; when a
|
|
904
1302
|
// host has not wired a resourceId, only the active/queue path is reachable.
|
|
905
1303
|
if (resourceId === undefined) {
|
|
@@ -908,31 +1306,45 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
|
|
|
908
1306
|
}, 409);
|
|
909
1307
|
}
|
|
910
1308
|
const behavior = requestedIdle(body);
|
|
911
|
-
const durableBlockingRun = await blockingRun?.();
|
|
1309
|
+
const durableBlockingRun = await options.blockingRun?.();
|
|
912
1310
|
if (durableBlockingRun &&
|
|
913
|
-
!samePrincipal(durableBlockingRun.principal, principal)) {
|
|
1311
|
+
!samePrincipal(durableBlockingRun.principal, options.principal)) {
|
|
914
1312
|
return principalMismatchResponse(durableBlockingRun.runId);
|
|
915
1313
|
}
|
|
1314
|
+
const policyRefusal = await contentPolicyRefusal(options.inspectContent, createMessageSignal(message), durableBlockingRun?.runId);
|
|
1315
|
+
if (policyRefusal)
|
|
1316
|
+
return policyRefusal;
|
|
916
1317
|
if (behavior === 'wake') {
|
|
917
1318
|
return handleWake({
|
|
918
1319
|
agent,
|
|
919
1320
|
deploymentTag,
|
|
920
1321
|
threadId,
|
|
921
1322
|
resourceId,
|
|
922
|
-
principal,
|
|
1323
|
+
principal: options.principal,
|
|
923
1324
|
entryPath,
|
|
924
|
-
runtimeDriven,
|
|
1325
|
+
runtimeDriven: options.runtimeDriven,
|
|
925
1326
|
consultRunCap,
|
|
926
1327
|
startIdleRun,
|
|
927
1328
|
serializeWake,
|
|
928
|
-
|
|
929
|
-
|
|
1329
|
+
executionFence: options.executionFence,
|
|
1330
|
+
blockingRun: durableBlockingRun
|
|
1331
|
+
? () => durableBlockingRun
|
|
1332
|
+
: options.blockingRun,
|
|
1333
|
+
persistenceAllowed: options.persistenceAllowed,
|
|
1334
|
+
memoryAvailable: options.memoryAvailable,
|
|
930
1335
|
message,
|
|
931
|
-
deliverActive: (runId) => agent.sendMessage(message, {
|
|
1336
|
+
deliverActive: (runId, memoryAvailable) => agent.sendMessage(message, {
|
|
932
1337
|
runId,
|
|
933
1338
|
threadId,
|
|
934
1339
|
resourceId,
|
|
935
1340
|
ifActive: { behavior: 'deliver' },
|
|
1341
|
+
// A stale active id can disappear before core sends. Persist only
|
|
1342
|
+
// when both the memory and authorization gates allow the write.
|
|
1343
|
+
ifIdle: {
|
|
1344
|
+
behavior: memoryAvailable && options.persistenceAllowed
|
|
1345
|
+
? 'persist'
|
|
1346
|
+
: 'discard',
|
|
1347
|
+
},
|
|
936
1348
|
}),
|
|
937
1349
|
persist: () => agent.sendMessage(message, {
|
|
938
1350
|
threadId,
|
|
@@ -941,25 +1353,30 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
|
|
|
941
1353
|
}),
|
|
942
1354
|
});
|
|
943
1355
|
}
|
|
944
|
-
if (behavior === 'persist' && !persistenceAllowed) {
|
|
945
|
-
return
|
|
946
|
-
decision: { action: 'discard', reason: 'persistence-forbidden' },
|
|
947
|
-
capped: false,
|
|
948
|
-
});
|
|
1356
|
+
if (behavior === 'persist' && !options.persistenceAllowed) {
|
|
1357
|
+
return persistenceForbiddenResponse({ capped: false });
|
|
949
1358
|
}
|
|
1359
|
+
const memoryAvailable = await options.memoryAvailable();
|
|
950
1360
|
const result = agent.sendMessage(message, {
|
|
951
1361
|
threadId,
|
|
952
1362
|
resourceId,
|
|
953
|
-
ifIdle: { behavior },
|
|
1363
|
+
ifIdle: { behavior: memoryAvailable ? behavior : 'discard' },
|
|
954
1364
|
});
|
|
955
1365
|
const decision = await result.accepted;
|
|
1366
|
+
if (result.persisted)
|
|
1367
|
+
await result.persisted;
|
|
1368
|
+
if (behavior === 'persist' &&
|
|
1369
|
+
!memoryAvailable &&
|
|
1370
|
+
recordValue(decision)?.action === 'discard') {
|
|
1371
|
+
return memoryUnavailableResponse();
|
|
1372
|
+
}
|
|
956
1373
|
return json({
|
|
957
1374
|
decision,
|
|
958
1375
|
capped: false,
|
|
959
1376
|
signalId: result.signal.id,
|
|
960
1377
|
});
|
|
961
1378
|
}
|
|
962
|
-
async function handleQueue(agent, body, threadId, resourceId,
|
|
1379
|
+
async function handleQueue(agent, body, threadId, resourceId, options) {
|
|
963
1380
|
if (!isContents(body.contents)) {
|
|
964
1381
|
return json({ error: 'contents (string) is required' }, 400);
|
|
965
1382
|
}
|
|
@@ -970,25 +1387,35 @@ async function handleQueue(agent, body, threadId, resourceId, principal, blockin
|
|
|
970
1387
|
contents: body.contents,
|
|
971
1388
|
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
972
1389
|
};
|
|
973
|
-
const durableBlockingRun = await blockingRun?.();
|
|
1390
|
+
const durableBlockingRun = await options.blockingRun?.();
|
|
974
1391
|
if (durableBlockingRun &&
|
|
975
|
-
!samePrincipal(durableBlockingRun.principal, principal)) {
|
|
1392
|
+
!samePrincipal(durableBlockingRun.principal, options.principal)) {
|
|
976
1393
|
return principalMismatchResponse(durableBlockingRun.runId);
|
|
977
1394
|
}
|
|
978
|
-
if (!persistenceAllowed) {
|
|
979
|
-
return
|
|
980
|
-
decision: { action: 'discard', reason: 'persistence-forbidden' },
|
|
981
|
-
});
|
|
1395
|
+
if (!options.persistenceAllowed) {
|
|
1396
|
+
return persistenceForbiddenResponse();
|
|
982
1397
|
}
|
|
983
|
-
const
|
|
1398
|
+
const policyRefusal = await contentPolicyRefusal(options.inspectContent, createMessageSignal(message), durableBlockingRun?.runId);
|
|
1399
|
+
if (policyRefusal)
|
|
1400
|
+
return policyRefusal;
|
|
1401
|
+
if (!(await options.memoryAvailable()))
|
|
1402
|
+
return memoryUnavailableResponse();
|
|
1403
|
+
const result = agent.sendMessage(message, {
|
|
1404
|
+
threadId,
|
|
1405
|
+
resourceId,
|
|
1406
|
+
ifActive: { behavior: 'persist' },
|
|
1407
|
+
ifIdle: { behavior: 'persist' },
|
|
1408
|
+
});
|
|
984
1409
|
const decision = await result.accepted;
|
|
1410
|
+
if (result.persisted)
|
|
1411
|
+
await result.persisted;
|
|
985
1412
|
return json({ decision, signalId: result.signal.id });
|
|
986
1413
|
}
|
|
987
|
-
async function handleSignal(agent, body, threadId, resourceId, consultRunCap, deploymentTag,
|
|
1414
|
+
async function handleSignal(agent, body, threadId, resourceId, consultRunCap, deploymentTag, entryPath, startIdleRun, serializeWake, options) {
|
|
988
1415
|
if (!isContents(body.contents)) {
|
|
989
1416
|
return json({ error: 'contents (string) is required' }, 400);
|
|
990
1417
|
}
|
|
991
|
-
// Route-level tagName defense
|
|
1418
|
+
// Route-level tagName defense: reject a non-XML-name tagName HERE with a
|
|
992
1419
|
// 400, rather than letting core's signalToXmlMarkup throw at render time inside
|
|
993
1420
|
// the agent turn. Core still escapes contents/attribute values and re-validates
|
|
994
1421
|
// names; this is the ingest-time half the plan calls "route-level defense".
|
|
@@ -996,21 +1423,31 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
996
1423
|
!XML_NAME_PATTERN.test(body.tagName)) {
|
|
997
1424
|
return json({ error: 'tagName is not a valid XML name' }, 400);
|
|
998
1425
|
}
|
|
999
|
-
const
|
|
1426
|
+
const baseSignal = {
|
|
1000
1427
|
type: 'reactive',
|
|
1001
1428
|
contents: body.contents,
|
|
1002
1429
|
...(typeof body.tagName === 'string' ? { tagName: body.tagName } : {}),
|
|
1003
1430
|
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
1004
1431
|
};
|
|
1432
|
+
const signal = options.persistenceAllowed
|
|
1433
|
+
? baseSignal
|
|
1434
|
+
: markPersistenceForbidden(baseSignal);
|
|
1005
1435
|
const activeBehavior = typeof body.ifActive === 'string' &&
|
|
1006
1436
|
ACTIVE_BEHAVIORS.includes(body.ifActive)
|
|
1007
1437
|
? body.ifActive
|
|
1008
1438
|
: 'deliver';
|
|
1009
|
-
const
|
|
1439
|
+
const activePersistenceForbidden = activeBehavior === 'persist' && !options.persistenceAllowed;
|
|
1440
|
+
const deliveredActiveBehavior = activePersistenceForbidden
|
|
1441
|
+
? 'discard'
|
|
1442
|
+
: activeBehavior;
|
|
1443
|
+
const durableBlockingRun = await options.blockingRun?.();
|
|
1010
1444
|
if (durableBlockingRun &&
|
|
1011
|
-
!samePrincipal(durableBlockingRun.principal, principal)) {
|
|
1445
|
+
!samePrincipal(durableBlockingRun.principal, options.principal)) {
|
|
1012
1446
|
return principalMismatchResponse(durableBlockingRun.runId);
|
|
1013
1447
|
}
|
|
1448
|
+
const policyRefusal = await contentPolicyRefusal(options.inspectContent, createSignal(signal), durableBlockingRun?.runId);
|
|
1449
|
+
if (policyRefusal)
|
|
1450
|
+
return policyRefusal;
|
|
1014
1451
|
if (resourceId === undefined) {
|
|
1015
1452
|
// Active-only target: no idle branch available without a resourceId.
|
|
1016
1453
|
const runId = crypto.randomUUID();
|
|
@@ -1020,7 +1457,7 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1020
1457
|
const result = agent.sendSignal(signal, {
|
|
1021
1458
|
threadId,
|
|
1022
1459
|
runId,
|
|
1023
|
-
ifActive: { behavior:
|
|
1460
|
+
ifActive: { behavior: deliveredActiveBehavior },
|
|
1024
1461
|
});
|
|
1025
1462
|
const decision = await result.accepted;
|
|
1026
1463
|
return json({ decision, signalId: result.signal.id });
|
|
@@ -1032,49 +1469,75 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1032
1469
|
deploymentTag,
|
|
1033
1470
|
threadId,
|
|
1034
1471
|
resourceId,
|
|
1035
|
-
principal,
|
|
1472
|
+
principal: options.principal,
|
|
1036
1473
|
entryPath,
|
|
1037
|
-
runtimeDriven,
|
|
1474
|
+
runtimeDriven: options.runtimeDriven,
|
|
1038
1475
|
consultRunCap,
|
|
1039
1476
|
startIdleRun,
|
|
1040
1477
|
serializeWake,
|
|
1041
|
-
|
|
1042
|
-
|
|
1478
|
+
executionFence: options.executionFence,
|
|
1479
|
+
blockingRun: durableBlockingRun
|
|
1480
|
+
? () => durableBlockingRun
|
|
1481
|
+
: options.blockingRun,
|
|
1482
|
+
persistenceAllowed: options.persistenceAllowed,
|
|
1483
|
+
memoryAvailable: options.memoryAvailable,
|
|
1043
1484
|
signal,
|
|
1044
|
-
|
|
1485
|
+
activeDiscardAllowed: activeBehavior === 'discard',
|
|
1486
|
+
deliverActive: (runId, memoryAvailable) => agent.sendSignal(signal, {
|
|
1045
1487
|
runId,
|
|
1046
1488
|
threadId,
|
|
1047
1489
|
resourceId,
|
|
1048
|
-
ifActive: { behavior:
|
|
1490
|
+
ifActive: { behavior: deliveredActiveBehavior },
|
|
1491
|
+
ifIdle: {
|
|
1492
|
+
behavior: memoryAvailable && options.persistenceAllowed
|
|
1493
|
+
? 'persist'
|
|
1494
|
+
: 'discard',
|
|
1495
|
+
},
|
|
1049
1496
|
}),
|
|
1050
1497
|
persist: () => agent.sendSignal(signal, {
|
|
1051
1498
|
threadId,
|
|
1052
1499
|
resourceId,
|
|
1053
|
-
ifActive: { behavior:
|
|
1500
|
+
ifActive: { behavior: deliveredActiveBehavior },
|
|
1054
1501
|
ifIdle: { behavior: 'persist' },
|
|
1055
1502
|
}),
|
|
1056
1503
|
});
|
|
1057
1504
|
}
|
|
1058
|
-
if (behavior === 'persist' && !persistenceAllowed) {
|
|
1059
|
-
return
|
|
1060
|
-
decision: { action: 'discard', reason: 'persistence-forbidden' },
|
|
1061
|
-
capped: false,
|
|
1062
|
-
});
|
|
1505
|
+
if (behavior === 'persist' && !options.persistenceAllowed) {
|
|
1506
|
+
return persistenceForbiddenResponse({ capped: false });
|
|
1063
1507
|
}
|
|
1508
|
+
const memoryAvailable = await options.memoryAvailable();
|
|
1509
|
+
const wasActive = activeThreadRunIdOf(agent, threadId, resourceId) !== undefined;
|
|
1064
1510
|
const result = agent.sendSignal(signal, {
|
|
1065
1511
|
threadId,
|
|
1066
1512
|
resourceId,
|
|
1067
|
-
ifActive: { behavior:
|
|
1068
|
-
ifIdle: { behavior },
|
|
1513
|
+
ifActive: { behavior: deliveredActiveBehavior },
|
|
1514
|
+
ifIdle: { behavior: memoryAvailable ? behavior : 'discard' },
|
|
1069
1515
|
});
|
|
1070
1516
|
const decision = await result.accepted;
|
|
1517
|
+
if (result.persisted)
|
|
1518
|
+
await result.persisted;
|
|
1519
|
+
const action = recordValue(decision)?.action;
|
|
1520
|
+
if (action === 'persist' && !memoryAvailable) {
|
|
1521
|
+
return memoryUnavailableResponse();
|
|
1522
|
+
}
|
|
1523
|
+
// An idle discard is either the caller's `ifIdle: 'discard'` or the memory
|
|
1524
|
+
// gate's substitution, handled by the next block.
|
|
1525
|
+
if (action === 'discard' &&
|
|
1526
|
+
behavior === 'persist' &&
|
|
1527
|
+
!memoryAvailable &&
|
|
1528
|
+
!(wasActive && deliveredActiveBehavior === 'discard')) {
|
|
1529
|
+
return memoryUnavailableResponse();
|
|
1530
|
+
}
|
|
1531
|
+
if (activePersistenceForbidden && wasActive && action === 'discard') {
|
|
1532
|
+
return persistenceForbiddenResponse({ capped: false });
|
|
1533
|
+
}
|
|
1071
1534
|
return json({
|
|
1072
1535
|
decision,
|
|
1073
1536
|
capped: false,
|
|
1074
1537
|
signalId: result.signal.id,
|
|
1075
1538
|
});
|
|
1076
1539
|
}
|
|
1077
|
-
async function handleState(agent, body, threadId, resourceId) {
|
|
1540
|
+
async function handleState(agent, body, threadId, resourceId, options) {
|
|
1078
1541
|
if (typeof body.id !== 'string' || typeof body.cacheKey !== 'string') {
|
|
1079
1542
|
return json({ error: 'id and cacheKey are required for a state signal' }, 400);
|
|
1080
1543
|
}
|
|
@@ -1093,7 +1556,38 @@ async function handleState(agent, body, threadId, resourceId) {
|
|
|
1093
1556
|
...(mode === 'snapshot' ? { value: body.value } : { delta: body.delta }),
|
|
1094
1557
|
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
1095
1558
|
};
|
|
1096
|
-
const
|
|
1559
|
+
const durableBlockingRun = await options.blockingRun?.();
|
|
1560
|
+
if (durableBlockingRun &&
|
|
1561
|
+
!samePrincipal(durableBlockingRun.principal, options.principal)) {
|
|
1562
|
+
return principalMismatchResponse(durableBlockingRun.runId);
|
|
1563
|
+
}
|
|
1564
|
+
if (!options.persistenceAllowed) {
|
|
1565
|
+
return persistenceForbiddenResponse();
|
|
1566
|
+
}
|
|
1567
|
+
// Core's createStateSignalInput strips id/cacheKey/mode/value/delta out of the
|
|
1568
|
+
// signal it renders (they ride in metadata, which signalToXmlMarkup never
|
|
1569
|
+
// emits) and defaults tagName to 'state'. Mirror exactly that, so the gate
|
|
1570
|
+
// inspects the markup the model will see and nothing else.
|
|
1571
|
+
const policyRefusal = await contentPolicyRefusal(options.inspectContent, createSignal({
|
|
1572
|
+
type: 'state',
|
|
1573
|
+
tagName: 'state',
|
|
1574
|
+
contents: state.contents,
|
|
1575
|
+
...(state.attributes !== undefined
|
|
1576
|
+
? { attributes: state.attributes }
|
|
1577
|
+
: {}),
|
|
1578
|
+
}), durableBlockingRun?.runId);
|
|
1579
|
+
if (policyRefusal)
|
|
1580
|
+
return policyRefusal;
|
|
1581
|
+
if (!(await options.memoryAvailable()))
|
|
1582
|
+
return memoryUnavailableResponse();
|
|
1583
|
+
const result = await agent.sendStateSignal(state, {
|
|
1584
|
+
threadId,
|
|
1585
|
+
resourceId,
|
|
1586
|
+
...(!options.runtimeDriven
|
|
1587
|
+
? { ifActive: { behavior: 'persist' } }
|
|
1588
|
+
: {}),
|
|
1589
|
+
ifIdle: { behavior: 'persist' },
|
|
1590
|
+
});
|
|
1097
1591
|
// A snapshot whose cacheKey value is unchanged is de-duped (skipped) — no run
|
|
1098
1592
|
// touched, no signal minted. Surface that distinctly rather than pretend a
|
|
1099
1593
|
// delivery happened.
|
|
@@ -1101,9 +1595,16 @@ async function handleState(agent, body, threadId, resourceId) {
|
|
|
1101
1595
|
return json({ skipped: true, reason: result.reason });
|
|
1102
1596
|
}
|
|
1103
1597
|
const decision = await result.accepted;
|
|
1104
|
-
|
|
1598
|
+
if (result.persisted)
|
|
1599
|
+
await result.persisted;
|
|
1600
|
+
const degraded = 'not-runtime-driven';
|
|
1601
|
+
return json({
|
|
1602
|
+
decision,
|
|
1603
|
+
signalId: result.signal.id,
|
|
1604
|
+
...(!options.runtimeDriven ? { degraded } : {}),
|
|
1605
|
+
});
|
|
1105
1606
|
}
|
|
1106
|
-
async function handleNotification(agent, body, threadId, resourceId) {
|
|
1607
|
+
async function handleNotification(agent, body, threadId, resourceId, resolveNotificationsStorage, options) {
|
|
1107
1608
|
if (typeof body.source !== 'string' ||
|
|
1108
1609
|
typeof body.kind !== 'string' ||
|
|
1109
1610
|
typeof body.summary !== 'string') {
|
|
@@ -1126,22 +1627,95 @@ async function handleNotification(agent, body, threadId, resourceId) {
|
|
|
1126
1627
|
: {}),
|
|
1127
1628
|
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
1128
1629
|
};
|
|
1129
|
-
//
|
|
1130
|
-
//
|
|
1131
|
-
//
|
|
1132
|
-
//
|
|
1133
|
-
//
|
|
1134
|
-
//
|
|
1135
|
-
//
|
|
1630
|
+
// Owners use core's delivery policy. The inbox row is the durable artifact,
|
|
1631
|
+
// so this route has no memory gate: without agent memory, a model-visible
|
|
1632
|
+
// persist is best-effort and the row stays pending. Non-owner notifications
|
|
1633
|
+
// are record-only here: the host's createNotificationDispatchTick delivers
|
|
1634
|
+
// them later (agent-starter runs it every 60 seconds). A host without that
|
|
1635
|
+
// tick records but never delivers them; the spike intentionally has no tick
|
|
1636
|
+
// and its provider probes assert only the inbox row. This branch bypasses an
|
|
1637
|
+
// agent-level notifications.deliveryPolicy and
|
|
1638
|
+
// __ensureNotificationDispatchReady; branded hosts cannot reach either seam
|
|
1639
|
+
// through the wrapped agent anyway.
|
|
1640
|
+
// The target requires a resourceId because the inbox is keyed by its owner.
|
|
1641
|
+
// Core's default policy does not summarize an idle thread immediately. A
|
|
1642
|
+
// medium-priority delivery can sample active, then fall idle across its
|
|
1643
|
+
// awaits. For a branded runner the resulting forced wake reaches the terminal
|
|
1644
|
+
// refusal path while the created record stays pending with its summary signal
|
|
1645
|
+
// id. An unbranded agent keeps core's own below-boundary run start; no shipped
|
|
1646
|
+
// host uses that degraded configuration.
|
|
1136
1647
|
if (resourceId === undefined) {
|
|
1137
1648
|
return json({ error: 'this thread has no resourceId wired; notifications need one' }, 409);
|
|
1138
1649
|
}
|
|
1650
|
+
// This gate is AUTHORITATIVE, not a preview: core can send an individual or
|
|
1651
|
+
// summary signal before the record reaches the dispatcher's second gate.
|
|
1652
|
+
// Storage owns the id, timestamps, and coalescing, so inspect a prospective
|
|
1653
|
+
// record carrying every untrusted model-visible field instead.
|
|
1654
|
+
if (options.inspectContent) {
|
|
1655
|
+
const prospectiveRecord = {
|
|
1656
|
+
id: 'prospective',
|
|
1657
|
+
threadId,
|
|
1658
|
+
resourceId,
|
|
1659
|
+
agentId: agent.id,
|
|
1660
|
+
source: notification.source,
|
|
1661
|
+
kind: notification.kind,
|
|
1662
|
+
summary: notification.summary,
|
|
1663
|
+
priority: notification.priority ?? 'medium',
|
|
1664
|
+
status: 'pending',
|
|
1665
|
+
coalescedCount: 1,
|
|
1666
|
+
...(notification.attributes !== undefined
|
|
1667
|
+
? { attributes: notification.attributes }
|
|
1668
|
+
: {}),
|
|
1669
|
+
createdAt: new Date(0),
|
|
1670
|
+
updatedAt: new Date(0),
|
|
1671
|
+
};
|
|
1672
|
+
// Core picks between two renderings after an async boundary this route does
|
|
1673
|
+
// not control, so inspect both — the same reason the schedule route inspects
|
|
1674
|
+
// both delivery branches. The individual signal renders `status="delivered"`
|
|
1675
|
+
// because that is the status core stamps on it when it sends; the summary
|
|
1676
|
+
// renders from the row as stored, which is why it keeps `status:'pending'`.
|
|
1677
|
+
for (const candidate of [
|
|
1678
|
+
createNotificationSignal({ ...prospectiveRecord, status: 'delivered' }),
|
|
1679
|
+
createNotificationSummarySignal(summarizeNotifications([prospectiveRecord])),
|
|
1680
|
+
]) {
|
|
1681
|
+
const policyRefusal = await contentPolicyRefusal(options.inspectContent, candidate);
|
|
1682
|
+
if (policyRefusal)
|
|
1683
|
+
return policyRefusal;
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
if (!options.persistenceAllowed) {
|
|
1687
|
+
const storage = await resolveNotificationsStorage?.();
|
|
1688
|
+
if (!storage) {
|
|
1689
|
+
return json({ error: 'notifications storage unavailable' }, 409);
|
|
1690
|
+
}
|
|
1691
|
+
const record = await storage.createNotification({
|
|
1692
|
+
...notification,
|
|
1693
|
+
threadId,
|
|
1694
|
+
resourceId,
|
|
1695
|
+
agentId: agent.id,
|
|
1696
|
+
deliverAt: new Date(),
|
|
1697
|
+
});
|
|
1698
|
+
return json({
|
|
1699
|
+
record,
|
|
1700
|
+
delivery: { action: 'deferred', reason: 'dispatcher' },
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1139
1703
|
const result = await agent.sendNotificationSignal(notification, {
|
|
1140
1704
|
threadId,
|
|
1141
1705
|
resourceId,
|
|
1706
|
+
...(!options.runtimeDriven
|
|
1707
|
+
? { ifActive: { behavior: 'persist' } }
|
|
1708
|
+
: {}),
|
|
1709
|
+
ifIdle: { behavior: 'persist' },
|
|
1142
1710
|
});
|
|
1143
1711
|
if (result.persisted)
|
|
1144
1712
|
await result.persisted;
|
|
1145
|
-
|
|
1713
|
+
const response = {
|
|
1714
|
+
record: result,
|
|
1715
|
+
...(!options.runtimeDriven ? { degraded: 'not-runtime-driven' } : {}),
|
|
1716
|
+
};
|
|
1717
|
+
if (result.accepted)
|
|
1718
|
+
response.delivery = await result.accepted;
|
|
1719
|
+
return json(response);
|
|
1146
1720
|
}
|
|
1147
1721
|
//# sourceMappingURL=thread-do-routes.js.map
|