@proofoftech/flowsafe 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/README.md +104 -5
  3. package/deployment-identity-protocol.d.mts +17 -0
  4. package/deployment-identity-protocol.mjs +32 -0
  5. package/dist/agent-host/catalog.js +1 -1
  6. package/dist/agent-host/catalog.js.map +1 -1
  7. package/dist/agent-host/thread-host.d.ts.map +1 -1
  8. package/dist/agent-host/thread-host.js +30 -4
  9. package/dist/agent-host/thread-host.js.map +1 -1
  10. package/dist/agent-runner/durable-agent-runner.d.ts +251 -20
  11. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  12. package/dist/agent-runner/durable-agent-runner.js +657 -57
  13. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  14. package/dist/deployment-identity-protocol.d.ts +1 -1
  15. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  16. package/dist/deployment-identity-protocol.js +1 -1
  17. package/dist/deployment-identity-protocol.js.map +1 -1
  18. package/dist/do-runner/deployment-identity.d.ts +2 -11
  19. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  20. package/dist/do-runner/deployment-identity.js +2 -29
  21. package/dist/do-runner/deployment-identity.js.map +1 -1
  22. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  23. package/dist/do-runner/do-error-response.js +9 -1
  24. package/dist/do-runner/do-error-response.js.map +1 -1
  25. package/dist/do-runner/durable-object.d.ts +13 -1
  26. package/dist/do-runner/durable-object.d.ts.map +1 -1
  27. package/dist/do-runner/durable-object.js +825 -29
  28. package/dist/do-runner/durable-object.js.map +1 -1
  29. package/dist/do-runner/index.d.ts +3 -1
  30. package/dist/do-runner/index.d.ts.map +1 -1
  31. package/dist/do-runner/index.js +2 -1
  32. package/dist/do-runner/index.js.map +1 -1
  33. package/dist/do-runner/runtime.d.ts +43 -0
  34. package/dist/do-runner/runtime.d.ts.map +1 -1
  35. package/dist/do-runner/runtime.js +67 -0
  36. package/dist/do-runner/runtime.js.map +1 -1
  37. package/dist/do-runner/suspension-deadline.d.ts +184 -0
  38. package/dist/do-runner/suspension-deadline.d.ts.map +1 -0
  39. package/dist/do-runner/suspension-deadline.js +452 -0
  40. package/dist/do-runner/suspension-deadline.js.map +1 -0
  41. package/dist/do-runner/thread-do.d.ts +5 -1
  42. package/dist/do-runner/thread-do.d.ts.map +1 -1
  43. package/dist/do-runner/thread-do.js +24 -1
  44. package/dist/do-runner/thread-do.js.map +1 -1
  45. package/dist/signal-providers/delivery.d.ts +32 -0
  46. package/dist/signal-providers/delivery.d.ts.map +1 -1
  47. package/dist/signal-providers/delivery.js +45 -0
  48. package/dist/signal-providers/delivery.js.map +1 -1
  49. package/dist/signal-providers/host-do.d.ts +11 -0
  50. package/dist/signal-providers/host-do.d.ts.map +1 -1
  51. package/dist/signal-providers/host-do.js +48 -14
  52. package/dist/signal-providers/host-do.js.map +1 -1
  53. package/dist/signal-providers/provider.d.ts +8 -0
  54. package/dist/signal-providers/provider.d.ts.map +1 -1
  55. package/dist/signal-providers/provider.js.map +1 -1
  56. package/dist/signal-providers/webhook-route.d.ts +6 -0
  57. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  58. package/dist/signal-providers/webhook-route.js +109 -21
  59. package/dist/signal-providers/webhook-route.js.map +1 -1
  60. package/dist/signals/client.d.ts +19 -5
  61. package/dist/signals/client.d.ts.map +1 -1
  62. package/dist/signals/client.js +25 -17
  63. package/dist/signals/client.js.map +1 -1
  64. package/dist/signals/index.d.ts +1 -1
  65. package/dist/signals/index.d.ts.map +1 -1
  66. package/dist/signals/index.js.map +1 -1
  67. package/dist/signals/notification-dispatch.d.ts +2 -0
  68. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  69. package/dist/signals/notification-dispatch.js +3 -0
  70. package/dist/signals/notification-dispatch.js.map +1 -1
  71. package/dist/signals/router.d.ts.map +1 -1
  72. package/dist/signals/router.js +3 -2
  73. package/dist/signals/router.js.map +1 -1
  74. package/dist/signals/thread-do-routes.d.ts +48 -10
  75. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  76. package/dist/signals/thread-do-routes.js +624 -118
  77. package/dist/signals/thread-do-routes.js.map +1 -1
  78. package/package.json +8 -6
@@ -22,8 +22,10 @@
22
22
  //
23
23
  // core's `agentThreadStreamRuntime` is NOT on the package exports map, so these
24
24
  // routes drive the PUBLIC Agent methods only (never a deep dist import — R-001).
25
+ import { createMessageSignal, createSignal, resolveDeliveryAttributes, signalToXmlMarkup, } from '@mastra/core/agent';
25
26
  import { createNotificationSignal, createNotificationSummarySignal, summarizeNotifications, } from '@mastra/core/notifications';
26
27
  import { RequestContext } from '@mastra/core/request-context';
28
+ import { FLOWSAFE_PERSISTENCE_FORBIDDEN } from '../agent-runner/durable-agent-runner.js';
27
29
  import { isRuntimeDrivenAgent, } from '../agent-runner/index.js';
28
30
  import { samePrincipal, } from '../approval-api/index.js';
29
31
  import { DoStatusError, isPathSafeId, } from '../do-runner/index.js';
