@proofoftech/flowsafe 0.28.0 → 0.31.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 (123) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +6 -2
  3. package/deployment-identity-protocol.mjs +3 -4
  4. package/dist/agent-host/catalog.js +1 -1
  5. package/dist/agent-host/catalog.js.map +1 -1
  6. package/dist/agent-host/index.d.ts +4 -1
  7. package/dist/agent-host/index.d.ts.map +1 -1
  8. package/dist/agent-host/index.js +2 -1
  9. package/dist/agent-host/index.js.map +1 -1
  10. package/dist/agent-host/thread-host.d.ts +18 -0
  11. package/dist/agent-host/thread-host.d.ts.map +1 -1
  12. package/dist/agent-host/thread-host.js +407 -10
  13. package/dist/agent-host/thread-host.js.map +1 -1
  14. package/dist/agent-host/thread-topology.d.ts +83 -0
  15. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  16. package/dist/agent-host/thread-topology.js +202 -1
  17. package/dist/agent-host/thread-topology.js.map +1 -1
  18. package/dist/agent-host/workflow-remote-step-route.d.ts +7 -0
  19. package/dist/agent-host/workflow-remote-step-route.d.ts.map +1 -0
  20. package/dist/agent-host/workflow-remote-step-route.js +148 -0
  21. package/dist/agent-host/workflow-remote-step-route.js.map +1 -0
  22. package/dist/agent-runner/agent-run-state.d.ts +1 -1
  23. package/dist/agent-runner/agent-run-state.d.ts.map +1 -1
  24. package/dist/agent-runner/agent-run-state.js +1 -0
  25. package/dist/agent-runner/agent-run-state.js.map +1 -1
  26. package/dist/agent-runner/durable-agent-runner.d.ts +1 -0
  27. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  28. package/dist/agent-runner/durable-agent-runner.js +69 -32
  29. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  30. package/dist/do-runner/durable-object.d.ts +2 -0
  31. package/dist/do-runner/durable-object.d.ts.map +1 -1
  32. package/dist/do-runner/durable-object.js +252 -3
  33. package/dist/do-runner/durable-object.js.map +1 -1
  34. package/dist/do-runner/execution-admission.d.ts +31 -0
  35. package/dist/do-runner/execution-admission.d.ts.map +1 -1
  36. package/dist/do-runner/execution-admission.js +26 -2
  37. package/dist/do-runner/execution-admission.js.map +1 -1
  38. package/dist/do-runner/execution-fence.d.ts +11 -2
  39. package/dist/do-runner/execution-fence.d.ts.map +1 -1
  40. package/dist/do-runner/execution-fence.js +44 -1
  41. package/dist/do-runner/execution-fence.js.map +1 -1
  42. package/dist/do-runner/index.d.ts +2 -1
  43. package/dist/do-runner/index.d.ts.map +1 -1
  44. package/dist/do-runner/index.js +2 -1
  45. package/dist/do-runner/index.js.map +1 -1
  46. package/dist/do-runner/inventory.d.ts +1 -1
  47. package/dist/do-runner/inventory.d.ts.map +1 -1
  48. package/dist/do-runner/inventory.js +85 -1
  49. package/dist/do-runner/inventory.js.map +1 -1
  50. package/dist/do-runner/notification-predicate.d.ts +1 -0
  51. package/dist/do-runner/notification-predicate.d.ts.map +1 -1
  52. package/dist/do-runner/notification-predicate.js +1 -0
  53. package/dist/do-runner/notification-predicate.js.map +1 -1
  54. package/dist/do-runner/remote-step-journal.d.ts +143 -0
  55. package/dist/do-runner/remote-step-journal.d.ts.map +1 -0
  56. package/dist/do-runner/remote-step-journal.js +2090 -0
  57. package/dist/do-runner/remote-step-journal.js.map +1 -0
  58. package/dist/host-kit/do-response.d.ts +19 -1
  59. package/dist/host-kit/do-response.d.ts.map +1 -1
  60. package/dist/host-kit/do-response.js +71 -2
  61. package/dist/host-kit/do-response.js.map +1 -1
  62. package/dist/host-kit/do-run-topology.d.ts +8 -2
  63. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  64. package/dist/host-kit/do-run-topology.js +26 -1
  65. package/dist/host-kit/do-run-topology.js.map +1 -1
  66. package/dist/host-kit/flowsafe-worker.d.ts +38 -4
  67. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  68. package/dist/host-kit/flowsafe-worker.js +104 -15
  69. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  70. package/dist/host-kit/index.d.ts +5 -5
  71. package/dist/host-kit/index.d.ts.map +1 -1
  72. package/dist/host-kit/index.js +3 -3
  73. package/dist/host-kit/index.js.map +1 -1
  74. package/dist/host-kit/maintenance-capability.js +3 -3
  75. package/dist/host-kit/maintenance-capability.js.map +1 -1
  76. package/dist/host-kit/state-egress.d.ts +34 -6
  77. package/dist/host-kit/state-egress.d.ts.map +1 -1
  78. package/dist/host-kit/state-egress.js +49 -8
  79. package/dist/host-kit/state-egress.js.map +1 -1
  80. package/dist/schedules/schedules-d1.d.ts +3 -3
  81. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  82. package/dist/schedules/schedules-d1.js +61 -62
  83. package/dist/schedules/schedules-d1.js.map +1 -1
  84. package/dist/schedules/tick.d.ts +4 -0
  85. package/dist/schedules/tick.d.ts.map +1 -1
  86. package/dist/schedules/tick.js +28 -7
  87. package/dist/schedules/tick.js.map +1 -1
  88. package/dist/signal-providers/delivery.d.ts +2 -1
  89. package/dist/signal-providers/delivery.d.ts.map +1 -1
  90. package/dist/signal-providers/delivery.js +20 -4
  91. package/dist/signal-providers/delivery.js.map +1 -1
  92. package/dist/signal-providers/host-do.d.ts +2 -0
  93. package/dist/signal-providers/host-do.d.ts.map +1 -1
  94. package/dist/signal-providers/host-do.js +16 -5
  95. package/dist/signal-providers/host-do.js.map +1 -1
  96. package/dist/signal-providers/subscription-d1.d.ts +3 -2
  97. package/dist/signal-providers/subscription-d1.d.ts.map +1 -1
  98. package/dist/signal-providers/subscription-d1.js +25 -7
  99. package/dist/signal-providers/subscription-d1.js.map +1 -1
  100. package/dist/signal-providers/webhook-route.d.ts +2 -0
  101. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  102. package/dist/signal-providers/webhook-route.js +18 -18
  103. package/dist/signal-providers/webhook-route.js.map +1 -1
  104. package/dist/signals/index.d.ts +1 -0
  105. package/dist/signals/index.d.ts.map +1 -1
  106. package/dist/signals/index.js.map +1 -1
  107. package/dist/signals/notification-dispatch.d.ts +2 -64
  108. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  109. package/dist/signals/notification-dispatch.js +20 -2
  110. package/dist/signals/notification-dispatch.js.map +1 -1
  111. package/dist/signals/notifications-d1.d.ts +100 -3
  112. package/dist/signals/notifications-d1.d.ts.map +1 -1
  113. package/dist/signals/notifications-d1.js +350 -16
  114. package/dist/signals/notifications-d1.js.map +1 -1
  115. package/dist/signals/storage.d.ts +1 -1
  116. package/dist/signals/storage.d.ts.map +1 -1
  117. package/dist/signals/storage.js +3 -3
  118. package/dist/signals/storage.js.map +1 -1
  119. package/dist/signals/thread-do-routes.d.ts +6 -3
  120. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  121. package/dist/signals/thread-do-routes.js +30 -5
  122. package/dist/signals/thread-do-routes.js.map +1 -1
  123. package/package.json +1 -1
