@proofoftech/flowsafe 0.15.0 → 0.16.1

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 (104) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +37 -3
  3. package/dist/agent-host/router.d.ts.map +1 -1
  4. package/dist/agent-host/router.js +44 -2
  5. package/dist/agent-host/router.js.map +1 -1
  6. package/dist/agent-host/thread-host.d.ts +7 -0
  7. package/dist/agent-host/thread-host.d.ts.map +1 -1
  8. package/dist/agent-host/thread-host.js +329 -213
  9. package/dist/agent-host/thread-host.js.map +1 -1
  10. package/dist/agent-host/thread-topology.d.ts +1 -0
  11. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  12. package/dist/agent-host/thread-topology.js +14 -1
  13. package/dist/agent-host/thread-topology.js.map +1 -1
  14. package/dist/agent-runner/durable-agent-runner.d.ts +4 -1
  15. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  16. package/dist/agent-runner/durable-agent-runner.js +8 -1
  17. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  18. package/dist/approval-api/d1-store.d.ts +4 -2
  19. package/dist/approval-api/d1-store.d.ts.map +1 -1
  20. package/dist/approval-api/d1-store.js +113 -13
  21. package/dist/approval-api/d1-store.js.map +1 -1
  22. package/dist/approval-api/index.d.ts +2 -2
  23. package/dist/approval-api/index.d.ts.map +1 -1
  24. package/dist/approval-api/index.js.map +1 -1
  25. package/dist/approval-api/service.d.ts.map +1 -1
  26. package/dist/approval-api/service.js +4 -1
  27. package/dist/approval-api/service.js.map +1 -1
  28. package/dist/approval-api/store-factory.d.ts +5 -1
  29. package/dist/approval-api/store-factory.d.ts.map +1 -1
  30. package/dist/approval-api/store-factory.js +7 -2
  31. package/dist/approval-api/store-factory.js.map +1 -1
  32. package/dist/approval-api/store.d.ts +6 -2
  33. package/dist/approval-api/store.d.ts.map +1 -1
  34. package/dist/approval-api/store.js +1 -1
  35. package/dist/approval-api/store.js.map +1 -1
  36. package/dist/do-runner/cf-types.d.ts +1 -0
  37. package/dist/do-runner/cf-types.d.ts.map +1 -1
  38. package/dist/do-runner/d1-storage.d.ts +32 -1
  39. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  40. package/dist/do-runner/d1-storage.js +160 -8
  41. package/dist/do-runner/d1-storage.js.map +1 -1
  42. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  43. package/dist/do-runner/do-error-response.js +15 -8
  44. package/dist/do-runner/do-error-response.js.map +1 -1
  45. package/dist/do-runner/durable-object.d.ts +7 -0
  46. package/dist/do-runner/durable-object.d.ts.map +1 -1
  47. package/dist/do-runner/durable-object.js +110 -9
  48. package/dist/do-runner/durable-object.js.map +1 -1
  49. package/dist/do-runner/execution-context.d.ts.map +1 -1
  50. package/dist/do-runner/execution-context.js +2 -0
  51. package/dist/do-runner/execution-context.js.map +1 -1
  52. package/dist/do-runner/index.d.ts +6 -5
  53. package/dist/do-runner/index.d.ts.map +1 -1
  54. package/dist/do-runner/index.js +2 -2
  55. package/dist/do-runner/index.js.map +1 -1
  56. package/dist/do-runner/run-lifecycle.d.ts +56 -0
  57. package/dist/do-runner/run-lifecycle.d.ts.map +1 -0
  58. package/dist/do-runner/run-lifecycle.js +179 -0
  59. package/dist/do-runner/run-lifecycle.js.map +1 -0
  60. package/dist/do-runner/runtime.d.ts +60 -2
  61. package/dist/do-runner/runtime.d.ts.map +1 -1
  62. package/dist/do-runner/runtime.js +545 -75
  63. package/dist/do-runner/runtime.js.map +1 -1
  64. package/dist/host-kit/approval-bridge.d.ts +7 -0
  65. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  66. package/dist/host-kit/approval-bridge.js +21 -0
  67. package/dist/host-kit/approval-bridge.js.map +1 -1
  68. package/dist/host-kit/do-response.d.ts.map +1 -1
  69. package/dist/host-kit/do-response.js +4 -1
  70. package/dist/host-kit/do-response.js.map +1 -1
  71. package/dist/host-kit/do-run-topology.d.ts +8 -3
  72. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  73. package/dist/host-kit/do-run-topology.js +20 -6
  74. package/dist/host-kit/do-run-topology.js.map +1 -1
  75. package/dist/host-kit/flowsafe-worker.d.ts +38 -23
  76. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  77. package/dist/host-kit/flowsafe-worker.js +149 -37
  78. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  79. package/dist/host-kit/host-approval-service.d.ts +1 -1
  80. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  81. package/dist/host-kit/host-approval-service.js +13 -4
  82. package/dist/host-kit/host-approval-service.js.map +1 -1
  83. package/dist/host-kit/index.d.ts +4 -4
  84. package/dist/host-kit/index.d.ts.map +1 -1
  85. package/dist/host-kit/index.js +2 -2
  86. package/dist/host-kit/index.js.map +1 -1
  87. package/dist/host-kit/run-route-error.d.ts +3 -2
  88. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  89. package/dist/host-kit/run-route-error.js +4 -2
  90. package/dist/host-kit/run-route-error.js.map +1 -1
  91. package/dist/host-kit/run-router.d.ts +4 -0
  92. package/dist/host-kit/run-router.d.ts.map +1 -1
  93. package/dist/host-kit/run-router.js +42 -9
  94. package/dist/host-kit/run-router.js.map +1 -1
  95. package/dist/host-kit/workflow-meta.d.ts +3 -3
  96. package/dist/schedules/schedules-d1.d.ts +8 -0
  97. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  98. package/dist/schedules/schedules-d1.js +59 -0
  99. package/dist/schedules/schedules-d1.js.map +1 -1
  100. package/dist/signals/thread-do-routes.d.ts +3 -1
  101. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  102. package/dist/signals/thread-do-routes.js +8 -0
  103. package/dist/signals/thread-do-routes.js.map +1 -1
  104. package/package.json +1 -1
