@proofoftech/flowsafe 0.21.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 +73 -0
- package/README.md +25 -12
- 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 +108 -58
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +11 -9
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +134 -96
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +424 -282
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/approval-api/actor-context.js +3 -3
- package/dist/approval-api/actor-context.js.map +1 -1
- package/dist/approval-api/service.d.ts +6 -9
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +6 -9
- package/dist/approval-api/service.js.map +1 -1
- package/dist/background-tasks/d1-storage.js +1 -1
- package/dist/background-tasks/d1-storage.js.map +1 -1
- package/dist/background-tasks/host.d.ts.map +1 -1
- package/dist/background-tasks/host.js +3 -2
- package/dist/background-tasks/host.js.map +1 -1
- package/dist/do-runner/d1-storage.d.ts +4 -2
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +4 -2
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +22 -22
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-context.d.ts +5 -1
- package/dist/do-runner/execution-context.d.ts.map +1 -1
- package/dist/do-runner/execution-context.js +5 -1
- package/dist/do-runner/execution-context.js.map +1 -1
- package/dist/do-runner/execution-fence.js +2 -2
- package/dist/do-runner/execution-fence.js.map +1 -1
- package/dist/do-runner/run-lifecycle.js +6 -6
- package/dist/do-runner/run-lifecycle.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/do-runner/start-idempotency.js +4 -4
- package/dist/do-runner/start-idempotency.js.map +1 -1
- package/dist/host-kit/approval-bridge.d.ts +8 -8
- package/dist/host-kit/approval-bridge.js +8 -8
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +5 -0
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/schedules/schedules-d1.js +1 -1
- package/dist/schedules/tick.d.ts +1 -8
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +8 -19
- package/dist/schedules/tick.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/d1-shared.js +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 +1 -12
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +0 -53
- package/dist/signals/notification-dispatch.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 +411 -230
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +14 -9
- package/scripts/seed-deployment-identity.mjs +25 -11
- package/patches/@mastra__core@1.53.0.patch +0 -54
|
@@ -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
|
|
@@ -32,7 +27,7 @@ import { admitsExistingRun, DoStatusError, ExecutionFencedError, executionFenced
|
|
|
32
27
|
import { internalErrorResponse } from '../internal-error-response.js';
|
|
33
28
|
import { positiveSafeInteger } from '../numeric-config.js';
|
|
34
29
|
import { createScheduleAgentDispatchReceipt, } from '../schedules/schedules-d1.js';
|
|
35
|
-
import {
|
|
30
|
+
import { captureNotificationDeliverySelection, captureNotificationDeliveryStorage, DEFAULT_MAX_NOTIFICATION_DELIVERY_ATTEMPTS, MAX_NOTIFICATION_DISPATCH_IDS, planNotificationDispatch, recordNotificationDeliveryFailure, reportNotificationDeliveryError, } from './notification-dispatch.js';
|
|
36
31
|
/**
|
|
37
32
|
* The idle-thread delivery behavior a send may ask for. `wake` starts a run
|
|
38
33
|
* after consulting the run cap; `persist` writes the signal to the durable
|
|
@@ -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)
|
|
@@ -563,7 +566,6 @@ async function handleNotificationDispatch(options) {
|
|
|
563
566
|
requestedBatchThreadState !== 'idle') {
|
|
564
567
|
return json({ error: 'batchThreadState must be null, active, or idle' }, 400);
|
|
565
568
|
}
|
|
566
|
-
assertNotificationSourceKeysPatched();
|
|
567
569
|
const deliveryStorage = captureNotificationDeliveryStorage(options.storage);
|
|
568
570
|
const selections = [];
|
|
569
571
|
// A record settles once: an already-discarded record must not be counted
|
|
@@ -679,13 +681,13 @@ async function handleNotificationDispatch(options) {
|
|
|
679
681
|
persistenceAllowed: options.persistenceAllowed,
|
|
680
682
|
memoryAvailable: options.memoryAvailable,
|
|
681
683
|
signal: deliverableSignal,
|
|
682
|
-
deliverActive: (runId,
|
|
684
|
+
deliverActive: (runId, activeMemoryAvailable, resolvedActiveBehavior) => options.agent.sendSignal(deliverableSignal, {
|
|
683
685
|
runId,
|
|
684
686
|
threadId: options.threadId,
|
|
685
687
|
resourceId,
|
|
686
|
-
ifActive: { behavior:
|
|
688
|
+
ifActive: { behavior: resolvedActiveBehavior },
|
|
687
689
|
ifIdle: {
|
|
688
|
-
behavior:
|
|
690
|
+
behavior: activeMemoryAvailable && options.persistenceAllowed
|
|
689
691
|
? 'persist'
|
|
690
692
|
: 'discard',
|
|
691
693
|
},
|
|
@@ -726,7 +728,9 @@ async function handleNotificationDispatch(options) {
|
|
|
726
728
|
const result = options.agent.sendSignal(signal, {
|
|
727
729
|
threadId: options.threadId,
|
|
728
730
|
resourceId,
|
|
729
|
-
ifActive: {
|
|
731
|
+
ifActive: {
|
|
732
|
+
behavior: activeBehaviorForRun('deliver', durableBlockingRun),
|
|
733
|
+
},
|
|
730
734
|
ifIdle: { behavior: 'persist' },
|
|
731
735
|
});
|
|
732
736
|
await result.accepted;
|
|
@@ -880,14 +884,8 @@ async function handleNotificationDispatch(options) {
|
|
|
880
884
|
});
|
|
881
885
|
}
|
|
882
886
|
/**
|
|
883
|
-
* Resolve the idle behavior a body asked for. A `wake` STARTS a run, so
|
|
884
|
-
*
|
|
885
|
-
* principal may persist and the agent has memory; otherwise the route answers
|
|
886
|
-
* `persistence-forbidden` or `memory-unavailable` instead of silently dropping
|
|
887
|
-
* the signal:
|
|
888
|
-
* - the agent must be RUNTIME-DRIVEN (its stream re-enters RunnerRuntime, not
|
|
889
|
-
* the default engine) — else `wakeRefused:'not-runtime-driven'`;
|
|
890
|
-
* - 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.
|
|
891
889
|
*/
|
|
892
890
|
function requestedIdle(body) {
|
|
893
891
|
const requested = body.ifIdle;
|
|
@@ -896,6 +894,34 @@ function requestedIdle(body) {
|
|
|
896
894
|
? requested
|
|
897
895
|
: 'persist';
|
|
898
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
|
+
}
|
|
899
925
|
function principalMismatchResponse(runId) {
|
|
900
926
|
return json({
|
|
901
927
|
decision: {
|
|
@@ -908,34 +934,14 @@ function principalMismatchResponse(runId) {
|
|
|
908
934
|
}
|
|
909
935
|
/**
|
|
910
936
|
* Report a lazily computed missing-memory gate after content inspection, only
|
|
911
|
-
* where a memory write would otherwise disappear.
|
|
912
|
-
* inbox recording never use this response. On an active thread it is returned
|
|
913
|
-
* for a persist outcome that would otherwise be silently dropped — an explicit
|
|
914
|
-
* `ifActive: 'persist'`, or the stale-active-id idle fall-through — and by
|
|
915
|
-
* `/state`, whose pre-send gate replaces core's hard memory requirement rather
|
|
916
|
-
* than covering a dropped write. A default or `ifIdle: 'persist'` request to
|
|
917
|
-
* `/signal/message` or `/signal` still delivers into an active run without
|
|
918
|
-
* memory; the memory gate responds only when core's outcome for the request
|
|
919
|
-
* replaced a persist (an idle discard substituted for a requested persist, or
|
|
920
|
-
* an active persist that no memory could write).
|
|
937
|
+
* where a memory write would otherwise disappear.
|
|
921
938
|
*/
|
|
922
939
|
function memoryUnavailableResponse() {
|
|
923
940
|
return json({
|
|
924
941
|
decision: { action: 'discard', reason: 'memory-unavailable' },
|
|
925
942
|
});
|
|
926
943
|
}
|
|
927
|
-
/**
|
|
928
|
-
* Report route-specific persistence authorization failures.
|
|
929
|
-
* `/queue` and `/state` refuse every non-owner request before sending.
|
|
930
|
-
* `/signal/message` and `/signal` refuse a default or requested `ifIdle: 'persist'`;
|
|
931
|
-
* `/signal` also degrades a requested `ifActive: 'persist'`.
|
|
932
|
-
* `/notification` never refuses because a non-owner is record-only for the
|
|
933
|
-
* dispatcher.
|
|
934
|
-
* Wake handling for `/signal/message`, `/signal`, `/signal/schedule`, and the
|
|
935
|
-
* notification dispatch lane returns this response from `handleWake` when a
|
|
936
|
-
* refused or capped wake, or a stale-active-id fall-through, would otherwise
|
|
937
|
-
* persist for a non-owner.
|
|
938
|
-
*/
|
|
944
|
+
/** Report route-specific persistence authorization failures. */
|
|
939
945
|
function persistenceForbiddenResponse(options) {
|
|
940
946
|
return json({
|
|
941
947
|
decision: { action: 'discard', reason: 'persistence-forbidden' },
|
|
@@ -978,12 +984,14 @@ async function handleWake(options) {
|
|
|
978
984
|
const memoryAvailable = await options.memoryAvailable();
|
|
979
985
|
await options.proof?.check(admitted);
|
|
980
986
|
options.proof?.assertActive(admitted);
|
|
981
|
-
const
|
|
987
|
+
const activeBehavior = activeBehaviorForRun(options.activeBehavior ?? 'deliver', durableBlockingRun);
|
|
988
|
+
const deliveredActiveBehavior = deliverableActiveBehavior(activeBehavior, options.persistenceAllowed);
|
|
989
|
+
const delivered = options.deliverActive(activeRunId, memoryAvailable, deliveredActiveBehavior);
|
|
982
990
|
const decision = await delivered.accepted;
|
|
983
991
|
if (delivered.persisted)
|
|
984
992
|
await delivered.persisted;
|
|
985
993
|
const action = recordValue(decision)?.action;
|
|
986
|
-
if (action === 'discard' &&
|
|
994
|
+
if (action === 'discard' && options.activeBehavior !== 'discard') {
|
|
987
995
|
return options.persistenceAllowed
|
|
988
996
|
? memoryUnavailableResponse()
|
|
989
997
|
: persistenceForbiddenResponse({ capped: false });
|
|
@@ -1031,13 +1039,13 @@ async function handleWake(options) {
|
|
|
1031
1039
|
? !(await options.consultRunCap())
|
|
1032
1040
|
: false;
|
|
1033
1041
|
if (refusal || capped) {
|
|
1034
|
-
//
|
|
1035
|
-
//
|
|
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
|
|
1036
1044
|
// nothing is lost while a deployment finishes its work — but a caller who
|
|
1037
1045
|
// said persistence is forbidden has already declared it does not want its
|
|
1038
1046
|
// signal parked, and honouring the fence by parking it anyway would
|
|
1039
1047
|
// override an authorization decision with an operational one. So it is
|
|
1040
|
-
// discarded,
|
|
1048
|
+
// discarded, and the response SAYS SO: `wakeRefused:
|
|
1041
1049
|
// 'execution-draining'` alongside `action: 'discard'` tells the caller
|
|
1042
1050
|
// exactly which condition dropped it, so a sender that would rather wait
|
|
1043
1051
|
// out the migration can retry instead of assuming delivery.
|
|
@@ -1150,9 +1158,9 @@ async function handleScheduleSignal(options) {
|
|
|
1150
1158
|
return json({ error: 'invalid schedule signal dispatch' }, 400);
|
|
1151
1159
|
}
|
|
1152
1160
|
const resourceId = options.resourceId;
|
|
1153
|
-
//
|
|
1154
|
-
//
|
|
1155
|
-
//
|
|
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
|
|
1156
1164
|
// unsettled is reserved for outcomes a later tick could still resolve.
|
|
1157
1165
|
const settleDiscard = async () => {
|
|
1158
1166
|
const receipt = createScheduleAgentDispatchReceipt('discard', {
|
|
@@ -1246,7 +1254,24 @@ async function handleScheduleSignal(options) {
|
|
|
1246
1254
|
}
|
|
1247
1255
|
return await settleDiscard();
|
|
1248
1256
|
}
|
|
1249
|
-
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 ?? {};
|
|
1250
1275
|
const baseMastra = recordValue(baseProviderOptions.mastra) ?? {};
|
|
1251
1276
|
const signal = {
|
|
1252
1277
|
id: dispatchId,
|
|
@@ -1268,12 +1293,20 @@ async function handleScheduleSignal(options) {
|
|
|
1268
1293
|
},
|
|
1269
1294
|
};
|
|
1270
1295
|
const ifActive = target.ifActive ?? { behavior: 'deliver' };
|
|
1296
|
+
const requestedActiveBehavior = ifActive.behavior ?? 'deliver';
|
|
1297
|
+
const effectiveIfActive = {
|
|
1298
|
+
...ifActive,
|
|
1299
|
+
behavior: activeBehaviorForRun(requestedActiveBehavior, durableBlockingRun),
|
|
1300
|
+
};
|
|
1271
1301
|
const ifIdle = target.ifIdle ?? { behavior: 'wake' };
|
|
1272
1302
|
const localActiveRunId = activeThreadRunIdOf(options.agent, options.threadId, resourceId);
|
|
1273
1303
|
const persistenceRequested = localActiveRunId
|
|
1274
|
-
?
|
|
1304
|
+
? effectiveIfActive.behavior === 'persist'
|
|
1275
1305
|
: (ifIdle.behavior ?? 'wake') === 'persist';
|
|
1276
|
-
|
|
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
|
|
1277
1310
|
? await options.schedulePersistenceAllowed({
|
|
1278
1311
|
scheduleId,
|
|
1279
1312
|
dispatchId,
|
|
@@ -1338,8 +1371,16 @@ async function handleScheduleSignal(options) {
|
|
|
1338
1371
|
const signalTarget = {
|
|
1339
1372
|
threadId: options.threadId,
|
|
1340
1373
|
resourceId,
|
|
1341
|
-
ifActive
|
|
1342
|
-
|
|
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
|
+
},
|
|
1343
1384
|
};
|
|
1344
1385
|
let decision;
|
|
1345
1386
|
let signalId;
|
|
@@ -1374,18 +1415,20 @@ async function handleScheduleSignal(options) {
|
|
|
1374
1415
|
persistenceAllowed,
|
|
1375
1416
|
memoryAvailable: options.memoryAvailable,
|
|
1376
1417
|
signal: idleSignal,
|
|
1418
|
+
activeBehavior: requestedActiveBehavior,
|
|
1377
1419
|
runId,
|
|
1378
1420
|
scheduleId,
|
|
1379
1421
|
dispatchId,
|
|
1380
1422
|
safeContext: { ...requestContext, ...idleRequestContext },
|
|
1381
|
-
|
|
1382
|
-
deliverActive: (activeRunId, memoryAvailable) => options.agent.sendSignal(deliverableSignal, {
|
|
1423
|
+
deliverActive: (activeRunId, activeMemoryAvailable, resolvedActiveBehavior) => options.agent.sendSignal(deliverableSignal, {
|
|
1383
1424
|
runId: activeRunId,
|
|
1384
1425
|
threadId: options.threadId,
|
|
1385
1426
|
resourceId,
|
|
1386
|
-
ifActive,
|
|
1427
|
+
ifActive: { ...ifActive, behavior: resolvedActiveBehavior },
|
|
1387
1428
|
ifIdle: {
|
|
1388
|
-
behavior:
|
|
1429
|
+
behavior: activeMemoryAvailable && persistenceAllowed
|
|
1430
|
+
? 'persist'
|
|
1431
|
+
: 'discard',
|
|
1389
1432
|
},
|
|
1390
1433
|
}),
|
|
1391
1434
|
persist: () => options.agent.sendSignal(deliverableSignal, {
|
|
@@ -1450,8 +1493,7 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
|
|
|
1450
1493
|
const message = options.persistenceAllowed
|
|
1451
1494
|
? baseMessage
|
|
1452
1495
|
: markPersistenceForbidden(baseMessage);
|
|
1453
|
-
// sendMessage requires a resourceId+threadId target for its idle branch
|
|
1454
|
-
// host has not wired a resourceId, only the active/queue path is reachable.
|
|
1496
|
+
// sendMessage requires a resourceId+threadId target for its idle branch.
|
|
1455
1497
|
if (resourceId === undefined) {
|
|
1456
1498
|
return json({
|
|
1457
1499
|
error: 'this thread has no resourceId wired; message delivery needs one',
|
|
@@ -1486,15 +1528,15 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
|
|
|
1486
1528
|
persistenceAllowed: options.persistenceAllowed,
|
|
1487
1529
|
memoryAvailable: options.memoryAvailable,
|
|
1488
1530
|
message,
|
|
1489
|
-
deliverActive: (runId,
|
|
1531
|
+
deliverActive: (runId, activeMemoryAvailable, resolvedActiveBehavior) => agent.sendMessage(message, {
|
|
1490
1532
|
runId,
|
|
1491
1533
|
threadId,
|
|
1492
1534
|
resourceId,
|
|
1493
|
-
ifActive: { behavior:
|
|
1535
|
+
ifActive: { behavior: resolvedActiveBehavior },
|
|
1494
1536
|
// A stale active id can disappear before core sends. Persist only
|
|
1495
1537
|
// when both the memory and authorization gates allow the write.
|
|
1496
1538
|
ifIdle: {
|
|
1497
|
-
behavior:
|
|
1539
|
+
behavior: activeMemoryAvailable && options.persistenceAllowed
|
|
1498
1540
|
? 'persist'
|
|
1499
1541
|
: 'discard',
|
|
1500
1542
|
},
|
|
@@ -1509,27 +1551,16 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
|
|
|
1509
1551
|
if (behavior === 'persist' && !options.persistenceAllowed) {
|
|
1510
1552
|
return persistenceForbiddenResponse({ capped: false });
|
|
1511
1553
|
}
|
|
1512
|
-
const
|
|
1513
|
-
|
|
1514
|
-
options.
|
|
1515
|
-
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), {
|
|
1516
1558
|
threadId,
|
|
1517
1559
|
resourceId,
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
await result.persisted;
|
|
1523
|
-
if (behavior === 'persist' &&
|
|
1524
|
-
!memoryAvailable &&
|
|
1525
|
-
recordValue(decision)?.action === 'discard') {
|
|
1526
|
-
return memoryUnavailableResponse();
|
|
1527
|
-
}
|
|
1528
|
-
return json({
|
|
1529
|
-
decision,
|
|
1530
|
-
capped: false,
|
|
1531
|
-
signalId: result.signal.id,
|
|
1532
|
-
});
|
|
1560
|
+
ifActive: deliveredActiveBehavior,
|
|
1561
|
+
ifIdle: behavior,
|
|
1562
|
+
}, options);
|
|
1563
|
+
return noWakeResponse(sent, behavior, deliveredActiveBehavior, activePersistenceForbidden);
|
|
1533
1564
|
}
|
|
1534
1565
|
async function handleQueue(agent, body, threadId, resourceId, options) {
|
|
1535
1566
|
if (!isContents(body.contents)) {
|
|
@@ -1575,11 +1606,16 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1575
1606
|
// Route-level tagName defense: reject a non-XML-name tagName HERE with a
|
|
1576
1607
|
// 400, rather than letting core's signalToXmlMarkup throw at render time inside
|
|
1577
1608
|
// the agent turn. Core still escapes contents/attribute values and re-validates
|
|
1578
|
-
// names
|
|
1609
|
+
// names.
|
|
1579
1610
|
if (typeof body.tagName === 'string' &&
|
|
1580
1611
|
!XML_NAME_PATTERN.test(body.tagName)) {
|
|
1581
1612
|
return json({ error: 'tagName is not a valid XML name' }, 400);
|
|
1582
1613
|
}
|
|
1614
|
+
if (resourceId === undefined) {
|
|
1615
|
+
return json({
|
|
1616
|
+
error: 'this thread has no resourceId wired; signal delivery needs one',
|
|
1617
|
+
}, 409);
|
|
1618
|
+
}
|
|
1583
1619
|
const baseSignal = {
|
|
1584
1620
|
type: 'reactive',
|
|
1585
1621
|
contents: body.contents,
|
|
@@ -1593,10 +1629,6 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1593
1629
|
ACTIVE_BEHAVIORS.includes(body.ifActive)
|
|
1594
1630
|
? body.ifActive
|
|
1595
1631
|
: 'deliver';
|
|
1596
|
-
const activePersistenceForbidden = activeBehavior === 'persist' && !options.persistenceAllowed;
|
|
1597
|
-
const deliveredActiveBehavior = activePersistenceForbidden
|
|
1598
|
-
? 'discard'
|
|
1599
|
-
: activeBehavior;
|
|
1600
1632
|
const durableBlockingRun = await options.blockingRun?.();
|
|
1601
1633
|
if (durableBlockingRun &&
|
|
1602
1634
|
!samePrincipal(durableBlockingRun.principal, options.principal)) {
|
|
@@ -1605,22 +1637,9 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1605
1637
|
const policyRefusal = await contentPolicyRefusal(options.inspectContent, createSignal(signal), durableBlockingRun?.runId);
|
|
1606
1638
|
if (policyRefusal)
|
|
1607
1639
|
return policyRefusal;
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
if (!isPathSafeId(runId)) {
|
|
1612
|
-
throw new Error('thread signal generated a non-path-safe run id');
|
|
1613
|
-
}
|
|
1614
|
-
await options.proof?.check();
|
|
1615
|
-
options.proof?.assertActive();
|
|
1616
|
-
const result = agent.sendSignal(signal, {
|
|
1617
|
-
threadId,
|
|
1618
|
-
runId,
|
|
1619
|
-
ifActive: { behavior: deliveredActiveBehavior },
|
|
1620
|
-
});
|
|
1621
|
-
const decision = await result.accepted;
|
|
1622
|
-
return json({ decision, signalId: result.signal.id });
|
|
1623
|
-
}
|
|
1640
|
+
const effectiveActiveBehavior = activeBehaviorForRun(activeBehavior, durableBlockingRun);
|
|
1641
|
+
const activePersistenceForbidden = effectiveActiveBehavior === 'persist' && !options.persistenceAllowed;
|
|
1642
|
+
const deliveredActiveBehavior = deliverableActiveBehavior(effectiveActiveBehavior, options.persistenceAllowed);
|
|
1624
1643
|
const behavior = requestedIdle(body);
|
|
1625
1644
|
if (behavior === 'wake') {
|
|
1626
1645
|
return handleWake({
|
|
@@ -1642,14 +1661,14 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1642
1661
|
persistenceAllowed: options.persistenceAllowed,
|
|
1643
1662
|
memoryAvailable: options.memoryAvailable,
|
|
1644
1663
|
signal,
|
|
1645
|
-
|
|
1646
|
-
deliverActive: (runId,
|
|
1664
|
+
activeBehavior,
|
|
1665
|
+
deliverActive: (runId, activeMemoryAvailable, resolvedActiveBehavior) => agent.sendSignal(signal, {
|
|
1647
1666
|
runId,
|
|
1648
1667
|
threadId,
|
|
1649
1668
|
resourceId,
|
|
1650
|
-
ifActive: { behavior:
|
|
1669
|
+
ifActive: { behavior: resolvedActiveBehavior },
|
|
1651
1670
|
ifIdle: {
|
|
1652
|
-
behavior:
|
|
1671
|
+
behavior: activeMemoryAvailable && options.persistenceAllowed
|
|
1653
1672
|
? 'persist'
|
|
1654
1673
|
: 'discard',
|
|
1655
1674
|
},
|
|
@@ -1665,19 +1684,16 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1665
1684
|
if (behavior === 'persist' && !options.persistenceAllowed) {
|
|
1666
1685
|
return persistenceForbiddenResponse({ capped: false });
|
|
1667
1686
|
}
|
|
1668
|
-
const
|
|
1669
|
-
const wasActive = activeThreadRunIdOf(agent, threadId, resourceId) !== undefined;
|
|
1670
|
-
await options.proof?.check();
|
|
1671
|
-
options.proof?.assertActive();
|
|
1672
|
-
const result = agent.sendSignal(signal, {
|
|
1687
|
+
const sent = await sendWithoutWake(agent, (sendOptions) => agent.sendSignal(signal, sendOptions), {
|
|
1673
1688
|
threadId,
|
|
1674
1689
|
resourceId,
|
|
1675
|
-
ifActive:
|
|
1676
|
-
ifIdle:
|
|
1677
|
-
});
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
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;
|
|
1681
1697
|
const action = recordValue(decision)?.action;
|
|
1682
1698
|
if (action === 'persist' && !memoryAvailable) {
|
|
1683
1699
|
return memoryUnavailableResponse();
|
|
@@ -1696,9 +1712,31 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
|
|
|
1696
1712
|
return json({
|
|
1697
1713
|
decision,
|
|
1698
1714
|
capped: false,
|
|
1699
|
-
signalId:
|
|
1715
|
+
signalId: signal.id,
|
|
1700
1716
|
});
|
|
1701
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
|
+
}
|
|
1702
1740
|
async function handleState(agent, body, threadId, resourceId, options) {
|
|
1703
1741
|
if (typeof body.id !== 'string' || typeof body.cacheKey !== 'string') {
|
|
1704
1742
|
return json({ error: 'id and cacheKey are required for a state signal' }, 400);
|
|
@@ -1768,6 +1806,27 @@ async function handleState(agent, body, threadId, resourceId, options) {
|
|
|
1768
1806
|
...(!options.runtimeDriven ? { degraded } : {}),
|
|
1769
1807
|
});
|
|
1770
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
|
+
}
|
|
1771
1830
|
async function handleNotification(agent, body, threadId, resourceId, resolveNotificationsStorage, options) {
|
|
1772
1831
|
if (typeof body.source !== 'string' ||
|
|
1773
1832
|
typeof body.kind !== 'string' ||
|
|
@@ -1791,41 +1850,30 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
|
|
|
1791
1850
|
: {}),
|
|
1792
1851
|
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
1793
1852
|
};
|
|
1794
|
-
// Owners use core's delivery policy. The inbox row is the durable artifact,
|
|
1795
|
-
// so this route has no memory gate: without agent memory, a model-visible
|
|
1796
|
-
// persist is best-effort and the row stays pending. Non-owner notifications
|
|
1797
|
-
// are record-only here: the host's createNotificationDispatchTick delivers
|
|
1798
|
-
// them later (agent-starter runs it every 60 seconds). A host without that
|
|
1799
|
-
// tick records but never delivers them; the spike intentionally has no tick
|
|
1800
|
-
// and its provider probes assert only the inbox row. This branch bypasses an
|
|
1801
|
-
// agent-level notifications.deliveryPolicy and
|
|
1802
|
-
// __ensureNotificationDispatchReady; branded hosts cannot reach either seam
|
|
1803
|
-
// through the wrapped agent anyway.
|
|
1804
1853
|
// The target requires a resourceId because the inbox is keyed by its owner.
|
|
1805
|
-
// Core's default policy does not summarize an idle thread immediately. A
|
|
1806
|
-
// medium-priority delivery can sample active, then fall idle across its
|
|
1807
|
-
// awaits. For a branded runner the resulting forced wake reaches the terminal
|
|
1808
|
-
// refusal path while the created record stays pending with its summary signal
|
|
1809
|
-
// id. An unbranded agent keeps core's own below-boundary run start; no shipped
|
|
1810
|
-
// host uses that degraded configuration.
|
|
1811
1854
|
if (resourceId === undefined) {
|
|
1812
1855
|
return json({ error: 'this thread has no resourceId wired; notifications need one' }, 409);
|
|
1813
1856
|
}
|
|
1814
|
-
//
|
|
1815
|
-
//
|
|
1816
|
-
//
|
|
1817
|
-
//
|
|
1818
|
-
//
|
|
1819
|
-
//
|
|
1820
|
-
//
|
|
1821
|
-
//
|
|
1822
|
-
//
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
//
|
|
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.
|
|
1829
1877
|
if (options.inspectContent) {
|
|
1830
1878
|
const prospectiveRecord = {
|
|
1831
1879
|
id: 'prospective',
|
|
@@ -1844,11 +1892,11 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
|
|
|
1844
1892
|
createdAt: new Date(0),
|
|
1845
1893
|
updatedAt: new Date(0),
|
|
1846
1894
|
};
|
|
1847
|
-
// Core
|
|
1848
|
-
//
|
|
1849
|
-
//
|
|
1850
|
-
//
|
|
1851
|
-
//
|
|
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'`.
|
|
1852
1900
|
for (const candidate of [
|
|
1853
1901
|
createNotificationSignal({ ...prospectiveRecord, status: 'delivered' }),
|
|
1854
1902
|
createNotificationSummarySignal(summarizeNotifications([prospectiveRecord])),
|
|
@@ -1858,11 +1906,24 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
|
|
|
1858
1906
|
return policyRefusal;
|
|
1859
1907
|
}
|
|
1860
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.
|
|
1861
1914
|
if (!options.persistenceAllowed) {
|
|
1862
1915
|
const storage = await resolveNotificationsStorage?.();
|
|
1863
1916
|
if (!storage) {
|
|
1864
1917
|
return json({ error: 'notifications storage unavailable' }, 409);
|
|
1865
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
|
+
}
|
|
1866
1927
|
await options.proof?.check();
|
|
1867
1928
|
options.proof?.assertActive();
|
|
1868
1929
|
const record = await storage.createNotification({
|
|
@@ -1877,24 +1938,144 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
|
|
|
1877
1938
|
delivery: { action: 'deferred', reason: 'dispatcher' },
|
|
1878
1939
|
});
|
|
1879
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
|
+
}
|
|
1880
1954
|
await options.proof?.check();
|
|
1881
1955
|
options.proof?.assertActive();
|
|
1882
1956
|
const result = await agent.sendNotificationSignal(notification, {
|
|
1883
1957
|
threadId,
|
|
1884
1958
|
resourceId,
|
|
1885
|
-
|
|
1886
|
-
? { ifActive: { behavior: 'persist' } }
|
|
1887
|
-
: {}),
|
|
1959
|
+
ifActive: { behavior: 'persist' },
|
|
1888
1960
|
ifIdle: { behavior: 'persist' },
|
|
1889
1961
|
});
|
|
1890
1962
|
if (result.persisted)
|
|
1891
1963
|
await result.persisted;
|
|
1892
1964
|
const response = {
|
|
1893
1965
|
record: result,
|
|
1894
|
-
|
|
1966
|
+
degraded: 'not-runtime-driven',
|
|
1895
1967
|
};
|
|
1896
1968
|
if (result.accepted)
|
|
1897
1969
|
response.delivery = await result.accepted;
|
|
1898
1970
|
return json(response);
|
|
1899
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
|
+
}
|
|
1900
2081
|
//# sourceMappingURL=thread-do-routes.js.map
|