@proofoftech/flowsafe 0.22.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +53 -0
- package/README.md +21 -6
- package/dist/agent-host/catalog.d.ts.map +1 -1
- package/dist/agent-host/catalog.js +5 -2
- package/dist/agent-host/catalog.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +16 -0
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +75 -27
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +114 -67
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +394 -235
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/do-runner/durable-object.js +1 -1
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/runtime.d.ts +23 -47
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +61 -68
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/signals/client.d.ts +7 -4
- package/dist/signals/client.d.ts.map +1 -1
- package/dist/signals/client.js +9 -7
- 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/thread-do-routes.d.ts +48 -9
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +404 -213
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +11 -5
|
@@ -4,20 +4,15 @@
|
|
|
4
4
|
// onto ONE isolate. The DO IS the serialization lease Mastra otherwise wants
|
|
5
5
|
// Redis for. These routes run AFTER ThreadDurableObject.fetch verifies the
|
|
6
6
|
// deployment identity and decodes the server-stamped principal. The scope's
|
|
7
|
-
// threadId and principal are trusted here; the ingestion gate
|
|
8
|
-
//
|
|
9
|
-
//
|
|
7
|
+
// threadId and principal are trusted here; the ingestion gate is the
|
|
8
|
+
// Worker-side createSignalRouter's job, the same split createRunRouter (Worker
|
|
9
|
+
// gate) → DurableObjectRunner (execution) uses.
|
|
10
10
|
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
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
|
|
19
|
-
// isolate, so affinity holds either way; a wired pubsub additionally makes
|
|
20
|
-
// observe()/replay align (pubsub.ts).
|
|
11
|
+
// Core keys its in-process signal registry by pub/sub identity. A runtime-driven
|
|
12
|
+
// wrapper carries the thread Durable Object's pub/sub from construction; these
|
|
13
|
+
// routes refuse a configured identity mismatch. Other agents receive the
|
|
14
|
+
// thread's pub/sub before each call. Without a host pub/sub, other agents fall
|
|
15
|
+
// back to core's module default and runtime-driven wrappers use their own stream bus.
|
|
21
16
|
//
|
|
22
17
|
// core's `agentThreadStreamRuntime` is NOT on the package exports map, so these
|
|
23
18
|
// routes drive only the PUBLIC Agent methods, never a deep dist import across
|
|
@@ -104,7 +99,7 @@ async function readJson(request) {
|
|
|
104
99
|
* The wire surface accepts STRING contents only — the common case, and the one
|
|
105
100
|
* the ingestion gate can size-cap and escape uniformly as defense in depth.
|
|
106
101
|
* Core's multimodal `AgentSignalContents` array form (TextPart/FilePart) is a
|
|
107
|
-
* documented residual, not exposed over this untrusted channel
|
|
102
|
+
* documented residual, not exposed over this untrusted channel.
|
|
108
103
|
*/
|
|
109
104
|
function isContents(value) {
|
|
110
105
|
return typeof value === 'string';
|
|
@@ -117,9 +112,7 @@ function isContents(value) {
|
|
|
117
112
|
* into a 400 at the route, and an invalid attribute name into a dropped
|
|
118
113
|
* attributes object (`isAttributes`), rather than a
|
|
119
114
|
* throw at render time inside the agent turn. Kept byte-identical to core
|
|
120
|
-
* (chunk `signalToXmlMarkup`: `/^[A-Za-z_][A-Za-z0-9_.-]*$/`)
|
|
121
|
-
* pins core's own neutralization of contents/attribute values so this
|
|
122
|
-
* mirror and that layer are checked together.
|
|
115
|
+
* (chunk `signalToXmlMarkup`: `/^[A-Za-z_][A-Za-z0-9_.-]*$/`).
|
|
123
116
|
*/
|
|
124
117
|
const XML_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
|
|
125
118
|
/**
|
|
@@ -152,6 +145,21 @@ function renderableAttributes(attributes) {
|
|
|
152
145
|
return true;
|
|
153
146
|
return Object.entries(attributes).every(([key, value]) => value === null || value === undefined || XML_NAME_PATTERN.test(key));
|
|
154
147
|
}
|
|
148
|
+
async function inspectPolicyResult(invoke) {
|
|
149
|
+
try {
|
|
150
|
+
const result = await invoke();
|
|
151
|
+
if (result?.allowed === true)
|
|
152
|
+
return 'allowed';
|
|
153
|
+
if (result?.allowed === false &&
|
|
154
|
+
(result.outcome === 'denied' || result.outcome === 'error')) {
|
|
155
|
+
return result.outcome;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return 'error';
|
|
160
|
+
}
|
|
161
|
+
return 'error';
|
|
162
|
+
}
|
|
155
163
|
async function inspectSignalContent(policy, input, signal, runId) {
|
|
156
164
|
if (typeof signal.contents !== 'string')
|
|
157
165
|
return 'error';
|
|
@@ -167,23 +175,11 @@ async function inspectSignalContent(policy, input, signal, runId) {
|
|
|
167
175
|
catch {
|
|
168
176
|
return 'error';
|
|
169
177
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
});
|
|
176
|
-
if (result?.allowed === true)
|
|
177
|
-
return 'allowed';
|
|
178
|
-
if (result?.allowed === false &&
|
|
179
|
-
(result.outcome === 'denied' || result.outcome === 'error')) {
|
|
180
|
-
return result.outcome;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
catch {
|
|
184
|
-
return 'error';
|
|
185
|
-
}
|
|
186
|
-
return 'error';
|
|
178
|
+
return inspectPolicyResult(() => policy({
|
|
179
|
+
...input,
|
|
180
|
+
text,
|
|
181
|
+
...(runId !== undefined ? { runId } : {}),
|
|
182
|
+
}));
|
|
187
183
|
}
|
|
188
184
|
function signalContentPolicyResponse(inspection) {
|
|
189
185
|
return inspection === 'denied'
|
|
@@ -192,7 +188,7 @@ function signalContentPolicyResponse(inspection) {
|
|
|
192
188
|
}
|
|
193
189
|
export function createThreadSignalRoutes(options) {
|
|
194
190
|
const maxDeliveryAttempts = positiveSafeInteger(options.maxDeliveryAttempts ?? DEFAULT_MAX_NOTIFICATION_DELIVERY_ATTEMPTS, 'notification maximum delivery attempts');
|
|
195
|
-
const { resolveAgent, resolveResourceId, consultRunCap, startIdleRun, resolveBlockingRun, serializeDispatch, resolveScheduleRunStatus, resolveScheduleTarget, canPersist, canPersistSchedule, resolveNotificationsStorage, resolveScheduleDispatchStore, contentPolicy, } = options;
|
|
191
|
+
const { resolveAgent, resolveResourceId, consultRunCap, startIdleRun, resolveBlockingRun, serializeDispatch, resolveScheduleRunStatus, resolveScheduleTarget, canPersist, canPersistSchedule, resolveNotificationsStorage, notificationDispatchAllowed, resolveScheduleDispatchStore, contentPolicy, scheduleProviderOptionsPolicy, } = options;
|
|
196
192
|
if (resolveBlockingRun && !serializeDispatch) {
|
|
197
193
|
throw new Error('signal routes require serializeDispatch with resolveBlockingRun');
|
|
198
194
|
}
|
|
@@ -209,19 +205,8 @@ export function createThreadSignalRoutes(options) {
|
|
|
209
205
|
notificationTail = next.then(() => undefined, () => undefined);
|
|
210
206
|
return next;
|
|
211
207
|
};
|
|
212
|
-
const route = async (
|
|
213
|
-
if (request.method !== 'POST')
|
|
214
|
-
return null;
|
|
215
|
-
const url = new URL(request.url);
|
|
208
|
+
const route = async (url, scope, entryPath, body) => {
|
|
216
209
|
const path = url.pathname;
|
|
217
|
-
if (path !== '/signal' && !path.startsWith('/signal/'))
|
|
218
|
-
return null;
|
|
219
|
-
const entryPath = entryPathForSignalRoute(path);
|
|
220
|
-
if (entryPath === undefined)
|
|
221
|
-
return json({ error: 'not found' }, 404);
|
|
222
|
-
const body = await readJson(request);
|
|
223
|
-
if (!body)
|
|
224
|
-
return json({ error: 'a JSON body is required' }, 400);
|
|
225
210
|
try {
|
|
226
211
|
// The execution fence, read ONCE for this request and before any store
|
|
227
212
|
// lookup. `migration-locked` refuses every signal route outright — the
|
|
@@ -230,7 +215,7 @@ export function createThreadSignalRoutes(options) {
|
|
|
230
215
|
// once the thread's active run is knowable.
|
|
231
216
|
//
|
|
232
217
|
// A read that fails throws ExecutionFenceUnreadableError, which the
|
|
233
|
-
// catch below answers
|
|
218
|
+
// catch below answers — degrade closed, never a silent open.
|
|
234
219
|
const executionFence = await readExecutionFence(scope.init.executionFence);
|
|
235
220
|
if (executionFence.state === 'migration-locked') {
|
|
236
221
|
return executionFencedResponse(executionFence.state, entryPath);
|
|
@@ -266,26 +251,28 @@ export function createThreadSignalRoutes(options) {
|
|
|
266
251
|
requestedAgentId === undefined) {
|
|
267
252
|
return json({ error: 'agentId is required for notification dispatch' }, 400);
|
|
268
253
|
}
|
|
269
|
-
//
|
|
270
|
-
//
|
|
271
|
-
// resolution inside this catch-all: construction/storage failures are
|
|
272
|
-
// internal and must not escape through the outer DO error response.
|
|
254
|
+
// Host resolution stays inside this catch-all so construction and storage
|
|
255
|
+
// failures use the route's internal error response.
|
|
273
256
|
const agent = await resolveAgent(scope, requestedAgentId, entryPath);
|
|
274
257
|
if (requestedAgentId !== undefined && agent.id !== requestedAgentId) {
|
|
275
258
|
return json({ error: 'agent binding does not match' }, 404);
|
|
276
259
|
}
|
|
277
260
|
const runtimeDriven = isRuntimeDrivenAgent(agent);
|
|
278
261
|
const pubsub = scope.init.pubsub;
|
|
279
|
-
if (pubsub)
|
|
262
|
+
if (pubsub && !runtimeDriven)
|
|
280
263
|
agent.__setPubSub(pubsub);
|
|
264
|
+
if (runtimeDriven &&
|
|
265
|
+
pubsub !== undefined &&
|
|
266
|
+
(typeof agent.getPubSub !== 'function' || agent.getPubSub() !== pubsub)) {
|
|
267
|
+
return json({ error: "agent pub/sub does not match this thread's" }, 503);
|
|
268
|
+
}
|
|
281
269
|
const resourceId = resolveResourceId?.(scope);
|
|
282
270
|
const threadId = scope.threadId;
|
|
283
271
|
// proof-only admits work on ONE run, so the gate lives here — the first
|
|
284
272
|
// point where the run a signal would reach is knowable, and the only one
|
|
285
273
|
// every route passes through. Deciding it inside handleWake would leave
|
|
286
|
-
// the lanes that never reach it
|
|
287
|
-
//
|
|
288
|
-
// wake path it owns.
|
|
274
|
+
// the lanes that never reach it ungated; handleWake keeps its own check
|
|
275
|
+
// for the wake path it owns.
|
|
289
276
|
let proof;
|
|
290
277
|
if (executionFence.state === 'proof-only') {
|
|
291
278
|
const runtime = scope.init.runtime;
|
|
@@ -394,7 +381,7 @@ export function createThreadSignalRoutes(options) {
|
|
|
394
381
|
proof,
|
|
395
382
|
});
|
|
396
383
|
}
|
|
397
|
-
// POST /signal — a system signal
|
|
384
|
+
// POST /signal — a system signal with its ifActive/ifIdle behaviors.
|
|
398
385
|
if (path === '/signal') {
|
|
399
386
|
return await handleSignal(agent, body, threadId, resourceId, consultRunCap, scope.deploymentTag, entryPath, startIdleRun, serializeWake, {
|
|
400
387
|
runtimeDriven,
|
|
@@ -439,6 +426,7 @@ export function createThreadSignalRoutes(options) {
|
|
|
439
426
|
store: await resolveScheduleDispatchStore(scope),
|
|
440
427
|
completed: completedScheduleDispatches,
|
|
441
428
|
inspectContent,
|
|
429
|
+
scheduleProviderOptionsPolicy,
|
|
442
430
|
proof,
|
|
443
431
|
});
|
|
444
432
|
}
|
|
@@ -481,17 +469,28 @@ export function createThreadSignalRoutes(options) {
|
|
|
481
469
|
proof,
|
|
482
470
|
}));
|
|
483
471
|
}
|
|
484
|
-
// POST /signal/notification — the durable AGENT inbox
|
|
472
|
+
// POST /signal/notification — the durable AGENT inbox.
|
|
485
473
|
if (path === '/signal/notification') {
|
|
486
474
|
return await serializeNotification(async () => handleNotification(agent, body, threadId, resourceId, resolveNotificationsStorage
|
|
487
475
|
? () => resolveNotificationsStorage(scope)
|
|
488
|
-
: undefined, {
|
|
476
|
+
: undefined, {
|
|
477
|
+
principal: scope.principal,
|
|
478
|
+
blockingRun,
|
|
479
|
+
persistenceAllowed,
|
|
480
|
+
runtimeDriven,
|
|
481
|
+
memoryAvailable,
|
|
482
|
+
inspectContent,
|
|
483
|
+
notificationDispatchAllowed: notificationDispatchAllowed
|
|
484
|
+
? () => notificationDispatchAllowed(scope, agent.id)
|
|
485
|
+
: undefined,
|
|
486
|
+
proof,
|
|
487
|
+
}));
|
|
489
488
|
}
|
|
490
489
|
return json({ error: 'not found' }, 404);
|
|
491
490
|
}
|
|
492
491
|
catch (error) {
|
|
493
|
-
// The fence refusing, or failing to answer. Surfaced with its own
|
|
494
|
-
// reason rather than the 502 below: a caller must be able to tell "this
|
|
492
|
+
// The fence refusing, or failing to answer. Surfaced with its own status
|
|
493
|
+
// and reason rather than the 502 below: a caller must be able to tell "this
|
|
495
494
|
// deployment is deliberately not executing" (retry after the migration)
|
|
496
495
|
// from "the model or a route is broken".
|
|
497
496
|
if (isExecutionFenceRefusal(error)) {
|
|
@@ -512,16 +511,23 @@ export function createThreadSignalRoutes(options) {
|
|
|
512
511
|
return internalErrorResponse('signals.thread', error, 502);
|
|
513
512
|
}
|
|
514
513
|
};
|
|
515
|
-
return (request, scope) => {
|
|
514
|
+
return async (request, scope) => {
|
|
516
515
|
if (request.method !== 'POST')
|
|
517
|
-
return
|
|
518
|
-
const
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
516
|
+
return null;
|
|
517
|
+
const url = new URL(request.url);
|
|
518
|
+
const path = url.pathname;
|
|
519
|
+
if (path !== '/signal' && !path.startsWith('/signal/'))
|
|
520
|
+
return null;
|
|
521
|
+
const entryPath = entryPathForSignalRoute(path);
|
|
522
|
+
if (entryPath === undefined)
|
|
523
|
+
return json({ error: 'not found' }, 404);
|
|
524
|
+
// A queued request keeps its parsed body if the sender disconnects.
|
|
525
|
+
const body = await readJson(request);
|
|
526
|
+
if (!body)
|
|
527
|
+
return json({ error: 'a JSON body is required' }, 400);
|
|
522
528
|
return serializeDispatch
|
|
523
|
-
? serializeDispatch(scope, () => route(
|
|
524
|
-
: route(
|
|
529
|
+
? serializeDispatch(scope, () => route(url, scope, entryPath, body))
|
|
530
|
+
: route(url, scope, entryPath, body);
|
|
525
531
|
};
|
|
526
532
|
}
|
|
527
533
|
async function handleNotificationDispatch(options) {
|
|
@@ -530,7 +536,9 @@ async function handleNotificationDispatch(options) {
|
|
|
530
536
|
ids.length === 0 ||
|
|
531
537
|
ids.length > MAX_NOTIFICATION_DISPATCH_IDS ||
|
|
532
538
|
!ids.every((id) => typeof id === 'string' && id.length > 0)) {
|
|
533
|
-
return json({
|
|
539
|
+
return json({
|
|
540
|
+
error: `notificationIds must contain 1-${MAX_NOTIFICATION_DISPATCH_IDS} strings`,
|
|
541
|
+
}, 400);
|
|
534
542
|
}
|
|
535
543
|
const uniqueIds = [...new Set(ids)];
|
|
536
544
|
if (options.resourceId === undefined ||
|
|
@@ -541,12 +549,7 @@ async function handleNotificationDispatch(options) {
|
|
|
541
549
|
const durableBlockingRun = await options.blockingRun?.();
|
|
542
550
|
if (durableBlockingRun &&
|
|
543
551
|
!samePrincipal(durableBlockingRun.principal, options.principal)) {
|
|
544
|
-
return
|
|
545
|
-
error: 'notification principal does not match the active run',
|
|
546
|
-
reason: 'principal-mismatch',
|
|
547
|
-
runId: durableBlockingRun.runId,
|
|
548
|
-
retry: true,
|
|
549
|
-
}, 409);
|
|
552
|
+
return notificationPrincipalMismatchResponse(durableBlockingRun.runId);
|
|
550
553
|
}
|
|
551
554
|
const now = typeof options.body.now === 'string'
|
|
552
555
|
? new Date(options.body.now)
|
|
@@ -678,11 +681,11 @@ async function handleNotificationDispatch(options) {
|
|
|
678
681
|
persistenceAllowed: options.persistenceAllowed,
|
|
679
682
|
memoryAvailable: options.memoryAvailable,
|
|
680
683
|
signal: deliverableSignal,
|
|
681
|
-
deliverActive: (runId, activeMemoryAvailable) => options.agent.sendSignal(deliverableSignal, {
|
|
684
|
+
deliverActive: (runId, activeMemoryAvailable, resolvedActiveBehavior) => options.agent.sendSignal(deliverableSignal, {
|
|
682
685
|
runId,
|
|
683
686
|
threadId: options.threadId,
|
|
684
687
|
resourceId,
|
|
685
|
-
ifActive: { behavior:
|
|
688
|
+
ifActive: { behavior: resolvedActiveBehavior },
|
|
686
689
|
ifIdle: {
|
|
687
690
|
behavior: activeMemoryAvailable && options.persistenceAllowed
|
|
688
691
|
? 'persist'
|
|
@@ -725,7 +728,9 @@ async function handleNotificationDispatch(options) {
|
|
|
725
728
|
const result = options.agent.sendSignal(signal, {
|
|
726
729
|
threadId: options.threadId,
|
|
727
730
|
resourceId,
|
|
728
|
-
ifActive: {
|
|
731
|
+
ifActive: {
|
|
732
|
+
behavior: activeBehaviorForRun('deliver', durableBlockingRun),
|
|
733
|
+
},
|
|
729
734
|
ifIdle: { behavior: 'persist' },
|
|
730
735
|
});
|
|
731
736
|
await result.accepted;
|
|
@@ -879,14 +884,8 @@ async function handleNotificationDispatch(options) {
|
|
|
879
884
|
});
|
|
880
885
|
}
|
|
881
886
|
/**
|
|
882
|
-
* Resolve the idle behavior a body asked for. A `wake` STARTS a run, so
|
|
883
|
-
*
|
|
884
|
-
* principal may persist and the agent has memory; otherwise the route answers
|
|
885
|
-
* `persistence-forbidden` or `memory-unavailable` instead of silently dropping
|
|
886
|
-
* the signal:
|
|
887
|
-
* - the agent must be RUNTIME-DRIVEN (its stream re-enters RunnerRuntime, not
|
|
888
|
-
* the default engine) — else `wakeRefused:'not-runtime-driven'`;
|
|
889
|
-
* - the deployment run cap must allow it — otherwise `capped:true`.
|
|
887
|
+
* Resolve the idle behavior a body asked for. A `wake` STARTS a run, so
|
|
888
|
+
* handleWake gates it.
|
|
890
889
|
*/
|
|
891
890
|
function requestedIdle(body) {
|
|
892
891
|
const requested = body.ifIdle;
|
|
@@ -895,6 +894,34 @@ function requestedIdle(body) {
|
|
|
895
894
|
? requested
|
|
896
895
|
: 'persist';
|
|
897
896
|
}
|
|
897
|
+
/** See resolveBlockingRun for why a run that is not executing gets persist. */
|
|
898
|
+
function activeBehaviorForRun(requested, blockingRun) {
|
|
899
|
+
return requested === 'deliver' &&
|
|
900
|
+
blockingRun?.status !== undefined &&
|
|
901
|
+
blockingRun.status !== 'running'
|
|
902
|
+
? 'persist'
|
|
903
|
+
: requested;
|
|
904
|
+
}
|
|
905
|
+
function deliverableActiveBehavior(behavior, persistenceAllowed) {
|
|
906
|
+
return behavior === 'persist' && !persistenceAllowed ? 'discard' : behavior;
|
|
907
|
+
}
|
|
908
|
+
function notificationPrincipalMismatchResponse(runId) {
|
|
909
|
+
return json({
|
|
910
|
+
error: 'notification principal does not match the active run',
|
|
911
|
+
reason: 'principal-mismatch',
|
|
912
|
+
runId,
|
|
913
|
+
retry: true,
|
|
914
|
+
}, 409);
|
|
915
|
+
}
|
|
916
|
+
const OWNER_NOTIFICATION_REFUSALS = {
|
|
917
|
+
'memory-unavailable': 'notification delivery requires agent memory',
|
|
918
|
+
'notification-pending': 'a matching notification is already pending',
|
|
919
|
+
'notification-dispatch-forbidden': 'the target agent does not accept notification dispatch',
|
|
920
|
+
'thread-blocked': 'the thread is blocked by another run',
|
|
921
|
+
};
|
|
922
|
+
function ownerNotificationRefusal(reason) {
|
|
923
|
+
return json({ error: OWNER_NOTIFICATION_REFUSALS[reason], reason }, 409);
|
|
924
|
+
}
|
|
898
925
|
function principalMismatchResponse(runId) {
|
|
899
926
|
return json({
|
|
900
927
|
decision: {
|
|
@@ -907,34 +934,14 @@ function principalMismatchResponse(runId) {
|
|
|
907
934
|
}
|
|
908
935
|
/**
|
|
909
936
|
* Report a lazily computed missing-memory gate after content inspection, only
|
|
910
|
-
* where a memory write would otherwise disappear.
|
|
911
|
-
* inbox recording never use this response. On an active thread it is returned
|
|
912
|
-
* for a persist outcome that would otherwise be silently dropped — an explicit
|
|
913
|
-
* `ifActive: 'persist'`, or the stale-active-id idle fall-through — and by
|
|
914
|
-
* `/state`, whose pre-send gate replaces core's hard memory requirement rather
|
|
915
|
-
* than covering a dropped write. A default or `ifIdle: 'persist'` request to
|
|
916
|
-
* `/signal/message` or `/signal` still delivers into an active run without
|
|
917
|
-
* memory; the memory gate responds only when core's outcome for the request
|
|
918
|
-
* replaced a persist (an idle discard substituted for a requested persist, or
|
|
919
|
-
* an active persist that no memory could write).
|
|
937
|
+
* where a memory write would otherwise disappear.
|
|
920
938
|
*/
|
|
921
939
|
function memoryUnavailableResponse() {
|
|
922
940
|
return json({
|
|
923
941
|
decision: { action: 'discard', reason: 'memory-unavailable' },
|
|
924
942
|
});
|
|
925
943
|
}
|
|
926
|
-
/**
|
|
927
|
-
* Report route-specific persistence authorization failures.
|
|
928
|
-
* `/queue` and `/state` refuse every non-owner request before sending.
|
|
929
|
-
* `/signal/message` and `/signal` refuse a default or requested `ifIdle: 'persist'`;
|
|
930
|
-
* `/signal` also degrades a requested `ifActive: 'persist'`.
|
|
931
|
-
* `/notification` never refuses because a non-owner is record-only for the
|
|
932
|
-
* dispatcher.
|
|
933
|
-
* Wake handling for `/signal/message`, `/signal`, `/signal/schedule`, and the
|
|
934
|
-
* notification dispatch lane returns this response from `handleWake` when a
|
|
935
|
-
* refused or capped wake, or a stale-active-id fall-through, would otherwise
|
|
936
|
-
* persist for a non-owner.
|
|
937
|
-
*/
|
|
944
|
+
/** Report route-specific persistence authorization failures. */
|
|
938
945
|
function persistenceForbiddenResponse(options) {
|
|
939
946
|
return json({
|
|
940
947
|
decision: { action: 'discard', reason: 'persistence-forbidden' },
|
|
@@ -977,12 +984,14 @@ async function handleWake(options) {
|
|
|
977
984
|
const memoryAvailable = await options.memoryAvailable();
|
|
978
985
|
await options.proof?.check(admitted);
|
|
979
986
|
options.proof?.assertActive(admitted);
|
|
980
|
-
const
|
|
987
|
+
const activeBehavior = activeBehaviorForRun(options.activeBehavior ?? 'deliver', durableBlockingRun);
|
|
988
|
+
const deliveredActiveBehavior = deliverableActiveBehavior(activeBehavior, options.persistenceAllowed);
|
|
989
|
+
const delivered = options.deliverActive(activeRunId, memoryAvailable, deliveredActiveBehavior);
|
|
981
990
|
const decision = await delivered.accepted;
|
|
982
991
|
if (delivered.persisted)
|
|
983
992
|
await delivered.persisted;
|
|
984
993
|
const action = recordValue(decision)?.action;
|
|
985
|
-
if (action === 'discard' &&
|
|
994
|
+
if (action === 'discard' && options.activeBehavior !== 'discard') {
|
|
986
995
|
return options.persistenceAllowed
|
|
987
996
|
? memoryUnavailableResponse()
|
|
988
997
|
: persistenceForbiddenResponse({ capped: false });
|
|
@@ -1030,13 +1039,13 @@ async function handleWake(options) {
|
|
|
1030
1039
|
? !(await options.consultRunCap())
|
|
1031
1040
|
: false;
|
|
1032
1041
|
if (refusal || capped) {
|
|
1033
|
-
//
|
|
1034
|
-
//
|
|
1042
|
+
// A drain can lose a signal here, and it is the CALLER'S choice, not the
|
|
1043
|
+
// fence's. `execution-draining` degrades a wake into a persist so
|
|
1035
1044
|
// nothing is lost while a deployment finishes its work — but a caller who
|
|
1036
1045
|
// said persistence is forbidden has already declared it does not want its
|
|
1037
1046
|
// signal parked, and honouring the fence by parking it anyway would
|
|
1038
1047
|
// override an authorization decision with an operational one. So it is
|
|
1039
|
-
// discarded,
|
|
1048
|
+
// discarded, and the response SAYS SO: `wakeRefused:
|
|
1040
1049
|
// 'execution-draining'` alongside `action: 'discard'` tells the caller
|
|
1041
1050
|
// exactly which condition dropped it, so a sender that would rather wait
|
|
1042
1051
|
// out the migration can retry instead of assuming delivery.
|
|
@@ -1149,9 +1158,9 @@ async function handleScheduleSignal(options) {
|
|
|
1149
1158
|
return json({ error: 'invalid schedule signal dispatch' }, 400);
|
|
1150
1159
|
}
|
|
1151
1160
|
const resourceId = options.resourceId;
|
|
1152
|
-
//
|
|
1153
|
-
//
|
|
1154
|
-
//
|
|
1161
|
+
// A terminal "this fire will not be delivered" outcome settles a canonical
|
|
1162
|
+
// receipt, so a replay of the dispatch returns it instead of re-deciding.
|
|
1163
|
+
// Settling is what lets the schedule advance; leaving the lease
|
|
1155
1164
|
// unsettled is reserved for outcomes a later tick could still resolve.
|
|
1156
1165
|
const settleDiscard = async () => {
|
|
1157
1166
|
const receipt = createScheduleAgentDispatchReceipt('discard', {
|
|
@@ -1245,7 +1254,24 @@ async function handleScheduleSignal(options) {
|
|
|
1245
1254
|
}
|
|
1246
1255
|
return await settleDiscard();
|
|
1247
1256
|
}
|
|
1248
|
-
const
|
|
1257
|
+
const storedProviderOptions = target.providerOptions;
|
|
1258
|
+
const scheduleProviderOptionsPolicy = options.scheduleProviderOptionsPolicy;
|
|
1259
|
+
if (scheduleProviderOptionsPolicy) {
|
|
1260
|
+
const inspection = await inspectPolicyResult(() => scheduleProviderOptionsPolicy({
|
|
1261
|
+
// The policy cannot change the options later delivered in the signal.
|
|
1262
|
+
providerOptions: structuredClone(storedProviderOptions),
|
|
1263
|
+
agentId: target.agentId,
|
|
1264
|
+
threadId: options.threadId,
|
|
1265
|
+
resourceId,
|
|
1266
|
+
}));
|
|
1267
|
+
if (inspection === 'denied') {
|
|
1268
|
+
return await settleDiscard();
|
|
1269
|
+
}
|
|
1270
|
+
if (inspection === 'error') {
|
|
1271
|
+
return json({ error: 'schedule provider options policy unavailable' }, 503);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
const baseProviderOptions = storedProviderOptions ?? {};
|
|
1249
1275
|
const baseMastra = recordValue(baseProviderOptions.mastra) ?? {};
|
|
1250
1276
|
const signal = {
|
|
1251
1277
|
id: dispatchId,
|
|
@@ -1267,12 +1293,20 @@ async function handleScheduleSignal(options) {
|
|
|
1267
1293
|
},
|
|
1268
1294
|
};
|
|
1269
1295
|
const ifActive = target.ifActive ?? { behavior: 'deliver' };
|
|
1296
|
+
const requestedActiveBehavior = ifActive.behavior ?? 'deliver';
|
|
1297
|
+
const effectiveIfActive = {
|
|
1298
|
+
...ifActive,
|
|
1299
|
+
behavior: activeBehaviorForRun(requestedActiveBehavior, durableBlockingRun),
|
|
1300
|
+
};
|
|
1270
1301
|
const ifIdle = target.ifIdle ?? { behavior: 'wake' };
|
|
1271
1302
|
const localActiveRunId = activeThreadRunIdOf(options.agent, options.threadId, resourceId);
|
|
1272
1303
|
const persistenceRequested = localActiveRunId
|
|
1273
|
-
?
|
|
1304
|
+
? effectiveIfActive.behavior === 'persist'
|
|
1274
1305
|
: (ifIdle.behavior ?? 'wake') === 'persist';
|
|
1275
|
-
|
|
1306
|
+
// Occupancy can change before the send, so either branch may persist.
|
|
1307
|
+
const persistenceAllowed = (effectiveIfActive.behavior === 'persist' ||
|
|
1308
|
+
(ifIdle.behavior ?? 'wake') === 'persist') &&
|
|
1309
|
+
options.schedulePersistenceAllowed
|
|
1276
1310
|
? await options.schedulePersistenceAllowed({
|
|
1277
1311
|
scheduleId,
|
|
1278
1312
|
dispatchId,
|
|
@@ -1337,8 +1371,16 @@ async function handleScheduleSignal(options) {
|
|
|
1337
1371
|
const signalTarget = {
|
|
1338
1372
|
threadId: options.threadId,
|
|
1339
1373
|
resourceId,
|
|
1340
|
-
ifActive
|
|
1341
|
-
|
|
1374
|
+
ifActive: {
|
|
1375
|
+
...effectiveIfActive,
|
|
1376
|
+
behavior: deliverableActiveBehavior(effectiveIfActive.behavior, persistenceAllowed),
|
|
1377
|
+
},
|
|
1378
|
+
ifIdle: {
|
|
1379
|
+
...signalIfIdle,
|
|
1380
|
+
behavior: signalIfIdle.behavior === 'persist' && !persistenceAllowed
|
|
1381
|
+
? 'discard'
|
|
1382
|
+
: signalIfIdle.behavior,
|
|
1383
|
+
},
|
|
1342
1384
|
};
|
|
1343
1385
|
let decision;
|
|
1344
1386
|
let signalId;
|
|
@@ -1373,16 +1415,16 @@ async function handleScheduleSignal(options) {
|
|
|
1373
1415
|
persistenceAllowed,
|
|
1374
1416
|
memoryAvailable: options.memoryAvailable,
|
|
1375
1417
|
signal: idleSignal,
|
|
1418
|
+
activeBehavior: requestedActiveBehavior,
|
|
1376
1419
|
runId,
|
|
1377
1420
|
scheduleId,
|
|
1378
1421
|
dispatchId,
|
|
1379
1422
|
safeContext: { ...requestContext, ...idleRequestContext },
|
|
1380
|
-
|
|
1381
|
-
deliverActive: (activeRunId, activeMemoryAvailable) => options.agent.sendSignal(deliverableSignal, {
|
|
1423
|
+
deliverActive: (activeRunId, activeMemoryAvailable, resolvedActiveBehavior) => options.agent.sendSignal(deliverableSignal, {
|
|
1382
1424
|
runId: activeRunId,
|
|
1383
1425
|
threadId: options.threadId,
|
|
1384
1426
|
resourceId,
|
|
1385
|
-
ifActive,
|
|
1427
|
+
ifActive: { ...ifActive, behavior: resolvedActiveBehavior },
|
|
1386
1428
|
ifIdle: {
|
|
1387
1429
|
behavior: activeMemoryAvailable && persistenceAllowed
|
|
1388
1430
|
? 'persist'
|
|
@@ -1451,8 +1493,7 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
|
|
|
1451
1493
|
const message = options.persistenceAllowed
|
|
1452
1494
|
? baseMessage
|
|
1453
1495
|
: markPersistenceForbidden(baseMessage);
|
|
1454
|
-
// sendMessage requires a resourceId+threadId target for its idle branch
|
|
1455
|
-
// host has not wired a resourceId, only the active/queue path is reachable.
|
|
1496
|
+
// sendMessage requires a resourceId+threadId target for its idle branch.
|
|
1456
1497
|
if (resourceId === undefined) {
|
|
1457
1498
|
return json({
|
|
1458
1499
|
error: 'this thread has no resourceId wired; message delivery needs one',
|
|
@@ -1487,11 +1528,11 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
|
|
|
1487
1528
|
persistenceAllowed: options.persistenceAllowed,
|
|
1488
1529
|
memoryAvailable: options.memoryAvailable,
|
|
1489
1530
|
message,
|
|
1490
|
-
deliverActive: (runId, activeMemoryAvailable) => agent.sendMessage(message, {
|
|
1531
|
+
deliverActive: (runId, activeMemoryAvailable, resolvedActiveBehavior) => agent.sendMessage(message, {
|
|
1491
1532
|
runId,
|
|
1492
1533
|
threadId,
|
|
1493
1534
|
resourceId,
|
|
1494
|
-
ifActive: { behavior:
|
|
1535
|
+
ifActive: { behavior: resolvedActiveBehavior },
|
|
1495
1536
|
// A stale active id can disappear before core sends. Persist only
|
|
1496
1537
|
// when both the memory and authorization gates allow the write.
|
|
1497
1538
|
ifIdle: {
|
|
@@ -1510,27 +1551,16 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
|
|
|
1510
1551
|
if (behavior === 'persist' && !options.persistenceAllowed) {
|
|
1511
1552
|
return persistenceForbiddenResponse({ capped: false });
|
|
1512
1553
|
}
|
|
1513
|
-
const
|
|
1514
|
-
|
|
1515
|
-
options.
|
|
1516
|
-
const
|
|
1554
|
+
const activeBehavior = activeBehaviorForRun('deliver', durableBlockingRun);
|
|
1555
|
+
const activePersistenceForbidden = activeBehavior === 'persist' && !options.persistenceAllowed;
|
|
1556
|
+
const deliveredActiveBehavior = deliverableActiveBehavior(activeBehavior, options.persistenceAllowed);
|
|
1557
|
+
const sent = await sendWithoutWake(agent, (sendOptions) => agent.sendMessage(message, sendOptions), {
|
|
1517
1558
|
threadId,
|
|
1518
1559
|
resourceId,
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
await result.persisted;
|
|
1524
|
-
if (behavior === 'persist' &&
|
|
1525
|
-
!memoryAvailable &&
|
|
1526
|
-
recordValue(decision)?.action === 'discard') {
|
|
1527
|
-
return memoryUnavailableResponse();
|
|
1528
|
-
}
|
|
1529
|
-
return json({
|
|
1530
|
-
decision,
|
|
1531
|
-
capped: false,
|
|
1532
|
-
signalId: result.signal.id,
|
|
1533
|
-
});
|
|
1560
|
+
ifActive: deliveredActiveBehavior,
|
|
1561
|
+
ifIdle: behavior,
|
|
1562
|
+
}, options);
|
|
1563
|
+
return noWakeResponse(sent, behavior, deliveredActiveBehavior, activePersistenceForbidden);
|
|
1534
1564
|
}
|
|
1535
1565
|
async function handleQueue(agent, body, threadId, resourceId, options) {
|
|
1536
1566
|
if (!isContents(body.contents)) {
|
|
@@ -1576,11 +1606,16 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1576
1606
|
// Route-level tagName defense: reject a non-XML-name tagName HERE with a
|
|
1577
1607
|
// 400, rather than letting core's signalToXmlMarkup throw at render time inside
|
|
1578
1608
|
// the agent turn. Core still escapes contents/attribute values and re-validates
|
|
1579
|
-
// names
|
|
1609
|
+
// names.
|
|
1580
1610
|
if (typeof body.tagName === 'string' &&
|
|
1581
1611
|
!XML_NAME_PATTERN.test(body.tagName)) {
|
|
1582
1612
|
return json({ error: 'tagName is not a valid XML name' }, 400);
|
|
1583
1613
|
}
|
|
1614
|
+
if (resourceId === undefined) {
|
|
1615
|
+
return json({
|
|
1616
|
+
error: 'this thread has no resourceId wired; signal delivery needs one',
|
|
1617
|
+
}, 409);
|
|
1618
|
+
}
|
|
1584
1619
|
const baseSignal = {
|
|
1585
1620
|
type: 'reactive',
|
|
1586
1621
|
contents: body.contents,
|
|
@@ -1594,10 +1629,6 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1594
1629
|
ACTIVE_BEHAVIORS.includes(body.ifActive)
|
|
1595
1630
|
? body.ifActive
|
|
1596
1631
|
: 'deliver';
|
|
1597
|
-
const activePersistenceForbidden = activeBehavior === 'persist' && !options.persistenceAllowed;
|
|
1598
|
-
const deliveredActiveBehavior = activePersistenceForbidden
|
|
1599
|
-
? 'discard'
|
|
1600
|
-
: activeBehavior;
|
|
1601
1632
|
const durableBlockingRun = await options.blockingRun?.();
|
|
1602
1633
|
if (durableBlockingRun &&
|
|
1603
1634
|
!samePrincipal(durableBlockingRun.principal, options.principal)) {
|
|
@@ -1606,22 +1637,9 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1606
1637
|
const policyRefusal = await contentPolicyRefusal(options.inspectContent, createSignal(signal), durableBlockingRun?.runId);
|
|
1607
1638
|
if (policyRefusal)
|
|
1608
1639
|
return policyRefusal;
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
if (!isPathSafeId(runId)) {
|
|
1613
|
-
throw new Error('thread signal generated a non-path-safe run id');
|
|
1614
|
-
}
|
|
1615
|
-
await options.proof?.check();
|
|
1616
|
-
options.proof?.assertActive();
|
|
1617
|
-
const result = agent.sendSignal(signal, {
|
|
1618
|
-
threadId,
|
|
1619
|
-
runId,
|
|
1620
|
-
ifActive: { behavior: deliveredActiveBehavior },
|
|
1621
|
-
});
|
|
1622
|
-
const decision = await result.accepted;
|
|
1623
|
-
return json({ decision, signalId: result.signal.id });
|
|
1624
|
-
}
|
|
1640
|
+
const effectiveActiveBehavior = activeBehaviorForRun(activeBehavior, durableBlockingRun);
|
|
1641
|
+
const activePersistenceForbidden = effectiveActiveBehavior === 'persist' && !options.persistenceAllowed;
|
|
1642
|
+
const deliveredActiveBehavior = deliverableActiveBehavior(effectiveActiveBehavior, options.persistenceAllowed);
|
|
1625
1643
|
const behavior = requestedIdle(body);
|
|
1626
1644
|
if (behavior === 'wake') {
|
|
1627
1645
|
return handleWake({
|
|
@@ -1643,12 +1661,12 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1643
1661
|
persistenceAllowed: options.persistenceAllowed,
|
|
1644
1662
|
memoryAvailable: options.memoryAvailable,
|
|
1645
1663
|
signal,
|
|
1646
|
-
|
|
1647
|
-
deliverActive: (runId, activeMemoryAvailable) => agent.sendSignal(signal, {
|
|
1664
|
+
activeBehavior,
|
|
1665
|
+
deliverActive: (runId, activeMemoryAvailable, resolvedActiveBehavior) => agent.sendSignal(signal, {
|
|
1648
1666
|
runId,
|
|
1649
1667
|
threadId,
|
|
1650
1668
|
resourceId,
|
|
1651
|
-
ifActive: { behavior:
|
|
1669
|
+
ifActive: { behavior: resolvedActiveBehavior },
|
|
1652
1670
|
ifIdle: {
|
|
1653
1671
|
behavior: activeMemoryAvailable && options.persistenceAllowed
|
|
1654
1672
|
? 'persist'
|
|
@@ -1666,19 +1684,16 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1666
1684
|
if (behavior === 'persist' && !options.persistenceAllowed) {
|
|
1667
1685
|
return persistenceForbiddenResponse({ capped: false });
|
|
1668
1686
|
}
|
|
1669
|
-
const
|
|
1670
|
-
const wasActive = activeThreadRunIdOf(agent, threadId, resourceId) !== undefined;
|
|
1671
|
-
await options.proof?.check();
|
|
1672
|
-
options.proof?.assertActive();
|
|
1673
|
-
const result = agent.sendSignal(signal, {
|
|
1687
|
+
const sent = await sendWithoutWake(agent, (sendOptions) => agent.sendSignal(signal, sendOptions), {
|
|
1674
1688
|
threadId,
|
|
1675
1689
|
resourceId,
|
|
1676
|
-
ifActive:
|
|
1677
|
-
ifIdle:
|
|
1678
|
-
});
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1690
|
+
ifActive: deliveredActiveBehavior,
|
|
1691
|
+
ifIdle: behavior,
|
|
1692
|
+
}, options);
|
|
1693
|
+
return noWakeResponse(sent, behavior, deliveredActiveBehavior, activePersistenceForbidden);
|
|
1694
|
+
}
|
|
1695
|
+
function noWakeResponse(sent, behavior, deliveredActiveBehavior, activePersistenceForbidden) {
|
|
1696
|
+
const { decision, signal, wasActive, memoryAvailable } = sent;
|
|
1682
1697
|
const action = recordValue(decision)?.action;
|
|
1683
1698
|
if (action === 'persist' && !memoryAvailable) {
|
|
1684
1699
|
return memoryUnavailableResponse();
|
|
@@ -1697,9 +1712,31 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1697
1712
|
return json({
|
|
1698
1713
|
decision,
|
|
1699
1714
|
capped: false,
|
|
1700
|
-
signalId:
|
|
1715
|
+
signalId: signal.id,
|
|
1701
1716
|
});
|
|
1702
1717
|
}
|
|
1718
|
+
/**
|
|
1719
|
+
* Send a signal or message that never wakes a run, behind the proof gate.
|
|
1720
|
+
* Without agent memory the idle behavior becomes `discard`, because core's
|
|
1721
|
+
* idle persist reports `persist` even when no memory wrote the signal.
|
|
1722
|
+
*/
|
|
1723
|
+
async function sendWithoutWake(agent, send, target, options) {
|
|
1724
|
+
const memoryAvailable = await options.memoryAvailable();
|
|
1725
|
+
const wasActive = activeThreadRunIdOf(agent, target.threadId, target.resourceId) !==
|
|
1726
|
+
undefined;
|
|
1727
|
+
await options.proof?.check();
|
|
1728
|
+
options.proof?.assertActive();
|
|
1729
|
+
const result = send({
|
|
1730
|
+
threadId: target.threadId,
|
|
1731
|
+
resourceId: target.resourceId,
|
|
1732
|
+
ifActive: { behavior: target.ifActive },
|
|
1733
|
+
ifIdle: { behavior: memoryAvailable ? target.ifIdle : 'discard' },
|
|
1734
|
+
});
|
|
1735
|
+
const decision = await result.accepted;
|
|
1736
|
+
if (result.persisted)
|
|
1737
|
+
await result.persisted;
|
|
1738
|
+
return { decision, signal: result.signal, wasActive, memoryAvailable };
|
|
1739
|
+
}
|
|
1703
1740
|
async function handleState(agent, body, threadId, resourceId, options) {
|
|
1704
1741
|
if (typeof body.id !== 'string' || typeof body.cacheKey !== 'string') {
|
|
1705
1742
|
return json({ error: 'id and cacheKey are required for a state signal' }, 400);
|
|
@@ -1769,6 +1806,27 @@ async function handleState(agent, body, threadId, resourceId, options) {
|
|
|
1769
1806
|
...(!options.runtimeDriven ? { degraded } : {}),
|
|
1770
1807
|
});
|
|
1771
1808
|
}
|
|
1809
|
+
function hasDueTime(row) {
|
|
1810
|
+
return row.deliverAt !== undefined || row.summaryAt !== undefined;
|
|
1811
|
+
}
|
|
1812
|
+
async function matchingPendingNotifications(storage, notification, threadId, resourceId, agentId) {
|
|
1813
|
+
if (!notification.dedupeKey && !notification.coalesceKey)
|
|
1814
|
+
return [];
|
|
1815
|
+
const pending = await storage.listNotifications({
|
|
1816
|
+
threadId,
|
|
1817
|
+
status: 'pending',
|
|
1818
|
+
source: notification.source,
|
|
1819
|
+
agentId,
|
|
1820
|
+
resourceId,
|
|
1821
|
+
});
|
|
1822
|
+
// Storage coalesces into a pending row with the same source, kind, agent,
|
|
1823
|
+
// resource and key. D1 can match an empty key when the other key is truthy.
|
|
1824
|
+
return pending.filter((row) => row.kind === notification.kind &&
|
|
1825
|
+
((notification.dedupeKey !== undefined &&
|
|
1826
|
+
row.dedupeKey === notification.dedupeKey) ||
|
|
1827
|
+
(notification.coalesceKey !== undefined &&
|
|
1828
|
+
row.coalesceKey === notification.coalesceKey)));
|
|
1829
|
+
}
|
|
1772
1830
|
async function handleNotification(agent, body, threadId, resourceId, resolveNotificationsStorage, options) {
|
|
1773
1831
|
if (typeof body.source !== 'string' ||
|
|
1774
1832
|
typeof body.kind !== 'string' ||
|
|
@@ -1792,30 +1850,30 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
|
|
|
1792
1850
|
: {}),
|
|
1793
1851
|
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
1794
1852
|
};
|
|
1795
|
-
// Owners use core's delivery policy. The inbox row is the durable artifact,
|
|
1796
|
-
// so this route has no memory gate: without agent memory, a model-visible
|
|
1797
|
-
// persist is best-effort and the row stays pending. Non-owner notifications
|
|
1798
|
-
// are record-only here: the host's createNotificationDispatchTick delivers
|
|
1799
|
-
// them later (agent-starter runs it every 60 seconds). A host without that
|
|
1800
|
-
// tick records but never delivers them; the spike intentionally has no tick
|
|
1801
|
-
// and its provider probes assert only the inbox row. This branch bypasses an
|
|
1802
|
-
// agent-level notifications.deliveryPolicy and
|
|
1803
|
-
// __ensureNotificationDispatchReady; branded hosts cannot reach either seam
|
|
1804
|
-
// through the wrapped agent anyway.
|
|
1805
1853
|
// The target requires a resourceId because the inbox is keyed by its owner.
|
|
1806
|
-
// Core's default policy does not summarize an idle thread immediately. A
|
|
1807
|
-
// medium-priority delivery can sample active, then fall idle across its
|
|
1808
|
-
// awaits. For a branded runner the resulting forced wake reaches the terminal
|
|
1809
|
-
// refusal path while the created record stays pending with its summary signal
|
|
1810
|
-
// id. An unbranded agent keeps core's own below-boundary run start; no shipped
|
|
1811
|
-
// host uses that degraded configuration.
|
|
1812
1854
|
if (resourceId === undefined) {
|
|
1813
1855
|
return json({ error: 'this thread has no resourceId wired; notifications need one' }, 409);
|
|
1814
1856
|
}
|
|
1815
|
-
//
|
|
1816
|
-
//
|
|
1817
|
-
//
|
|
1818
|
-
//
|
|
1857
|
+
// An owner's notification to a runtime-driven agent is recorded, then
|
|
1858
|
+
// delivered at ingestion under the owner's principal: into the owner's
|
|
1859
|
+
// running run, otherwise persisted to memory. It never wakes a run, and its
|
|
1860
|
+
// row is never due, so the dispatcher, whose deliveries and wakes belong to
|
|
1861
|
+
// the dispatch principal, never selects it. Core's sendNotificationSignal
|
|
1862
|
+
// cannot serve it: its in-process delivery reads the notifications store
|
|
1863
|
+
// from the agent's own Mastra, and the FlowSafe wrapper is registered on
|
|
1864
|
+
// none. The branch keys on the brand rather than on Mastra registration
|
|
1865
|
+
// because a registered wrapper still carries no delivery policy (see
|
|
1866
|
+
// "DurableAgent does not forward the wrapped Agent's `notifications`" in
|
|
1867
|
+
// agent-runner/durable-agent-runner.ts).
|
|
1868
|
+
if (options.persistenceAllowed && options.runtimeDriven) {
|
|
1869
|
+
return handleOwnerNotification(agent, notification, threadId, resourceId, resolveNotificationsStorage, options);
|
|
1870
|
+
}
|
|
1871
|
+
// On core's delivery path this gate is AUTHORITATIVE, not a preview: core can
|
|
1872
|
+
// send an individual or summary signal before the record reaches the
|
|
1873
|
+
// dispatcher's second gate. On the record-only branch it refuses the row
|
|
1874
|
+
// before it is written. Storage owns the id, timestamps, and coalescing, so
|
|
1875
|
+
// inspect a prospective record carrying every untrusted model-visible field
|
|
1876
|
+
// instead.
|
|
1819
1877
|
if (options.inspectContent) {
|
|
1820
1878
|
const prospectiveRecord = {
|
|
1821
1879
|
id: 'prospective',
|
|
@@ -1834,11 +1892,11 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
|
|
|
1834
1892
|
createdAt: new Date(0),
|
|
1835
1893
|
updatedAt: new Date(0),
|
|
1836
1894
|
};
|
|
1837
|
-
// Core
|
|
1838
|
-
//
|
|
1839
|
-
//
|
|
1840
|
-
//
|
|
1841
|
-
//
|
|
1895
|
+
// Core's delivery policy, or the dispatcher on a later tick, picks between
|
|
1896
|
+
// two renderings, so inspect both. The individual signal renders
|
|
1897
|
+
// `status="delivered"` because that is the status its sender stamps on it;
|
|
1898
|
+
// the summary renders from the row as stored, which is why it keeps
|
|
1899
|
+
// `status:'pending'`.
|
|
1842
1900
|
for (const candidate of [
|
|
1843
1901
|
createNotificationSignal({ ...prospectiveRecord, status: 'delivered' }),
|
|
1844
1902
|
createNotificationSummarySignal(summarizeNotifications([prospectiveRecord])),
|
|
@@ -1848,11 +1906,24 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
|
|
|
1848
1906
|
return policyRefusal;
|
|
1849
1907
|
}
|
|
1850
1908
|
}
|
|
1909
|
+
// A non-owner's notification is record-only for any agent: the row is due
|
|
1910
|
+
// now, and the host's createNotificationDispatchTick delivers it as the
|
|
1911
|
+
// dispatch principal. A host without that tick records it but never
|
|
1912
|
+
// delivers it. The record-only branch bypasses an agent-level
|
|
1913
|
+
// notifications.deliveryPolicy and __ensureNotificationDispatchReady.
|
|
1851
1914
|
if (!options.persistenceAllowed) {
|
|
1852
1915
|
const storage = await resolveNotificationsStorage?.();
|
|
1853
1916
|
if (!storage) {
|
|
1854
1917
|
return json({ error: 'notifications storage unavailable' }, 409);
|
|
1855
1918
|
}
|
|
1919
|
+
if (options.notificationDispatchAllowed &&
|
|
1920
|
+
!(await options.notificationDispatchAllowed())) {
|
|
1921
|
+
return ownerNotificationRefusal('notification-dispatch-forbidden');
|
|
1922
|
+
}
|
|
1923
|
+
// Owner residue cannot become due under the dispatch principal.
|
|
1924
|
+
if ((await matchingPendingNotifications(storage, notification, threadId, resourceId, agent.id)).some((row) => !hasDueTime(row))) {
|
|
1925
|
+
return ownerNotificationRefusal('notification-pending');
|
|
1926
|
+
}
|
|
1856
1927
|
await options.proof?.check();
|
|
1857
1928
|
options.proof?.assertActive();
|
|
1858
1929
|
const record = await storage.createNotification({
|
|
@@ -1867,24 +1938,144 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
|
|
|
1867
1938
|
delivery: { action: 'deferred', reason: 'dispatcher' },
|
|
1868
1939
|
});
|
|
1869
1940
|
}
|
|
1941
|
+
// An unbranded agent's owner notification uses core's delivery policy, whose
|
|
1942
|
+
// summary wake override can start a run below this boundary, outside
|
|
1943
|
+
// RunnerRuntime, the host entry gate and the run cap (@mastra/core 1.67.0,
|
|
1944
|
+
// agent-Dk0N0Nlg.js:38431, :38447). The inbox row is the durable artifact, so
|
|
1945
|
+
// that path has no memory gate: without agent memory, a model-visible
|
|
1946
|
+
// persist is best-effort and the row stays pending.
|
|
1947
|
+
const notificationsStore = await agent
|
|
1948
|
+
.getMastraInstance?.()
|
|
1949
|
+
?.getStorage()
|
|
1950
|
+
?.getStore('notifications');
|
|
1951
|
+
if (!notificationsStore) {
|
|
1952
|
+
return json({ error: 'notifications storage unavailable' }, 409);
|
|
1953
|
+
}
|
|
1870
1954
|
await options.proof?.check();
|
|
1871
1955
|
options.proof?.assertActive();
|
|
1872
1956
|
const result = await agent.sendNotificationSignal(notification, {
|
|
1873
1957
|
threadId,
|
|
1874
1958
|
resourceId,
|
|
1875
|
-
|
|
1876
|
-
? { ifActive: { behavior: 'persist' } }
|
|
1877
|
-
: {}),
|
|
1959
|
+
ifActive: { behavior: 'persist' },
|
|
1878
1960
|
ifIdle: { behavior: 'persist' },
|
|
1879
1961
|
});
|
|
1880
1962
|
if (result.persisted)
|
|
1881
1963
|
await result.persisted;
|
|
1882
1964
|
const response = {
|
|
1883
1965
|
record: result,
|
|
1884
|
-
|
|
1966
|
+
degraded: 'not-runtime-driven',
|
|
1885
1967
|
};
|
|
1886
1968
|
if (result.accepted)
|
|
1887
1969
|
response.delivery = await result.accepted;
|
|
1888
1970
|
return json(response);
|
|
1889
1971
|
}
|
|
1972
|
+
async function handleOwnerNotification(agent, notification, threadId, resourceId, resolveNotificationsStorage, options) {
|
|
1973
|
+
const durableBlockingRun = await options.blockingRun?.();
|
|
1974
|
+
if (durableBlockingRun &&
|
|
1975
|
+
!samePrincipal(durableBlockingRun.principal, options.principal)) {
|
|
1976
|
+
return notificationPrincipalMismatchResponse(durableBlockingRun.runId);
|
|
1977
|
+
}
|
|
1978
|
+
const ifActive = activeBehaviorForRun('deliver', durableBlockingRun);
|
|
1979
|
+
const memoryAvailable = await options.memoryAvailable();
|
|
1980
|
+
if (!memoryAvailable &&
|
|
1981
|
+
(ifActive === 'persist' ||
|
|
1982
|
+
activeThreadRunIdOf(agent, threadId, resourceId) === undefined)) {
|
|
1983
|
+
return ownerNotificationRefusal('memory-unavailable');
|
|
1984
|
+
}
|
|
1985
|
+
const storage = await resolveNotificationsStorage?.();
|
|
1986
|
+
if (!storage) {
|
|
1987
|
+
return json({ error: 'notifications storage unavailable' }, 409);
|
|
1988
|
+
}
|
|
1989
|
+
if ((await matchingPendingNotifications(storage, notification, threadId, resourceId, agent.id)).some(hasDueTime)) {
|
|
1990
|
+
return ownerNotificationRefusal('notification-pending');
|
|
1991
|
+
}
|
|
1992
|
+
await options.proof?.check();
|
|
1993
|
+
options.proof?.assertActive();
|
|
1994
|
+
// No deliverAt or summaryAt, so no dispatch pass ever selects the row.
|
|
1995
|
+
const stored = await storage.createNotification({
|
|
1996
|
+
...notification,
|
|
1997
|
+
id: crypto.randomUUID(),
|
|
1998
|
+
threadId,
|
|
1999
|
+
resourceId,
|
|
2000
|
+
agentId: agent.id,
|
|
2001
|
+
});
|
|
2002
|
+
const now = new Date();
|
|
2003
|
+
let settled = false;
|
|
2004
|
+
let accepted;
|
|
2005
|
+
// Every settle write passes the proof gate first. When the gate refuses, the
|
|
2006
|
+
// row stays pending with no due time rather than bypass it.
|
|
2007
|
+
const settle = async (patch) => {
|
|
2008
|
+
await options.proof?.check();
|
|
2009
|
+
options.proof?.assertActive();
|
|
2010
|
+
const record = await storage.updateNotification({
|
|
2011
|
+
...patch,
|
|
2012
|
+
id: stored.id,
|
|
2013
|
+
threadId: stored.threadId,
|
|
2014
|
+
lastDeliveryAttemptAt: now,
|
|
2015
|
+
});
|
|
2016
|
+
settled = true;
|
|
2017
|
+
return record;
|
|
2018
|
+
};
|
|
2019
|
+
try {
|
|
2020
|
+
// Built from the stored row, which a coalesce may have merged, so the
|
|
2021
|
+
// policy inspects exactly the signal that is sent.
|
|
2022
|
+
const signal = createNotificationSignal({
|
|
2023
|
+
...stored,
|
|
2024
|
+
status: 'delivered',
|
|
2025
|
+
deliveredAt: now,
|
|
2026
|
+
});
|
|
2027
|
+
const inspection = options.inspectContent
|
|
2028
|
+
? await options.inspectContent(signal, durableBlockingRun?.runId)
|
|
2029
|
+
: 'allowed';
|
|
2030
|
+
if (inspection !== 'allowed') {
|
|
2031
|
+
await settle({
|
|
2032
|
+
status: 'discarded',
|
|
2033
|
+
deliveryReason: inspection === 'denied'
|
|
2034
|
+
? 'content-policy-denied'
|
|
2035
|
+
: 'content-policy-error',
|
|
2036
|
+
});
|
|
2037
|
+
return signalContentPolicyResponse(inspection);
|
|
2038
|
+
}
|
|
2039
|
+
const sent = await sendWithoutWake(agent, (sendOptions) => agent.sendSignal(signal, sendOptions), { threadId, resourceId, ifActive, ifIdle: 'persist' }, options);
|
|
2040
|
+
const decision = recordValue(sent.decision);
|
|
2041
|
+
const action = decision?.action;
|
|
2042
|
+
if (action === 'deliver' ||
|
|
2043
|
+
(action === 'persist' && sent.memoryAvailable)) {
|
|
2044
|
+
accepted = {
|
|
2045
|
+
signalId: sent.signal.id,
|
|
2046
|
+
delivery: { ...decision, signalId: sent.signal.id },
|
|
2047
|
+
};
|
|
2048
|
+
const record = await settle({
|
|
2049
|
+
status: 'delivered',
|
|
2050
|
+
deliveredSignalId: accepted.signalId,
|
|
2051
|
+
});
|
|
2052
|
+
return json({ record, delivery: accepted.delivery });
|
|
2053
|
+
}
|
|
2054
|
+
const cause = (action === 'persist' || action === 'discard') && !sent.memoryAvailable
|
|
2055
|
+
? 'memory-unavailable'
|
|
2056
|
+
: action === 'blocked'
|
|
2057
|
+
? 'thread-blocked'
|
|
2058
|
+
: 'delivery-failed';
|
|
2059
|
+
await settle({ status: 'discarded', deliveryReason: cause });
|
|
2060
|
+
if (cause === 'delivery-failed') {
|
|
2061
|
+
throw new Error(`owner notification was not delivered (${String(action ?? 'unknown')})`);
|
|
2062
|
+
}
|
|
2063
|
+
return ownerNotificationRefusal(cause);
|
|
2064
|
+
}
|
|
2065
|
+
catch (error) {
|
|
2066
|
+
if (isExecutionFenceRefusal(error))
|
|
2067
|
+
throw error;
|
|
2068
|
+
if (accepted !== undefined) {
|
|
2069
|
+
const record = await settle({
|
|
2070
|
+
status: 'delivered',
|
|
2071
|
+
deliveredSignalId: accepted.signalId,
|
|
2072
|
+
});
|
|
2073
|
+
return json({ record, delivery: accepted.delivery });
|
|
2074
|
+
}
|
|
2075
|
+
if (!settled) {
|
|
2076
|
+
await settle({ status: 'discarded', deliveryReason: 'delivery-failed' });
|
|
2077
|
+
}
|
|
2078
|
+
throw error;
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
1890
2081
|
//# sourceMappingURL=thread-do-routes.js.map
|