@@ -7,7 +7,7 @@ import { canonicalResourceOwner, principalActor, principalAuditFields, principal
7
7
  import { isExecutionPrincipalId, } from '../approval-api/principal.js';
8
8
  import { DoStatusError, isPathSafeId, resolveScheduleStartOwner, resourceIdFromKey, } from '../do-runner/index.js';
9
9
  import { mastraRegistryEntries } from '../do-runner/mastra-registry.js';
10
- import { reconcileApprovalsForSummary } from '../host-kit/index.js';
10
+ import { abandonApprovalsForRun, reconcileApprovalsForSummary, } from '../host-kit/index.js';
11
11
  import { createAgentModuleCatalog } from './catalog.js';
12
12
  import { AGENT_HOST_ROUTE_PREFIX } from './thread-topology.js';
13
13
  import { createTrustedAgentRequestContext, deriveTrustedAgentContext, sanitizeStoredAgentContext, } from './trusted-context.js';
@@ -59,6 +59,8 @@ const TERMINAL_RUN_STATUSES = [
59
59
  'canceled',
60
60
  'bailed',
61
61
  'skipped',
62
+ 'cancelled',
63
+ 'timed_out',
62
64
  ];
63
65
  const AGENT_OWNER_RECOVERY_PREFIX = 'flowsafe:agent-owner-recovery:v1:';
64
66
  const AGENT_OWNER_RECOVERY_DELAY_MS = 60_000;
@@ -483,32 +485,37 @@ export function createThreadAgentHost(options) {
483
485
  await storage.delete(key);
484
486
  });
485
487
  const releaseEphemeralOwnerClaims = async (recovery) => {
488
+ const ownership = options.resourceAccess();
489
+ const release = async (kind, resourceId) => {
490
+ if (await ownership.release(kind, resourceId, recovery.owner))
491
+ return;
492
+ if (await ownership.owner(kind, resourceId)) {
493
+ throw new Error(`${kind} '${resourceId}' ownership could not be released`);
494
+ }
495
+ };
486
496
  await Promise.all([
487
- options
488
- .resourceAccess()
489
- .release('resource', recovery.resourceId, recovery.owner),
490
- options
491
- .resourceAccess()
492
- .release('thread', recovery.threadId, recovery.owner),
497
+ release('resource', recovery.resourceId),
498
+ release('thread', recovery.threadId),
493
499
  ]);
494
500
  };
