@proofoftech/flowsafe 0.20.0 → 0.21.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 (233) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +55 -8
  3. package/deployment-identity-protocol.d.mts +28 -3
  4. package/deployment-identity-protocol.mjs +275 -21
  5. package/dist/agent-host/router.d.ts.map +1 -1
  6. package/dist/agent-host/router.js +11 -2
  7. package/dist/agent-host/router.js.map +1 -1
  8. package/dist/agent-host/thread-host.d.ts +3 -1
  9. package/dist/agent-host/thread-host.d.ts.map +1 -1
  10. package/dist/agent-host/thread-host.js +837 -332
  11. package/dist/agent-host/thread-host.js.map +1 -1
  12. package/dist/agent-host/thread-topology.d.ts +8 -0
  13. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  14. package/dist/agent-host/thread-topology.js +239 -62
  15. package/dist/agent-host/thread-topology.js.map +1 -1
  16. package/dist/agent-runner/durable-agent-runner.d.ts +90 -6
  17. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  18. package/dist/agent-runner/durable-agent-runner.js +371 -29
  19. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  20. package/dist/agent-runner/index.d.ts +1 -1
  21. package/dist/agent-runner/index.d.ts.map +1 -1
  22. package/dist/agent-runner/index.js.map +1 -1
  23. package/dist/approval-api/actor-context.d.ts +4 -0
  24. package/dist/approval-api/actor-context.d.ts.map +1 -1
  25. package/dist/approval-api/actor-context.js +53 -5
  26. package/dist/approval-api/actor-context.js.map +1 -1
  27. package/dist/approval-api/principal.d.ts +1 -1
  28. package/dist/approval-api/principal.js +1 -1
  29. package/dist/approval-api/retention.d.ts +1 -2
  30. package/dist/approval-api/retention.d.ts.map +1 -1
  31. package/dist/approval-api/retention.js.map +1 -1
  32. package/dist/approval-api/service.d.ts +10 -14
  33. package/dist/approval-api/service.d.ts.map +1 -1
  34. package/dist/approval-api/service.js +49 -22
  35. package/dist/approval-api/service.js.map +1 -1
  36. package/dist/audit-export/index.d.ts +2 -2
  37. package/dist/audit-export/index.js +2 -2
  38. package/dist/background-tasks/d1-storage.d.ts +4 -3
  39. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  40. package/dist/background-tasks/d1-storage.js +7 -13
  41. package/dist/background-tasks/d1-storage.js.map +1 -1
  42. package/dist/do-runner/constants.d.ts +3 -0
  43. package/dist/do-runner/constants.d.ts.map +1 -0
  44. package/dist/do-runner/constants.js +3 -0
  45. package/dist/do-runner/constants.js.map +1 -0
  46. package/dist/do-runner/d1-storage.d.ts +31 -157
  47. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  48. package/dist/do-runner/d1-storage.js +933 -402
  49. package/dist/do-runner/d1-storage.js.map +1 -1
  50. package/dist/do-runner/durable-object.d.ts.map +1 -1
  51. package/dist/do-runner/durable-object.js +462 -175
  52. package/dist/do-runner/durable-object.js.map +1 -1
  53. package/dist/do-runner/execution-admission.d.ts +114 -0
  54. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  55. package/dist/do-runner/execution-admission.js +206 -0
  56. package/dist/do-runner/execution-admission.js.map +1 -0
  57. package/dist/do-runner/execution-context.d.ts.map +1 -1
  58. package/dist/do-runner/execution-context.js +1 -0
  59. package/dist/do-runner/execution-context.js.map +1 -1
  60. package/dist/do-runner/execution-fence.d.ts +74 -30
  61. package/dist/do-runner/execution-fence.d.ts.map +1 -1
  62. package/dist/do-runner/execution-fence.js +684 -120
  63. package/dist/do-runner/execution-fence.js.map +1 -1
  64. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  65. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  66. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  67. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  68. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  69. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  70. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  71. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  72. package/dist/do-runner/index.d.ts +13 -8
  73. package/dist/do-runner/index.d.ts.map +1 -1
  74. package/dist/do-runner/index.js +6 -2
  75. package/dist/do-runner/index.js.map +1 -1
  76. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  77. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  78. package/dist/do-runner/initial-admission-refusal.js +41 -0
  79. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  80. package/dist/do-runner/inventory.d.ts +2 -1
  81. package/dist/do-runner/inventory.d.ts.map +1 -1
  82. package/dist/do-runner/inventory.js +28 -39
  83. package/dist/do-runner/inventory.js.map +1 -1
  84. package/dist/do-runner/notification-predicate.d.ts +7 -7
  85. package/dist/do-runner/notification-predicate.d.ts.map +1 -1
  86. package/dist/do-runner/notification-predicate.js +134 -7
  87. package/dist/do-runner/notification-predicate.js.map +1 -1
  88. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  89. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  90. package/dist/do-runner/run-lifecycle.js +67 -13
  91. package/dist/do-runner/run-lifecycle.js.map +1 -1
  92. package/dist/do-runner/run-provenance.d.ts +38 -0
  93. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  94. package/dist/do-runner/run-provenance.js +152 -0
  95. package/dist/do-runner/run-provenance.js.map +1 -0
  96. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  97. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  98. package/dist/do-runner/run-storage-tables.js +4 -0
  99. package/dist/do-runner/run-storage-tables.js.map +1 -0
  100. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  101. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  102. package/dist/do-runner/run-terminal-state.js +105 -0
  103. package/dist/do-runner/run-terminal-state.js.map +1 -0
  104. package/dist/do-runner/runtime.d.ts +108 -46
  105. package/dist/do-runner/runtime.d.ts.map +1 -1
  106. package/dist/do-runner/runtime.js +927 -438
  107. package/dist/do-runner/runtime.js.map +1 -1
  108. package/dist/do-runner/start-idempotency.d.ts +35 -258
  109. package/dist/do-runner/start-idempotency.d.ts.map +1 -1
  110. package/dist/do-runner/start-idempotency.js +602 -494
  111. package/dist/do-runner/start-idempotency.js.map +1 -1
  112. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  113. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  114. package/dist/do-runner/start-reservation-contract.js +338 -0
  115. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  116. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  117. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  118. package/dist/do-runner/suspension-deadline.js +8 -12
  119. package/dist/do-runner/suspension-deadline.js.map +1 -1
  120. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  121. package/dist/do-runner/table-prefix.js +2 -1
  122. package/dist/do-runner/table-prefix.js.map +1 -1
  123. package/dist/do-runner/testing.d.ts +3 -0
  124. package/dist/do-runner/testing.d.ts.map +1 -0
  125. package/dist/do-runner/testing.js +3 -0
  126. package/dist/do-runner/testing.js.map +1 -0
  127. package/dist/do-runner/thread-do.d.ts +2 -1
  128. package/dist/do-runner/thread-do.d.ts.map +1 -1
  129. package/dist/do-runner/thread-do.js +14 -10
  130. package/dist/do-runner/thread-do.js.map +1 -1
  131. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  132. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  133. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  134. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  135. package/dist/goals/objective-routes.d.ts +1 -5
  136. package/dist/goals/objective-routes.d.ts.map +1 -1
  137. package/dist/goals/objective-routes.js +32 -53
  138. package/dist/goals/objective-routes.js.map +1 -1
  139. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  140. package/dist/host-kit/approval-bridge.js +10 -7
  141. package/dist/host-kit/approval-bridge.js.map +1 -1
  142. package/dist/host-kit/do-response.d.ts +16 -0
  143. package/dist/host-kit/do-response.d.ts.map +1 -1
  144. package/dist/host-kit/do-response.js +181 -0
  145. package/dist/host-kit/do-response.js.map +1 -1
  146. package/dist/host-kit/do-run-topology.d.ts +2 -14
  147. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  148. package/dist/host-kit/do-run-topology.js +31 -24
  149. package/dist/host-kit/do-run-topology.js.map +1 -1
  150. package/dist/host-kit/env-vars.d.ts.map +1 -1
  151. package/dist/host-kit/env-vars.js +5 -6
  152. package/dist/host-kit/env-vars.js.map +1 -1
  153. package/dist/host-kit/flowsafe-worker.d.ts +38 -6
  154. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  155. package/dist/host-kit/flowsafe-worker.js +110 -93
  156. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  157. package/dist/host-kit/host-approval-service.d.ts +4 -14
  158. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  159. package/dist/host-kit/host-approval-service.js +23 -40
  160. package/dist/host-kit/host-approval-service.js.map +1 -1
  161. package/dist/host-kit/index.d.ts +7 -1
  162. package/dist/host-kit/index.d.ts.map +1 -1
  163. package/dist/host-kit/index.js +4 -0
  164. package/dist/host-kit/index.js.map +1 -1
  165. package/dist/host-kit/run-route-error.d.ts +3 -17
  166. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  167. package/dist/host-kit/run-route-error.js +4 -24
  168. package/dist/host-kit/run-route-error.js.map +1 -1
  169. package/dist/host-kit/run-router.d.ts +6 -2
  170. package/dist/host-kit/run-router.d.ts.map +1 -1
  171. package/dist/host-kit/run-router.js +93 -80
  172. package/dist/host-kit/run-router.js.map +1 -1
  173. package/dist/host-kit/thread-topology.d.ts +1 -1
  174. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  175. package/dist/host-kit/thread-topology.js +7 -3
  176. package/dist/host-kit/thread-topology.js.map +1 -1
  177. package/dist/internal-error-response.d.ts.map +1 -1
  178. package/dist/internal-error-response.js +16 -6
  179. package/dist/internal-error-response.js.map +1 -1
  180. package/dist/schedules/index.d.ts +1 -0
  181. package/dist/schedules/index.d.ts.map +1 -1
  182. package/dist/schedules/index.js +1 -7
  183. package/dist/schedules/index.js.map +1 -1
  184. package/dist/schedules/mutation-contract.d.ts +38 -0
  185. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  186. package/dist/schedules/mutation-contract.js +21 -0
  187. package/dist/schedules/mutation-contract.js.map +1 -0
  188. package/dist/schedules/router.d.ts +11 -19
  189. package/dist/schedules/router.d.ts.map +1 -1
  190. package/dist/schedules/router.js +130 -49
  191. package/dist/schedules/router.js.map +1 -1
  192. package/dist/schedules/schedules-d1.d.ts +11 -5
  193. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  194. package/dist/schedules/schedules-d1.js +570 -143
  195. package/dist/schedules/schedules-d1.js.map +1 -1
  196. package/dist/schedules/storage.d.ts +0 -7
  197. package/dist/schedules/storage.d.ts.map +1 -1
  198. package/dist/schedules/storage.js +0 -27
  199. package/dist/schedules/storage.js.map +1 -1
  200. package/dist/schedules/tick.d.ts.map +1 -1
  201. package/dist/schedules/tick.js +7 -1
  202. package/dist/schedules/tick.js.map +1 -1
  203. package/dist/signal-providers/webhook-route.d.ts +1 -1
  204. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  205. package/dist/signal-providers/webhook-route.js +99 -109
  206. package/dist/signal-providers/webhook-route.js.map +1 -1
  207. package/dist/signals/d1-shared.d.ts +11 -8
  208. package/dist/signals/d1-shared.d.ts.map +1 -1
  209. package/dist/signals/d1-shared.js +1 -6
  210. package/dist/signals/d1-shared.js.map +1 -1
  211. package/dist/signals/index.d.ts +1 -1
  212. package/dist/signals/index.d.ts.map +1 -1
  213. package/dist/signals/index.js +1 -1
  214. package/dist/signals/index.js.map +1 -1
  215. package/dist/signals/notification-dispatch.d.ts +96 -5
  216. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  217. package/dist/signals/notification-dispatch.js +418 -53
  218. package/dist/signals/notification-dispatch.js.map +1 -1
  219. package/dist/signals/notifications-d1.d.ts +6 -1
  220. package/dist/signals/notifications-d1.d.ts.map +1 -1
  221. package/dist/signals/notifications-d1.js +215 -10
  222. package/dist/signals/notifications-d1.js.map +1 -1
  223. package/dist/signals/router.d.ts +6 -4
  224. package/dist/signals/router.d.ts.map +1 -1
  225. package/dist/signals/router.js +49 -84
  226. package/dist/signals/router.js.map +1 -1
  227. package/dist/signals/thread-do-routes.d.ts +2 -0
  228. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  229. package/dist/signals/thread-do-routes.js +252 -73
  230. package/dist/signals/thread-do-routes.js.map +1 -1
  231. package/package.json +6 -3
  232. package/patches/@mastra__core@1.53.0.patch +54 -0
  233. package/scripts/seed-deployment-identity.mjs +12 -5