@@ -33,13 +35,33 @@ import { deferNotificationAfterFailure, MAX_NOTIFICATION_DISPATCH_IDS, planNotif
33
35
  /**
34
36
  * The idle-thread delivery behavior a send may ask for. `wake` starts a run
35
37
  * after consulting the run cap; `persist` writes the signal to the durable
36
- * inbox for the next turn; `discard` drops it. Mirrors core
38
+ * inbox for the next host-started turn; `discard` drops it. Mirrors core
37
39
  * `AgentSignalIdleBehavior`, re-declared so the route body validates the wire
38
40
  * value rather than trusting an `as`.
39
41
  */
40
42
  export const IDLE_BEHAVIORS = ['wake', 'persist', 'discard'];
41
43
  /** The active-thread delivery behavior. Mirrors core `AgentSignalActiveBehavior`. */
42
44
  export const ACTIVE_BEHAVIORS = ['deliver', 'persist', 'discard'];
45
+ /**
46
+ * Put the persistence prohibition in signal metadata so core preserves it
47
+ * through the database round trip without showing it to the model. Attributes
48
+ * are rendered into model-visible markup by `signalToXmlMarkup`; metadata is
49
+ * not.
50
+ */
51
+ function markPersistenceForbidden(input) {
52
+ return {
53
+ ...input,
54
+ metadata: {
55
+ ...input.metadata,
56
+ [FLOWSAFE_PERSISTENCE_FORBIDDEN]: true,
57
+ },
58
+ };
59
+ }
60
+ function activeThreadRunIdOf(agent, threadId, resourceId) {
61
+ return typeof agent.getActiveThreadRunId === 'function'
62
+ ? agent.getActiveThreadRunId({ threadId, resourceId })
63
+ : undefined;
64
+ }
43
65
  function entryPathForSignalRoute(path) {
44
66
  switch (path) {
45
67
  case '/signal/message':
@@ -91,26 +113,84 @@ function isContents(value) {
91
113
  * (and attribute names) inside `signalToXmlMarkup` — MIRRORED here, not
92
114
  * deep-imported: `XML_NAME_PATTERN` / `assertXmlName` are not on core's exports
93
115
  * map. Validating the caller-supplied `tagName` at INGEST turns an invalid one
94
- * into a 400 at the route rather than a
116
+ * into a 400 at the route, and an invalid attribute name into a dropped
117
+ * attributes object (`isAttributes`), rather than a
95
118
  * throw at render time inside the agent turn. Kept byte-identical to core
96
119
  * (chunk `signalToXmlMarkup`: `/^[A-Za-z_][A-Za-z0-9_.-]*$/`); the render test
97
120
  * pins core's own neutralization of contents/attribute values so this
98
121
  * mirror and that layer are checked together.
99
122
  */
100
123
  const XML_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
101
- /** Attributes must be a flat record of primitives (core `AgentSignalAttributes`). */
124
+ /**
125
+ * Attributes must be a flat record of primitives (core `AgentSignalAttributes`)
126
+ * whose rendered KEYS are XML names. Core's `signalAttributesToXml` drops
127
+ * null/undefined entries and then asserts the name of every remaining key, so
128
+ * an unrenderable key would otherwise throw at render time — inside the agent
129
+ * turn, or here at the content gate — long after the route accepted it. A
130
+ * malformed attributes object is dropped whole, exactly as a malformed
131
+ * attribute VALUE already is.
132
+ */
102
133
  function isAttributes(value) {
103
134
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
104
135
  return false;
105
136
  }
106
- return Object.values(value).every((v) => v === null ||
137
+ return Object.entries(value).every(([key, v]) => v === null ||
107
138
  v === undefined ||
108
- typeof v === 'string' ||
109
- typeof v === 'number' ||
110
- typeof v === 'boolean');
139
+ (XML_NAME_PATTERN.test(key) &&
140
+ (typeof v === 'string' ||
141
+ typeof v === 'number' ||
142
+ typeof v === 'boolean')));
143
+ }
144
+ /**
145
+ * Whether already-typed attributes can be rendered — the key half of the
146
+ * `isAttributes` rule, for server-owned records that arrive typed and so need
147
+ * no value check. Absent attributes render fine.
148
+ */
149
+ function renderableAttributes(attributes) {
150
+ if (attributes === undefined)
151
+ return true;
152
+ return Object.entries(attributes).every(([key, value]) => value === null || value === undefined || XML_NAME_PATTERN.test(key));
153
+ }
154
+ async function inspectSignalContent(policy, input, signal, runId) {
155
+ if (typeof signal.contents !== 'string')
156
+ return 'error';
157
+ let text;
158
+ try {
159
+ text = signalToXmlMarkup({
160
+ type: signal.type,
161
+ tagName: signal.tagName,
162
+ attributes: signal.attributes,
163
+ contents: signal.contents,
164
+ });
165
+ }
166
+ catch {
167
+ return 'error';
168
+ }
169
+ try {
170
+ const result = await policy({
171
+ ...input,
172
+ text,
173
+ ...(runId !== undefined ? { runId } : {}),
174
+ });
175
+ if (result?.allowed === true)
176
+ return 'allowed';
177
+ if (result?.allowed === false &&
178
+ (result.outcome === 'denied' || result.outcome === 'error')) {
179
+ return result.outcome;
180
+ }
181
+ }
182
+ catch {
183
+ return 'error';
184
+ }
185
+ return 'error';
186
+ }
187
+ function signalContentPolicyResponse(inspection) {
188
+ return inspection === 'denied'
189
+ ? json({ error: 'signal content denied' }, 422)
190
+ : json({ error: 'signal content policy unavailable' }, 503);
111
191
  }
112
192
  export function createThreadSignalRoutes(options) {
113
- const { resolveAgent, resolveResourceId, consultRunCap, startIdleRun, resolveBlockingRun, serializeDispatch, resolveScheduleRunStatus, resolveScheduleTarget, canPersist, canPersistSchedule, resolveNotificationsStorage, resolveScheduleDispatchStore, } = options;
193
+ const { resolveAgent, resolveResourceId, consultRunCap, startIdleRun, resolveBlockingRun, serializeDispatch, resolveScheduleRunStatus, resolveScheduleTarget, canPersist, canPersistSchedule, resolveNotificationsStorage, resolveScheduleDispatchStore, contentPolicy, } = options;
114
194
  if (resolveBlockingRun && !serializeDispatch) {
115
195
  throw new Error('signal routes require serializeDispatch with resolveBlockingRun');
116
196
  }
@@ -186,6 +266,23 @@ export function createThreadSignalRoutes(options) {
186
266
  agent.__setPubSub(pubsub);
187
267
  const resourceId = resolveResourceId?.(scope);
188
268
  const threadId = scope.threadId;
269
+ let memoryResolution;
270
+ const memoryAvailable = () => {
271
+ memoryResolution ??= (async () => {
272
+ try {
273
+ return (typeof agent.getMemory === 'function' &&
274
+ Boolean(await agent.getMemory()));
275
+ }
276
+ catch {
277
+ console.error(JSON.stringify({
278
+ type: 'signal-memory-resolution-failed',
279
+ threadId,
280
+ }));
281
+ return false;
282
+ }
283
+ })();
284
+ return memoryResolution;
285
+ };
189
286
  const deliveredResourceId = url.searchParams.get('resourceId');
190
287
  if (path === '/signal/notification' &&
191
288
  deliveredResourceId !== null &&
@@ -196,18 +293,51 @@ export function createThreadSignalRoutes(options) {
196
293
  ? () => resolveBlockingRun(scope)
197
294
  : undefined;
198
295
  const persistenceAllowed = canPersist ? await canPersist(scope) : true;
296
+ const inspectContent = contentPolicy
297
+ ? (signal, runId) => inspectSignalContent(contentPolicy, {
298
+ agentId: agent.id,
299
+ threadId,
300
+ ...(resourceId !== undefined ? { resourceId } : {}),
301
+ ...(scope.deploymentTag !== undefined
302
+ ? { deploymentTag: scope.deploymentTag }
303
+ : {}),
304
+ entryPath,
305
+ principal: scope.principal,
306
+ }, signal, runId)
307
+ : undefined;
199
308
  // POST /signal/message — immediate user message (joins the active loop or,
200
309
  // idle, wakes/persists per ifIdle).
201
310
  if (path === '/signal/message') {
202
- return await handleMessage(agent, body, threadId, resourceId, consultRunCap, scope.deploymentTag, runtimeDriven, scope.principal, entryPath, startIdleRun, serializeWake, blockingRun, persistenceAllowed);
311
+ return await handleMessage(agent, body, threadId, resourceId, consultRunCap, scope.deploymentTag, entryPath, startIdleRun, serializeWake, {
312
+ runtimeDriven,
313
+ principal: scope.principal,
314
+ blockingRun,
315
+ persistenceAllowed,
316
+ memoryAvailable,
317
+ inspectContent,
318
+ });
203
319
  }
204
- // POST /signal/queue — deliver on the NEXT turn (never wakes).
320
+ // POST /signal/queue — persisted for the next host-started turn; never
321
+ // wakes, in either state.
205
322
  if (path === '/signal/queue') {
206
- return await handleQueue(agent, body, threadId, resourceId, scope.principal, blockingRun, persistenceAllowed);
323
+ return await handleQueue(agent, body, threadId, resourceId, {
324
+ principal: scope.principal,
325
+ blockingRun,
326
+ persistenceAllowed,
327
+ memoryAvailable,
328
+ inspectContent,
329
+ });
207
330
  }
208
331
  // POST /signal — a system signal (ifActive/ifIdle deliver/persist/discard/wake).
209
332
  if (path === '/signal') {
210
- return await handleSignal(agent, body, threadId, resourceId, consultRunCap, scope.deploymentTag, runtimeDriven, scope.principal, entryPath, startIdleRun, serializeWake, blockingRun, persistenceAllowed);
333
+ return await handleSignal(agent, body, threadId, resourceId, consultRunCap, scope.deploymentTag, entryPath, startIdleRun, serializeWake, {
334
+ runtimeDriven,
335
+ principal: scope.principal,
336
+ blockingRun,
337
+ persistenceAllowed,
338
+ memoryAvailable,
339
+ inspectContent,
340
+ });
211
341
  }
212
342
  if (path === '/signal/schedule') {
213
343
  if (!resolveScheduleDispatchStore) {
@@ -230,6 +360,7 @@ export function createThreadSignalRoutes(options) {
230
360
  serializeWake,
231
361
  blockingRun,
232
362
  persistenceAllowed,
363
+ memoryAvailable,
233
364
  schedulePersistenceAllowed: canPersistSchedule
234
365
  ? (input) => canPersistSchedule(scope, input)
235
366
  : undefined,
@@ -238,11 +369,19 @@ export function createThreadSignalRoutes(options) {
238
369
  : undefined,
239
370
  store: await resolveScheduleDispatchStore(scope),
240
371
  completed: completedScheduleDispatches,
372
+ inspectContent,
241
373
  });
242
374
  }
243
375
  // POST /signal/state — a durable thread-state lane (snapshot/delta).
244
376
  if (path === '/signal/state') {
245
- return await handleState(agent, body, threadId, resourceId);
377
+ return await handleState(agent, body, threadId, resourceId, {
378
+ principal: scope.principal,
379
+ blockingRun,
380
+ persistenceAllowed,
381
+ runtimeDriven,
382
+ memoryAvailable,
383
+ inspectContent,
384
+ });
246
385
  }
247
386
  if (requestedAgentId !== undefined) {
248
387
  if (!resolveNotificationsStorage) {
@@ -262,13 +401,17 @@ export function createThreadSignalRoutes(options) {
262
401
  serializeWake,
263
402
  blockingRun,
264
403
  persistenceAllowed,
404
+ memoryAvailable,
265
405
  storage: await resolveNotificationsStorage(scope),
266
406
  agentId: requestedAgentId,
407
+ inspectContent,
267
408
  }));
268
409
  }
269
410
  // POST /signal/notification — the durable AGENT inbox (mastra_notifications).
270
411
  if (path === '/signal/notification') {
271
- return await serializeNotification(() => handleNotification(agent, body, threadId, resourceId));
412
+ return await serializeNotification(async () => handleNotification(agent, body, threadId, resourceId, resolveNotificationsStorage
413
+ ? () => resolveNotificationsStorage(scope)
414
+ : undefined, { persistenceAllowed, runtimeDriven, inspectContent }));
272
415
  }
273
416
  return json({ error: 'not found' }, 404);
274
417
  }
@@ -367,20 +510,44 @@ async function handleNotificationDispatch(options) {
367
510
  requestedBatchThreadState === 'idle'
368
511
  ? requestedBatchThreadState
369
512
  : durableBlockingRun ||
370
- (typeof options.agent.getActiveThreadRunId === 'function' &&
371
- options.agent.getActiveThreadRunId({
372
- threadId: options.threadId,
373
- resourceId,
374
- }))
513
+ activeThreadRunIdOf(options.agent, options.threadId, resourceId)
375
514
  ? 'active'
376
515
  : 'idle';
377
516
  let delivered = 0;
378
517
  let failed = 0;
518
+ let discarded = 0;
519
+ // Records whose terminal discard is already durable. A later throw in the
520
+ // same group funnels the group into `updateFailure`; without this, an
521
+ // already-discarded record would be counted twice and have its
522
+ // content-policy reason overwritten by an unrelated storage error.
523
+ const settledDiscards = new Set();
379
524
  const updateFailure = async (record, error) => {
525
+ if (settledDiscards.has(record.id))
526
+ return;
380
527
  failed += 1;
381
528
  await deferNotificationAfterFailure(options.storage, record, now, error);
382
529
  };
530
+ const discardAfterDenial = async (record) => {
531
+ await options.storage.updateNotification({
532
+ id: record.id,
533
+ threadId: record.threadId,
534
+ status: 'discarded',
535
+ deliveryReason: 'content-policy-denied',
536
+ lastDeliveryAttemptAt: now,
537
+ });
538
+ settledDiscards.add(record.id);
539
+ discarded += 1;
540
+ };
541
+ const inspect = async (signal) => {
542
+ if (!options.inspectContent)
543
+ return 'allowed';
544
+ return options.inspectContent(signal, durableBlockingRun?.runId ??
545
+ activeThreadRunIdOf(options.agent, options.threadId, resourceId));
546
+ };
383
547
  const send = async (signal) => {
548
+ const deliverableSignal = options.persistenceAllowed
549
+ ? signal
550
+ : markPersistenceForbidden(signal);
384
551
  const response = await handleWake({
385
552
  agent: options.agent,
386
553
  deploymentTag: options.deploymentTag,
@@ -396,14 +563,20 @@ async function handleNotificationDispatch(options) {
396
563
  ? () => durableBlockingRun
397
564
  : options.blockingRun,
398
565
  persistenceAllowed: options.persistenceAllowed,
399
- signal,
400
- deliverActive: (runId) => options.agent.sendSignal(signal, {
566
+ memoryAvailable: options.memoryAvailable,
567
+ signal: deliverableSignal,
568
+ deliverActive: (runId, memoryAvailable) => options.agent.sendSignal(deliverableSignal, {
401
569
  runId,
402
570
  threadId: options.threadId,
403
571
  resourceId,
404
572
  ifActive: { behavior: 'deliver' },
573
+ ifIdle: {
574
+ behavior: memoryAvailable && options.persistenceAllowed
575
+ ? 'persist'
576
+ : 'discard',
577
+ },
405
578
  }),
406
- persist: () => options.agent.sendSignal(signal, {
579
+ persist: () => options.agent.sendSignal(deliverableSignal, {
407
580
  threadId: options.threadId,
408
581
  resourceId,
409
582
  ifIdle: { behavior: 'persist' },
@@ -413,6 +586,8 @@ async function handleNotificationDispatch(options) {
413
586
  throw new Error(`notification signal returned ${response.status}`);
414
587
  const result = (await response.json());
415
588
  const action = recordValue(result.decision)?.action;
589
+ // A stale active id can fall through to idle. Persistence-forbidden and
590
+ // memory-unavailable discards are failed delivery, never a fresh wake.
416
591
  if (action !== 'wake' &&
417
592
  action !== 'deliver' &&
418
593
  !(action === 'persist' && options.persistenceAllowed)) {
@@ -426,6 +601,9 @@ async function handleNotificationDispatch(options) {
426
601
  if (!options.persistenceAllowed) {
427
602
  throw new Error('signal persistence is forbidden for this principal');
428
603
  }
604
+ if (!(await options.memoryAvailable())) {
605
+ throw new Error('signal persistence requires agent memory');
606
+ }
429
607
  const result = options.agent.sendSignal(signal, {
430
608
  threadId: options.threadId,
431
609
  resourceId,
@@ -439,8 +617,24 @@ async function handleNotificationDispatch(options) {
439
617
  };
440
618
  for (const item of planNotificationDispatch(records, now)) {
441
619
  if (item.type === 'summary') {
620
+ // Everything from rendering onward stays inside this try: a storage
621
+ // failure in the discard/failure bookkeeping below must be contained to
622
+ // this group, exactly as the individual branch contains its own, rather
623
+ // than escaping and abandoning the rest of the plan.
442
624
  try {
443
625
  const signal = createNotificationSummarySignal(summarizeNotifications(item.records));
626
+ const inspection = await inspect(signal);
627
+ if (inspection === 'denied') {
628
+ for (const record of item.records)
629
+ await discardAfterDenial(record);
630
+ continue;
631
+ }
632
+ if (inspection === 'error') {
633
+ for (const record of item.records) {
634
+ await updateFailure(record, new Error('signal content policy failed'));
635
+ }
636
+ continue;
637
+ }
444
638
  const lowPriority = item.records.every((record) => record.priority === 'low');
445
639
  const signalId = lowPriority && options.persistenceAllowed
446
640
  ? await persistWithoutWake(signal)
@@ -485,11 +679,21 @@ async function handleNotificationDispatch(options) {
485
679
  skipped += 1;
486
680
  continue;
487
681
  }
488
- const signalId = await send(createNotificationSignal({
682
+ const signal = createNotificationSignal({
489
683
  ...record,
490
684
  status: 'delivered',
491
685
  deliveredAt: now,
492
- }));
686
+ });
687
+ const inspection = await inspect(signal);
688
+ if (inspection === 'denied') {
689
+ await discardAfterDenial(record);
690
+ continue;
691
+ }
692
+ if (inspection === 'error') {
693
+ await updateFailure(record, new Error('signal content policy failed'));
694
+ continue;
695
+ }
696
+ const signalId = await send(signal);
493
697
  await options.storage.updateNotification({
494
698
  id: record.id,
495
699
  threadId: record.threadId,
@@ -506,14 +710,17 @@ async function handleNotificationDispatch(options) {
506
710
  return json({
507
711
  delivered,
508
712
  failed,
713
+ ...(discarded > 0 ? { discarded } : {}),
509
714
  ...(skipped > 0 ? { skipped } : {}),
510
715
  ...(carriesBatchThreadState ? { batchThreadState } : {}),
511
716
  });
512
717
  }
513
718
  /**
514
719
  * Resolve the idle behavior a body asked for. A `wake` STARTS a run, so it is
515
- * gated twice, both fail-closed to a durable persist (the signal survives the
516
- * next turn rather than dropping or billing):
720
+ * gated twice. A refused or capped wake degrades to a durable persist when the
721
+ * principal may persist and the agent has memory; otherwise the route answers
722
+ * `persistence-forbidden` or `memory-unavailable` instead of silently dropping
723
+ * the signal:
517
724
  * - the agent must be RUNTIME-DRIVEN (its stream re-enters RunnerRuntime, not
518
725
  * the default engine) — else `wakeRefused:'not-runtime-driven'`;
519
726
  * - the deployment run cap must allow it — otherwise `capped:true`.
@@ -535,15 +742,50 @@ function principalMismatchResponse(runId) {
535
742
  capped: false,
536
743
  });
537
744
  }
745
+ /**
746
+ * Report a lazily computed missing-memory gate after content inspection, only
747
+ * where a memory write would otherwise disappear. Wake-start and notification
748
+ * inbox recording never use this response. On an active thread it is returned
749
+ * for a persist outcome that would otherwise be silently dropped — an explicit
750
+ * `ifActive: 'persist'`, or the stale-active-id idle fall-through — and by
751
+ * `/state`, whose pre-send gate replaces core's hard memory requirement rather
752
+ * than covering a dropped write. A default or `ifIdle: 'persist'` request to
753
+ * `/signal/message` or `/signal` still delivers into an active run without
754
+ * memory; the memory gate responds only when core's outcome for the request
755
+ * replaced a persist (an idle discard substituted for a requested persist, or
756
+ * an active persist that no memory could write).
757
+ */
758
+ function memoryUnavailableResponse() {
759
+ return json({
760
+ decision: { action: 'discard', reason: 'memory-unavailable' },
761
+ });
762
+ }
763
+ /**
764
+ * Report route-specific persistence authorization failures.
765
+ * `/queue` and `/state` refuse every non-owner request before sending.
766
+ * `/signal/message` and `/signal` refuse a default or requested `ifIdle: 'persist'`;
767
+ * `/signal` also degrades a requested `ifActive: 'persist'`.
768
+ * `/notification` never refuses because a non-owner is record-only for the
769
+ * dispatcher.
770
+ * Wake handling for `/signal/message`, `/signal`, `/signal/schedule`, and the
771
+ * notification dispatch lane returns this response from `handleWake` when a
772
+ * refused or capped wake, or a stale-active-id fall-through, would otherwise
773
+ * persist for a non-owner.
774
+ */
775
+ function persistenceForbiddenResponse(options) {
776
+ return json({
777
+ decision: { action: 'discard', reason: 'persistence-forbidden' },
778
+ ...(options?.capped !== undefined ? { capped: options.capped } : {}),
779
+ ...(options?.wakeRefused !== undefined
780
+ ? { wakeRefused: options.wakeRefused }
781
+ : {}),
782
+ ...(options?.signalId !== undefined ? { signalId: options.signalId } : {}),
783
+ });
784
+ }
538
785
  async function handleWake(options) {
539
786
  return options.serializeWake(async () => {
540
787
  const durableBlockingRun = await options.blockingRun?.();
541
- const activeRunId = typeof options.agent.getActiveThreadRunId === 'function'
542
- ? options.agent.getActiveThreadRunId({
543
- threadId: options.threadId,
544
- resourceId: options.resourceId,
545
- })
546
- : undefined;
788
+ const activeRunId = activeThreadRunIdOf(options.agent, options.threadId, options.resourceId);
547
789
  if (durableBlockingRun &&
548
790
  !samePrincipal(durableBlockingRun.principal, options.principal)) {
549
791
  return principalMismatchResponse(durableBlockingRun.runId);
@@ -559,9 +801,22 @@ async function handleWake(options) {
559
801
  capped: false,
560
802
  });
561
803
  }
562
- const delivered = options.deliverActive(activeRunId);
804
+ const memoryAvailable = await options.memoryAvailable();
805
+ const delivered = options.deliverActive(activeRunId, memoryAvailable);
806
+ const decision = await delivered.accepted;
807
+ if (delivered.persisted)
808
+ await delivered.persisted;
809
+ const action = recordValue(decision)?.action;
810
+ if (action === 'discard' && !options.activeDiscardAllowed) {
811
+ return options.persistenceAllowed
812
+ ? memoryUnavailableResponse()
813
+ : persistenceForbiddenResponse({ capped: false });
814
+ }
815
+ if (action === 'persist' && !memoryAvailable) {
816
+ return memoryUnavailableResponse();
817
+ }
563
818
  return json({
564
- decision: await delivered.accepted,
819
+ decision,
565
820
  capped: false,
566
821
  signalId: delivered.signal.id,
567
822
  });
@@ -590,11 +845,7 @@ async function handleWake(options) {
590
845
  : false;
591
846
  if (refusal || capped) {
592
847
  if (!options.persistenceAllowed) {
593
- return json({
594
- decision: {
595
- action: 'discard',
596
- reason: 'persistence-forbidden',
597
- },
848
+ return persistenceForbiddenResponse({
598
849
  capped,
599
850
  ...(refusal ? { wakeRefused: refusal } : {}),
600
851
  ...(options.signal?.id !== undefined
@@ -602,6 +853,8 @@ async function handleWake(options) {
602
853
  : {}),
603
854
  });
604
855
  }
856
+ if (!(await options.memoryAvailable()))
857
+ return memoryUnavailableResponse();
605
858
  const persisted = options.persist();
606
859
  const decision = await persisted.accepted;
607
860
  if (persisted.persisted)
@@ -700,9 +953,19 @@ async function handleScheduleSignal(options) {
700
953
  return json({ error: 'invalid schedule signal dispatch' }, 400);
701
954
  }
702
955
  const resourceId = options.resourceId;
703
- if (target.tagName !== undefined && !XML_NAME_PATTERN.test(target.tagName)) {
704
- return json({ error: 'tagName is not a valid XML name' }, 400);
705
- }
956
+ // Every terminal "this fire will not be delivered" outcome settles the same
957
+ // canonical receipt, so a replay of the dispatch returns it instead of
958
+ // re-deciding. Settling is what lets the schedule advance; leaving the lease
959
+ // unsettled is reserved for outcomes a later tick could still resolve.
960
+ const settleDiscard = async () => {
961
+ const receipt = createScheduleAgentDispatchReceipt('discard', {
962
+ signalId: dispatchId,
963
+ });
964
+ options.completed.set(dispatchId, receipt);
965
+ await options.store.settle(scheduleId, dispatchId, receipt);
966
+ options.completed.delete(dispatchId);
967
+ return json({ receipt });
968
+ };
706
969
  const completed = options.completed.get(dispatchId);
707
970
  if (completed) {
708
971
  await options.store.settle(scheduleId, dispatchId, completed);
@@ -750,12 +1013,33 @@ async function handleScheduleSignal(options) {
750
1013
  options.completed.delete(dispatchId);
751
1014
  return json({ receipt });
752
1015
  }
1016
+ // A stored target that cannot be rendered as XML can never be delivered: core
1017
+ // asserts the tag name and every surviving attribute name inside
1018
+ // signalToXmlMarkup, and a schedule's attributes never pass through
1019
+ // `isAttributes` (core types them as a bare string record). Returning an error
1020
+ // would leave the lease unsettled and hand the same permanently broken target
1021
+ // to every later tick, so settle it terminally and let the schedule advance.
1022
+ const effectiveTagName = target.tagName ?? 'schedule';
1023
+ if (!XML_NAME_PATTERN.test(effectiveTagName) ||
1024
+ !renderableAttributes(target.attributes) ||
1025
+ !renderableAttributes(target.ifActive?.attributes) ||
1026
+ !renderableAttributes(target.ifIdle?.attributes)) {
1027
+ // The operator has to be able to find the broken schedule; the offending
1028
+ // name itself stays out of the log.
1029
+ console.error(JSON.stringify({
1030
+ type: 'schedule-target-unrenderable',
1031
+ scheduleId,
1032
+ dispatchId,
1033
+ agentId: target.agentId,
1034
+ }));
1035
+ return await settleDiscard();
1036
+ }
753
1037
  const baseProviderOptions = target.providerOptions ?? {};
754
1038
  const baseMastra = recordValue(baseProviderOptions.mastra) ?? {};
755
1039
  const signal = {
756
1040
  id: dispatchId,
757
1041
  type: target.signalType ?? 'notification',
758
- tagName: target.tagName ?? 'schedule',
1042
+ tagName: effectiveTagName,
759
1043
  contents: target.prompt,
760
1044
  ...(target.attributes !== undefined
761
1045
  ? { attributes: target.attributes }
@@ -773,12 +1057,7 @@ async function handleScheduleSignal(options) {
773
1057
  };
774
1058
  const ifActive = target.ifActive ?? { behavior: 'deliver' };
775
1059
  const ifIdle = target.ifIdle ?? { behavior: 'wake' };
776
- const localActiveRunId = typeof options.agent.getActiveThreadRunId === 'function'
777
- ? options.agent.getActiveThreadRunId({
778
- threadId: options.threadId,
779
- resourceId,
780
- })
781
- : undefined;
1060
+ const localActiveRunId = activeThreadRunIdOf(options.agent, options.threadId, resourceId);
782
1061
  const persistenceRequested = localActiveRunId
783
1062
  ? (ifActive.behavior ?? 'deliver') === 'persist'
784
1063
  : (ifIdle.behavior ?? 'wake') === 'persist';
@@ -793,15 +1072,39 @@ async function handleScheduleSignal(options) {
793
1072
  })
794
1073
  : options.persistenceAllowed;
795
1074
  if (persistenceRequested && !persistenceAllowed) {
796
- const receipt = {
797
- action: 'discard',
798
- outcome: 'discarded',
799
- signalId: dispatchId,
800
- };
801
- options.completed.set(dispatchId, receipt);
802
- await options.store.settle(scheduleId, dispatchId, receipt);
803
- options.completed.delete(dispatchId);
804
- return json({ receipt });
1075
+ return await settleDiscard();
1076
+ }
1077
+ const deliverableSignal = persistenceAllowed
1078
+ ? signal
1079
+ : markPersistenceForbidden(signal);
1080
+ if (options.inspectContent) {
1081
+ // Mastra chooses the active or idle branch after an async boundary, so both
1082
+ // renderings are inspected. `resolveDeliveryAttributes` returns the SAME
1083
+ // object when a branch declares no attributes — the default — so the common
1084
+ // case is one inspection, not two identical ones (a host policy backed by a
1085
+ // classifier would otherwise pay twice per fire and audit twice).
1086
+ const createdSignal = createSignal(deliverableSignal);
1087
+ const activeSignal = resolveDeliveryAttributes(createdSignal, ifActive.attributes);
1088
+ const idleSignal = resolveDeliveryAttributes(createdSignal, ifIdle.attributes);
1089
+ const executingRunId = localActiveRunId ?? durableBlockingRun?.runId;
1090
+ const [activeInspection, idleInspection] = activeSignal === idleSignal
1091
+ ? [
1092
+ await options.inspectContent(activeSignal, executingRunId ?? runId),
1093
+ undefined,
1094
+ ]
1095
+ : await Promise.all([
1096
+ options.inspectContent(activeSignal, executingRunId),
1097
+ options.inspectContent(idleSignal, runId),
1098
+ ]);
1099
+ // Denial wins over an evaluator failure on the other branch: only one branch
1100
+ // ever delivers, but which one is not known here, so refusing terminally is
1101
+ // the fail-closed answer.
1102
+ if (activeInspection === 'denied' || idleInspection === 'denied') {
1103
+ return await settleDiscard();
1104
+ }
1105
+ if (activeInspection === 'error' || idleInspection === 'error') {
1106
+ return signalContentPolicyResponse('error');
1107
+ }
805
1108
  }
806
1109
  const idleRequestContext = ifIdle.streamOptions?.requestContext ?? streamRequestContext;
807
1110
  const signalIfIdle = {
@@ -830,9 +1133,14 @@ async function handleScheduleSignal(options) {
830
1133
  let signalId;
831
1134
  if ((ifIdle.behavior ?? 'wake') === 'wake') {
832
1135
  const idleSignal = {
833
- ...signal,
1136
+ ...deliverableSignal,
834
1137
  ...(ifIdle.attributes !== undefined
835
- ? { attributes: { ...signal.attributes, ...ifIdle.attributes } }
1138
+ ? {
1139
+ attributes: {
1140
+ ...deliverableSignal.attributes,
1141
+ ...ifIdle.attributes,
1142
+ },
1143
+ }
836
1144
  : {}),
837
1145
  };
838
1146
  const response = await handleWake({
@@ -850,18 +1158,23 @@ async function handleScheduleSignal(options) {
850
1158
  ? () => durableBlockingRun
851
1159
  : options.blockingRun,
852
1160
  persistenceAllowed,
1161
+ memoryAvailable: options.memoryAvailable,
853
1162
  signal: idleSignal,
854
1163
  runId,
855
1164
  scheduleId,
856
1165
  dispatchId,
857
1166
  safeContext: { ...requestContext, ...idleRequestContext },
858
- deliverActive: (activeRunId) => options.agent.sendSignal(signal, {
1167
+ activeDiscardAllowed: ifActive.behavior === 'discard',
1168
+ deliverActive: (activeRunId, memoryAvailable) => options.agent.sendSignal(deliverableSignal, {
859
1169
  runId: activeRunId,
860
1170
  threadId: options.threadId,
861
1171
  resourceId,
862
1172
  ifActive,
1173
+ ifIdle: {
1174
+ behavior: memoryAvailable && persistenceAllowed ? 'persist' : 'discard',
1175
+ },
863
1176
  }),
864
- persist: () => options.agent.sendSignal(signal, {
1177
+ persist: () => options.agent.sendSignal(deliverableSignal, {
865
1178
  threadId: options.threadId,
866
1179
  resourceId,
867
1180
  ifActive,
@@ -876,9 +1189,17 @@ async function handleScheduleSignal(options) {
876
1189
  typeof payload.signalId === 'string' ? payload.signalId : undefined;
877
1190
  }
878
1191
  else {
879
- const sent = options.agent.sendSignal(signal, signalTarget);
1192
+ const sent = options.agent.sendSignal(deliverableSignal, signalTarget);
880
1193
  decision = await sent.accepted;
881
- if (recordValue(decision)?.action === 'persist' && sent.persisted) {
1194
+ const action = recordValue(decision)?.action;
1195
+ if (action === 'persist' && !(await options.memoryAvailable())) {
1196
+ if (sent.persisted)
1197
+ await sent.persisted;
1198
+ // A memory-less host cannot persist this fire; an unsettled lease would
1199
+ // replay it every tick.
1200
+ return await settleDiscard();
1201
+ }
1202
+ if (action === 'persist' && sent.persisted) {
882
1203
  await sent.persisted;
883
1204
  }
884
1205
  signalId = sent.signal.id;
@@ -892,14 +1213,25 @@ async function handleScheduleSignal(options) {
892
1213
  options.completed.delete(dispatchId);
893
1214
  return json({ receipt });
894
1215
  }
895
- async function handleMessage(agent, body, threadId, resourceId, consultRunCap, deploymentTag, runtimeDriven, principal, entryPath, startIdleRun, serializeWake, blockingRun, persistenceAllowed) {
1216
+ async function contentPolicyRefusal(inspectContent, signal, runId) {
1217
+ if (!inspectContent)
1218
+ return undefined;
1219
+ const inspection = await inspectContent(signal, runId);
1220
+ return inspection === 'allowed'
1221
+ ? undefined
1222
+ : signalContentPolicyResponse(inspection);
1223
+ }
1224
+ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, deploymentTag, entryPath, startIdleRun, serializeWake, options) {
896
1225
  if (!isContents(body.contents)) {
897
1226
  return json({ error: 'contents (string) is required' }, 400);
898
1227
  }
899
- const message = {
1228
+ const baseMessage = {
900
1229
  contents: body.contents,
901
1230
  ...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
902
1231
  };
1232
+ const message = options.persistenceAllowed
1233
+ ? baseMessage
1234
+ : markPersistenceForbidden(baseMessage);
903
1235
  // sendMessage requires a resourceId+threadId target for its idle branch; when a
904
1236
  // host has not wired a resourceId, only the active/queue path is reachable.
905
1237
  if (resourceId === undefined) {
@@ -908,31 +1240,44 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
908
1240
  }, 409);
909
1241
  }
910
1242
  const behavior = requestedIdle(body);
911
- const durableBlockingRun = await blockingRun?.();
1243
+ const durableBlockingRun = await options.blockingRun?.();
912
1244
  if (durableBlockingRun &&
913
- !samePrincipal(durableBlockingRun.principal, principal)) {
1245
+ !samePrincipal(durableBlockingRun.principal, options.principal)) {
914
1246
  return principalMismatchResponse(durableBlockingRun.runId);
915
1247
  }
1248
+ const policyRefusal = await contentPolicyRefusal(options.inspectContent, createMessageSignal(message), durableBlockingRun?.runId);
1249
+ if (policyRefusal)
1250
+ return policyRefusal;
916
1251
  if (behavior === 'wake') {
917
1252
  return handleWake({
918
1253
  agent,
919
1254
  deploymentTag,
920
1255
  threadId,
921
1256
  resourceId,
922
- principal,
1257
+ principal: options.principal,
923
1258
  entryPath,
924
- runtimeDriven,
1259
+ runtimeDriven: options.runtimeDriven,
925
1260
  consultRunCap,
926
1261
  startIdleRun,
927
1262
  serializeWake,
928
- blockingRun: durableBlockingRun ? () => durableBlockingRun : blockingRun,
929
- persistenceAllowed,
1263
+ blockingRun: durableBlockingRun
1264
+ ? () => durableBlockingRun
1265
+ : options.blockingRun,
1266
+ persistenceAllowed: options.persistenceAllowed,
1267
+ memoryAvailable: options.memoryAvailable,
930
1268
  message,
931
- deliverActive: (runId) => agent.sendMessage(message, {
1269
+ deliverActive: (runId, memoryAvailable) => agent.sendMessage(message, {
932
1270
  runId,
933
1271
  threadId,
934
1272
  resourceId,
935
1273
  ifActive: { behavior: 'deliver' },
1274
+ // A stale active id can disappear before core sends. Persist only
1275
+ // when both the memory and authorization gates allow the write.
1276
+ ifIdle: {
1277
+ behavior: memoryAvailable && options.persistenceAllowed
1278
+ ? 'persist'
1279
+ : 'discard',
1280
+ },
936
1281
  }),
937
1282
  persist: () => agent.sendMessage(message, {
938
1283
  threadId,
@@ -941,25 +1286,30 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
941
1286
  }),
942
1287
  });
943
1288
  }
944
- if (behavior === 'persist' && !persistenceAllowed) {
945
- return json({
946
- decision: { action: 'discard', reason: 'persistence-forbidden' },
947
- capped: false,
948
- });
1289
+ if (behavior === 'persist' && !options.persistenceAllowed) {
1290
+ return persistenceForbiddenResponse({ capped: false });
949
1291
  }
1292
+ const memoryAvailable = await options.memoryAvailable();
950
1293
  const result = agent.sendMessage(message, {
951
1294
  threadId,
952
1295
  resourceId,
953
- ifIdle: { behavior },
1296
+ ifIdle: { behavior: memoryAvailable ? behavior : 'discard' },
954
1297
  });
955
1298
  const decision = await result.accepted;
1299
+ if (result.persisted)
1300
+ await result.persisted;
1301
+ if (behavior === 'persist' &&
1302
+ !memoryAvailable &&
1303
+ recordValue(decision)?.action === 'discard') {
1304
+ return memoryUnavailableResponse();
1305
+ }
956
1306
  return json({
957
1307
  decision,
958
1308
  capped: false,
959
1309
  signalId: result.signal.id,
960
1310
  });
961
1311
  }
962
- async function handleQueue(agent, body, threadId, resourceId, principal, blockingRun, persistenceAllowed) {
1312
+ async function handleQueue(agent, body, threadId, resourceId, options) {
963
1313
  if (!isContents(body.contents)) {
964
1314
  return json({ error: 'contents (string) is required' }, 400);
965
1315
  }
@@ -970,21 +1320,31 @@ async function handleQueue(agent, body, threadId, resourceId, principal, blockin
970
1320
  contents: body.contents,
971
1321
  ...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
972
1322
  };
973
- const durableBlockingRun = await blockingRun?.();
1323
+ const durableBlockingRun = await options.blockingRun?.();
974
1324
  if (durableBlockingRun &&
975
- !samePrincipal(durableBlockingRun.principal, principal)) {
1325
+ !samePrincipal(durableBlockingRun.principal, options.principal)) {
976
1326
  return principalMismatchResponse(durableBlockingRun.runId);
977
1327
  }
978
- if (!persistenceAllowed) {
979
- return json({
980
- decision: { action: 'discard', reason: 'persistence-forbidden' },
981
- });
1328
+ if (!options.persistenceAllowed) {
1329
+ return persistenceForbiddenResponse();
982
1330
  }
983
- const result = agent.queueMessage(message, { threadId, resourceId });
1331
+ const policyRefusal = await contentPolicyRefusal(options.inspectContent, createMessageSignal(message), durableBlockingRun?.runId);
1332
+ if (policyRefusal)
1333
+ return policyRefusal;
1334
+ if (!(await options.memoryAvailable()))
1335
+ return memoryUnavailableResponse();
1336
+ const result = agent.sendMessage(message, {
1337
+ threadId,
1338
+ resourceId,
1339
+ ifActive: { behavior: 'persist' },
1340
+ ifIdle: { behavior: 'persist' },
1341
+ });
984
1342
  const decision = await result.accepted;
1343
+ if (result.persisted)
1344
+ await result.persisted;
985
1345
  return json({ decision, signalId: result.signal.id });
986
1346
  }
987
- async function handleSignal(agent, body, threadId, resourceId, consultRunCap, deploymentTag, runtimeDriven, principal, entryPath, startIdleRun, serializeWake, blockingRun, persistenceAllowed) {
1347
+ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, deploymentTag, entryPath, startIdleRun, serializeWake, options) {
988
1348
  if (!isContents(body.contents)) {
989
1349
  return json({ error: 'contents (string) is required' }, 400);
990
1350
  }
@@ -996,21 +1356,31 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
996
1356
  !XML_NAME_PATTERN.test(body.tagName)) {
997
1357
  return json({ error: 'tagName is not a valid XML name' }, 400);
998
1358
  }
999
- const signal = {
1359
+ const baseSignal = {
1000
1360
  type: 'reactive',
1001
1361
  contents: body.contents,
1002
1362
  ...(typeof body.tagName === 'string' ? { tagName: body.tagName } : {}),
1003
1363
  ...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
1004
1364
  };
1365
+ const signal = options.persistenceAllowed
1366
+ ? baseSignal
1367
+ : markPersistenceForbidden(baseSignal);
1005
1368
  const activeBehavior = typeof body.ifActive === 'string' &&
1006
1369
  ACTIVE_BEHAVIORS.includes(body.ifActive)
1007
1370
  ? body.ifActive
1008
1371
  : 'deliver';
1009
- const durableBlockingRun = await blockingRun?.();
1372
+ const activePersistenceForbidden = activeBehavior === 'persist' && !options.persistenceAllowed;
1373
+ const deliveredActiveBehavior = activePersistenceForbidden
1374
+ ? 'discard'
1375
+ : activeBehavior;
1376
+ const durableBlockingRun = await options.blockingRun?.();
1010
1377
  if (durableBlockingRun &&
1011
- !samePrincipal(durableBlockingRun.principal, principal)) {
1378
+ !samePrincipal(durableBlockingRun.principal, options.principal)) {
1012
1379
  return principalMismatchResponse(durableBlockingRun.runId);
1013
1380
  }
1381
+ const policyRefusal = await contentPolicyRefusal(options.inspectContent, createSignal(signal), durableBlockingRun?.runId);
1382
+ if (policyRefusal)
1383
+ return policyRefusal;
1014
1384
  if (resourceId === undefined) {
1015
1385
  // Active-only target: no idle branch available without a resourceId.
1016
1386
  const runId = crypto.randomUUID();
@@ -1020,7 +1390,7 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
1020
1390
  const result = agent.sendSignal(signal, {
1021
1391
  threadId,
1022
1392
  runId,
1023
- ifActive: { behavior: activeBehavior },
1393
+ ifActive: { behavior: deliveredActiveBehavior },
1024
1394
  });
1025
1395
  const decision = await result.accepted;
1026
1396
  return json({ decision, signalId: result.signal.id });
@@ -1032,49 +1402,74 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
1032
1402
  deploymentTag,
1033
1403
  threadId,
1034
1404
  resourceId,
1035
- principal,
1405
+ principal: options.principal,
1036
1406
  entryPath,
1037
- runtimeDriven,
1407
+ runtimeDriven: options.runtimeDriven,
1038
1408
  consultRunCap,
1039
1409
  startIdleRun,
1040
1410
  serializeWake,
1041
- blockingRun: durableBlockingRun ? () => durableBlockingRun : blockingRun,
1042
- persistenceAllowed,
1411
+ blockingRun: durableBlockingRun
1412
+ ? () => durableBlockingRun
1413
+ : options.blockingRun,
1414
+ persistenceAllowed: options.persistenceAllowed,
1415
+ memoryAvailable: options.memoryAvailable,
1043
1416
  signal,
1044
- deliverActive: (runId) => agent.sendSignal(signal, {
1417
+ activeDiscardAllowed: activeBehavior === 'discard',
1418
+ deliverActive: (runId, memoryAvailable) => agent.sendSignal(signal, {
1045
1419
  runId,
1046
1420
  threadId,
1047
1421
  resourceId,
1048
- ifActive: { behavior: activeBehavior },
1422
+ ifActive: { behavior: deliveredActiveBehavior },
1423
+ ifIdle: {
1424
+ behavior: memoryAvailable && options.persistenceAllowed
1425
+ ? 'persist'
1426
+ : 'discard',
1427
+ },
1049
1428
  }),
1050
1429
  persist: () => agent.sendSignal(signal, {
1051
1430
  threadId,
1052
1431
  resourceId,
1053
- ifActive: { behavior: activeBehavior },
1432
+ ifActive: { behavior: deliveredActiveBehavior },
1054
1433
  ifIdle: { behavior: 'persist' },
1055
1434
  }),
1056
1435
  });
1057
1436
  }
1058
- if (behavior === 'persist' && !persistenceAllowed) {
1059
- return json({
1060
- decision: { action: 'discard', reason: 'persistence-forbidden' },
1061
- capped: false,
1062
- });
1437
+ if (behavior === 'persist' && !options.persistenceAllowed) {
1438
+ return persistenceForbiddenResponse({ capped: false });
1063
1439
  }
1440
+ const memoryAvailable = await options.memoryAvailable();
1441
+ const wasActive = activeThreadRunIdOf(agent, threadId, resourceId) !== undefined;
1064
1442
  const result = agent.sendSignal(signal, {
1065
1443
  threadId,
1066
1444
  resourceId,
1067
- ifActive: { behavior: activeBehavior },
1068
- ifIdle: { behavior },
1445
+ ifActive: { behavior: deliveredActiveBehavior },
1446
+ ifIdle: { behavior: memoryAvailable ? behavior : 'discard' },
1069
1447
  });
1070
1448
  const decision = await result.accepted;
1449
+ if (result.persisted)
1450
+ await result.persisted;
1451
+ const action = recordValue(decision)?.action;
1452
+ if (action === 'persist' && !memoryAvailable) {
1453
+ return memoryUnavailableResponse();
1454
+ }
1455
+ // An idle discard is either the caller's `ifIdle: 'discard'` or the memory
1456
+ // gate's substitution, handled by the next block.
1457
+ if (action === 'discard' &&
1458
+ behavior === 'persist' &&
1459
+ !memoryAvailable &&
1460
+ !(wasActive && deliveredActiveBehavior === 'discard')) {
1461
+ return memoryUnavailableResponse();
1462
+ }
1463
+ if (activePersistenceForbidden && wasActive && action === 'discard') {
1464
+ return persistenceForbiddenResponse({ capped: false });
1465
+ }
1071
1466
  return json({
1072
1467
  decision,
1073
1468
  capped: false,
1074
1469
  signalId: result.signal.id,
1075
1470
  });
1076
1471
  }
1077
- async function handleState(agent, body, threadId, resourceId) {
1472
+ async function handleState(agent, body, threadId, resourceId, options) {
1078
1473
  if (typeof body.id !== 'string' || typeof body.cacheKey !== 'string') {
1079
1474
  return json({ error: 'id and cacheKey are required for a state signal' }, 400);
1080
1475
  }
@@ -1093,7 +1488,38 @@ async function handleState(agent, body, threadId, resourceId) {
1093
1488
  ...(mode === 'snapshot' ? { value: body.value } : { delta: body.delta }),
1094
1489
  ...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
1095
1490
  };
1096
- const result = await agent.sendStateSignal(state, { threadId, resourceId });
1491
+ const durableBlockingRun = await options.blockingRun?.();
1492
+ if (durableBlockingRun &&
1493
+ !samePrincipal(durableBlockingRun.principal, options.principal)) {
1494
+ return principalMismatchResponse(durableBlockingRun.runId);
1495
+ }
1496
+ if (!options.persistenceAllowed) {
1497
+ return persistenceForbiddenResponse();
1498
+ }
1499
+ // Core's createStateSignalInput strips id/cacheKey/mode/value/delta out of the
1500
+ // signal it renders (they ride in metadata, which signalToXmlMarkup never
1501
+ // emits) and defaults tagName to 'state'. Mirror exactly that, so the gate
1502
+ // inspects the markup the model will see and nothing else.
1503
+ const policyRefusal = await contentPolicyRefusal(options.inspectContent, createSignal({
1504
+ type: 'state',
1505
+ tagName: 'state',
1506
+ contents: state.contents,
1507
+ ...(state.attributes !== undefined
1508
+ ? { attributes: state.attributes }
1509
+ : {}),
1510
+ }), durableBlockingRun?.runId);
1511
+ if (policyRefusal)
1512
+ return policyRefusal;
1513
+ if (!(await options.memoryAvailable()))
1514
+ return memoryUnavailableResponse();
1515
+ const result = await agent.sendStateSignal(state, {
1516
+ threadId,
1517
+ resourceId,
1518
+ ...(!options.runtimeDriven
1519
+ ? { ifActive: { behavior: 'persist' } }
1520
+ : {}),
1521
+ ifIdle: { behavior: 'persist' },
1522
+ });
1097
1523
  // A snapshot whose cacheKey value is unchanged is de-duped (skipped) — no run
1098
1524
  // touched, no signal minted. Surface that distinctly rather than pretend a
1099
1525
  // delivery happened.
@@ -1101,9 +1527,16 @@ async function handleState(agent, body, threadId, resourceId) {
1101
1527
  return json({ skipped: true, reason: result.reason });
1102
1528
  }
1103
1529
  const decision = await result.accepted;
1104
- return json({ decision, signalId: result.signal.id });
1530
+ if (result.persisted)
1531
+ await result.persisted;
1532
+ const degraded = 'not-runtime-driven';
1533
+ return json({
1534
+ decision,
1535
+ signalId: result.signal.id,
1536
+ ...(!options.runtimeDriven ? { degraded } : {}),
1537
+ });
1105
1538
  }
1106
- async function handleNotification(agent, body, threadId, resourceId) {
1539
+ async function handleNotification(agent, body, threadId, resourceId, resolveNotificationsStorage, options) {
1107
1540
  if (typeof body.source !== 'string' ||
1108
1541
  typeof body.kind !== 'string' ||
1109
1542
  typeof body.summary !== 'string') {
@@ -1126,22 +1559,95 @@ async function handleNotification(agent, body, threadId, resourceId) {
1126
1559
  : {}),
1127
1560
  ...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
1128
1561
  };
1129
- // agent.sendNotificationSignal persists via the Mastra storage's notifications
1130
- // domain (mastra_notifications) — D1-backed once createD1Storage composes
1131
- // D1NotificationsStorage — and returns the created record. The durable inbox
1132
- // surfaces on the next turn (the dispatcher reads it at run start); nothing
1133
- // wakes here (P6/P8: an inbound notification is untrusted context, never a
1134
- // capability). Core's notification target REQUIRES a resourceId (it keys the
1135
- // inbox on the owner), so a thread with none wired cannot take one.
1562
+ // Owners use core's delivery policy. The inbox row is the durable artifact,
1563
+ // so this route has no memory gate: without agent memory, a model-visible
1564
+ // persist is best-effort and the row stays pending. Non-owner notifications
1565
+ // are record-only here: the host's createNotificationDispatchTick delivers
1566
+ // them later (agent-starter runs it every 60 seconds). A host without that
1567
+ // tick records but never delivers them; the spike intentionally has no tick
1568
+ // and its provider probes assert only the inbox row. This branch bypasses an
1569
+ // agent-level notifications.deliveryPolicy and
1570
+ // __ensureNotificationDispatchReady; branded hosts cannot reach either seam
1571
+ // through the wrapped agent anyway.
1572
+ // The target requires a resourceId because the inbox is keyed by its owner.
1573
+ // Core's default policy does not summarize an idle thread immediately. A
1574
+ // medium-priority delivery can sample active, then fall idle across its
1575
+ // awaits. For a branded runner the resulting forced wake reaches the terminal
1576
+ // refusal path while the created record stays pending with its summary signal
1577
+ // id. An unbranded agent keeps core's own below-boundary run start; no shipped
1578
+ // host uses that degraded configuration.
1136
1579
  if (resourceId === undefined) {
1137
1580
  return json({ error: 'this thread has no resourceId wired; notifications need one' }, 409);
1138
1581
  }
1582
+ // This gate is AUTHORITATIVE, not a preview: core can send an individual or
1583
+ // summary signal before the record reaches the dispatcher's second gate.
1584
+ // Storage owns the id, timestamps, and coalescing, so inspect a prospective
1585
+ // record carrying every untrusted model-visible field instead.
1586
+ if (options.inspectContent) {
1587
+ const prospectiveRecord = {
1588
+ id: 'prospective',
1589
+ threadId,
1590
+ resourceId,
1591
+ agentId: agent.id,
1592
+ source: notification.source,
1593
+ kind: notification.kind,
1594
+ summary: notification.summary,
1595
+ priority: notification.priority ?? 'medium',
1596
+ status: 'pending',
1597
+ coalescedCount: 1,
1598
+ ...(notification.attributes !== undefined
1599
+ ? { attributes: notification.attributes }
1600
+ : {}),
1601
+ createdAt: new Date(0),
1602
+ updatedAt: new Date(0),
1603
+ };
1604
+ // Core picks between two renderings after an async boundary this route does
1605
+ // not control, so inspect both — the same reason the schedule route inspects
1606
+ // both delivery branches. The individual signal renders `status="delivered"`
1607
+ // because that is the status core stamps on it when it sends; the summary
1608
+ // renders from the row as stored, which is why it keeps `status:'pending'`.
1609
+ for (const candidate of [
1610
+ createNotificationSignal({ ...prospectiveRecord, status: 'delivered' }),
1611
+ createNotificationSummarySignal(summarizeNotifications([prospectiveRecord])),
1612
+ ]) {
1613
+ const policyRefusal = await contentPolicyRefusal(options.inspectContent, candidate);
1614
+ if (policyRefusal)
1615
+ return policyRefusal;
1616
+ }
1617
+ }
1618
+ if (!options.persistenceAllowed) {
1619
+ const storage = await resolveNotificationsStorage?.();
1620
+ if (!storage) {
1621
+ return json({ error: 'notifications storage unavailable' }, 409);
1622
+ }
1623
+ const record = await storage.createNotification({
1624
+ ...notification,
1625
+ threadId,
1626
+ resourceId,
1627
+ agentId: agent.id,
1628
+ deliverAt: new Date(),
1629
+ });
1630
+ return json({
1631
+ record,
1632
+ delivery: { action: 'deferred', reason: 'dispatcher' },
1633
+ });
1634
+ }
1139
1635
  const result = await agent.sendNotificationSignal(notification, {
1140
1636
  threadId,
1141
1637
  resourceId,
1638
+ ...(!options.runtimeDriven
1639
+ ? { ifActive: { behavior: 'persist' } }
1640
+ : {}),
1641
+ ifIdle: { behavior: 'persist' },
1142
1642
  });
1143
1643
  if (result.persisted)
1144
1644
  await result.persisted;
1145
- return json({ record: result });
1645
+ const response = {
1646
+ record: result,
1647
+ ...(!options.runtimeDriven ? { degraded: 'not-runtime-driven' } : {}),
1648
+ };
1649
+ if (result.accepted)
1650
+ response.delivery = await result.accepted;
1651
+ return json(response);
1146
1652
  }
1147
1653
  //# sourceMappingURL=thread-do-routes.js.map