501
+ const finalizeOwnerRecovery = (recovery, summary) => withRecoveryLock(async () => {
502
+ const storage = options.stateStorage();
503
+ await options.resourceAccess().settleReservation(recovery.token, []);
504
+ if (!recovery.threaded && !isTerminalRunStatus(summary.status)) {
505
+ await ensureOwnerRecoveryAlarm(storage);
506
+ return;
507
+ }
508
+ if (!recovery.threaded) {
509
+ await releaseEphemeralOwnerClaims(recovery);
510
+ }
511
+ const key = ownerRecoveryKey(recovery.runId);
512
+ const current = await storage.get(key);
513
+ if (current?.token === recovery.token)
514
+ await storage.delete(key);
515
+ });
495
516
  const finalizeOwnerRecoveryBestEffort = async (recovery, summary) => {
496
517
  try {
497
- await withRecoveryLock(async () => {
498
- const storage = options.stateStorage();
499
- await options.resourceAccess().settleReservation(recovery.token, []);
500
- if (!recovery.threaded && !isTerminalRunStatus(summary.status)) {
501
- await ensureOwnerRecoveryAlarm(storage);
502
- return;
503
- }
504
- if (!recovery.threaded) {
505
- await releaseEphemeralOwnerClaims(recovery);
506
- }
507
- const key = ownerRecoveryKey(recovery.runId);
508
- const current = await storage.get(key);
509
- if (current?.token === recovery.token)
510
- await storage.delete(key);
511
- });
518
+ await finalizeOwnerRecovery(recovery, summary);
512
519
  }
513
520
  catch (error) {
514
521
  console.error('agent owner recovery cleanup failed', error);
@@ -520,6 +527,30 @@ export function createThreadAgentHost(options) {
520
527
  }
521
528
  }
522
529
  };