@@ -28,10 +28,11 @@ import { RequestContext } from '@mastra/core/request-context';
28
28
  import { FLOWSAFE_PERSISTENCE_FORBIDDEN } from '../agent-runner/durable-agent-runner.js';
29
29
  import { isRuntimeDrivenAgent, } from '../agent-runner/index.js';
30
30
  import { samePrincipal, } from '../approval-api/index.js';
31
- import { admitsExistingRun, DoStatusError, executionFencedResponse, isExecutionFenceRefusal, isPathSafeId, readExecutionFence, } from '../do-runner/index.js';
31
+ import { admitsExistingRun, DoStatusError, ExecutionFencedError, executionFencedResponse, isExecutionFenceRefusal, isPathSafeId, readExecutionFence, } from '../do-runner/index.js';
32
32
  import { internalErrorResponse } from '../internal-error-response.js';
33
+ import { positiveSafeInteger } from '../numeric-config.js';
33
34
  import { createScheduleAgentDispatchReceipt, } from '../schedules/schedules-d1.js';
34
- import { deferNotificationAfterFailure, MAX_NOTIFICATION_DISPATCH_IDS, planNotificationDispatch, } from './notification-dispatch.js';
35
+ import { assertNotificationDeliveryPolicyPatched, assertNotificationSourceKeysPatched, captureNotificationDeliverySelection, captureNotificationDeliveryStorage, DEFAULT_MAX_NOTIFICATION_DELIVERY_ATTEMPTS, MAX_NOTIFICATION_DISPATCH_IDS, planNotificationDispatch, recordNotificationDeliveryFailure, reportNotificationDeliveryError, } from './notification-dispatch.js';
35
36
  /**
36
37
  * The idle-thread delivery behavior a send may ask for. `wake` starts a run
37
38
  * after consulting the run cap; `persist` writes the signal to the durable
@@ -190,6 +191,7 @@ function signalContentPolicyResponse(inspection) {
190
191
  : json({ error: 'signal content policy unavailable' }, 503);
191
192
  }
192
193
  export function createThreadSignalRoutes(options) {
194
+ const maxDeliveryAttempts = positiveSafeInteger(options.maxDeliveryAttempts ?? DEFAULT_MAX_NOTIFICATION_DELIVERY_ATTEMPTS, 'notification maximum delivery attempts');
193
195
  const { resolveAgent, resolveResourceId, consultRunCap, startIdleRun, resolveBlockingRun, serializeDispatch, resolveScheduleRunStatus, resolveScheduleTarget, canPersist, canPersistSchedule, resolveNotificationsStorage, resolveScheduleDispatchStore, contentPolicy, } = options;
194
196
  if (resolveBlockingRun && !serializeDispatch) {
195
197
  throw new Error('signal routes require serializeDispatch with resolveBlockingRun');
@@ -284,11 +286,43 @@ export function createThreadSignalRoutes(options) {
284
286
  // the lanes that never reach it (the persist routes, and a default
285
287
  // non-wake delivery) ungated; handleWake keeps its own check for the
286
288
  // wake path it owns.
289
+ let proof;
287
290
  if (executionFence.state === 'proof-only') {
288
- const activeRunId = activeThreadRunIdOf(agent, threadId, resourceId ?? '');
289
- if (!admitsExistingRun(executionFence, activeRunId)) {
290
- return executionFencedResponse(executionFence.state, entryPath);
291
- }
291
+ const runtime = scope.init.runtime;
292
+ const reader = agent.proofExecutionFor;
293
+ if (!runtimeDriven ||
294
+ typeof reader !== 'function' ||
295
+ runtime.executionFence !== scope.init.executionFence)
296
+ throw new ExecutionFencedError(executionFence.state, entryPath);
297
+ const capture = async (runId) => {
298
+ if (runId === undefined)
299
+ throw new ExecutionFencedError(executionFence.state, entryPath);
300
+ const execution = await Reflect.apply(reader, agent, [
301
+ runtime,
302
+ threadId,
303
+ runId,
304
+ ]);
305
+ if (execution === undefined ||
306
+ !admitsExistingRun(executionFence, execution))
307
+ throw new ExecutionFencedError(executionFence.state, entryPath);
308
+ return Object.freeze({ ...execution });
309
+ };
310
+ const admitted = await capture(activeThreadRunIdOf(agent, threadId, resourceId ?? ''));
311
+ const assertActive = (expected = admitted) => {
312
+ if (activeThreadRunIdOf(agent, threadId, resourceId ?? '') !==
313
+ expected.runId)
314
+ throw new ExecutionFencedError(executionFence.state, entryPath);
315
+ };
316
+ proof = {
317
+ capture,
318
+ async check(expected = admitted) {
319
+ const current = await capture(expected.runId);
320
+ if (!admitsExistingRun({ state: 'proof-only', proofExecution: expected }, current))
321
+ throw new ExecutionFencedError(executionFence.state, entryPath);
322
+ },
323
+ assertActive,
324
+ };
325
+ assertActive();
292
326
  }
293
327
  let memoryResolution;
294
328
  const memoryAvailable = () => {
@@ -298,10 +332,15 @@ export function createThreadSignalRoutes(options) {
298
332
  Boolean(await agent.getMemory()));
299
333
  }
300
334
  catch {
301
- console.error(JSON.stringify({
302
- type: 'signal-memory-resolution-failed',
303
- threadId,
304
- }));
335
+ try {
336
+ console.error(JSON.stringify({
337
+ type: 'signal-memory-resolution-failed',
338
+ threadId,
339
+ }));
340
+ }
341
+ catch {
342
+ // Diagnostics cannot change the memory fallback.
343
+ }
305
344
  return false;
306
345
  }
307
346
  })();
@@ -339,6 +378,7 @@ export function createThreadSignalRoutes(options) {
339
378
  persistenceAllowed,
340
379
  memoryAvailable,
341
380
  inspectContent,
381
+ proof,
342
382
  executionFence,
343
383
  });
344
384
  }
@@ -351,6 +391,7 @@ export function createThreadSignalRoutes(options) {
351
391
  persistenceAllowed,
352
392
  memoryAvailable,
353
393
  inspectContent,
394
+ proof,
354
395
  });
355
396
  }
356
397
  // POST /signal — a system signal (ifActive/ifIdle deliver/persist/discard/wake).
@@ -362,6 +403,7 @@ export function createThreadSignalRoutes(options) {
362
403
  persistenceAllowed,
363
404
  memoryAvailable,
364
405
  inspectContent,
406
+ proof,
365
407
  executionFence,
366
408
  });
367
409
  }
@@ -397,6 +439,7 @@ export function createThreadSignalRoutes(options) {
397
439
  store: await resolveScheduleDispatchStore(scope),
398
440
  completed: completedScheduleDispatches,
399
441
  inspectContent,
442
+ proof,
400
443
  });
401
444
  }
402
445
  // POST /signal/state — a durable thread-state lane (snapshot/delta).
@@ -408,6 +451,7 @@ export function createThreadSignalRoutes(options) {
408
451
  runtimeDriven,
409
452
  memoryAvailable,
410
453
  inspectContent,
454
+ proof,
411
455
  });
412
456
  }
413
457
  if (requestedAgentId !== undefined) {
@@ -431,15 +475,17 @@ export function createThreadSignalRoutes(options) {
431
475
  persistenceAllowed,
432
476
  memoryAvailable,
433
477
  storage: await resolveNotificationsStorage(scope),
478
+ maxDeliveryAttempts,
434
479
  agentId: requestedAgentId,
435
480
  inspectContent,
481
+ proof,
436
482
  }));
437
483
  }
438
484
  // POST /signal/notification — the durable AGENT inbox (mastra_notifications).
439
485
  if (path === '/signal/notification') {
440
486
  return await serializeNotification(async () => handleNotification(agent, body, threadId, resourceId, resolveNotificationsStorage
441
487
  ? () => resolveNotificationsStorage(scope)
442
- : undefined, { persistenceAllowed, runtimeDriven, inspectContent }));
488
+ : undefined, { persistenceAllowed, runtimeDriven, inspectContent, proof }));
443
489
  }
444
490
  return json({ error: 'not found' }, 404);
445
491
  }
@@ -508,6 +554,7 @@ async function handleNotificationDispatch(options) {
508
554
  if (Number.isNaN(now.getTime())) {
509
555
  return json({ error: 'now must be an ISO timestamp' }, 400);
510
556
  }
557
+ const nowMs = now.getTime();
511
558
  const carriesBatchThreadState = Object.hasOwn(options.body, 'batchThreadState');
512
559
  const requestedBatchThreadState = options.body.batchThreadState;
513
560
  if (carriesBatchThreadState &&
@@ -516,30 +563,61 @@ async function handleNotificationDispatch(options) {
516
563
  requestedBatchThreadState !== 'idle') {
517
564
  return json({ error: 'batchThreadState must be null, active, or idle' }, 400);
518
565
  }
519
- const records = [];
566
+ assertNotificationSourceKeysPatched();
567
+ const deliveryStorage = captureNotificationDeliveryStorage(options.storage);
568
+ const selections = [];
569
+ // A record settles once: an already-discarded record must not be counted
570
+ // twice, nor have its content-policy reason overwritten by an unrelated
571
+ // storage error. `recordFailure` returns early for the same reason.
572
+ const settled = new Set();
573
+ let delivered = 0;
574
+ let failed = 0;
575
+ let discarded = 0;
520
576
  let skipped = 0;
577
+ const settle = (id, outcome) => {
578
+ if (settled.has(id))
579
+ return;
580
+ settled.add(id);
581
+ if (outcome === 'delivered')
582
+ delivered += 1;
583
+ else if (outcome === 'failed')
584
+ failed += 1;
585
+ else if (outcome === 'discarded')
586
+ discarded += 1;
587
+ else
588
+ skipped += 1;
589
+ };
521
590
  for (const id of uniqueIds) {
522
- const current = await options.storage.getNotification({
591
+ const current = await deliveryStorage.getNotification({
523
592
  threadId: options.threadId,
524
593
  id,
525
594
  });
526
595
  if (current?.status !== 'pending' || current.deliveredSignalId) {
527
- skipped += 1;
596
+ settle(id, 'skipped');
528
597
  continue;
529
598
  }
530
- if (current.resourceId !== options.resourceId ||
599
+ if (current.id !== id ||
600
+ current.threadId !== options.threadId ||
601
+ current.resourceId !== options.resourceId ||
531
602
  current.agentId !== options.agentId) {
532
603
  return json({ error: 'notification binding does not match' }, 404);
533
604
  }
534
- const due = (current.deliverAt !== undefined &&
535
- current.deliverAt.getTime() <= now.getTime()) ||
536
- (current.summaryAt !== undefined &&
537
- current.summaryAt.getTime() <= now.getTime());
538
- if (!due) {
539
- skipped += 1;
540
- continue;
605
+ try {
606
+ const selection = captureNotificationDeliverySelection(current);
607
+ const { record } = selection;
608
+ const due = (record.deliverAt !== undefined &&
609
+ record.deliverAt.getTime() <= nowMs) ||
610
+ (record.summaryAt !== undefined && record.summaryAt.getTime() <= nowMs);
611
+ if (!due) {
612
+ settle(id, 'skipped');
613
+ continue;
614
+ }
615
+ selections.push(selection);
616
+ }
617
+ catch (error) {
618
+ settle(id, 'failed');
619
+ reportNotificationDeliveryError(error);
541
620
  }
542
- records.push(current);
543
621
  }
544
622
  const batchThreadState = requestedBatchThreadState === 'active' ||
545
623
  requestedBatchThreadState === 'idle'
@@ -548,30 +626,29 @@ async function handleNotificationDispatch(options) {
548
626
  activeThreadRunIdOf(options.agent, options.threadId, resourceId)
549
627
  ? 'active'
550
628
  : 'idle';
551
- let delivered = 0;
552
- let failed = 0;
553
- let discarded = 0;
554
- // Records whose terminal discard is already durable. A later throw in the
555
- // same group funnels the group into `updateFailure`; without this, an
556
- // already-discarded record would be counted twice and have its
557
- // content-policy reason overwritten by an unrelated storage error.
558
- const settledDiscards = new Set();
559
- const updateFailure = async (record, error) => {
560
- if (settledDiscards.has(record.id))
629
+ const recordFailure = async (expected, action) => {
630
+ if (action.type === 'failure' && isExecutionFenceRefusal(action.error))
631
+ throw action.error;
632
+ if (!expected)
633
+ throw new Error('notification observation is unavailable');
634
+ if (settled.has(expected.id))
561
635
  return;
562
- failed += 1;
563
- await deferNotificationAfterFailure(options.storage, record, now, error);
636
+ await options.proof?.check();
637
+ options.proof?.assertActive();
638
+ const outcome = await recordNotificationDeliveryFailure(deliveryStorage, expected, new Date(nowMs), options.maxDeliveryAttempts, action);
639
+ settle(expected.id, outcome === 'discarded' ? 'discarded' : 'failed');
564
640
  };
565
641
  const discardAfterDenial = async (record) => {
642
+ await options.proof?.check();
643
+ options.proof?.assertActive();
566
644
  await options.storage.updateNotification({
567
645
  id: record.id,
568
646
  threadId: record.threadId,
569
647
  status: 'discarded',
570
648
  deliveryReason: 'content-policy-denied',
571
- lastDeliveryAttemptAt: now,
649
+ lastDeliveryAttemptAt: new Date(nowMs),
572
650
  });
573
- settledDiscards.add(record.id);
574
- discarded += 1;
651
+ settle(record.id, 'discarded');
575
652
  };
576
653
  const inspect = async (signal) => {
577
654
  if (!options.inspectContent)
@@ -595,6 +672,7 @@ async function handleNotificationDispatch(options) {
595
672
  startIdleRun: options.startIdleRun,
596
673
  serializeWake: options.serializeWake,
597
674
  executionFence: options.executionFence,
675
+ proof: options.proof,
598
676
  blockingRun: durableBlockingRun
599
677
  ? () => durableBlockingRun
600
678
  : options.blockingRun,
@@ -618,8 +696,11 @@ async function handleNotificationDispatch(options) {
618
696
  ifIdle: { behavior: 'persist' },
619
697
  }),
620
698
  });
621
- if (!response.ok)
699
+ if (!response.ok) {
700
+ if (options.executionFence.state === 'proof-only')
701
+ throw new ExecutionFencedError('proof-only', 'notification signal');
622
702
  throw new Error(`notification signal returned ${response.status}`);
703
+ }
623
704
  const result = (await response.json());
624
705
  const action = recordValue(result.decision)?.action;
625
706
  // A stale active id can fall through to idle. Persistence-forbidden and
@@ -640,6 +721,8 @@ async function handleNotificationDispatch(options) {
640
721
  if (!(await options.memoryAvailable())) {
641
722
  throw new Error('signal persistence requires agent memory');
642
723
  }
724
+ await options.proof?.check();
725
+ options.proof?.assertActive();
643
726
  const result = options.agent.sendSignal(signal, {
644
727
  threadId: options.threadId,
645
728
  resourceId,
@@ -651,12 +734,21 @@ async function handleNotificationDispatch(options) {
651
734
  await result.persisted;
652
735
  return result.signal.id;
653
736
  };
737
+ const records = [];
738
+ const observations = new Map();
739
+ for (const { record, expected } of selections) {
740
+ if (expected.deliveryAttempts >= options.maxDeliveryAttempts) {
741
+ await recordFailure(expected, { type: 'exhausted' });
742
+ continue;
743
+ }
744
+ records.push(record);
745
+ observations.set(record.id, expected);
746
+ }
654
747
  for (const item of planNotificationDispatch(records, now)) {
655
748
  if (item.type === 'summary') {
656
- // Everything from rendering onward stays inside this try: a storage
657
- // failure in the discard/failure bookkeeping below must be contained to
658
- // this group, exactly as the individual branch contains its own, rather
659
- // than escaping and abandoning the rest of the plan.
749
+ // A summary group's failure, from rendering through bookkeeping, is
750
+ // contained to this group rather than escaping and abandoning the rest
751
+ // of the plan.
660
752
  try {
661
753
  const signal = createNotificationSummarySignal(summarizeNotifications(item.records));
662
754
  const inspection = await inspect(signal);
@@ -667,7 +759,10 @@ async function handleNotificationDispatch(options) {
667
759
  }
668
760
  if (inspection === 'error') {
669
761
  for (const record of item.records) {
670
- await updateFailure(record, new Error('signal content policy failed'));
762
+ await recordFailure(observations.get(record.id), {
763
+ type: 'failure',
764
+ error: new Error('signal content policy failed'),
765
+ });
671
766
  }
672
767
  continue;
673
768
  }
@@ -676,49 +771,70 @@ async function handleNotificationDispatch(options) {
676
771
  ? await persistWithoutWake(signal)
677
772
  : await send(signal);
678
773
  for (const record of item.records) {
774
+ await options.proof?.check();
775
+ options.proof?.assertActive();
679
776
  await options.storage.updateNotification({
680
777
  id: record.id,
681
778
  threadId: record.threadId,
682
779
  summaryAt: null,
683
780
  summarySignalId: signalId,
684
- lastDeliveryAttemptAt: now,
781
+ lastDeliveryAttemptAt: new Date(nowMs),
685
782
  });
686
- delivered += 1;
783
+ settle(record.id, 'delivered');
687
784
  }
688
785
  }
689
786
  catch (error) {
690
- for (const record of item.records)
691
- await updateFailure(record, error);
787
+ for (const record of item.records) {
788
+ await recordFailure(observations.get(record.id), {
789
+ type: 'failure',
790
+ error,
791
+ });
792
+ }
692
793
  }
693
794
  continue;
694
795
  }
695
796
  const selected = item.record;
797
+ let expected = observations.get(selected.id);
696
798
  try {
697
- const record = await options.storage.getNotification({
799
+ const current = await deliveryStorage.getNotification({
698
800
  threadId: selected.threadId,
699
801
  id: selected.id,
700
802
  });
701
- const summaryDue = Boolean(record?.summaryAt && record.summaryAt.getTime() <= now.getTime());
702
- const deliveryDue = Boolean(record?.deliverAt && record.deliverAt.getTime() <= now.getTime());
703
- if (record?.status !== 'pending' ||
704
- record.deliveredSignalId ||
705
- record.resourceId !== resourceId ||
706
- record.agentId !== options.agentId ||
707
- summaryDue ||
708
- !deliveryDue) {
709
- skipped += 1;
803
+ if (current?.status !== 'pending' ||
804
+ current.deliveredSignalId ||
805
+ current.id !== selected.id ||
806
+ current.threadId !== options.threadId ||
807
+ current.resourceId !== resourceId ||
808
+ current.agentId !== options.agentId) {
809
+ settle(selected.id, 'skipped');
810
+ continue;
811
+ }
812
+ // Clearing the pre-read observation keeps a failure between here and the
813
+ // re-capture from being recorded against stale state.
814
+ expected = undefined;
815
+ const selection = captureNotificationDeliverySelection(current);
816
+ const { record } = selection;
817
+ expected = selection.expected;
818
+ const summaryDue = Boolean(record.summaryAt && record.summaryAt.getTime() <= nowMs);
819
+ const deliveryDue = Boolean(record.deliverAt && record.deliverAt.getTime() <= nowMs);
820
+ if (summaryDue || !deliveryDue) {
821
+ settle(selected.id, 'skipped');
822
+ continue;
823
+ }
824
+ if (expected.deliveryAttempts >= options.maxDeliveryAttempts) {
825
+ await recordFailure(expected, { type: 'exhausted' });
710
826
  continue;
711
827
  }
712
828
  if (record.priority === 'high' &&
713
829
  record.summarySignalId &&
714
830
  batchThreadState === 'active') {
715
- skipped += 1;
831
+ settle(selected.id, 'skipped');
716
832
  continue;
717
833
  }
718
834
  const signal = createNotificationSignal({
719
835
  ...record,
720
836
  status: 'delivered',
721
- deliveredAt: now,
837
+ deliveredAt: new Date(nowMs),
722
838
  });
723
839
  const inspection = await inspect(signal);
724
840
  if (inspection === 'denied') {
@@ -726,21 +842,33 @@ async function handleNotificationDispatch(options) {
726
842
  continue;
727
843
  }
728
844
  if (inspection === 'error') {
729
- await updateFailure(record, new Error('signal content policy failed'));
845
+ await recordFailure(expected, {
846
+ type: 'failure',
847
+ error: new Error('signal content policy failed'),
848
+ });
730
849
  continue;
731
850
  }
732
851
  const signalId = await send(signal);
852
+ await options.proof?.check();
853
+ options.proof?.assertActive();
733
854
  await options.storage.updateNotification({
734
855
  id: record.id,
735
856
  threadId: record.threadId,
736
857
  status: 'delivered',
737
858
  deliveredSignalId: signalId,
738
- lastDeliveryAttemptAt: now,
859
+ lastDeliveryAttemptAt: new Date(nowMs),
739
860
  });
740
- delivered += 1;
861
+ settle(record.id, 'delivered');
741
862
  }
742
863
  catch (error) {
743
- await updateFailure(selected, error);
864
+ if (isExecutionFenceRefusal(error))
865
+ throw error;
866
+ if (expected)
867
+ await recordFailure(expected, { type: 'failure', error });
868
+ else {
869
+ settle(selected.id, 'failed');
870
+ reportNotificationDeliveryError(error);
871
+ }
744
872
  }
745
873
  }
746
874
  return json({
@@ -831,9 +959,11 @@ async function handleWake(options) {
831
959
  // what the drain is waiting for — and in proof-only it is admitted only
832
960
  // for the nominated run. The check sits after the principal gate so a
833
961
  // fenced deployment leaks nothing a permitted caller could not see.
834
- if (activeRunId && !admitsExistingRun(fence, activeRunId)) {
835
- return executionFencedResponse(fence.state, 'signal delivery');
836
- }
962
+ const admitted = fence.state === 'proof-only'
963
+ ? await options.proof?.capture(activeRunId)
964
+ : undefined;
965
+ if (fence.state === 'proof-only' && admitted === undefined)
966
+ throw new ExecutionFencedError(fence.state, 'signal delivery');
837
967
  if (activeRunId) {
838
968
  if (durableBlockingRun && durableBlockingRun.runId !== activeRunId) {
839
969
  return json({
@@ -846,6 +976,8 @@ async function handleWake(options) {
846
976
  });
847
977
  }
848
978
  const memoryAvailable = await options.memoryAvailable();
979
+ await options.proof?.check(admitted);
980
+ options.proof?.assertActive(admitted);
849
981
  const delivered = options.deliverActive(activeRunId, memoryAvailable);
850
982
  const decision = await delivered.accepted;
851
983
  if (delivered.persisted)
@@ -1026,6 +1158,8 @@ async function handleScheduleSignal(options) {
1026
1158
  const receipt = createScheduleAgentDispatchReceipt('discard', {
1027
1159
  signalId: dispatchId,
1028
1160
  });
1161
+ await options.proof?.check();
1162
+ options.proof?.assertActive();
1029
1163
  options.completed.set(dispatchId, receipt);
1030
1164
  await options.store.settle(scheduleId, dispatchId, receipt);
1031
1165
  options.completed.delete(dispatchId);
@@ -1033,10 +1167,14 @@ async function handleScheduleSignal(options) {
1033
1167
  };
1034
1168
  const completed = options.completed.get(dispatchId);
1035
1169
  if (completed) {
1170
+ await options.proof?.check();
1171
+ options.proof?.assertActive();
1036
1172
  await options.store.settle(scheduleId, dispatchId, completed);
1037
1173
  options.completed.delete(dispatchId);
1038
1174
  return json({ receipt: completed });
1039
1175
  }
1176
+ await options.proof?.check();
1177
+ options.proof?.assertActive();
1040
1178
  const state = await options.store.begin(scheduleId, dispatchId);
1041
1179
  if (state.state === 'missing') {
1042
1180
  return json({ error: 'schedule dispatch not found' }, 404);
@@ -1059,6 +1197,8 @@ async function handleScheduleSignal(options) {
1059
1197
  runId: recoveredRun.runId,
1060
1198
  signalId: dispatchId,
1061
1199
  };
1200
+ await options.proof?.check();
1201
+ options.proof?.assertActive();
1062
1202
  options.completed.set(dispatchId, receipt);
1063
1203
  await options.store.settle(scheduleId, dispatchId, receipt);
1064
1204
  options.completed.delete(dispatchId);
@@ -1073,6 +1213,8 @@ async function handleScheduleSignal(options) {
1073
1213
  runId: durableBlockingRun.runId,
1074
1214
  signalId: dispatchId,
1075
1215
  };
1216
+ await options.proof?.check();
1217
+ options.proof?.assertActive();
1076
1218
  options.completed.set(dispatchId, receipt);
1077
1219
  await options.store.settle(scheduleId, dispatchId, receipt);
1078
1220
  options.completed.delete(dispatchId);
@@ -1091,12 +1233,17 @@ async function handleScheduleSignal(options) {
1091
1233
  !renderableAttributes(target.ifIdle?.attributes)) {
1092
1234
  // The operator has to be able to find the broken schedule; the offending
1093
1235
  // name itself stays out of the log.
1094
- console.error(JSON.stringify({
1095
- type: 'schedule-target-unrenderable',
1096
- scheduleId,
1097
- dispatchId,
1098
- agentId: target.agentId,
1099
- }));
1236
+ try {
1237
+ console.error(JSON.stringify({
1238
+ type: 'schedule-target-unrenderable',
1239
+ scheduleId,
1240
+ dispatchId,
1241
+ agentId: target.agentId,
1242
+ }));
1243
+ }
1244
+ catch {
1245
+ // Diagnostics cannot prevent terminal settlement.
1246
+ }
1100
1247
  return await settleDiscard();
1101
1248
  }
1102
1249
  const baseProviderOptions = target.providerOptions ?? {};
@@ -1220,6 +1367,7 @@ async function handleScheduleSignal(options) {
1220
1367
  startIdleRun: options.startIdleRun,
1221
1368
  serializeWake: options.serializeWake,
1222
1369
  executionFence: options.executionFence,
1370
+ proof: options.proof,
1223
1371
  blockingRun: durableBlockingRun
1224
1372
  ? () => durableBlockingRun
1225
1373
  : options.blockingRun,
@@ -1255,6 +1403,8 @@ async function handleScheduleSignal(options) {
1255
1403
  typeof payload.signalId === 'string' ? payload.signalId : undefined;
1256
1404
  }
1257
1405
  else {
1406
+ await options.proof?.check();
1407
+ options.proof?.assertActive();
1258
1408
  const sent = options.agent.sendSignal(deliverableSignal, signalTarget);
1259
1409
  decision = await sent.accepted;
1260
1410
  const action = recordValue(decision)?.action;
@@ -1274,6 +1424,8 @@ async function handleScheduleSignal(options) {
1274
1424
  if (!receipt) {
1275
1425
  throw new Error('agent schedule returned an invalid signal decision');
1276
1426
  }
1427
+ await options.proof?.check();
1428
+ options.proof?.assertActive();
1277
1429
  options.completed.set(dispatchId, receipt);
1278
1430
  await options.store.settle(scheduleId, dispatchId, receipt);
1279
1431
  options.completed.delete(dispatchId);
@@ -1327,6 +1479,7 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
1327
1479
  startIdleRun,
1328
1480
  serializeWake,
1329
1481
  executionFence: options.executionFence,
1482
+ proof: options.proof,
1330
1483
  blockingRun: durableBlockingRun
1331
1484
  ? () => durableBlockingRun
1332
1485
  : options.blockingRun,
@@ -1357,6 +1510,8 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
1357
1510
  return persistenceForbiddenResponse({ capped: false });
1358
1511
  }
1359
1512
  const memoryAvailable = await options.memoryAvailable();
1513
+ await options.proof?.check();
1514
+ options.proof?.assertActive();
1360
1515
  const result = agent.sendMessage(message, {
1361
1516
  threadId,
1362
1517
  resourceId,
@@ -1400,6 +1555,8 @@ async function handleQueue(agent, body, threadId, resourceId, options) {
1400
1555
  return policyRefusal;
1401
1556
  if (!(await options.memoryAvailable()))
1402
1557
  return memoryUnavailableResponse();
1558
+ await options.proof?.check();
1559
+ options.proof?.assertActive();
1403
1560
  const result = agent.sendMessage(message, {
1404
1561
  threadId,
1405
1562
  resourceId,
@@ -1454,6 +1611,8 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
1454
1611
  if (!isPathSafeId(runId)) {
1455
1612
  throw new Error('thread signal generated a non-path-safe run id');
1456
1613
  }
1614
+ await options.proof?.check();
1615
+ options.proof?.assertActive();
1457
1616
  const result = agent.sendSignal(signal, {
1458
1617
  threadId,
1459
1618
  runId,
@@ -1476,6 +1635,7 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
1476
1635
  startIdleRun,
1477
1636
  serializeWake,
1478
1637
  executionFence: options.executionFence,
1638
+ proof: options.proof,
1479
1639
  blockingRun: durableBlockingRun
1480
1640
  ? () => durableBlockingRun
1481
1641
  : options.blockingRun,
@@ -1507,6 +1667,8 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
1507
1667
  }
1508
1668
  const memoryAvailable = await options.memoryAvailable();
1509
1669
  const wasActive = activeThreadRunIdOf(agent, threadId, resourceId) !== undefined;
1670
+ await options.proof?.check();
1671
+ options.proof?.assertActive();
1510
1672
  const result = agent.sendSignal(signal, {
1511
1673
  threadId,
1512
1674
  resourceId,
@@ -1580,6 +1742,8 @@ async function handleState(agent, body, threadId, resourceId, options) {
1580
1742
  return policyRefusal;
1581
1743
  if (!(await options.memoryAvailable()))
1582
1744
  return memoryUnavailableResponse();
1745
+ await options.proof?.check();
1746
+ options.proof?.assertActive();
1583
1747
  const result = await agent.sendStateSignal(state, {
1584
1748
  threadId,
1585
1749
  resourceId,
@@ -1647,6 +1811,17 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
1647
1811
  if (resourceId === undefined) {
1648
1812
  return json({ error: 'this thread has no resourceId wired; notifications need one' }, 409);
1649
1813
  }
1814
+ // Ingestion reaches core's patched functions below — the content-policy gate
1815
+ // renders a prospective summary through summarizeNotifications, and core's
1816
+ // inline sender resolves the configured source delivery policy — so the
1817
+ // refusal sits above the branches rather than beside a single reach. It
1818
+ // refuses the record-only branch as well, which a deployment that ingests
1819
+ // here and delegates dispatch elsewhere pays. The route's catch answers 502
1820
+ // with the message on the server log. Each subject has its own probe: the
1821
+ // synchronous call covers summarizeNotifications, and the awaited one covers
1822
+ // the source delivery policy lookup, which resolves asynchronously.
1823
+ assertNotificationSourceKeysPatched();
1824
+ await assertNotificationDeliveryPolicyPatched();
1650
1825
  // This gate is AUTHORITATIVE, not a preview: core can send an individual or
1651
1826
  // summary signal before the record reaches the dispatcher's second gate.
1652
1827
  // Storage owns the id, timestamps, and coalescing, so inspect a prospective
@@ -1688,6 +1863,8 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
1688
1863
  if (!storage) {
1689
1864
  return json({ error: 'notifications storage unavailable' }, 409);
1690
1865
  }
1866
+ await options.proof?.check();
1867
+ options.proof?.assertActive();
1691
1868
  const record = await storage.createNotification({
1692
1869
  ...notification,
1693
1870
  threadId,
@@ -1700,6 +1877,8 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
1700
1877
  delivery: { action: 'deferred', reason: 'dispatcher' },
1701
1878
  });
1702
1879
  }
1880
+ await options.proof?.check();
1881
+ options.proof?.assertActive();
1703
1882
  const result = await agent.sendNotificationSignal(notification, {
1704
1883
  threadId,
1705
1884
  resourceId,