@@ -13,12 +13,14 @@ import { ExecutionFenceUnreadableError, isRunStartPendingError, normalizeD1RunEx
13
13
  import { DoStatusError, isPathSafeId, RunNotSuspendedError, resolveScheduleStartOwner, resourceIdFromKey, SUSPENSION_TIMEOUT_RESUME_KEY, } from '../do-runner/index.js';
14
14
  import { isDefinitiveInitialAdmissionRefusal } from '../do-runner/initial-admission-refusal.js';
15
15
  import { mastraRegistryEntries } from '../do-runner/mastra-registry.js';
16
+ import { REMOTE_STEP_MARKER, } from '../do-runner/remote-step-journal.js';
16
17
  import { exceedsRunInputDepth, runInputDepthMessage, someValueExceedsRunInputDepth, } from '../do-runner/run-input-depth.js';
17
18
  import { lifecycleFromRequestContext, terminalCleanupFor, } from '../do-runner/run-lifecycle.js';
18
19
  import { isTerminalRunStatus, } from '../do-runner/run-terminal-state.js';
19
20
  import { captureReservation, sameReservationIdentity, } from '../do-runner/start-reservation-contract.js';
20
21
  import { persistedStartRecord } from '../host-kit/do-response.js';
21
22
  import { abandonApprovalsForRun, reconcileApprovalsForSummary, } from '../host-kit/index.js';
23
+ import { projectNotificationOperation, } from '../signals/notifications-d1.js';
22
24
  import { createAgentModuleCatalog } from './catalog.js';
23
25
  import { AGENT_HOST_ROUTE_PREFIX, publicAgentRunEnvelope, } from './thread-topology.js';
24
26
  import { createTrustedAgentRequestContext, deriveTrustedAgentContext, sanitizeStoredAgentContext, } from './trusted-context.js';
@@ -64,6 +66,9 @@ async function objectBody(request) {
64
66
  return value;
65
67
  }
66
68
  const AGENT_OWNER_RECOVERY_PREFIX = 'flowsafe:agent-owner-recovery:v1:';
69
+ const AGENT_NOTIFICATION_RECOVERY_PREFIX = 'flowsafe:agent-notification-recovery:v1:';
70
+ const AGENT_NOTIFICATION_RECOVERY_CURSOR_KEY = 'flowsafe:agent-notification-recovery-cursor:v1';
71
+ const AGENT_NOTIFICATION_RECOVERY_BATCH = 16;
67
72
  const AGENT_OWNER_RECOVERY_DELAY_MS = 60_000;
68
73
  function sameRunRecord(actual, expected) {
69
74
  return (actual !== undefined &&
@@ -131,6 +136,40 @@ function record(value) {
131
136
  ? value
132
137
  : undefined;
133
138
  }
139
+ async function retainedNotificationInput(invocation, operation, executorQuiescentAt) {
140
+ let savedInput;
141
+ try {
142
+ savedInput = record(JSON.parse(operation.requestJson));
143
+ }
144
+ catch {
145
+ throw new AgentHostRequestError(503, 'remote step operation is unreadable');
146
+ }
147
+ if (typeof savedInput?.createdAt !== 'string')
148
+ throw new AgentHostRequestError(503, 'remote step operation is unreadable');
149
+ const stableInput = {
150
+ ...savedInput,
151
+ createdAt: new Date(savedInput.createdAt),
152
+ };
153
+ let projection;
154
+ try {
155
+ projection = await projectNotificationOperation(stableInput);
156
+ }
157
+ catch {
158
+ throw new AgentHostRequestError(503, 'remote step operation is unreadable');
159
+ }
160
+ if (JSON.stringify(stableInput) !== operation.requestJson ||
161
+ stableInput.id !== operation.notificationId ||
162
+ stableInput.threadId !== invocation.threadId ||
163
+ stableInput.resourceId !== invocation.resourceId ||
164
+ stableInput.agentId !== invocation.agentId ||
165
+ stableInput.sourceId !== invocation.invocationId ||
166
+ savedInput.createdAt !== new Date(executorQuiescentAt).toISOString() ||
167
+ projection.version !== operation.projectionVersion ||
168
+ projection.requestJson !== operation.projectionJson ||
169
+ projection.requestDigest !== operation.requestDigest)
170
+ throw new AgentHostRequestError(503, 'remote step operation is unreadable');
171
+ return stableInput;
172
+ }
134
173
  function scheduleAgentContext(target) {
135
174
  const idle = record(target.ifIdle);
136
175
  const streamOptions = record(idle?.streamOptions);
@@ -249,6 +288,33 @@ function ndjson(stream, initialOffset) {
249
288
  });
250
289
  }
251
290
  export function createThreadAgentHost(options) {
291
+ const notificationProfile = options.remoteStepNotification;
292
+ if (notificationProfile &&
293
+ (options.remoteSteps !== notificationProfile.journal ||
294
+ !isPathSafeId(notificationProfile.agentId) ||
295
+ !isPathSafeId(notificationProfile.operationId) ||
296
+ !notificationProfile.source ||
297
+ !notificationProfile.kind ||
298
+ !notificationProfile.summary ||
299
+ typeof notificationProfile.ensureScheduledRecovery !== 'function' ||
300
+ (notificationProfile.receiptLimit !== undefined &&
301
+ (!Number.isSafeInteger(notificationProfile.receiptLimit) ||
302
+ notificationProfile.receiptLimit < 0))))
303
+ throw new TypeError('remote step notification profile is malformed');
304
+ const notificationReceiptLimit = notificationProfile?.receiptLimit;
305
+ let notificationStorage;
306
+ const resourceForThread = (threadId) => {
307
+ let resourceId;
308
+ try {
309
+ resourceId = (options.resourceIdFromKey ?? resourceIdFromKey)(threadId);
310
+ }
311
+ catch {
312
+ throw new AgentHostRequestError(503, 'resource mapping is unavailable');
313
+ }
314
+ if (!isPathSafeId(resourceId))
315
+ throw new AgentHostRequestError(503, 'resource mapping is unavailable');
316
+ return resourceId;
317
+ };
252
318
  let catalogPromise;
253
319
  let runtime;
254
320
  const executions = new Map();
@@ -473,7 +539,7 @@ export function createThreadAgentHost(options) {
473
539
  return { runId, principal: runRecord.principal };
474
540
  const state = await selectedAgentState(scope, {
475
541
  agentId: runRecord.agentId,
476
- resourceId: resourceIdFromKey(scope.threadId),
542
+ resourceId: resourceForThread(scope.threadId),
477
543
  runId,
478
544
  }, { includeLegacy: true });
479
545
  if (!state || state.kind === 'initial')
@@ -585,7 +651,7 @@ export function createThreadAgentHost(options) {
585
651
  !isPathSafeId(stored.agentId) ||
586
652
  !isPathSafeId(stored.threadId) ||
587
653
  !isPathSafeId(stored.resourceId) ||
588
- stored.resourceId !== resourceIdFromKey(threadId) ||
654
+ stored.resourceId !== resourceForThread(threadId) ||
589
655
  !isPathSafeId(stored.runId) ||
590
656
  !isPathSafeId(stored.token) ||
591
657
  ownerRecoveryKey(stored.runId) !== key ||
@@ -698,17 +764,28 @@ export function createThreadAgentHost(options) {
698
764
  throw new AgentHostRequestError(404, 'agent not found');
699
765
  return durable.getWorkflow().id;
700
766
  };
767
+ const matchesStartResource = (threadId, resourceId, persistedResourceId) => persistedResourceId === undefined
768
+ ? resourceId === resourceIdFromKey(threadId)
769
+ : persistedResourceId === resourceId;
701
770
  async function selectedAgentState(scope, ref, readOptions) {
702
771
  const includeLegacy = readOptions?.includeLegacy === true;
703
- if (ref.resourceId !== resourceIdFromKey(scope.threadId))
772
+ if (ref.resourceId !== resourceForThread(scope.threadId))
704
773
  throw new AgentHostRequestError(404, 'run not found');
705
774
  const current = await runtimeFor(scope);
706
775
  const durable = current.agents.get(ref.agentId);
707
776
  if (!current.catalog.get(ref.agentId) || !durable)
708
777
  throw new AgentHostRequestError(404, 'agent not found');
778
+ const assertSelectedResource = (state) => {
779
+ const target = state && state.kind !== 'legacy' ? state.execution.target : undefined;
780
+ if (state &&
781
+ (target?.kind === 'workflow' ||
782
+ !matchesStartResource(scope.threadId, ref.resourceId, target?.kind === 'agent' ? target.resourceId : undefined)))
783
+ throw new AgentRunSelectorMismatchError(durable.getWorkflow().id, ref.runId);
784
+ return state;
785
+ };
709
786
  if (includeLegacy)
710
- return durable.authoritativeAgentStartState(scope.init.runtime, scope.threadId, ref.runId, { includeLegacy: true });
711
- return durable.authoritativeAgentStartState(scope.init.runtime, scope.threadId, ref.runId);
787
+ return assertSelectedResource(await durable.authoritativeAgentStartState(scope.init.runtime, scope.threadId, ref.runId, { includeLegacy: true }));
788
+ return assertSelectedResource(await durable.authoritativeAgentStartState(scope.init.runtime, scope.threadId, ref.runId));
712
789
  }
713
790
  const publicAgentState = async (scope, ref) => {
714
791
  try {
@@ -732,6 +809,7 @@ export function createThreadAgentHost(options) {
732
809
  state.execution.target.kind !== 'agent' ||
733
810
  state.execution.target.id !== recovery.agentId ||
734
811
  state.execution.target.threadId !== recovery.threadId ||
812
+ !matchesStartResource(recovery.threadId, recovery.resourceId, state.execution.target.resourceId) ||
735
813
  state.execution.owner.kind !== recovery.runRecord.principal.kind ||
736
814
  state.execution.owner.id !== recovery.runRecord.principal.id)
737
815
  throw new Error('agent owner recovery does not match the execution');
@@ -792,7 +870,7 @@ export function createThreadAgentHost(options) {
792
870
  if (state.kind === 'legacy') {
793
871
  const ref = {
794
872
  agentId: expected.agentId,
795
- resourceId: resourceIdFromKey(scope.threadId),
873
+ resourceId: resourceForThread(scope.threadId),
796
874
  runId,
797
875
  };
798
876
  await assertLegacyTerminalCurrent(scope, ref, state, expected);
@@ -807,6 +885,7 @@ export function createThreadAgentHost(options) {
807
885
  if (state.execution.target.kind !== 'agent' ||
808
886
  state.execution.target.id !== expected.agentId ||
809
887
  state.execution.target.threadId !== scope.threadId ||
888
+ !matchesStartResource(scope.threadId, resourceForThread(scope.threadId), state.execution.target.resourceId) ||
810
889
  state.execution.owner.kind !== expected.principal.kind ||
811
890
  state.execution.owner.id !== expected.principal.id)
812
891
  throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
@@ -1032,6 +1111,39 @@ export function createThreadAgentHost(options) {
1032
1111
  safeContext: sanitizeStoredAgentContext(state.snapshot.requestContext),
1033
1112
  };
1034
1113
  };
1114
+ const readRemoteStepHostAuthority = async (scope, invocation) => {
1115
+ const ref = {
1116
+ agentId: invocation.agentId,
1117
+ resourceId: invocation.resourceId,
1118
+ runId: invocation.runId,
1119
+ };
1120
+ const selected = await snapshotExecutionFor(scope, ref);
1121
+ const state = selected.state;
1122
+ if (state.kind !== 'result' ||
1123
+ state.storage !== 'd1' ||
1124
+ state.execution.tablePrefix !== invocation.tablePrefix ||
1125
+ state.execution.workflowId !== invocation.workflowId ||
1126
+ state.execution.startToken !== invocation.startToken ||
1127
+ state.execution.target.kind !== 'agent' ||
1128
+ state.execution.target.id !== invocation.agentId ||
1129
+ state.execution.target.threadId !== invocation.threadId ||
1130
+ state.execution.target.resourceId !== invocation.resourceId ||
1131
+ state.execution.owner.kind !== invocation.principal.kind ||
1132
+ state.execution.owner.id !== invocation.principal.id)
1133
+ throw new AgentHostRequestError(409, 'remote step run changed');
1134
+ const stored = await readRun(ref.runId);
1135
+ if (!stored ||
1136
+ stored.agentId !== ref.agentId ||
1137
+ !samePrincipal(stored.principal, invocation.principal))
1138
+ throw new AgentHostRequestError(404, 'run not found');
1139
+ const binding = await readBinding();
1140
+ if ((selected.threaded &&
1141
+ (binding?.agentId !== ref.agentId ||
1142
+ binding.resourceId !== ref.resourceId)) ||
1143
+ (!selected.threaded && binding))
1144
+ throw new AgentHostRequestError(404, 'run not found');
1145
+ return { ref, selected, state, stored };
1146
+ };
1035
1147
  const statusFor = async (scope, ref, knownState) => {
1036
1148
  const stored = await readRun(ref.runId);
1037
1149
  const selected = knownState === undefined
@@ -1195,6 +1307,48 @@ export function createThreadAgentHost(options) {
1195
1307
  await storage.delete(key);
1196
1308
  return null;
1197
1309
  }));
1310
+ const recoverNotificationOperation = async (scope, invocationId) => {
1311
+ instanceScopeFor(scope);
1312
+ const profile = notificationProfile;
1313
+ if (!profile || !isPathSafeId(invocationId))
1314
+ throw new AgentHostRequestError(404, 'invocation not found');
1315
+ const invocation = await profile.journal.get(invocationId);
1316
+ if (!invocation ||
1317
+ invocation.deploymentId !== profile.journal.deploymentId ||
1318
+ invocation.tablePrefix !== profile.journal.tablePrefix ||
1319
+ invocation.threadId !== scope.threadId ||
1320
+ invocation.agentId !== profile.agentId ||
1321
+ !samePrincipal(invocation.principal, scope.principal) ||
1322
+ record(invocation.request)?.notificationOperationId !==
1323
+ profile.operationId)
1324
+ throw new AgentHostRequestError(404, 'invocation not found');
1325
+ const operation = await profile.journal.readNotificationOperation(invocationId);
1326
+ if (!operation || operation.operationId !== profile.operationId)
1327
+ throw new AgentHostRequestError(409, 'remote step operation changed');
1328
+ if (operation.state === 'resume-admitted' ||
1329
+ operation.state === 'unresolved' ||
1330
+ operation.state === 'prepared')
1331
+ return 'unresolved';
1332
+ await readRemoteStepHostAuthority(scope, invocation);
1333
+ const retained = await profile.journal.readRetainedResult(invocationId);
1334
+ if (!retained || invocation.status !== 'result-retained')
1335
+ throw new AgentHostRequestError(409, 'remote step result is unavailable');
1336
+ const stableInput = await retainedNotificationInput(invocation, operation, retained.executorQuiescentAt);
1337
+ if (!notificationStorage)
1338
+ notificationStorage = profile.journal.notificationStorage(notificationReceiptLimit);
1339
+ const storage = notificationStorage;
1340
+ if (operation.state === 'effect-admitted') {
1341
+ const receipt = await storage.createNotificationOnce(operation.operationKey, stableInput, { admittedInvocation: invocation });
1342
+ await profile.journal.recordNotificationReceipt(invocationId, receipt);
1343
+ return 'receipt-recorded';
1344
+ }
1345
+ const receipt = await storage.readNotificationOperationReceipt(operation.operationKey);
1346
+ if (receipt?.requestDigest !== operation.requestDigest ||
1347
+ receipt.notificationId !== operation.notificationId ||
1348
+ receipt.threadId !== invocation.threadId)
1349
+ throw new AgentHostRequestError(503, 'remote step notification receipt is unreadable');
1350
+ return 'receipt-recorded';
1351
+ };
1198
1352
  const host = {
1199
1353
  requestContextForRun: (base) => async (workflowId, runId, leg) => {
1200
1354
  const values = base ? await base(workflowId, runId, leg) : undefined;
@@ -1209,6 +1363,7 @@ export function createThreadAgentHost(options) {
1209
1363
  : values;
1210
1364
  },
1211
1365
  serializeDispatch: withDispatchLock,
1366
+ recoverNotificationOperation: (scope, invocationId) => withDispatchLock(() => recoverNotificationOperation(scope, invocationId)),
1212
1367
  notificationDispatchAllowed: async (scope, agentId) => {
1213
1368
  instanceScopeFor(scope);
1214
1369
  return (await catalogFor(scope)).automationAllowed(agentId, {
@@ -1274,11 +1429,71 @@ export function createThreadAgentHost(options) {
1274
1429
  firstFailure ??= { error };
1275
1430
  }
1276
1431
  }
1432
+ if (notificationProfile) {
1433
+ const cursor = (await storage.get(AGENT_NOTIFICATION_RECOVERY_CURSOR_KEY)) ?? '';
1434
+ if (typeof cursor !== 'string' ||
1435
+ (cursor !== '' &&
1436
+ (!cursor.startsWith(AGENT_NOTIFICATION_RECOVERY_PREFIX) ||
1437
+ !isPathSafeId(cursor.slice(AGENT_NOTIFICATION_RECOVERY_PREFIX.length)))))
1438
+ throw new AgentHostRequestError(503, 'remote step recovery cursor is unreadable');
1439
+ let notifications = await storage.list({
1440
+ prefix: AGENT_NOTIFICATION_RECOVERY_PREFIX,
1441
+ ...(cursor === '' ? {} : { startAfter: cursor }),
1442
+ limit: AGENT_NOTIFICATION_RECOVERY_BATCH,
1443
+ });
1444
+ if (notifications.size === 0 && cursor !== '')
1445
+ notifications = await storage.list({
1446
+ prefix: AGENT_NOTIFICATION_RECOVERY_PREFIX,
1447
+ limit: AGENT_NOTIFICATION_RECOVERY_BATCH,
1448
+ });
1449
+ for (const [key, stored] of notifications) {
1450
+ const invocationId = key.slice(AGENT_NOTIFICATION_RECOVERY_PREFIX.length);
1451
+ try {
1452
+ if (stored !== invocationId || !isPathSafeId(invocationId))
1453
+ throw new AgentHostRequestError(503, 'remote step recovery marker is unreadable');
1454
+ const invocation = await notificationProfile.journal.get(invocationId);
1455
+ if (!invocation ||
1456
+ invocation.threadId !== scope.threadId ||
1457
+ invocation.deploymentId !==
1458
+ notificationProfile.journal.deploymentId ||
1459
+ invocation.tablePrefix !==
1460
+ notificationProfile.journal.tablePrefix)
1461
+ throw new AgentHostRequestError(503, 'remote step recovery identity changed');
1462
+ const operation = await notificationProfile.journal.readNotificationOperation(invocationId);
1463
+ if (operation?.state === 'effect-admitted' ||
1464
+ operation?.state === 'receipt-recorded') {
1465
+ const recovered = await recoverNotificationOperation({ ...scope, principal: invocation.principal }, invocationId);
1466
+ if (recovered !== 'receipt-recorded')
1467
+ throw new AgentHostRequestError(503, 'remote step notification recovery is unresolved');
1468
+ }
1469
+ else if (operation?.state !== 'resume-admitted' &&
1470
+ operation?.state !== 'unresolved') {
1471
+ throw new AgentHostRequestError(503, 'remote step notification recovery is unresolved');
1472
+ }
1473
+ await storage.delete(key);
1474
+ }
1475
+ catch (error) {
1476
+ console.error(JSON.stringify({
1477
+ type: 'remote-step-notification-recovery-failed',
1478
+ threadId: scope.threadId,
1479
+ invocationId,
1480
+ error: errorMessageOf(error),
1481
+ }));
1482
+ firstFailure ??= { error };
1483
+ }
1484
+ }
1485
+ const last = [...notifications.keys()].at(-1);
1486
+ await storage.put(AGENT_NOTIFICATION_RECOVERY_CURSOR_KEY, last ?? '');
1487
+ }
1277
1488
  await withRecoveryLock(async () => {
1278
1489
  const remaining = await storage.list({
1279
1490
  prefix: AGENT_OWNER_RECOVERY_PREFIX,
1280
1491
  });
1281
- if (remaining.size > 0) {
1492
+ const remainingNotifications = await storage.list({
1493
+ prefix: AGENT_NOTIFICATION_RECOVERY_PREFIX,
1494
+ limit: 1,
1495
+ });
1496
+ if (remaining.size > 0 || remainingNotifications.size > 0) {
1282
1497
  await ensureOwnerRecoveryAlarm(storage);
1283
1498
  }
1284
1499
  else {
@@ -1350,6 +1565,7 @@ export function createThreadAgentHost(options) {
1350
1565
  kind: 'agent',
1351
1566
  id: ref.agentId,
1352
1567
  threadId: ref.threadId,
1568
+ resourceId: ref.resourceId,
1353
1569
  }),
1354
1570
  });
1355
1571
  const hasPrompt = source.target === undefined && input.prompt !== undefined;
@@ -1403,7 +1619,7 @@ export function createThreadAgentHost(options) {
1403
1619
  throw error;
1404
1620
  }
1405
1621
  const { current, module, principalPermissions } = await authorize(scope, ref.agentId, entry, scope.principal);
1406
- if (ref.resourceId !== resourceIdFromKey(scope.threadId)) {
1622
+ if (ref.resourceId !== resourceForThread(scope.threadId)) {
1407
1623
  throw new AgentHostRequestError(404, 'run not found');
1408
1624
  }
1409
1625
  const execution = {
@@ -1587,7 +1803,7 @@ export function createThreadAgentHost(options) {
1587
1803
  const binding = await readBinding();
1588
1804
  if (!binding)
1589
1805
  throw new AgentHostRequestError(404, 'agent not found');
1590
- if (binding.resourceId !== resourceIdFromKey(scope.threadId)) {
1806
+ if (binding.resourceId !== resourceForThread(scope.threadId)) {
1591
1807
  throw new AgentHostRequestError(404, 'agent not found');
1592
1808
  }
1593
1809
  if (input.agentId && input.agentId !== binding.agentId) {
@@ -1684,6 +1900,16 @@ export function createThreadAgentHost(options) {
1684
1900
  preflightUrl.pathname === `${AGENT_HOST_ROUTE_PREFIX}/resume`
1685
1901
  ? await objectBody(request)
1686
1902
  : undefined;
1903
+ const remoteStepBody = request.method === 'POST' &&
1904
+ preflightUrl.pathname ===
1905
+ `${AGENT_HOST_ROUTE_PREFIX}/remote-step-resume`
1906
+ ? await objectBody(request)
1907
+ : undefined;
1908
+ const notificationRecoveryBody = request.method === 'POST' &&
1909
+ preflightUrl.pathname ===
1910
+ `${AGENT_HOST_ROUTE_PREFIX}/remote-step-notification-recover`
1911
+ ? await objectBody(request)
1912
+ : undefined;
1687
1913
  return withDispatchLock(async () => {
1688
1914
  const url = new URL(request.url);
1689
1915
  if (request.method === 'GET' &&
@@ -1692,7 +1918,7 @@ export function createThreadAgentHost(options) {
1692
1918
  const agentId = url.searchParams.get('agentId');
1693
1919
  const binding = await readBinding();
1694
1920
  if (!resourceId ||
1695
- resourceId !== resourceIdFromKey(scope.threadId) ||
1921
+ resourceId !== resourceForThread(scope.threadId) ||
1696
1922
  binding?.resourceId !== resourceId ||
1697
1923
  (agentId !== null && binding.agentId !== agentId)) {
1698
1924
  throw new AgentHostRequestError(404, 'agent not found');
@@ -1766,6 +1992,177 @@ export function createThreadAgentHost(options) {
1766
1992
  : {}),
1767
1993
  }));
1768
1994
  }
1995
+ if (notificationRecoveryBody) {
1996
+ const invocationId = notificationRecoveryBody.invocationId;
1997
+ if (!isPathSafeId(invocationId))
1998
+ throw new AgentHostRequestError(404, 'invocation not found');
1999
+ return json({
2000
+ state: await recoverNotificationOperation(scope, invocationId),
2001
+ });
2002
+ }
2003
+ if (remoteStepBody) {
2004
+ const reader = options.remoteSteps;
2005
+ if (!reader)
2006
+ throw new AgentHostRequestError(503, 'remote steps are unavailable');
2007
+ const invocationId = remoteStepBody.invocationId;
2008
+ if (!isPathSafeId(invocationId))
2009
+ throw new AgentHostRequestError(404, 'invocation not found');
2010
+ const invocation = await reader.get(invocationId);
2011
+ if (!invocation ||
2012
+ invocation.deploymentId !== reader.deploymentId ||
2013
+ invocation.tablePrefix !== reader.tablePrefix ||
2014
+ invocation.threadId !== scope.threadId ||
2015
+ !samePrincipal(invocation.principal, scope.principal))
2016
+ throw new AgentHostRequestError(404, 'invocation not found');
2017
+ if (invocation.status === 'resuming')
2018
+ throw new AgentHostRequestError(503, 'remote step resume awaits executor quiescence');
2019
+ const retained = await reader.readRetainedResult(invocationId);
2020
+ if (!invocation ||
2021
+ !retained ||
2022
+ retained.invocationId !== invocationId ||
2023
+ invocation.status !== 'result-retained' ||
2024
+ invocation.deadlineAt <= Date.now())
2025
+ throw new AgentHostRequestError(404, 'invocation not found');
2026
+ const { ref, selected, state, stored } = await readRemoteStepHostAuthority(scope, invocation);
2027
+ const key = invocation.stepPath.join('.');
2028
+ const summary = state.summary;
2029
+ const payload = summary.suspendPayload !== null &&
2030
+ typeof summary.suspendPayload === 'object' &&
2031
+ !Array.isArray(summary.suspendPayload)
2032
+ ? summary.suspendPayload[key]
2033
+ : undefined;
2034
+ const suspended = payload !== null && typeof payload === 'object'
2035
+ ? payload
2036
+ : undefined;
2037
+ const tool = suspended?.toolCallSuspended !== null &&
2038
+ typeof suspended?.toolCallSuspended === 'object'
2039
+ ? suspended.toolCallSuspended
2040
+ : undefined;
2041
+ if (summary.status !== 'suspended' ||
2042
+ !summary.suspended?.some((path) => JSON.stringify(path) === JSON.stringify(invocation.stepPath)) ||
2043
+ summary.suspendedAt?.[key] !== invocation.suspendedAt ||
2044
+ summary.resumeCount?.[key] !== invocation.resumeCount ||
2045
+ suspended?.type !== 'suspension' ||
2046
+ tool?.remoteStep !== REMOTE_STEP_MARKER)
2047
+ throw new AgentHostRequestError(409, 'remote step suspension changed');
2048
+ let recordedResult;
2049
+ try {
2050
+ recordedResult = JSON.parse(retained.resultJson);
2051
+ }
2052
+ catch {
2053
+ throw new AgentHostRequestError(503, 'remote step result is unreadable');
2054
+ }
2055
+ const { current, module, principalPermissions } = await authorize(scope, ref.agentId, 'remote-step.resume', stored.principal);
2056
+ const durable = current.agents.get(module.meta.id);
2057
+ if (!durable)
2058
+ throw new Error('guarded agent was not registered');
2059
+ const execution = {
2060
+ agentId: ref.agentId,
2061
+ deploymentTag: scope.deploymentTag,
2062
+ principal: stored.principal,
2063
+ threadId: scope.threadId,
2064
+ resourceId: ref.resourceId,
2065
+ runId: ref.runId,
2066
+ entryPath: 'remote-step.resume',
2067
+ principalPermissions,
2068
+ safeContext: selected.safeContext,
2069
+ };
2070
+ let leaseOwner;
2071
+ if (notificationProfile &&
2072
+ invocation.agentId === notificationProfile.agentId &&
2073
+ record(invocation.request)?.notificationOperationId ===
2074
+ notificationProfile.operationId) {
2075
+ const journal = notificationProfile.journal;
2076
+ const existing = await journal.readNotificationOperation(invocationId);
2077
+ if (existing &&
2078
+ (existing.invocationId !== invocationId ||
2079
+ existing.operationId !== notificationProfile.operationId))
2080
+ throw new AgentHostRequestError(409, 'remote step operation changed');
2081
+ const operation = existing ??
2082
+ (await journal.prepareNotificationOperation(invocationId, notificationProfile.operationId, {
2083
+ threadId: invocation.threadId,
2084
+ resourceId: invocation.resourceId,
2085
+ agentId: invocation.agentId,
2086
+ source: notificationProfile.source,
2087
+ kind: notificationProfile.kind,
2088
+ summary: notificationProfile.summary,
2089
+ sourceId: invocation.invocationId,
2090
+ createdAt: new Date(retained.executorQuiescentAt),
2091
+ ...(notificationProfile.payload === undefined
2092
+ ? {}
2093
+ : { payload: notificationProfile.payload }),
2094
+ }));
2095
+ const stableInput = await retainedNotificationInput(invocation, operation, retained.executorQuiescentAt);
2096
+ if (!notificationStorage)
2097
+ notificationStorage = journal.notificationStorage(notificationReceiptLimit);
2098
+ const notifications = notificationStorage;
2099
+ if (operation.state === 'prepared' ||
2100
+ operation.state === 'effect-admitted') {
2101
+ if (operation.state === 'prepared')
2102
+ await notificationProfile.ensureScheduledRecovery();
2103
+ const admitted = await journal.admitNotificationEffect(invocationId);
2104
+ if (admitted.operationKey !== operation.operationKey ||
2105
+ admitted.requestDigest !== operation.requestDigest)
2106
+ throw new AgentHostRequestError(409, 'remote step operation changed');
2107
+ await withRecoveryLock(async () => {
2108
+ const storage = options.stateStorage();
2109
+ await ensureOwnerRecoveryAlarm(storage);
2110
+ await storage.put(`${AGENT_NOTIFICATION_RECOVERY_PREFIX}${invocationId}`, invocationId);
2111
+ await ensureOwnerRecoveryAlarm(storage);
2112
+ });
2113
+ const receipt = await notifications.createNotificationOnce(admitted.operationKey, stableInput, { admittedInvocation: invocation });
2114
+ await journal.recordNotificationReceipt(invocationId, receipt);
2115
+ await options
2116
+ .stateStorage()
2117
+ .delete(`${AGENT_NOTIFICATION_RECOVERY_PREFIX}${invocationId}`);
2118
+ }
2119
+ else if (operation.state === 'receipt-recorded') {
2120
+ const receipt = await notifications.readNotificationOperationReceipt(operation.operationKey);
2121
+ if (receipt?.requestDigest !== operation.requestDigest ||
2122
+ receipt.notificationId !== operation.notificationId ||
2123
+ receipt.threadId !== invocation.threadId)
2124
+ throw new AgentHostRequestError(503, 'remote step notification receipt is unreadable');
2125
+ }
2126
+ else {
2127
+ throw new AgentHostRequestError(503, 'remote step continuation is unresolved');
2128
+ }
2129
+ execution.principalPermissions = (await authorize(scope, ref.agentId, 'remote-step.resume', stored.principal)).principalPermissions;
2130
+ leaseOwner = await journal.admitNotificationResume(invocationId);
2131
+ }
2132
+ else {
2133
+ leaseOwner = await reader.claimResume(invocationId, 60_000);
2134
+ }
2135
+ const resumed = await withExecution(execution, () => durable.resumeViaRuntime({
2136
+ runId: ref.runId,
2137
+ requestedBy: stored.principal.id,
2138
+ step: [...invocation.stepPath],
2139
+ resumeData: resumeData(recordedResult),
2140
+ requestedByKind: stored.principal.kind,
2141
+ expectedSuspension: {
2142
+ suspendedAt: invocation.suspendedAt,
2143
+ ...(invocation.resumeCount === undefined
2144
+ ? {}
2145
+ : { resumeCount: invocation.resumeCount }),
2146
+ },
2147
+ ...(selected.threaded
2148
+ ? {
2149
+ memory: {
2150
+ thread: scope.threadId,
2151
+ resource: ref.resourceId,
2152
+ },
2153
+ }
2154
+ : {}),
2155
+ }));
2156
+ const settlement = await reader.settleAfterResume(invocationId, leaseOwner, resumed);
2157
+ if (settlement === 'retry' || settlement === 'advanced-without-proof')
2158
+ throw new AgentHostRequestError(503, 'remote step resume outcome is unresolved');
2159
+ if (settlement !== 'applied')
2160
+ throw new AgentHostRequestError(409, 'remote step result was not applied');
2161
+ const result = await envelopeFor(scope, ref, stored.principal, resumed);
2162
+ if (isTerminalRunStatus(resumed.status))
2163
+ await finalizeTerminalAgentState(scope, ref, undefined, stored);
2164
+ return json(result);
2165
+ }
1769
2166
  if (resumeBody) {
1770
2167
  const body = resumeBody;
1771
2168
  const ref = runRef(scope, body);