530
+ const validateOwnerRecovery = (threadId, key, stored) => {
531
+ if (stored?.version !== 1 ||
532
+ stored.threadId !== threadId ||
533
+ !isPathSafeId(stored.agentId) ||
534
+ !isPathSafeId(stored.resourceId) ||
535
+ !isPathSafeId(stored.runId) ||
536
+ !isPathSafeId(stored.token) ||
537
+ ownerRecoveryKey(stored.runId) !== key ||
538
+ typeof stored.threaded !== 'boolean' ||
539
+ typeof stored.bindingPreexisting !== 'boolean') {
540
+ throw new Error('stored agent owner recovery is malformed');
541
+ }
542
+ resourceOwner(stored.owner);
543
+ };
544
+ const finalizeTerminalAgentState = async (threadId, runId, summary) => {
545
+ const storage = options.stateStorage();
546
+ const key = ownerRecoveryKey(runId);
547
+ const recovery = await storage.get(key);
548
+ if (recovery) {
549
+ validateOwnerRecovery(threadId, key, recovery);
550
+ await finalizeOwnerRecovery(recovery, summary);
551
+ }
552
+ await deleteAgentRunRecord(storage, runId);
553
+ };
523
554
  const withExecution = async (execution, operation) => {
524
555
  if (executions.has(execution.runId)) {
525
556
  throw new AgentHostRequestError(409, `run '${execution.runId}' already has an active operation`);
@@ -676,18 +707,7 @@ export function createThreadAgentHost(options) {
676
707
  return result;
677
708
  };
678
709
  recoverOwner = async (scopeRuntime, threadId, key, stored, ignoreActive = false) => withBindingLock(() => withRecoveryLock(async () => {
679
- if (stored?.version !== 1 ||
680
- stored.threadId !== threadId ||
681
- !isPathSafeId(stored.agentId) ||
682
- !isPathSafeId(stored.resourceId) ||
683
- !isPathSafeId(stored.runId) ||
684
- !isPathSafeId(stored.token) ||
685
- ownerRecoveryKey(stored.runId) !== key ||
686
- typeof stored.threaded !== 'boolean' ||
687
- typeof stored.bindingPreexisting !== 'boolean') {
688
- throw new Error('stored agent owner recovery is malformed');
689
- }
690
- resourceOwner(stored.owner);
710
+ validateOwnerRecovery(threadId, key, stored);
691
711
  const storage = options.stateStorage();
692
712
  const currentRecovery = await storage.get(key);
693
713
  if (currentRecovery?.token !== stored.token)
@@ -918,7 +938,7 @@ export function createThreadAgentHost(options) {
918
938
  return recovery;
919
939
  });
920
940
  try {
921
- await durable.streamUntilPersisted(messages, {
941
+ const streamOptions = {
922
942
  runId: ref.runId,
923
943
  requestContext: createTrustedAgentRequestContext(execution),
924
944
  ...(input.threaded !== false
@@ -934,7 +954,14 @@ export function createThreadAgentHost(options) {
934
954
  ...(resolvedProviderOptions !== undefined
935
955
  ? { providerOptions: providerOptions(resolvedProviderOptions) }
936
956
  : {}),
937
- }, scope.principal.id, scope.principal.kind, recovery.token);
957
+ };
958
+ const scheduleDispatch = source.target &&
959
+ input.scheduleId &&
960
+ input.dispatchId &&
961
+ input.scheduleDispatchLease === 'executing'
962
+ ? { scheduleId: input.scheduleId, dispatchId: input.dispatchId }
963
+ : undefined;
964
+ await durable.streamUntilPersisted(messages, streamOptions, scope.principal.id, scope.principal.kind, recovery.token, ...(scheduleDispatch ? [scheduleDispatch] : []));
938
965
  const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
939
966
  if (!summary)
940
967
  throw new Error('agent run did not persist a summary');
@@ -1001,202 +1028,291 @@ export function createThreadAgentHost(options) {
1001
1028
  durableAgent,
1002
1029
  };
1003
1030
  },
1004
- route: (request, scope) => withDispatchLock(async () => {
1005
- const url = new URL(request.url);
1006
- if (!url.pathname.startsWith(AGENT_HOST_ROUTE_PREFIX))
1007
- return null;
1008
- if (request.method === 'GET' &&
1009
- url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/binding`) {
1010
- const resourceId = url.searchParams.get('resourceId');
1011
- const agentId = url.searchParams.get('agentId');
1012
- const binding = await readBinding();
1013
- if (!resourceId ||
1014
- resourceId !== resourceIdFromKey(scope.threadId) ||
1015
- binding?.resourceId !== resourceId ||
1016
- (agentId !== null && binding.agentId !== agentId)) {
1017
- throw new AgentHostRequestError(404, 'agent not found');
1018
- }
1019
- return json({ bound: true });
1020
- }
1031
+ route: async (request, scope) => {
1032
+ let preflightedTermination = false;
1033
+ const preflightUrl = new URL(request.url);
1034
+ const preflightSuffix = preflightUrl.pathname.startsWith(AGENT_HOST_ROUTE_PREFIX)
1035
+ ? preflightUrl.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length)
1036
+ : '';
1037
+ const preflightSegments = preflightSuffix.split('/').filter(Boolean);
1021
1038
  if (request.method === 'POST' &&
1022
- url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/start`) {
1023
- const body = await objectBody(request);
1024
- if ('resourceOwner' in body || 'requestedBy' in body) {
1025
- throw new AgentHostRequestError(400, 'start owner and requester are derived from trusted provenance');
1039
+ preflightSegments.length === 4 &&
1040
+ preflightSegments[0] === 'runs' &&
1041
+ preflightSegments[3] === 'terminate') {
1042
+ const agentId = decode(preflightSegments[1]);
1043
+ const runId = decode(preflightSegments[2]);
1044
+ const resourceId = preflightUrl.searchParams.get('resourceId');
1045
+ if (!agentId || !runId || !resourceId) {
1046
+ throw new AgentHostRequestError(404, 'run not found');
1026
1047
  }
1027
- const ref = runRef(scope, body);
1028
- const requestedEntry = entryPath(body.entryPath);
1029
- if (requestedEntry !== 'schedule.fire' &&
1030
- typeof body.prompt !== 'string') {
1031
- throw new AgentHostRequestError(400, 'prompt is required');
1048
+ const ref = runRef(scope, {
1049
+ agentId,
1050
+ threadId: scope.threadId,
1051
+ resourceId,
1052
+ runId,
1053
+ });
1054
+ const storedRun = await readRun(ref.runId);
1055
+ if (storedRun && storedRun.agentId !== ref.agentId) {
1056
+ throw new AgentHostRequestError(404, 'run not found');
1057
+ }
1058
+ await snapshotExecutionFor(scope, ref);
1059
+ const owner = await options.resourceAccess().owner('run', ref.runId);
1060
+ if (preflightUrl.searchParams.get('replay') !== '1') {
1061
+ await scope.init.runtime.cancelActiveExecution(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, 'cancelled', [scope.principal, owner ?? scope.principal]);
1062
+ preflightedTermination = true;
1032
1063
  }
1033
- return json(await host.start(scope, {
1034
- ...ref,
1035
- ...(typeof body.prompt === 'string'
1036
- ? { prompt: body.prompt }
1037
- : {}),
1038
- entryPath: requestedEntry,
1039
- threaded: body.threaded !== false,
1040
- safeContext: safeContext(body.safeContext),
1041
- providerOptions: providerOptions(body.providerOptions),
1042
- ...(body.scheduleId !== undefined
1043
- ? {
1044
- scheduleId: isPathSafeId(body.scheduleId)
1045
- ? body.scheduleId
1046
- : (() => {
1047
- throw new AgentHostRequestError(404, 'run not found');
1048
- })(),
1049
- }
1050
- : {}),
1051
- ...(body.dispatchId !== undefined
1052
- ? {
1053
- dispatchId: isPathSafeId(body.dispatchId)
1054
- ? body.dispatchId
1055
- : (() => {
1056
- throw new AgentHostRequestError(404, 'run not found');
1057
- })(),
1058
- }
1059
- : {}),
1060
- }));
1061
1064
  }
1062
- if (request.method === 'POST' &&
1063
- url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/resume`) {
1064
- const body = await objectBody(request);
1065
- const ref = runRef(scope, body);
1066
- const snapshotExecution = await snapshotExecutionFor(scope, ref);
1067
- await statusFor(scope, ref, snapshotExecution.threaded);
1068
- const stored = await readRun(ref.runId);
1069
- if (!stored ||
1070
- stored.agentId !== ref.agentId ||
1071
- !samePrincipal(stored.principal, scope.principal)) {
1072
- throw new AgentHostRequestError(404, 'run not found');
1065
+ return withDispatchLock(async () => {
1066
+ const url = new URL(request.url);
1067
+ if (!url.pathname.startsWith(AGENT_HOST_ROUTE_PREFIX))
1068
+ return null;
1069
+ if (request.method === 'GET' &&
1070
+ url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/binding`) {
1071
+ const resourceId = url.searchParams.get('resourceId');
1072
+ const agentId = url.searchParams.get('agentId');
1073
+ const binding = await readBinding();
1074
+ if (!resourceId ||
1075
+ resourceId !== resourceIdFromKey(scope.threadId) ||
1076
+ binding?.resourceId !== resourceId ||
1077
+ (agentId !== null && binding.agentId !== agentId)) {
1078
+ throw new AgentHostRequestError(404, 'agent not found');
1079
+ }
1080
+ return json({ bound: true });
1073
1081
  }
1074
- const { current, module, principalPermissions } = await authorize(scope, ref.agentId, entryPath(body.entryPath), stored.principal);
1075
- const durable = current.agents.get(module.meta.id);
1076
- if (!durable)
1077
- throw new Error('guarded agent was not registered');
1078
- const requesterId = requestedBy(body.requestedBy);
1079
- const step = typeof body.step === 'string' ||
1080
- (Array.isArray(body.step) &&
1081
- body.step.every((part) => typeof part === 'string'))
1082
- ? body.step
1083
- : undefined;
1084
- const execution = {
1085
- agentId: ref.agentId,
1086
- deploymentTag: scope.deploymentTag,
1087
- principal: stored.principal,
1088
- threadId: scope.threadId,
1089
- resourceId: ref.resourceId,
1090
- runId: ref.runId,
1091
- entryPath: 'approval.resume',
1092
- // The re-derived resolution, not the start leg's: the resume merges
1093
- // over the persisted context, so this leg's projection retires a
1094
- // stale one minted under an older policy snapshot.
1095
- principalPermissions,
1096
- safeContext: snapshotExecution.safeContext,
1097
- };
1098
- const summary = await withExecution(execution, async () => {
1099
- return durable.resumeViaRuntime({
1100
- runId: ref.runId,
1101
- requestedBy: requesterId,
1102
- ...(step !== undefined ? { step } : {}),
1103
- ...('resumeData' in body ? { resumeData: body.resumeData } : {}),
1104
- ...(snapshotExecution.threaded
1082
+ if (request.method === 'POST' &&
1083
+ url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/start`) {
1084
+ const body = await objectBody(request);
1085
+ if ('resourceOwner' in body || 'requestedBy' in body) {
1086
+ throw new AgentHostRequestError(400, 'start owner and requester are derived from trusted provenance');
1087
+ }
1088
+ const ref = runRef(scope, body);
1089
+ const requestedEntry = entryPath(body.entryPath);
1090
+ if (requestedEntry !== 'schedule.fire' &&
1091
+ typeof body.prompt !== 'string') {
1092
+ throw new AgentHostRequestError(400, 'prompt is required');
1093
+ }
1094
+ return json(await host.start(scope, {
1095
+ ...ref,
1096
+ ...(typeof body.prompt === 'string'
1097
+ ? { prompt: body.prompt }
1098
+ : {}),
1099
+ entryPath: requestedEntry,
1100
+ threaded: body.threaded !== false,
1101
+ safeContext: safeContext(body.safeContext),
1102
+ providerOptions: providerOptions(body.providerOptions),
1103
+ ...(body.scheduleId !== undefined
1105
1104
  ? {
1106
- memory: {
1107
- thread: scope.threadId,
1108
- resource: ref.resourceId,
1109
- },
1105
+ scheduleId: isPathSafeId(body.scheduleId)
1106
+ ? body.scheduleId
1107
+ : (() => {
1108
+ throw new AgentHostRequestError(404, 'run not found');
1109
+ })(),
1110
1110
  }
1111
1111
  : {}),
1112
+ ...(body.dispatchId !== undefined
1113
+ ? {
1114
+ dispatchId: isPathSafeId(body.dispatchId)
1115
+ ? body.dispatchId
1116
+ : (() => {
1117
+ throw new AgentHostRequestError(404, 'run not found');
1118
+ })(),
1119
+ }
1120
+ : {}),
1121
+ }));
1122
+ }
1123
+ if (request.method === 'POST' &&
1124
+ url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/resume`) {
1125
+ const body = await objectBody(request);
1126
+ const ref = runRef(scope, body);
1127
+ const snapshotExecution = await snapshotExecutionFor(scope, ref);
1128
+ await statusFor(scope, ref, snapshotExecution.threaded);
1129
+ const stored = await readRun(ref.runId);
1130
+ if (!stored ||
1131
+ stored.agentId !== ref.agentId ||
1132
+ !samePrincipal(stored.principal, scope.principal)) {
1133
+ throw new AgentHostRequestError(404, 'run not found');
1134
+ }
1135
+ const { current, module, principalPermissions } = await authorize(scope, ref.agentId, entryPath(body.entryPath), stored.principal);
1136
+ const durable = current.agents.get(module.meta.id);
1137
+ if (!durable)
1138
+ throw new Error('guarded agent was not registered');
1139
+ const requesterId = requestedBy(body.requestedBy);
1140
+ const step = typeof body.step === 'string' ||
1141
+ (Array.isArray(body.step) &&
1142
+ body.step.every((part) => typeof part === 'string'))
1143
+ ? body.step
1144
+ : undefined;
1145
+ const execution = {
1146
+ agentId: ref.agentId,
1147
+ deploymentTag: scope.deploymentTag,
1148
+ principal: stored.principal,
1149
+ threadId: scope.threadId,
1150
+ resourceId: ref.resourceId,
1151
+ runId: ref.runId,
1152
+ entryPath: 'approval.resume',
1153
+ // The re-derived resolution, not the start leg's: the resume merges
1154
+ // over the persisted context, so this leg's projection retires a
1155
+ // stale one minted under an older policy snapshot.
1156
+ principalPermissions,
1157
+ safeContext: snapshotExecution.safeContext,
1158
+ };
1159
+ const summary = await withExecution(execution, async () => {
1160
+ return durable.resumeViaRuntime({
1161
+ runId: ref.runId,
1162
+ requestedBy: requesterId,
1163
+ ...(step !== undefined ? { step } : {}),
1164
+ ...('resumeData' in body ? { resumeData: body.resumeData } : {}),
1165
+ ...(snapshotExecution.threaded
1166
+ ? {
1167
+ memory: {
1168
+ thread: scope.threadId,
1169
+ resource: ref.resourceId,
1170
+ },
1171
+ }
1172
+ : {}),
1173
+ });
1112
1174
  });
1113
- });
1114
- const result = await envelopeFor(scope, ref, stored.principal, summary);
1115
- if (isTerminalRunStatus(summary.status)) {
1116
- await deleteAgentRunRecord(options.stateStorage(), ref.runId);
1117
- const recovery = await options
1118
- .stateStorage()
1119
- .get(ownerRecoveryKey(ref.runId));
1120
- if (recovery) {
1121
- await finalizeOwnerRecoveryBestEffort(recovery, summary);
1175
+ const result = await envelopeFor(scope, ref, stored.principal, summary);
1176
+ if (isTerminalRunStatus(summary.status)) {
1177
+ await deleteAgentRunRecord(options.stateStorage(), ref.runId);
1178
+ const recovery = await options
1179
+ .stateStorage()
1180
+ .get(ownerRecoveryKey(ref.runId));
1181
+ if (recovery) {
1182
+ await finalizeOwnerRecoveryBestEffort(recovery, summary);
1183
+ }
1122
1184
  }
1185
+ return json(result);
1123
1186
  }
1124
- return json(result);
1125
- }
1126
- const suffix = url.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length);
1127
- const segments = suffix.split('/').filter(Boolean);
1128
- if (segments[0] !== 'runs')
1129
- return json({ error: 'not found' }, 404);
1130
- const agentId = decode(segments[1]);
1131
- const runId = decode(segments[2]);
1132
- const resourceId = url.searchParams.get('resourceId');
1133
- if (!agentId || !runId || !resourceId) {
1134
- throw new AgentHostRequestError(404, 'run not found');
1135
- }
1136
- const ref = runRef(scope, {
1137
- agentId,
1138
- threadId: scope.threadId,
1139
- resourceId,
1140
- runId,
1141
- });
1142
- if (segments.length === 3 && request.method === 'GET') {
1143
- if (url.searchParams.get('dispatch') === '1') {
1144
- const key = ownerRecoveryKey(ref.runId);
1145
- const pending = await options
1146
- .stateStorage()
1147
- .get(key);
1148
- if (pending) {
1149
- await recoverOwner(scope.init.runtime, scope.threadId, key, pending, true);
1187
+ const suffix = url.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length);
1188
+ const segments = suffix.split('/').filter(Boolean);
1189
+ if (segments[0] !== 'runs')
1190
+ return json({ error: 'not found' }, 404);
1191
+ const agentId = decode(segments[1]);
1192
+ const runId = decode(segments[2]);
1193
+ const resourceId = url.searchParams.get('resourceId');
1194
+ if (!agentId || !runId || !resourceId) {
1195
+ throw new AgentHostRequestError(404, 'run not found');
1196
+ }
1197
+ const ref = runRef(scope, {
1198
+ agentId,
1199
+ threadId: scope.threadId,
1200
+ resourceId,
1201
+ runId,
1202
+ });
1203
+ if (segments.length === 3 && request.method === 'GET') {
1204
+ if (url.searchParams.get('dispatch') === '1') {
1205
+ const key = ownerRecoveryKey(ref.runId);
1206
+ const pending = await options
1207
+ .stateStorage()
1208
+ .get(key);
1209
+ if (pending) {
1210
+ await recoverOwner(scope.init.runtime, scope.threadId, key, pending, true);
1211
+ }
1212
+ return json(await statusFor(scope, ref));
1150
1213
  }
1151
1214
  return json(await statusFor(scope, ref));
1152
1215
  }
1153
- return json(await statusFor(scope, ref));
1154
- }
1155
- if (segments.length === 4 &&
1156
- segments[3] === 'stream' &&
1157
- request.method === 'GET') {
1158
- const run = await statusFor(scope, ref);
1159
- const offset = Number(url.searchParams.get('offset') ?? '0');
1160
- if (!Number.isSafeInteger(offset) || offset < 0) {
1161
- throw new AgentHostRequestError(400, 'invalid stream offset');
1162
- }
1163
- const current = await runtimeFor(scope);
1164
- const durable = current.agents.get(ref.agentId);
1165
- if (!durable)
1166
- throw new AgentHostRequestError(404, 'agent not found');
1167
- const live = durable.runRegistry.has(ref.runId);
1168
- let historyLength = 0;
1169
- try {
1170
- const history = await durable.pubsub.getHistory(AGENT_STREAM_TOPIC(ref.runId));
1171
- historyLength = Array.isArray(history) ? history.length : 0;
1172
- }
1173
- catch {
1174
- // A live registry can still serve future events in this isolate.
1175
- }
1176
- if (!live && historyLength === 0) {
1177
- throw new AgentHostRequestError(409, 'stream replay is unavailable; inspect the authoritative status endpoint');
1216
+ if (segments.length === 4 &&
1217
+ segments[3] === 'terminate' &&
1218
+ request.method === 'POST') {
1219
+ const runtime = scope.init.runtime;
1220
+ const replayOnly = url.searchParams.get('replay') === '1';
1221
+ const storedRun = await readRun(ref.runId);
1222
+ if (storedRun && storedRun.agentId !== ref.agentId) {
1223
+ throw new AgentHostRequestError(404, 'run not found');
1224
+ }
1225
+ await snapshotExecutionFor(scope, ref);
1226
+ const preflightOwner = await options
1227
+ .resourceAccess()
1228
+ .owner('run', ref.runId);
1229
+ if (!replayOnly && !preflightedTermination) {
1230
+ await runtime.cancelActiveExecution(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, 'cancelled', [scope.principal, preflightOwner ?? scope.principal]);
1231
+ }
1232
+ const owner = await options.resourceAccess().owner('run', ref.runId);
1233
+ if (replayOnly) {
1234
+ const existing = await runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
1235
+ if (existing?.status !== 'cancelled' &&
1236
+ existing?.status !== 'timed_out') {
1237
+ throw new AgentHostRequestError(404, 'run not found');
1238
+ }
1239
+ }
1240
+ const transition = await runtime.terminateAsPrincipal(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, scope.principal, owner ?? scope.principal);
1241
+ let summary = transition.summary;
1242
+ if (!transition.cleanup.cleanupCompleted) {
1243
+ await abandonApprovalsForRun(options.approvalService(scope), DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, transition.cleanup.status, options.systemPrincipalId ?? 'flowsafe-system');
1244
+ const dispatch = transition.cleanup.scheduleDispatch;
1245
+ if (dispatch) {
1246
+ if (!options.discardScheduleDispatch) {
1247
+ throw new Error('scheduled agent termination requires a dispatch-discard hook');
1248
+ }
1249
+ await options.discardScheduleDispatch(dispatch.scheduleId, dispatch.dispatchId, ref.runId);
1250
+ }
1251
+ const released = await options
1252
+ .resourceAccess()
1253
+ .release('run', ref.runId, owner ?? scope.principal);
1254
+ if (!released) {
1255
+ const current = await options
1256
+ .resourceAccess()
1257
+ .owner('run', ref.runId);
1258
+ if (current) {
1259
+ throw new Error(`run '${ref.runId}' ownership could not be released`);
1260
+ }
1261
+ }
1262
+ }
1263
+ await finalizeTerminalAgentState(scope.threadId, ref.runId, summary);
1264
+ if (!transition.cleanup.cleanupCompleted) {
1265
+ summary = await runtime.completeTerminalCleanup(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, transition.cleanup.revision);
1266
+ }
1267
+ return json(await envelopeFor(scope, ref, storedRun?.principal ?? scope.principal, summary));
1178
1268
  }
1179
- if (isTerminalRunStatus(run.summary.status)) {
1180
- if (historyLength === 0) {
1269
+ if (segments.length === 4 &&
1270
+ segments[3] === 'stream' &&
1271
+ request.method === 'GET') {
1272
+ const run = await statusFor(scope, ref);
1273
+ const offset = Number(url.searchParams.get('offset') ?? '0');
1274
+ if (!Number.isSafeInteger(offset) || offset < 0) {
1275
+ throw new AgentHostRequestError(400, 'invalid stream offset');
1276
+ }
1277
+ const current = await runtimeFor(scope);
1278
+ const durable = current.agents.get(ref.agentId);
1279
+ if (!durable)
1280
+ throw new AgentHostRequestError(404, 'agent not found');
1281
+ const live = durable.runRegistry.has(ref.runId);
1282
+ let historyLength = 0;
1283
+ try {
1284
+ const history = await durable.pubsub.getHistory(AGENT_STREAM_TOPIC(ref.runId));
1285
+ historyLength = Array.isArray(history) ? history.length : 0;
1286
+ }
1287
+ catch {
1288
+ // A live registry can still serve future events in this isolate.
1289
+ }
1290
+ if (!live && historyLength === 0) {
1181
1291
  throw new AgentHostRequestError(409, 'stream replay is unavailable; inspect the authoritative status endpoint');
1182
1292
  }
1183
- if (offset >= historyLength) {
1184
- return ndjson(new ReadableStream({
1185
- start(controller) {
1186
- controller.close();
1187
- },
1188
- }), offset);
1293
+ if (isTerminalRunStatus(run.summary.status)) {
1294
+ if (historyLength === 0) {
1295
+ throw new AgentHostRequestError(409, 'stream replay is unavailable; inspect the authoritative status endpoint');
1296
+ }
1297
+ if (offset >= historyLength) {
1298
+ return ndjson(new ReadableStream({
1299
+ start(controller) {
1300
+ controller.close();
1301
+ },
1302
+ }), offset);
1303
+ }
1189
1304
  }
1305
+ const observed = await durable.observe(ref.runId, { offset });
1306
+ return ndjson(observed.fullStream, offset);
1190
1307
  }
1191
- const observed = await durable.observe(ref.runId, { offset });
1192
- return ndjson(observed.fullStream, offset);
1193
- }
1194
- const known = segments.length === 3 ||
1195
- (segments.length === 4 && segments[3] === 'stream');
1196
- return known
1197
- ? json({ error: 'method not allowed' }, 405)
1198
- : json({ error: 'not found' }, 404);
1199
- }),
1308
+ const known = segments.length === 3 ||
1309
+ (segments.length === 4 &&
1310
+ (segments[3] === 'stream' || segments[3] === 'terminate'));
1311
+ return known
1312
+ ? json({ error: 'method not allowed' }, 405)
1313
+ : json({ error: 'not found' }, 404);
1314
+ });
1315
+ },
1200
1316
  };
1201
1317
  return host;
1202
1318
  }