@proofoftech/flowsafe 0.20.0 → 0.22.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 (238) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +55 -10
  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 +858 -351
  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 +243 -64
  15. package/dist/agent-host/thread-topology.js.map +1 -1
  16. package/dist/agent-runner/durable-agent-runner.d.ts +89 -14
  17. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  18. package/dist/agent-runner/durable-agent-runner.js +369 -44
  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 +13 -20
  33. package/dist/approval-api/service.d.ts.map +1 -1
  34. package/dist/approval-api/service.js +52 -28
  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 +8 -14
  41. package/dist/background-tasks/d1-storage.js.map +1 -1
  42. package/dist/background-tasks/host.d.ts.map +1 -1
  43. package/dist/background-tasks/host.js +3 -2
  44. package/dist/background-tasks/host.js.map +1 -1
  45. package/dist/do-runner/constants.d.ts +3 -0
  46. package/dist/do-runner/constants.d.ts.map +1 -0
  47. package/dist/do-runner/constants.js +3 -0
  48. package/dist/do-runner/constants.js.map +1 -0
  49. package/dist/do-runner/d1-storage.d.ts +34 -158
  50. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  51. package/dist/do-runner/d1-storage.js +935 -402
  52. package/dist/do-runner/d1-storage.js.map +1 -1
  53. package/dist/do-runner/durable-object.d.ts.map +1 -1
  54. package/dist/do-runner/durable-object.js +472 -185
  55. package/dist/do-runner/durable-object.js.map +1 -1
  56. package/dist/do-runner/execution-admission.d.ts +114 -0
  57. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  58. package/dist/do-runner/execution-admission.js +206 -0
  59. package/dist/do-runner/execution-admission.js.map +1 -0
  60. package/dist/do-runner/execution-context.d.ts +5 -1
  61. package/dist/do-runner/execution-context.d.ts.map +1 -1
  62. package/dist/do-runner/execution-context.js +6 -1
  63. package/dist/do-runner/execution-context.js.map +1 -1
  64. package/dist/do-runner/execution-fence.d.ts +74 -30
  65. package/dist/do-runner/execution-fence.d.ts.map +1 -1
  66. package/dist/do-runner/execution-fence.js +684 -120
  67. package/dist/do-runner/execution-fence.js.map +1 -1
  68. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  69. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  70. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  71. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  72. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  73. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  74. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  75. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  76. package/dist/do-runner/index.d.ts +13 -8
  77. package/dist/do-runner/index.d.ts.map +1 -1
  78. package/dist/do-runner/index.js +6 -2
  79. package/dist/do-runner/index.js.map +1 -1
  80. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  81. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  82. package/dist/do-runner/initial-admission-refusal.js +41 -0
  83. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  84. package/dist/do-runner/inventory.d.ts +2 -1
  85. package/dist/do-runner/inventory.d.ts.map +1 -1
  86. package/dist/do-runner/inventory.js +28 -39
  87. package/dist/do-runner/inventory.js.map +1 -1
  88. package/dist/do-runner/notification-predicate.d.ts +7 -7
  89. package/dist/do-runner/notification-predicate.d.ts.map +1 -1
  90. package/dist/do-runner/notification-predicate.js +134 -7
  91. package/dist/do-runner/notification-predicate.js.map +1 -1
  92. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  93. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  94. package/dist/do-runner/run-lifecycle.js +69 -15
  95. package/dist/do-runner/run-lifecycle.js.map +1 -1
  96. package/dist/do-runner/run-provenance.d.ts +38 -0
  97. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  98. package/dist/do-runner/run-provenance.js +152 -0
  99. package/dist/do-runner/run-provenance.js.map +1 -0
  100. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  101. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  102. package/dist/do-runner/run-storage-tables.js +4 -0
  103. package/dist/do-runner/run-storage-tables.js.map +1 -0
  104. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  105. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  106. package/dist/do-runner/run-terminal-state.js +105 -0
  107. package/dist/do-runner/run-terminal-state.js.map +1 -0
  108. package/dist/do-runner/runtime.d.ts +108 -46
  109. package/dist/do-runner/runtime.d.ts.map +1 -1
  110. package/dist/do-runner/runtime.js +927 -438
  111. package/dist/do-runner/runtime.js.map +1 -1
  112. package/dist/do-runner/start-idempotency.d.ts +35 -258
  113. package/dist/do-runner/start-idempotency.d.ts.map +1 -1
  114. package/dist/do-runner/start-idempotency.js +606 -498
  115. package/dist/do-runner/start-idempotency.js.map +1 -1
  116. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  117. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  118. package/dist/do-runner/start-reservation-contract.js +338 -0
  119. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  120. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  121. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  122. package/dist/do-runner/suspension-deadline.js +8 -12
  123. package/dist/do-runner/suspension-deadline.js.map +1 -1
  124. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  125. package/dist/do-runner/table-prefix.js +2 -1
  126. package/dist/do-runner/table-prefix.js.map +1 -1
  127. package/dist/do-runner/testing.d.ts +3 -0
  128. package/dist/do-runner/testing.d.ts.map +1 -0
  129. package/dist/do-runner/testing.js +3 -0
  130. package/dist/do-runner/testing.js.map +1 -0
  131. package/dist/do-runner/thread-do.d.ts +2 -1
  132. package/dist/do-runner/thread-do.d.ts.map +1 -1
  133. package/dist/do-runner/thread-do.js +14 -10
  134. package/dist/do-runner/thread-do.js.map +1 -1
  135. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  136. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  137. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  138. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  139. package/dist/goals/objective-routes.d.ts +1 -5
  140. package/dist/goals/objective-routes.d.ts.map +1 -1
  141. package/dist/goals/objective-routes.js +32 -53
  142. package/dist/goals/objective-routes.js.map +1 -1
  143. package/dist/host-kit/approval-bridge.d.ts +8 -8
  144. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  145. package/dist/host-kit/approval-bridge.js +18 -15
  146. package/dist/host-kit/approval-bridge.js.map +1 -1
  147. package/dist/host-kit/do-response.d.ts +16 -0
  148. package/dist/host-kit/do-response.d.ts.map +1 -1
  149. package/dist/host-kit/do-response.js +181 -0
  150. package/dist/host-kit/do-response.js.map +1 -1
  151. package/dist/host-kit/do-run-topology.d.ts +2 -14
  152. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  153. package/dist/host-kit/do-run-topology.js +31 -24
  154. package/dist/host-kit/do-run-topology.js.map +1 -1
  155. package/dist/host-kit/env-vars.d.ts.map +1 -1
  156. package/dist/host-kit/env-vars.js +5 -6
  157. package/dist/host-kit/env-vars.js.map +1 -1
  158. package/dist/host-kit/flowsafe-worker.d.ts +38 -6
  159. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  160. package/dist/host-kit/flowsafe-worker.js +115 -93
  161. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  162. package/dist/host-kit/host-approval-service.d.ts +4 -14
  163. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  164. package/dist/host-kit/host-approval-service.js +23 -40
  165. package/dist/host-kit/host-approval-service.js.map +1 -1
  166. package/dist/host-kit/index.d.ts +7 -1
  167. package/dist/host-kit/index.d.ts.map +1 -1
  168. package/dist/host-kit/index.js +4 -0
  169. package/dist/host-kit/index.js.map +1 -1
  170. package/dist/host-kit/run-route-error.d.ts +3 -17
  171. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  172. package/dist/host-kit/run-route-error.js +4 -24
  173. package/dist/host-kit/run-route-error.js.map +1 -1
  174. package/dist/host-kit/run-router.d.ts +6 -2
  175. package/dist/host-kit/run-router.d.ts.map +1 -1
  176. package/dist/host-kit/run-router.js +93 -80
  177. package/dist/host-kit/run-router.js.map +1 -1
  178. package/dist/host-kit/thread-topology.d.ts +1 -1
  179. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  180. package/dist/host-kit/thread-topology.js +7 -3
  181. package/dist/host-kit/thread-topology.js.map +1 -1
  182. package/dist/internal-error-response.d.ts.map +1 -1
  183. package/dist/internal-error-response.js +16 -6
  184. package/dist/internal-error-response.js.map +1 -1
  185. package/dist/schedules/index.d.ts +1 -0
  186. package/dist/schedules/index.d.ts.map +1 -1
  187. package/dist/schedules/index.js +1 -7
  188. package/dist/schedules/index.js.map +1 -1
  189. package/dist/schedules/mutation-contract.d.ts +38 -0
  190. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  191. package/dist/schedules/mutation-contract.js +21 -0
  192. package/dist/schedules/mutation-contract.js.map +1 -0
  193. package/dist/schedules/router.d.ts +11 -19
  194. package/dist/schedules/router.d.ts.map +1 -1
  195. package/dist/schedules/router.js +130 -49
  196. package/dist/schedules/router.js.map +1 -1
  197. package/dist/schedules/schedules-d1.d.ts +11 -5
  198. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  199. package/dist/schedules/schedules-d1.js +571 -144
  200. package/dist/schedules/schedules-d1.js.map +1 -1
  201. package/dist/schedules/storage.d.ts +0 -7
  202. package/dist/schedules/storage.d.ts.map +1 -1
  203. package/dist/schedules/storage.js +0 -27
  204. package/dist/schedules/storage.js.map +1 -1
  205. package/dist/schedules/tick.d.ts +1 -8
  206. package/dist/schedules/tick.d.ts.map +1 -1
  207. package/dist/schedules/tick.js +15 -20
  208. package/dist/schedules/tick.js.map +1 -1
  209. package/dist/signal-providers/webhook-route.d.ts +1 -1
  210. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  211. package/dist/signal-providers/webhook-route.js +99 -109
  212. package/dist/signal-providers/webhook-route.js.map +1 -1
  213. package/dist/signals/d1-shared.d.ts +11 -8
  214. package/dist/signals/d1-shared.d.ts.map +1 -1
  215. package/dist/signals/d1-shared.js +2 -7
  216. package/dist/signals/d1-shared.js.map +1 -1
  217. package/dist/signals/index.d.ts +1 -1
  218. package/dist/signals/index.d.ts.map +1 -1
  219. package/dist/signals/index.js +1 -1
  220. package/dist/signals/index.js.map +1 -1
  221. package/dist/signals/notification-dispatch.d.ts +84 -4
  222. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  223. package/dist/signals/notification-dispatch.js +365 -53
  224. package/dist/signals/notification-dispatch.js.map +1 -1
  225. package/dist/signals/notifications-d1.d.ts +6 -1
  226. package/dist/signals/notifications-d1.d.ts.map +1 -1
  227. package/dist/signals/notifications-d1.js +215 -10
  228. package/dist/signals/notifications-d1.js.map +1 -1
  229. package/dist/signals/router.d.ts +6 -4
  230. package/dist/signals/router.d.ts.map +1 -1
  231. package/dist/signals/router.js +49 -84
  232. package/dist/signals/router.js.map +1 -1
  233. package/dist/signals/thread-do-routes.d.ts +2 -0
  234. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  235. package/dist/signals/thread-do-routes.js +250 -81
  236. package/dist/signals/thread-do-routes.js.map +1 -1
  237. package/package.json +9 -7
  238. package/scripts/seed-deployment-identity.mjs +27 -6
@@ -1,15 +1,22 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- import { AGENT_STREAM_TOPIC } from '@mastra/core/agent/durable';
2
+ import { AGENT_STREAM_TOPIC, globalRunRegistry, } from '@mastra/core/agent/durable';
3
3
  import { Mastra } from '@mastra/core/mastra';
4
4
  import { isPrincipalPermissions } from '@proofoftech/breakwater/rbac';
5
- import { AGENT_ENTRY_PATHS, AGENT_RUN_STORAGE_KEY_PREFIX, bindAgentThread, createFlowsafeDurableAgent, DURABLE_AGENTIC_LOOP_WORKFLOW_ID, deleteAgentRunRecord, deleteAgentThreadBinding, readAgentRunRecord, readAgentThreadBinding, writeAgentRunRecord, } from '../agent-runner/index.js';
5
+ import { AgentRunSelectorMismatchError, } from '../agent-runner/durable-agent-runner.js';
6
+ import { AGENT_ENTRY_PATHS, AGENT_RUN_STORAGE_KEY_PREFIX, bindAgentThread, createFlowsafeDurableAgent, deleteAgentRunRecord, deleteAgentThreadBinding, readAgentRunRecord, readAgentThreadBinding, writeAgentRunRecord, } from '../agent-runner/index.js';
6
7
  import { canonicalResourceOwner, principalActor, principalAuditFields, principalOwner, RUN_START_ROLES, samePrincipal, } from '../approval-api/index.js';
7
- import { isExecutionPrincipalId, } from '../approval-api/principal.js';
8
+ import { assertExecutionPrincipal, isExecutionPrincipalId, } from '../approval-api/principal.js';
9
+ import { ExecutionFenceUnreadableError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeRunExecutionIdentity, RunStartPendingError, } from '../do-runner/execution-admission.js';
8
10
  import { DoStatusError, isPathSafeId, resolveScheduleStartOwner, resourceIdFromKey, SUSPENSION_TIMEOUT_RESUME_KEY, } from '../do-runner/index.js';
11
+ import { isDefinitiveInitialAdmissionRefusal } from '../do-runner/initial-admission-refusal.js';
9
12
  import { mastraRegistryEntries } from '../do-runner/mastra-registry.js';
13
+ import { lifecycleFromRequestContext, terminalCleanupFor, } from '../do-runner/run-lifecycle.js';
14
+ import { isTerminalRunStatus } from '../do-runner/run-terminal-state.js';
15
+ import { captureReservation, sameReservationIdentity, } from '../do-runner/start-reservation-contract.js';
16
+ import { persistedStartRecord } from '../host-kit/do-response.js';
10
17
  import { abandonApprovalsForRun, reconcileApprovalsForSummary, } from '../host-kit/index.js';
11
18
  import { createAgentModuleCatalog } from './catalog.js';
12
- import { AGENT_HOST_ROUTE_PREFIX } from './thread-topology.js';
19
+ import { AGENT_HOST_ROUTE_PREFIX, publicAgentRunEnvelope, } from './thread-topology.js';
13
20
  import { createTrustedAgentRequestContext, deriveTrustedAgentContext, sanitizeStoredAgentContext, } from './trusted-context.js';
14
21
  class AgentHostRequestError extends DoStatusError {
15
22
  status;
@@ -52,20 +59,40 @@ async function objectBody(request) {
52
59
  }
53
60
  return value;
54
61
  }
55
- const TERMINAL_RUN_STATUSES = [
56
- 'success',
57
- 'failed',
58
- 'tripwire',
59
- 'canceled',
60
- 'bailed',
61
- 'skipped',
62
- 'cancelled',
63
- 'timed_out',
64
- ];
65
62
  const AGENT_OWNER_RECOVERY_PREFIX = 'flowsafe:agent-owner-recovery:v1:';
66
63
  const AGENT_OWNER_RECOVERY_DELAY_MS = 60_000;
67
- function isTerminalRunStatus(status) {
68
- return TERMINAL_RUN_STATUSES.includes(status);
64
+ function sameRunRecord(actual, expected) {
65
+ return (actual !== undefined &&
66
+ actual.version === expected.version &&
67
+ actual.agentId === expected.agentId &&
68
+ actual.originEntryPath === expected.originEntryPath &&
69
+ samePrincipal(actual.principal, expected.principal));
70
+ }
71
+ function sameOwnerRecovery(actual, expected) {
72
+ const claim = actual.startReservation, wanted = expected.startReservation;
73
+ return (actual.version === expected.version &&
74
+ actual.phase === expected.phase &&
75
+ actual.token === expected.token &&
76
+ actual.agentId === expected.agentId &&
77
+ actual.threadId === expected.threadId &&
78
+ actual.resourceId === expected.resourceId &&
79
+ actual.runId === expected.runId &&
80
+ actual.owner.kind === expected.owner.kind &&
81
+ actual.owner.id === expected.owner.id &&
82
+ actual.threaded === expected.threaded &&
83
+ actual.bindingPreexisting === expected.bindingPreexisting &&
84
+ sameRunRecord(actual.runRecord, expected.runRecord) &&
85
+ actual.execution?.tablePrefix === expected.execution?.tablePrefix &&
86
+ actual.execution?.workflowId === expected.execution?.workflowId &&
87
+ actual.execution?.runId === expected.execution?.runId &&
88
+ actual.execution?.startToken === expected.execution?.startToken &&
89
+ (claim === undefined
90
+ ? wanted === undefined
91
+ : wanted !== undefined &&
92
+ sameReservationIdentity(claim, wanted) &&
93
+ claim.state === wanted.state &&
94
+ claim.updatedAt === wanted.updatedAt &&
95
+ claim.binding.kind === wanted.binding.kind));
69
96
  }
70
97
  function entryPath(value) {
71
98
  if (typeof value !== 'string' ||
@@ -219,20 +246,9 @@ export function createThreadAgentHost(options) {
219
246
  const withBindingLock = createFifoLock();
220
247
  const withDispatchLock = createFifoLock();
221
248
  const withRecoveryLock = createFifoLock();
222
- /**
223
- * Run ids this object is currently starting — the liveness half of the
224
- * idempotent-start replay decision, and the reason a retried agent start can
225
- * tell "the first one is still working" from "the first one died holding the
226
- * claim" without a timer.
227
- *
228
- * In memory, never stored: liveness is a property of an isolate that is
229
- * running code, so the honest answer after an eviction is `false`, and any
230
- * durable proxy would keep saying `true` for a run nothing is executing.
231
- * Scoped to this host instance, which `instanceScopeFor` already pins to one
232
- * Durable Object — the same object an agent run is bound to for its whole
233
- * life, so this object's answer is the only one there is.
234
- */
249
+ /** Claim durability does not establish current run liveness. */
235
250
  const startsInFlight = new Set();
251
+ const unwoundExecutions = new WeakSet();
236
252
  const instanceScopeFor = (scope) => {
237
253
  if (stableScope) {
238
254
  if (stableScope.threadId !== scope.threadId ||
@@ -259,13 +275,14 @@ export function createThreadAgentHost(options) {
259
275
  return catalogPromise;
260
276
  };
261
277
  const runtimeFor = async (scope) => {
278
+ instanceScopeFor(scope);
279
+ const catalog = await catalogFor(scope);
262
280
  if (runtime) {
263
281
  if (runtime.scopeRuntime !== scope.init.runtime) {
264
282
  throw new Error('thread agent host cannot be shared across DO instances');
265
283
  }
266
284
  return runtime;
267
285
  }
268
- const catalog = await catalogFor(scope);
269
286
  const mastra = new Mastra({
270
287
  storage: options.storage(instanceScopeFor(scope)),
271
288
  // Preserve ordinary key lookup, but remap Object.prototype collisions in
@@ -425,25 +442,34 @@ export function createThreadAgentHost(options) {
425
442
  };
426
443
  const readBinding = () => readAgentThreadBinding(options.stateStorage());
427
444
  const readRun = (runId) => readAgentRunRecord(options.stateStorage(), runId);
428
- const findBlockingRun = async (scopeRuntime) => {
445
+ const findBlockingRun = async (scope) => {
429
446
  const storage = options.stateStorage();
430
447
  const records = await storage.list({
431
448
  prefix: AGENT_RUN_STORAGE_KEY_PREFIX,
432
449
  });
450
+ if (records.size === 0)
451
+ return undefined;
433
452
  for (const key of records.keys()) {
434
453
  const runId = key.slice(AGENT_RUN_STORAGE_KEY_PREFIX.length);
435
- const record = await readRun(runId);
436
- if (!record)
454
+ const runRecord = await readRun(runId);
455
+ if (!runRecord)
437
456
  continue;
438
- const summary = await scopeRuntime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, runId);
439
- if (executions.has(runId) ||
440
- (summary !== null && !isTerminalRunStatus(summary.status))) {
441
- return { runId, principal: record.principal };
442
- }
443
- const recovery = await storage.get(AGENT_OWNER_RECOVERY_PREFIX + runId);
444
- if (recovery)
445
- return { runId, principal: record.principal };
446
- await deleteAgentRunRecord(storage, runId);
457
+ if (executions.has(runId))
458
+ return { runId, principal: runRecord.principal };
459
+ const state = await selectedAgentState(scope, {
460
+ agentId: runRecord.agentId,
461
+ resourceId: resourceIdFromKey(scope.threadId),
462
+ runId,
463
+ }, { includeLegacy: true });
464
+ if (!state ||
465
+ state.kind === 'initial' ||
466
+ !isTerminalRunStatus(state.summary.status) ||
467
+ (state.kind === 'legacy' && !isTerminalRunStatus(state.snapshot.status)))
468
+ return { runId, principal: runRecord.principal };
469
+ const recovery = await storage.get(ownerRecoveryKey(runId));
470
+ if (recovery !== undefined)
471
+ return { runId, principal: runRecord.principal };
472
+ await withRecoveryLock(() => finalizeTerminalRecord(scope, runId, runRecord, state));
447
473
  }
448
474
  return undefined;
449
475
  };
@@ -483,14 +509,14 @@ export function createThreadAgentHost(options) {
483
509
  }
484
510
  if (!threaded)
485
511
  throw new AgentHostRequestError(404, 'run not found');
486
- const [threadOwner, resourceOwner] = await Promise.all([
512
+ const [threadOwner, resolvedResourceOwner] = await Promise.all([
487
513
  ownership.owner('thread', ref.threadId),
488
514
  ownership.owner('resource', ref.resourceId),
489
515
  ]);
490
516
  if (!threadOwner ||
491
- !resourceOwner ||
492
- threadOwner.kind !== resourceOwner.kind ||
493
- threadOwner.id !== resourceOwner.id) {
517
+ !resolvedResourceOwner ||
518
+ threadOwner.kind !== resolvedResourceOwner.kind ||
519
+ threadOwner.id !== resolvedResourceOwner.id) {
494
520
  throw new AgentHostRequestError(404, 'run not found');
495
521
  }
496
522
  return { owner: threadOwner };
@@ -512,8 +538,10 @@ export function createThreadAgentHost(options) {
512
538
  const storage = options.stateStorage();
513
539
  const key = ownerRecoveryKey(recovery.runId);
514
540
  const current = await storage.get(key);
515
- if (current?.token === recovery.token)
516
- await storage.delete(key);
541
+ if (current === undefined ||
542
+ !sameOwnerRecovery(validateOwnerRecovery(recovery.threadId, key, current), recovery))
543
+ throw new Error('agent owner recovery changed');
544
+ await storage.delete(key);
517
545
  });
518
546
  const releaseEphemeralOwnerClaims = async (recovery) => {
519
547
  const ownership = options.resourceAccess();
@@ -529,58 +557,340 @@ export function createThreadAgentHost(options) {
529
557
  release('thread', recovery.threadId),
530
558
  ]);
531
559
  };
532
- const finalizeOwnerRecovery = (recovery, summary) => withRecoveryLock(async () => {
533
- const storage = options.stateStorage();
534
- await options.resourceAccess().settleReservation(recovery.token, []);
535
- if (!recovery.threaded && !isTerminalRunStatus(summary.status)) {
536
- await ensureOwnerRecoveryAlarm(storage);
537
- return;
538
- }
539
- if (!recovery.threaded) {
540
- await releaseEphemeralOwnerClaims(recovery);
541
- }
542
- const key = ownerRecoveryKey(recovery.runId);
543
- const current = await storage.get(key);
544
- if (current?.token === recovery.token)
545
- await storage.delete(key);
546
- });
547
- const finalizeOwnerRecoveryBestEffort = async (recovery, summary) => {
560
+ const validateOwnerRecovery = (threadId, key, value) => {
548
561
  try {
549
- await finalizeOwnerRecovery(recovery, summary);
562
+ const stored = persistedStartRecord(value);
563
+ if (stored.version !== 2 ||
564
+ stored.threadId !== threadId ||
565
+ !isPathSafeId(stored.agentId) ||
566
+ !isPathSafeId(stored.threadId) ||
567
+ !isPathSafeId(stored.resourceId) ||
568
+ stored.resourceId !== resourceIdFromKey(threadId) ||
569
+ !isPathSafeId(stored.runId) ||
570
+ !isPathSafeId(stored.token) ||
571
+ ownerRecoveryKey(stored.runId) !== key ||
572
+ typeof stored.threaded !== 'boolean' ||
573
+ typeof stored.bindingPreexisting !== 'boolean')
574
+ throw new Error('invalid journal');
575
+ const owner = resourceOwner(persistedStartRecord(stored.owner));
576
+ const rawRecord = persistedStartRecord(stored.runRecord);
577
+ if (rawRecord.version !== 2 || rawRecord.agentId !== stored.agentId)
578
+ throw new Error('invalid run record');
579
+ const runRecord = {
580
+ version: 2,
581
+ agentId: stored.agentId,
582
+ principal: assertExecutionPrincipal(persistedStartRecord(rawRecord.principal), 'stored agent run'),
583
+ originEntryPath: entryPath(rawRecord.originEntryPath),
584
+ };
585
+ const rawClaim = stored.startReservation === undefined
586
+ ? undefined
587
+ : persistedStartRecord(stored.startReservation);
588
+ const claim = rawClaim === undefined
589
+ ? undefined
590
+ : captureReservation({
591
+ ...rawClaim,
592
+ owner: persistedStartRecord(rawClaim.owner),
593
+ binding: persistedStartRecord(rawClaim.binding),
594
+ }, 'started');
595
+ if (claim &&
596
+ (claim.targetKind !== 'agent' ||
597
+ claim.targetId !== stored.agentId ||
598
+ claim.threadId !== threadId ||
599
+ claim.runId !== stored.runId ||
600
+ claim.owner.kind !== runRecord.principal.kind ||
601
+ claim.owner.id !== runRecord.principal.id))
602
+ throw new Error('invalid start claim');
603
+ const base = {
604
+ version: 2,
605
+ agentId: stored.agentId,
606
+ threadId,
607
+ resourceId: stored.resourceId,
608
+ runId: stored.runId,
609
+ token: stored.token,
610
+ owner,
611
+ threaded: stored.threaded,
612
+ bindingPreexisting: stored.bindingPreexisting,
613
+ runRecord,
614
+ ...(claim ? { startReservation: claim } : {}),
615
+ };
616
+ if (stored.phase === 'preparing' && !Object.hasOwn(stored, 'execution'))
617
+ return { ...base, phase: 'preparing' };
618
+ if (stored.phase !== 'prepared' && stored.phase !== 'prepared-unfenced')
619
+ throw new Error('invalid phase');
620
+ const raw = persistedStartRecord(stored.execution);
621
+ const execution = normalizeRunExecutionIdentity(raw);
622
+ if (execution.tablePrefix !== raw.tablePrefix ||
623
+ execution.runId !== stored.runId)
624
+ throw new Error('invalid execution');
625
+ return stored.phase === 'prepared'
626
+ ? {
627
+ ...base,
628
+ phase: 'prepared',
629
+ execution: normalizeD1RunExecutionIdentity(execution),
630
+ }
631
+ : { ...base, phase: 'prepared-unfenced', execution };
550
632
  }
551
- catch (error) {
552
- console.error('agent owner recovery cleanup failed', error);
633
+ catch {
634
+ throw new Error('stored agent owner recovery is malformed');
635
+ }
636
+ };
637
+ const prepareOwnerRecovery = async (scope, recovery, supplied) => {
638
+ const identity = normalizeRunExecutionIdentity(supplied);
639
+ const currentRuntime = await runtimeFor(scope);
640
+ const durable = currentRuntime.agents.get(recovery.agentId);
641
+ if (!durable ||
642
+ identity.workflowId !== durable.getWorkflow().id ||
643
+ identity.runId !== recovery.runId)
644
+ throw new Error('prepared agent identity mismatch');
645
+ const prepared = scope.init.runtime.executionFence
646
+ ? {
647
+ ...recovery,
648
+ phase: 'prepared',
649
+ execution: normalizeD1RunExecutionIdentity(identity),
650
+ }
651
+ : { ...recovery, phase: 'prepared-unfenced', execution: identity };
652
+ return withRecoveryLock(async () => {
653
+ const storage = options.stateStorage(), key = ownerRecoveryKey(recovery.runId);
654
+ const current = validateOwnerRecovery(scope.threadId, key, await storage.get(key));
655
+ if (sameOwnerRecovery(current, prepared))
656
+ return prepared;
657
+ if (current.phase !== 'preparing' ||
658
+ !sameOwnerRecovery(current, recovery))
659
+ throw new Error('agent owner recovery changed');
553
660
  try {
554
- await withRecoveryLock(() => ensureOwnerRecoveryAlarm(options.stateStorage()));
661
+ await storage.put(key, prepared);
555
662
  }
556
- catch (alarmError) {
557
- console.error('agent owner recovery rearm failed', alarmError);
663
+ catch (error) {
664
+ const reread = await storage.get(key);
665
+ if (reread === undefined ||
666
+ !sameOwnerRecovery(validateOwnerRecovery(scope.threadId, key, reread), prepared))
667
+ throw error;
558
668
  }
669
+ return prepared;
670
+ });
671
+ };
672
+ const workflowIdFor = async (scope, agentId) => {
673
+ const current = await runtimeFor(scope);
674
+ const durable = current.agents.get(agentId);
675
+ if (!durable)
676
+ throw new AgentHostRequestError(404, 'agent not found');
677
+ return durable.getWorkflow().id;
678
+ };
679
+ async function selectedAgentState(scope, ref, readOptions) {
680
+ const includeLegacy = readOptions?.includeLegacy === true;
681
+ if (ref.resourceId !== resourceIdFromKey(scope.threadId))
682
+ throw new AgentHostRequestError(404, 'run not found');
683
+ const current = await runtimeFor(scope);
684
+ const durable = current.agents.get(ref.agentId);
685
+ if (!current.catalog.get(ref.agentId) || !durable)
686
+ throw new AgentHostRequestError(404, 'agent not found');
687
+ if (includeLegacy)
688
+ return durable.authoritativeAgentStartState(scope.init.runtime, scope.threadId, ref.runId, { includeLegacy: true });
689
+ return durable.authoritativeAgentStartState(scope.init.runtime, scope.threadId, ref.runId);
690
+ }
691
+ const publicAgentState = async (scope, ref) => {
692
+ try {
693
+ return await selectedAgentState(scope, ref, { includeLegacy: true });
694
+ }
695
+ catch (error) {
696
+ if (error instanceof AgentRunSelectorMismatchError)
697
+ throw new AgentHostRequestError(404, 'run not found');
698
+ throw error;
559
699
  }
560
700
  };
561
- const validateOwnerRecovery = (threadId, key, stored) => {
562
- if (stored?.version !== 1 ||
563
- stored.threadId !== threadId ||
564
- !isPathSafeId(stored.agentId) ||
565
- !isPathSafeId(stored.resourceId) ||
566
- !isPathSafeId(stored.runId) ||
567
- !isPathSafeId(stored.token) ||
568
- ownerRecoveryKey(stored.runId) !== key ||
569
- typeof stored.threaded !== 'boolean' ||
570
- typeof stored.bindingPreexisting !== 'boolean') {
571
- throw new Error('stored agent owner recovery is malformed');
701
+ const matchRecoveryState = (recovery, state) => {
702
+ const expected = recovery.execution;
703
+ if (!state ||
704
+ !expected ||
705
+ state.execution.tablePrefix !== expected.tablePrefix ||
706
+ state.execution.workflowId !== expected.workflowId ||
707
+ state.execution.runId !== expected.runId ||
708
+ state.execution.startToken !== expected.startToken ||
709
+ state.threaded !== recovery.threaded ||
710
+ state.execution.target.kind !== 'agent' ||
711
+ state.execution.target.id !== recovery.agentId ||
712
+ state.execution.target.threadId !== recovery.threadId ||
713
+ state.execution.owner.kind !== recovery.runRecord.principal.kind ||
714
+ state.execution.owner.id !== recovery.runRecord.principal.id)
715
+ throw new Error('agent owner recovery does not match the execution');
716
+ return state;
717
+ };
718
+ const assertRecoveryCurrent = async (recovery) => {
719
+ const key = ownerRecoveryKey(recovery.runId), current = await options.stateStorage().get(key);
720
+ if (current === undefined ||
721
+ !sameOwnerRecovery(validateOwnerRecovery(recovery.threadId, key, current), recovery))
722
+ throw new Error('agent owner recovery changed');
723
+ };
724
+ const assertLegacyTerminalCurrent = async (scope, ref, state, expectedRecord) => {
725
+ if (!isTerminalRunStatus(state.snapshot.status) ||
726
+ !isTerminalRunStatus(state.summary.status) ||
727
+ state.address.runId !== ref.runId ||
728
+ record(state.snapshot.context?.input)?.agentId !== ref.agentId)
729
+ throw new ExecutionFenceUnreadableError('legacy run cleanup is unresolved');
730
+ const quiescent = () => !executions.has(ref.runId) &&
731
+ !scope.init.runtime.isRunActive(state.address.workflowId, ref.runId);
732
+ if (!quiescent())
733
+ throw new RunStartPendingError();
734
+ const [binding, current, journal] = await Promise.all([
735
+ readBinding(),
736
+ readRun(ref.runId),
737
+ options.stateStorage().get(ownerRecoveryKey(ref.runId)),
738
+ ]);
739
+ if (journal !== undefined)
740
+ throw new ExecutionFenceUnreadableError('legacy run cleanup is unresolved');
741
+ const bindingMatches = binding?.agentId === ref.agentId && binding.resourceId === ref.resourceId;
742
+ if ((state.threaded && !bindingMatches) || (!state.threaded && binding))
743
+ throw new AgentHostRequestError(404, 'run not found');
744
+ if (current !== undefined &&
745
+ (expectedRecord === undefined || !sameRunRecord(current, expectedRecord)))
746
+ throw new Error('agent run record changed');
747
+ if (!quiescent())
748
+ throw new RunStartPendingError();
749
+ };
750
+ const finalizeTerminalRecord = async (scope, runId, expected, state, ownFrame) => {
751
+ if (state.kind === 'initial' || !isTerminalRunStatus(state.summary.status))
752
+ throw new RunStartPendingError();
753
+ if (state.kind === 'legacy') {
754
+ const ref = {
755
+ agentId: expected.agentId,
756
+ resourceId: resourceIdFromKey(scope.threadId),
757
+ runId,
758
+ };
759
+ await assertLegacyTerminalCurrent(scope, ref, state, expected);
760
+ const current = await readRun(runId);
761
+ if (current !== undefined && !sameRunRecord(current, expected))
762
+ throw new Error('agent run record changed');
763
+ await assertLegacyTerminalCurrent(scope, ref, state, expected);
764
+ if (current)
765
+ await deleteAgentRunRecord(options.stateStorage(), runId);
766
+ return;
572
767
  }
573
- resourceOwner(stored.owner);
768
+ if (state.execution.target.kind !== 'agent' ||
769
+ state.execution.target.id !== expected.agentId ||
770
+ state.execution.target.threadId !== scope.threadId ||
771
+ state.execution.owner.kind !== expected.principal.kind ||
772
+ state.execution.owner.id !== expected.principal.id)
773
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
774
+ const quiescent = () => {
775
+ const active = executions.get(runId);
776
+ return ((active === undefined ||
777
+ (active === ownFrame && unwoundExecutions.has(active))) &&
778
+ !scope.init.runtime.isRunActive(state.execution.workflowId, runId));
779
+ };
780
+ if (!quiescent())
781
+ throw new RunStartPendingError();
782
+ await scope.init.runtime.settleStartExecution(state);
783
+ const current = await readRun(runId);
784
+ if (current !== undefined && !sameRunRecord(current, expected))
785
+ throw new Error('agent run record changed');
786
+ if (!quiescent())
787
+ throw new RunStartPendingError();
788
+ if (current)
789
+ await deleteAgentRunRecord(options.stateStorage(), runId);
574
790
  };
575
- const finalizeTerminalAgentState = async (threadId, runId, summary) => {
576
- const storage = options.stateStorage();
577
- const key = ownerRecoveryKey(runId);
578
- const recovery = await storage.get(key);
579
- if (recovery) {
580
- validateOwnerRecovery(threadId, key, recovery);
581
- await finalizeOwnerRecovery(recovery, summary);
791
+ const finalizeJournalBookkeeping = async (recovery, summary) => {
792
+ await assertRecoveryCurrent(recovery);
793
+ if (!recovery.threaded && !isTerminalRunStatus(summary.status)) {
794
+ await ensureOwnerRecoveryAlarm(options.stateStorage());
795
+ return false;
582
796
  }
583
- await deleteAgentRunRecord(storage, runId);
797
+ if (!recovery.threaded)
798
+ await releaseEphemeralOwnerClaims(recovery);
799
+ if (isTerminalRunStatus(summary.status)) {
800
+ const current = await readRun(recovery.runId);
801
+ if (current !== undefined && !sameRunRecord(current, recovery.runRecord))
802
+ throw new Error('agent run record changed');
803
+ if (current)
804
+ await deleteAgentRunRecord(options.stateStorage(), recovery.runId);
805
+ }
806
+ return true;
807
+ };
808
+ const finishLifecycle = async (scope, recovery, transition) => {
809
+ await assertRecoveryCurrent(recovery);
810
+ const workflowId = recovery.execution?.workflowId;
811
+ if (!workflowId)
812
+ throw new Error('agent recovery has no execution');
813
+ await options.resourceAccess().settleReservation(recovery.token, []);
814
+ await assertRecoveryCurrent(recovery);
815
+ if (!transition.cleanup.cleanupCompleted) {
816
+ await abandonApprovalsForRun(options.approvalService(scope), workflowId, recovery.runId, transition.cleanup.status, systemPrincipalId);
817
+ const dispatch = transition.cleanup.scheduleDispatch;
818
+ if (dispatch) {
819
+ if (!options.discardScheduleDispatch)
820
+ throw new Error('scheduled agent termination requires a dispatch-discard hook');
821
+ await options.discardScheduleDispatch(dispatch.scheduleId, dispatch.dispatchId, recovery.runId);
822
+ }
823
+ const ownership = options.resourceAccess();
824
+ if (!(await ownership.release('run', recovery.runId, recovery.owner)) &&
825
+ (await ownership.owner('run', recovery.runId)))
826
+ throw new Error('run ownership could not be released');
827
+ }
828
+ await finalizeJournalBookkeeping(recovery, transition.summary);
829
+ return transition.cleanup.cleanupCompleted
830
+ ? transition.summary
831
+ : scope.init.runtime.completeTerminalCleanup(workflowId, recovery.runId, transition.cleanup.revision);
832
+ };
833
+ const finalizeOwnerRecovery = async (scope, recovery, state, ownFrame) => withBindingLock(async () => {
834
+ if (recovery.startReservation && !scope.init.runtime.startIdempotency)
835
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
836
+ const active = executions.get(recovery.runId);
837
+ if ((active !== undefined &&
838
+ (active !== ownFrame || !unwoundExecutions.has(active))) ||
839
+ scope.init.runtime.isRunActive(state.execution.workflowId, recovery.runId))
840
+ throw new RunStartPendingError();
841
+ await assertRecoveryCurrent(recovery);
842
+ const selected = matchRecoveryState(recovery, state);
843
+ if (selected.kind === 'initial')
844
+ throw new RunStartPendingError();
845
+ if (isTerminalRunStatus(selected.summary.status))
846
+ await scope.init.runtime.settleStartExecution(selected, recovery.startReservation);
847
+ const cleanup = terminalCleanupFor(lifecycleFromRequestContext(selected.snapshot.requestContext));
848
+ let summary = selected.summary;
849
+ const clear = await withRecoveryLock(async () => {
850
+ await assertRecoveryCurrent(recovery);
851
+ if (cleanup) {
852
+ summary = await finishLifecycle(scope, recovery, {
853
+ summary,
854
+ transitioned: false,
855
+ casMatched: true,
856
+ cleanup,
857
+ });
858
+ return true;
859
+ }
860
+ await options.resourceAccess().settleReservation(recovery.token, []);
861
+ return finalizeJournalBookkeeping(recovery, summary);
862
+ });
863
+ if (clear)
864
+ await clearOwnerRecovery(recovery);
865
+ return summary;
866
+ });
867
+ const finalizeTerminalAgentState = async (scope, ref, state, expectedRecord) => {
868
+ const selected = state ?? (await selectedAgentState(scope, ref, { includeLegacy: true }));
869
+ if (!selected ||
870
+ selected.kind === 'initial' ||
871
+ !isTerminalRunStatus(selected.summary.status))
872
+ throw new RunStartPendingError();
873
+ const stored = await options
874
+ .stateStorage()
875
+ .get(ownerRecoveryKey(ref.runId));
876
+ if (stored !== undefined) {
877
+ if (selected.kind === 'legacy')
878
+ throw new ExecutionFenceUnreadableError('legacy run cleanup is unresolved');
879
+ const recovery = validateOwnerRecovery(scope.threadId, ownerRecoveryKey(ref.runId), stored);
880
+ await finalizeOwnerRecovery(scope, recovery, selected);
881
+ return;
882
+ }
883
+ await withBindingLock(() => withRecoveryLock(async () => {
884
+ if (expectedRecord)
885
+ await finalizeTerminalRecord(scope, ref.runId, expectedRecord, selected);
886
+ else if (selected.kind === 'legacy')
887
+ await assertLegacyTerminalCurrent(scope, ref, selected, undefined);
888
+ else {
889
+ if ((await readRun(ref.runId)) !== undefined)
890
+ throw new Error('agent run record changed');
891
+ await scope.init.runtime.settleStartExecution(selected);
892
+ }
893
+ }));
584
894
  };
585
895
  const withExecution = async (execution, operation) => {
586
896
  if (executions.has(execution.runId)) {
@@ -591,13 +901,13 @@ export function createThreadAgentHost(options) {
591
901
  return await operation();
592
902
  }
593
903
  finally {
594
- executions.delete(execution.runId);
904
+ if (executions.get(execution.runId) === execution)
905
+ executions.delete(execution.runId);
595
906
  }
596
907
  };
597
908
  // Reconciling approvals is trusted platform work with no person behind it.
598
- // It used to mint role:'operator', which is why an approval bridge looked
599
- // indistinguishable from a human operator in the audit trail. The bridge
600
- // mints its own principal from this id.
909
+ // The bridge mints its own principal from this id, so the audit trail shows
910
+ // an automated principal rather than a human operator.
601
911
  const systemPrincipalId = options.systemPrincipalId ?? 'flowsafe-system';
602
912
  // Deliberately NOT vouched. Its only consumer projects it to an ApprovalActor
603
913
  // for a role-gated READ, which grants nothing an automated principal does not
@@ -621,7 +931,7 @@ export function createThreadAgentHost(options) {
621
931
  throw new Error('suspended agent run has no durable requester provenance');
622
932
  }
623
933
  const service = options.approvalService(instanceScopeFor(scope));
624
- await reconcileApprovalsForSummary(service, DURABLE_AGENTIC_LOOP_WORKFLOW_ID, summary, systemPrincipalId, {
934
+ await reconcileApprovalsForSummary(service, await workflowIdFor(scope, agentId), summary, systemPrincipalId, {
625
935
  kind: 'agent-thread',
626
936
  agentId,
627
937
  threadId: scope.threadId,
@@ -629,16 +939,16 @@ export function createThreadAgentHost(options) {
629
939
  principal,
630
940
  }, summary.requestedBy);
631
941
  const records = await service.list({
632
- workflowId: DURABLE_AGENTIC_LOOP_WORKFLOW_ID,
942
+ workflowId: await workflowIdFor(scope, agentId),
633
943
  runId: summary.runId,
634
944
  }, principalActor(systemPrincipal()));
635
945
  const keys = new Set((summary.suspended ?? []).map((path) => path.join('.')));
636
- return records.filter((record) => {
637
- const key = record.stepPath?.join('.');
946
+ return records.filter((runRecord) => {
947
+ const key = runRecord.stepPath?.join('.');
638
948
  return (key !== undefined &&
639
949
  keys.has(key) &&
640
- record.suspendedAt === summary.suspendedAt?.[key] &&
641
- record.resumeCount === summary.resumeCount?.[key]);
950
+ runRecord.suspendedAt === summary.suspendedAt?.[key] &&
951
+ runRecord.resumeCount === summary.resumeCount?.[key]);
642
952
  });
643
953
  };
644
954
  const envelopeFor = async (scope, ref, principal, summary) => {
@@ -669,127 +979,166 @@ export function createThreadAgentHost(options) {
669
979
  approvals,
670
980
  };
671
981
  };
672
- const snapshotExecutionFor = async (scope, ref) => {
673
- const workflows = await options
674
- .storage(instanceScopeFor(scope))
675
- .getStore('workflows');
676
- const snapshot = await workflows?.loadWorkflowSnapshot({
677
- workflowName: DURABLE_AGENTIC_LOOP_WORKFLOW_ID,
678
- runId: ref.runId,
679
- });
680
- const input = snapshot?.context.input;
681
- const requestContext = snapshot?.requestContext;
682
- const correlation = requestContext?.['breakwater.auditContext'];
683
- const memory = input?.messageListState?.memoryInfo;
684
- const memoryMatches = memory === null ||
685
- (memory?.threadId === scope.threadId &&
686
- memory.resourceId === ref.resourceId);
687
- if (input?.agentId !== ref.agentId ||
688
- requestContext?.runId !== ref.runId ||
689
- requestContext.threadId !== scope.threadId ||
690
- requestContext.resourceId !== ref.resourceId ||
691
- correlation?.agentId !== ref.agentId ||
692
- correlation.threadId !== scope.threadId ||
693
- correlation.resourceId !== ref.resourceId ||
694
- !memoryMatches) {
982
+ const snapshotExecutionFor = async (scope, ref, knownState) => {
983
+ const state = knownState === undefined
984
+ ? await selectedAgentState(scope, ref, { includeLegacy: true })
985
+ : knownState;
986
+ if (!state)
695
987
  throw new AgentHostRequestError(404, 'run not found');
696
- }
988
+ if (state.kind === 'initial')
989
+ throw new RunStartPendingError();
697
990
  return {
698
- threaded: memory !== null,
699
- safeContext: sanitizeStoredAgentContext(requestContext),
991
+ state,
992
+ threaded: state.threaded,
993
+ safeContext: sanitizeStoredAgentContext(state.snapshot.requestContext),
700
994
  };
701
995
  };
702
- let recoverOwner;
703
- const statusFor = async (scope, ref, knownThreaded) => {
704
- const binding = await readBinding();
705
- const current = await runtimeFor(scope);
706
- if (!current.catalog.get(ref.agentId)) {
707
- throw new AgentHostRequestError(404, 'agent not found');
708
- }
709
- const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
710
- if (!summary)
996
+ const statusFor = async (scope, ref, knownState) => {
997
+ const stored = await readRun(ref.runId);
998
+ const selected = knownState === undefined
999
+ ? await selectedAgentState(scope, ref, { includeLegacy: true })
1000
+ : knownState;
1001
+ if (!selected)
711
1002
  throw new AgentHostRequestError(404, 'run not found');
712
- const threaded = knownThreaded ?? (await snapshotExecutionFor(scope, ref)).threaded;
1003
+ if (selected.kind === 'initial')
1004
+ throw new RunStartPendingError();
1005
+ const summary = selected.summary;
1006
+ const binding = await readBinding();
713
1007
  const bindingMatches = binding?.agentId === ref.agentId && binding.resourceId === ref.resourceId;
714
- if ((threaded && !bindingMatches) || (!threaded && binding)) {
1008
+ if ((selected.threaded && !bindingMatches) ||
1009
+ (!selected.threaded && binding))
715
1010
  throw new AgentHostRequestError(404, 'run not found');
716
- }
717
- const stored = await readRun(ref.runId);
718
- if (stored && stored.agentId !== ref.agentId) {
1011
+ if (stored && stored.agentId !== ref.agentId)
719
1012
  throw new AgentHostRequestError(404, 'run not found');
720
- }
721
- if (summary.status === 'suspended' && !stored) {
1013
+ if (summary.status === 'suspended' && !stored)
722
1014
  throw new AgentHostRequestError(409, 'suspended agent run has no recoverable execution principal');
1015
+ if (isTerminalRunStatus(summary.status))
1016
+ await finalizeTerminalAgentState(scope, ref, selected, stored);
1017
+ return envelopeFor(scope, ref, stored?.principal ?? scope.principal, summary);
1018
+ };
1019
+ const recoverOwner = async (scope, key, value, ownFrame, ownFailure) => withBindingLock(() => withRecoveryLock(async () => {
1020
+ const stored = validateOwnerRecovery(scope.threadId, key, value);
1021
+ if (stored.startReservation && !scope.init.runtime.startIdempotency)
1022
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
1023
+ await assertRecoveryCurrent(stored);
1024
+ const quiescent = () => {
1025
+ const active = executions.get(stored.runId);
1026
+ return (active === undefined ||
1027
+ (active === ownFrame && unwoundExecutions.has(active)));
1028
+ };
1029
+ if (!quiescent() ||
1030
+ scope.init.runtime
1031
+ .workflowIds()
1032
+ .some((workflowId) => scope.init.runtime.isRunActive(workflowId, stored.runId)))
1033
+ throw new RunStartPendingError();
1034
+ let recovered = null;
1035
+ if (stored.phase !== 'preparing') {
1036
+ const current = await runtimeFor(scope);
1037
+ const durable = current.agents.get(stored.agentId);
1038
+ if (!durable ||
1039
+ stored.execution.workflowId !== durable.getWorkflow().id)
1040
+ throw new Error('stored agent owner recovery does not match the wrapper');
1041
+ if (scope.init.runtime.isRunActive(stored.execution.workflowId, stored.runId))
1042
+ throw new RunStartPendingError();
1043
+ if (stored.phase === 'prepared') {
1044
+ recovered = await scope.init.runtime.recoverStartAttempt(stored.execution, {
1045
+ attemptToken: stored.token,
1046
+ isOwnerQuiescent: quiescent,
1047
+ startReservation: stored.startReservation,
1048
+ expectedTarget: {
1049
+ kind: 'agent',
1050
+ id: stored.agentId,
1051
+ threadId: stored.threadId,
1052
+ owner: principalOwner(stored.runRecord.principal),
1053
+ threaded: stored.threaded,
1054
+ },
1055
+ });
1056
+ }
1057
+ else {
1058
+ const selected = matchRecoveryState(stored, await selectedAgentState(scope, stored));
1059
+ if (selected.kind === 'initial')
1060
+ throw new RunStartPendingError();
1061
+ if (isTerminalRunStatus(selected.summary.status))
1062
+ await scope.init.runtime.settleStartExecution(selected, stored.startReservation);
1063
+ const cleanup = terminalCleanupFor(lifecycleFromRequestContext(selected.snapshot.requestContext));
1064
+ recovered = cleanup
1065
+ ? {
1066
+ kind: 'lifecycle',
1067
+ transition: {
1068
+ summary: selected.summary,
1069
+ transitioned: false,
1070
+ casMatched: true,
1071
+ cleanup,
1072
+ },
1073
+ }
1074
+ : { kind: 'ordinary', summary: selected.summary };
1075
+ }
723
1076
  }
724
- const principal = stored?.principal ?? scope.principal;
725
- const result = await envelopeFor(scope, ref, principal, summary);
726
- if (isTerminalRunStatus(summary.status) && stored) {
727
- await deleteAgentRunRecord(options.stateStorage(), ref.runId);
728
- }
729
- if (isTerminalRunStatus(summary.status)) {
730
- const key = ownerRecoveryKey(ref.runId);
731
- const recovery = await options
732
- .stateStorage()
733
- .get(key);
734
- if (recovery) {
735
- await recoverOwner(scope.init.runtime, scope.threadId, key, recovery, true);
1077
+ if (recovered) {
1078
+ let summary = recovered.kind === 'ordinary'
1079
+ ? recovered.summary
1080
+ : recovered.transition.summary;
1081
+ let clear;
1082
+ if (recovered.kind === 'lifecycle') {
1083
+ summary = await finishLifecycle(scope, stored, recovered.transition);
1084
+ clear = true;
1085
+ }
1086
+ else {
1087
+ await assertRecoveryCurrent(stored);
1088
+ await options.resourceAccess().settleReservation(stored.token, []);
1089
+ clear = await finalizeJournalBookkeeping(stored, summary);
736
1090
  }
1091
+ if (clear) {
1092
+ await assertRecoveryCurrent(stored);
1093
+ await options.stateStorage().delete(key);
1094
+ }
1095
+ return summary;
1096
+ }
1097
+ await assertRecoveryCurrent(stored);
1098
+ const localZero = () => stored.phase === 'prepared' &&
1099
+ ownFrame !== undefined &&
1100
+ executions.get(stored.runId) === ownFrame &&
1101
+ unwoundExecutions.has(ownFrame) &&
1102
+ isDefinitiveInitialAdmissionRefusal(ownFailure, stored.execution);
1103
+ if (stored.phase === 'prepared' && !localZero()) {
1104
+ await options.resourceAccess().settleReservation(stored.token, [
1105
+ { kind: 'run', resourceId: stored.runId },
1106
+ { kind: 'thread', resourceId: stored.threadId },
1107
+ { kind: 'resource', resourceId: stored.resourceId },
1108
+ ]);
1109
+ await ensureOwnerRecoveryAlarm(options.stateStorage());
1110
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
737
1111
  }
738
- return result;
739
- };
740
- recoverOwner = async (scopeRuntime, threadId, key, stored, ignoreActive = false) => withBindingLock(() => withRecoveryLock(async () => {
741
- validateOwnerRecovery(threadId, key, stored);
742
1112
  const storage = options.stateStorage();
743
- const currentRecovery = await storage.get(key);
744
- if (currentRecovery?.token !== stored.token)
745
- return 'pending';
746
- if (!ignoreActive && executions.has(stored.runId))
747
- return 'pending';
748
- const summary = await scopeRuntime.recoverStartAttempt(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, stored.runId, stored.token);
749
- const [binding, record] = await Promise.all([
750
- readBinding(),
751
- readRun(stored.runId),
752
- ]);
753
- const bindingMatches = binding?.agentId === stored.agentId &&
1113
+ const binding = await readBinding(), runRecord = await readRun(stored.runId);
1114
+ await assertRecoveryCurrent(stored);
1115
+ const matches = binding?.agentId === stored.agentId &&
754
1116
  binding.resourceId === stored.resourceId;
755
- if (record && (!summary || isTerminalRunStatus(summary.status))) {
1117
+ if (runRecord && !sameRunRecord(runRecord, stored.runRecord))
1118
+ throw new Error('agent run record changed');
1119
+ if (runRecord)
756
1120
  await deleteAgentRunRecord(storage, stored.runId);
757
- }
758
- if (!summary && !stored.bindingPreexisting && bindingMatches) {
1121
+ if (!stored.bindingPreexisting && matches)
759
1122
  await deleteAgentThreadBinding(storage, {
760
1123
  agentId: stored.agentId,
761
1124
  resourceId: stored.resourceId,
762
1125
  });
763
- }
764
- if (summary) {
765
- await options.resourceAccess().settleReservation(stored.token, []);
766
- if (!stored.threaded && !isTerminalRunStatus(summary.status)) {
767
- await ensureOwnerRecoveryAlarm(storage);
768
- return 'pending';
769
- }
770
- if (!stored.threaded)
771
- await releaseEphemeralOwnerClaims(stored);
772
- const current = await storage.get(key);
773
- if (current?.token === stored.token)
774
- await storage.delete(key);
775
- return 'cleared';
776
- }
777
1126
  const release = [{ kind: 'run', resourceId: stored.runId }];
778
- const retainThread = stored.threaded && stored.bindingPreexisting && bindingMatches;
779
- if (!retainThread) {
1127
+ if (!(stored.threaded && stored.bindingPreexisting && matches))
780
1128
  release.push({ kind: 'resource', resourceId: stored.resourceId }, { kind: 'thread', resourceId: stored.threadId });
781
- }
782
1129
  await options.resourceAccess().settleReservation(stored.token, release);
783
- const current = await storage.get(key);
784
- if (current?.token === stored.token)
785
- await storage.delete(key);
786
- return 'cleared';
1130
+ await assertRecoveryCurrent(stored);
1131
+ if (stored.phase === 'prepared' && !localZero())
1132
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
1133
+ await storage.delete(key);
1134
+ return null;
787
1135
  }));
788
1136
  const host = {
789
1137
  requestContextForRun: (base) => async (workflowId, runId, leg) => {
790
1138
  const values = base ? await base(workflowId, runId, leg) : undefined;
791
1139
  const execution = executions.get(runId);
792
- return execution && workflowId === DURABLE_AGENTIC_LOOP_WORKFLOW_ID
1140
+ return execution &&
1141
+ workflowId === runtime?.agents.get(execution.agentId)?.getWorkflow().id
793
1142
  ? {
794
1143
  ...execution.safeContext,
795
1144
  ...values,
@@ -798,55 +1147,113 @@ export function createThreadAgentHost(options) {
798
1147
  : values;
799
1148
  },
800
1149
  serializeDispatch: withDispatchLock,
801
- blockingRun: (scope) => findBlockingRun(scope.init.runtime),
1150
+ blockingRun: (scope) => withBindingLock(() => findBlockingRun(instanceScopeFor(scope))),
802
1151
  scheduleDispatchStatus: async (scope, input) => {
803
1152
  const ref = runRef(scope, {
804
1153
  ...input,
805
1154
  threadId: scope.threadId,
806
1155
  });
807
1156
  const key = ownerRecoveryKey(ref.runId);
808
- const recovery = await options
809
- .stateStorage()
810
- .get(key);
811
- if (recovery) {
812
- await recoverOwner(scope.init.runtime, scope.threadId, key, recovery, true);
1157
+ const recovery = await options.stateStorage().get(key);
1158
+ if (recovery !== undefined) {
1159
+ await recoverOwner(scope, key, recovery);
813
1160
  }
814
- const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
815
- if (!summary)
1161
+ const selected = await selectedAgentState(scope, ref, {
1162
+ includeLegacy: true,
1163
+ });
1164
+ if (!selected)
816
1165
  return undefined;
817
- return (await statusFor(scope, ref)).summary;
1166
+ if (selected.kind === 'initial')
1167
+ throw new RunStartPendingError();
1168
+ return (await statusFor(scope, ref, selected)).summary;
818
1169
  },
819
- recoverOwnership: (scopeRuntime, threadId) => withDispatchLock(async () => {
820
- const storage = options.stateStorage();
821
- try {
822
- const pending = await storage.list({
823
- prefix: AGENT_OWNER_RECOVERY_PREFIX,
824
- });
825
- for (const [key, stored] of pending) {
826
- await recoverOwner(scopeRuntime, threadId, key, stored);
827
- }
828
- await withRecoveryLock(async () => {
829
- const remaining = await storage.list({
1170
+ recoverOwnership: (inputScope) => {
1171
+ const scope = instanceScopeFor(inputScope);
1172
+ return withDispatchLock(async () => {
1173
+ const storage = options.stateStorage();
1174
+ try {
1175
+ const pending = await storage.list({
830
1176
  prefix: AGENT_OWNER_RECOVERY_PREFIX,
831
1177
  });
832
- if (remaining.size > 0) {
833
- await ensureOwnerRecoveryAlarm(storage);
1178
+ for (const [key, stored] of pending) {
1179
+ await recoverOwner(scope, key, stored);
834
1180
  }
835
- else {
836
- await storage.deleteAlarm();
837
- }
838
- });
839
- }
840
- catch (error) {
841
- await withRecoveryLock(() => ensureOwnerRecoveryAlarm(storage));
842
- throw error;
843
- }
844
- }),
845
- start: async (scope, input) => {
846
- const ref = runRef(scope, input);
1181
+ await withRecoveryLock(async () => {
1182
+ const remaining = await storage.list({
1183
+ prefix: AGENT_OWNER_RECOVERY_PREFIX,
1184
+ });
1185
+ if (remaining.size > 0) {
1186
+ await ensureOwnerRecoveryAlarm(storage);
1187
+ }
1188
+ else {
1189
+ await storage.deleteAlarm();
1190
+ }
1191
+ });
1192
+ }
1193
+ catch (error) {
1194
+ await withRecoveryLock(() => ensureOwnerRecoveryAlarm(storage));
1195
+ throw error;
1196
+ }
1197
+ });
1198
+ },
1199
+ start: async (sourceScope, sourceInput) => {
1200
+ const principal = assertExecutionPrincipal(sourceScope.principal, 'thread start principal');
1201
+ const mutationEpoch = normalizeMutationEpoch(sourceScope.mutationEpoch);
1202
+ const { threadId, deploymentTag, init } = sourceScope;
1203
+ const scope = Object.freeze({
1204
+ principal,
1205
+ mutationEpoch,
1206
+ threadId,
1207
+ deploymentTag,
1208
+ init,
1209
+ });
1210
+ const { agentId, threadId: inputThreadId, resourceId, runId, prompt, messages: inputMessages, entryPath: inputEntryPath, threaded: inputThreaded, scheduleId, dispatchId, scheduleDispatchLease, safeContext: inputSafeContext, providerOptions: inputProviderOptions, idempotencyKey, startReservation: suppliedReservation, } = sourceInput;
1211
+ const startReservation = suppliedReservation === undefined
1212
+ ? undefined
1213
+ : captureReservation(suppliedReservation, 'started');
1214
+ if (startReservation &&
1215
+ (startReservation.key !== idempotencyKey ||
1216
+ startReservation.runId !== runId ||
1217
+ startReservation.threadId !== threadId ||
1218
+ startReservation.targetKind !== 'agent' ||
1219
+ startReservation.targetId !== agentId ||
1220
+ startReservation.owner.kind !== principal.kind ||
1221
+ startReservation.owner.id !== principal.id ||
1222
+ !init.runtime.startIdempotency))
1223
+ throw new AgentHostRequestError(400, 'start reservation does not match the trusted start');
1224
+ const input = {
1225
+ agentId,
1226
+ threadId: inputThreadId,
1227
+ resourceId,
1228
+ runId,
1229
+ prompt,
1230
+ messages: inputMessages,
1231
+ entryPath: inputEntryPath,
1232
+ threaded: inputThreaded,
1233
+ scheduleId,
1234
+ dispatchId,
1235
+ scheduleDispatchLease,
1236
+ safeContext: inputSafeContext,
1237
+ providerOptions: inputProviderOptions,
1238
+ idempotencyKey,
1239
+ };
1240
+ const ref = Object.freeze(runRef(scope, input));
847
1241
  const entry = entryPath(input.entryPath);
848
1242
  const threaded = input.threaded !== false;
849
1243
  const source = await resolveStartSource(scope, ref, entry, threaded, input.scheduleId, input.dispatchId);
1244
+ const rawOwner = source.owner;
1245
+ const owner = canonicalResourceOwner({
1246
+ kind: rawOwner.kind,
1247
+ id: rawOwner.id,
1248
+ });
1249
+ const startIdentity = Object.freeze({
1250
+ owner: principalOwner(principal),
1251
+ target: Object.freeze({
1252
+ kind: 'agent',
1253
+ id: ref.agentId,
1254
+ threadId: ref.threadId,
1255
+ }),
1256
+ });
850
1257
  const hasPrompt = source.target === undefined && input.prompt !== undefined;
851
1258
  const hasMessages = source.target === undefined && input.messages !== undefined;
852
1259
  if ((source.target === undefined && hasPrompt === hasMessages) ||
@@ -867,7 +1274,6 @@ export function createThreadAgentHost(options) {
867
1274
  const resolvedProviderOptions = source.target
868
1275
  ? source.target.providerOptions
869
1276
  : input.providerOptions;
870
- const owner = source.owner;
871
1277
  const { current, module, principalPermissions } = await authorize(scope, ref.agentId, entry, scope.principal);
872
1278
  if (ref.resourceId !== resourceIdFromKey(scope.threadId)) {
873
1279
  throw new AgentHostRequestError(404, 'run not found');
@@ -888,16 +1294,14 @@ export function createThreadAgentHost(options) {
888
1294
  const durable = current.agents.get(module.meta.id);
889
1295
  if (!durable)
890
1296
  throw new Error('guarded agent was not registered');
1297
+ const recoveryKey = ownerRecoveryKey(ref.runId);
1298
+ const pending = await options.stateStorage().get(recoveryKey);
1299
+ if (pending !== undefined) {
1300
+ await recoverOwner(scope, recoveryKey, pending);
1301
+ }
891
1302
  return withExecution(execution, async () => {
892
- const recoveryKey = ownerRecoveryKey(ref.runId);
893
- const pending = await options
894
- .stateStorage()
895
- .get(recoveryKey);
896
- if (pending) {
897
- await recoverOwner(scope.init.runtime, scope.threadId, recoveryKey, pending, true);
898
- }
899
1303
  const existingRecord = await readRun(ref.runId);
900
- const existingSummary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
1304
+ const existingSummary = await scope.init.runtime.status(await workflowIdFor(scope, ref.agentId), ref.runId);
901
1305
  if (existingRecord || existingSummary) {
902
1306
  throw new AgentHostRequestError(409, `run '${ref.runId}' already exists`);
903
1307
  }
@@ -912,7 +1316,10 @@ export function createThreadAgentHost(options) {
912
1316
  principal: scope.principal,
913
1317
  originEntryPath: entry,
914
1318
  };
915
- const recovery = await withBindingLock(async () => {
1319
+ let recovery = await withBindingLock(async () => {
1320
+ const blocking = await findBlockingRun(scope);
1321
+ if (blocking && blocking.runId !== ref.runId)
1322
+ throw new AgentHostRequestError(409, `thread is blocked by run '${blocking.runId}'`);
916
1323
  const existing = await readBinding();
917
1324
  if (!threaded && existing) {
918
1325
  throw new AgentHostRequestError(409, 'unthreaded starts require an unbound object');
@@ -929,12 +1336,11 @@ export function createThreadAgentHost(options) {
929
1336
  throw new AgentHostRequestError(409, 'thread is bound to another agent');
930
1337
  }
931
1338
  }
932
- const blocking = await findBlockingRun(scope.init.runtime);
933
- if (blocking && blocking.runId !== ref.runId) {
934
- throw new AgentHostRequestError(409, `thread is blocked by run '${blocking.runId}'`);
935
- }
936
- const recovery = {
937
- version: 1,
1339
+ const recoveryState = {
1340
+ version: 2,
1341
+ phase: 'preparing',
1342
+ runRecord: stored,
1343
+ ...(startReservation ? { startReservation } : {}),
938
1344
  agentId: ref.agentId,
939
1345
  threadId: scope.threadId,
940
1346
  resourceId: ref.resourceId,
@@ -945,17 +1351,19 @@ export function createThreadAgentHost(options) {
945
1351
  bindingPreexisting: existing !== undefined,
946
1352
  };
947
1353
  if (!threaded &&
948
- (await Promise.all(claims.map((claim) => options.resourceAccess().owner(claim.kind, claim.resourceId)))).some((registered) => registered !== undefined)) {
1354
+ (await Promise.all(claims.map((claim) => options
1355
+ .resourceAccess()
1356
+ .owner(claim.kind, claim.resourceId)))).some((registered) => registered !== undefined)) {
949
1357
  throw new AgentHostRequestError(404, 'run not found');
950
1358
  }
951
- await armOwnerRecovery(recovery);
1359
+ await armOwnerRecovery(recoveryState);
952
1360
  if (!(await options
953
1361
  .resourceAccess()
954
- .reserveAll(claims, owner, recovery.token))) {
1362
+ .reserveAll(claims, owner, recoveryState.token))) {
955
1363
  await options
956
1364
  .resourceAccess()
957
- .settleReservation(recovery.token, claims);
958
- await clearOwnerRecovery(recovery);
1365
+ .settleReservation(recoveryState.token, claims);
1366
+ await clearOwnerRecovery(recoveryState);
959
1367
  throw new AgentHostRequestError(404, 'run not found');
960
1368
  }
961
1369
  if (threaded && !existing) {
@@ -966,7 +1374,7 @@ export function createThreadAgentHost(options) {
966
1374
  });
967
1375
  }
968
1376
  await writeAgentRunRecord(options.stateStorage(), ref.runId, stored);
969
- return recovery;
1377
+ return recoveryState;
970
1378
  });
971
1379
  // From here to the finally below, this object IS the run's execution.
972
1380
  // Registered BEFORE the stream so the window a replaying start asks
@@ -976,7 +1384,7 @@ export function createThreadAgentHost(options) {
976
1384
  const streamOptions = {
977
1385
  runId: ref.runId,
978
1386
  requestContext: createTrustedAgentRequestContext(execution),
979
- ...(input.threaded !== false
1387
+ ...(threaded
980
1388
  ? {
981
1389
  memory: {
982
1390
  thread: scope.threadId,
@@ -996,54 +1404,46 @@ export function createThreadAgentHost(options) {
996
1404
  input.scheduleDispatchLease === 'executing'
997
1405
  ? { scheduleId: input.scheduleId, dispatchId: input.dispatchId }
998
1406
  : undefined;
999
- await durable.streamUntilPersisted(messages, streamOptions, scope.principal.id, scope.principal.kind, recovery.token, scheduleDispatch, input.idempotencyKey);
1000
- const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
1001
- if (!summary)
1002
- throw new Error('agent run did not persist a summary');
1003
- const result = await envelopeFor(scope, ref, scope.principal, summary);
1004
- if (isTerminalRunStatus(result.summary.status)) {
1005
- await deleteAgentRunRecord(options.stateStorage(), ref.runId);
1407
+ try {
1408
+ await durable.streamUntilPersisted(messages, streamOptions, principal.id, principal.kind, recovery.token, scheduleDispatch, idempotencyKey, {
1409
+ ...(mutationEpoch === undefined ? {} : { mutationEpoch }),
1410
+ startIdentity,
1411
+ agentStart: { threaded },
1412
+ ...(startReservation ? { startReservation } : {}),
1413
+ onPreparedStartIdentity: async (identity) => {
1414
+ recovery = await prepareOwnerRecovery(scope, recovery, identity);
1415
+ },
1416
+ runOwnerGuard: { owner, reservationToken: recovery.token },
1417
+ });
1418
+ }
1419
+ finally {
1420
+ unwoundExecutions.add(execution);
1006
1421
  }
1007
- await finalizeOwnerRecoveryBestEffort(recovery, summary);
1422
+ const selected = matchRecoveryState(recovery, await selectedAgentState(scope, ref));
1423
+ if (selected.kind === 'initial')
1424
+ throw new RunStartPendingError();
1425
+ const summary = await finalizeOwnerRecovery(scope, recovery, selected, execution);
1426
+ const result = await envelopeFor(scope, ref, scope.principal, summary);
1008
1427
  return result;
1009
1428
  }
1010
1429
  catch (error) {
1011
- let summary;
1430
+ unwoundExecutions.add(execution);
1012
1431
  try {
1013
- summary = await scope.init.runtime.recoverStartAttempt(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, recovery.token);
1014
- }
1015
- catch (recoverError) {
1016
- // Unknown authoritative state: retain metadata and fail closed —
1017
- // and logged, never swallowed silently, because this read is the
1018
- // only thing that could tell an interrupted start apart from a
1019
- // failed one, and its own failure is why the journal is left
1020
- // armed for a wake that can read. The caller still sees the
1021
- // ORIGINAL start error.
1022
- console.error('interrupted start could not read authoritative state', recoverError);
1023
- }
1024
- if (summary === null ||
1025
- (summary && isTerminalRunStatus(summary.status))) {
1026
- await deleteAgentRunRecord(options.stateStorage(), ref.runId);
1027
- }
1028
- if (summary) {
1029
- await finalizeOwnerRecoveryBestEffort(recovery, summary);
1030
- return envelopeFor(scope, ref, scope.principal, summary);
1031
- }
1032
- else if (summary === null) {
1033
- try {
1034
- await recoverOwner(scope.init.runtime, scope.threadId, recoveryKey, recovery, true);
1035
- }
1036
- catch (recoveryError) {
1037
- console.error('agent owner recovery failed', recoveryError);
1432
+ const storedRecovery = await options
1433
+ .stateStorage()
1434
+ .get(recoveryKey);
1435
+ if (storedRecovery !== undefined) {
1436
+ const latest = validateOwnerRecovery(scope.threadId, recoveryKey, storedRecovery);
1437
+ if (!sameOwnerRecovery(latest, recovery))
1438
+ throw new Error('agent owner recovery changed');
1439
+ const summary = await recoverOwner(scope, recoveryKey, latest, execution, error);
1440
+ if (summary)
1441
+ return envelopeFor(scope, ref, scope.principal, summary);
1038
1442
  }
1039
1443
  }
1040
- else {
1041
- try {
1042
- await withRecoveryLock(() => ensureOwnerRecoveryAlarm(options.stateStorage()));
1043
- }
1044
- catch (alarmError) {
1045
- console.error('agent owner recovery rearm failed', alarmError);
1046
- }
1444
+ catch (recoveryError) {
1445
+ console.error('agent owner recovery failed', recoveryError);
1446
+ await withRecoveryLock(() => ensureOwnerRecoveryAlarm(options.stateStorage()));
1047
1447
  }
1048
1448
  throw error;
1049
1449
  }
@@ -1082,22 +1482,40 @@ export function createThreadAgentHost(options) {
1082
1482
  ? preflightUrl.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length)
1083
1483
  : '';
1084
1484
  const preflightSegments = preflightSuffix.split('/').filter(Boolean);
1085
- // The liveness probe, answered BEFORE withDispatchLock on purpose: the
1086
- // start it is asking about holds that lock for its whole first leg, so a
1087
- // probe that queued behind it would block for exactly as long as the run
1088
- // it was trying to describe — and time out reporting nothing.
1089
- //
1090
- // It reads no storage and reveals only whether this object is currently
1091
- // executing a run id the caller already had to know. Authorization is the
1092
- // deployment-identity header every request to this object carries: the
1093
- // probe travels the internal Worker-to-DO channel, and the reservation on
1094
- // the far side already proved the caller owns the key that names this run.
1485
+ // The start holds the dispatch lock while its liveness probe must remain responsive.
1095
1486
  if (request.method === 'GET' &&
1096
1487
  preflightSegments.length === 4 &&
1097
1488
  preflightSegments[0] === 'runs' &&
1098
1489
  preflightSegments[3] === 'start-liveness') {
1490
+ instanceScopeFor(scope);
1491
+ const agentId = decode(preflightSegments[1]);
1099
1492
  const runId = decode(preflightSegments[2]);
1100
- return json({ live: runId !== undefined && startsInFlight.has(runId) });
1493
+ return json({
1494
+ live: agentId !== undefined &&
1495
+ runId !== undefined &&
1496
+ (startsInFlight.has(runId) ||
1497
+ executions.has(runId) ||
1498
+ (runtime?.agents.get(agentId)?.isRunLive(runId) ??
1499
+ globalRunRegistry.has(runId))),
1500
+ });
1501
+ }
1502
+ if (request.method === 'GET' &&
1503
+ preflightSegments.length === 3 &&
1504
+ preflightSegments[0] === 'runs' &&
1505
+ preflightUrl.searchParams.get('replay') === '1') {
1506
+ const ref = runRef(scope, {
1507
+ agentId: decode(preflightSegments[1]),
1508
+ runId: decode(preflightSegments[2]),
1509
+ threadId: scope.threadId,
1510
+ resourceId: preflightUrl.searchParams.get('resourceId'),
1511
+ });
1512
+ const state = await selectedAgentState(scope, ref);
1513
+ if (state &&
1514
+ (state.execution.owner.kind !== scope.principal.kind ||
1515
+ state.execution.owner.id !== scope.principal.id))
1516
+ throw new AgentHostRequestError(404, 'run not found');
1517
+ if (state?.kind === 'initial')
1518
+ return json({ kind: 'initial', execution: state.execution });
1101
1519
  }
1102
1520
  if (request.method === 'POST' &&
1103
1521
  preflightSegments.length === 4 &&
@@ -1119,10 +1537,12 @@ export function createThreadAgentHost(options) {
1119
1537
  if (storedRun && storedRun.agentId !== ref.agentId) {
1120
1538
  throw new AgentHostRequestError(404, 'run not found');
1121
1539
  }
1122
- await snapshotExecutionFor(scope, ref);
1540
+ await snapshotExecutionFor(scope, ref, preflightUrl.searchParams.get('replay') === '1'
1541
+ ? undefined
1542
+ : await publicAgentState(scope, ref));
1123
1543
  const owner = await options.resourceAccess().owner('run', ref.runId);
1124
1544
  if (preflightUrl.searchParams.get('replay') !== '1') {
1125
- await scope.init.runtime.cancelActiveExecution(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, 'cancelled', [scope.principal, owner ?? scope.principal]);
1545
+ await scope.init.runtime.cancelActiveExecution(await workflowIdFor(scope, ref.agentId), ref.runId, 'cancelled', [scope.principal, owner ?? scope.principal]);
1126
1546
  preflightedTermination = true;
1127
1547
  }
1128
1548
  }
@@ -1146,9 +1566,24 @@ export function createThreadAgentHost(options) {
1146
1566
  if (request.method === 'POST' &&
1147
1567
  url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/start`) {
1148
1568
  const body = await objectBody(request);
1149
- if ('resourceOwner' in body || 'requestedBy' in body) {
1569
+ if ('resourceOwner' in body ||
1570
+ 'requestedBy' in body ||
1571
+ [
1572
+ 'mutationEpoch',
1573
+ 'startIdentity',
1574
+ 'agentStart',
1575
+ 'execution',
1576
+ 'tablePrefix',
1577
+ 'startToken',
1578
+ 'attemptToken',
1579
+ 'runOwnerGuard',
1580
+ 'onPreparedStartIdentity',
1581
+ ].some((key) => Object.hasOwn(body, key))) {
1150
1582
  throw new AgentHostRequestError(400, 'start owner and requester are derived from trusted provenance');
1151
1583
  }
1584
+ const startReservation = body.startReservation === undefined
1585
+ ? undefined
1586
+ : captureReservation(body.startReservation, 'started');
1152
1587
  const ref = runRef(scope, body);
1153
1588
  const requestedEntry = entryPath(body.entryPath);
1154
1589
  if (requestedEntry !== 'schedule.fire' &&
@@ -1157,6 +1592,7 @@ export function createThreadAgentHost(options) {
1157
1592
  }
1158
1593
  return json(await host.start(scope, {
1159
1594
  ...ref,
1595
+ startReservation,
1160
1596
  ...(typeof body.prompt === 'string'
1161
1597
  ? { prompt: body.prompt }
1162
1598
  : {}),
@@ -1200,7 +1636,7 @@ export function createThreadAgentHost(options) {
1200
1636
  const body = await objectBody(request);
1201
1637
  const ref = runRef(scope, body);
1202
1638
  const snapshotExecution = await snapshotExecutionFor(scope, ref);
1203
- await statusFor(scope, ref, snapshotExecution.threaded);
1639
+ await statusFor(scope, ref, snapshotExecution.state);
1204
1640
  const stored = await readRun(ref.runId);
1205
1641
  if (!stored ||
1206
1642
  stored.agentId !== ref.agentId ||
@@ -1251,15 +1687,8 @@ export function createThreadAgentHost(options) {
1251
1687
  });
1252
1688
  });
1253
1689
  const result = await envelopeFor(scope, ref, stored.principal, summary);
1254
- if (isTerminalRunStatus(summary.status)) {
1255
- await deleteAgentRunRecord(options.stateStorage(), ref.runId);
1256
- const recovery = await options
1257
- .stateStorage()
1258
- .get(ownerRecoveryKey(ref.runId));
1259
- if (recovery) {
1260
- await finalizeOwnerRecoveryBestEffort(recovery, summary);
1261
- }
1262
- }
1690
+ if (isTerminalRunStatus(summary.status))
1691
+ await finalizeTerminalAgentState(scope, ref, undefined, stored);
1263
1692
  return json(result);
1264
1693
  }
1265
1694
  const suffix = url.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length);
@@ -1279,75 +1708,153 @@ export function createThreadAgentHost(options) {
1279
1708
  runId,
1280
1709
  });
1281
1710
  if (segments.length === 3 && request.method === 'GET') {
1711
+ if (url.searchParams.get('replay') === '1') {
1712
+ const selected = await selectedAgentState(scope, ref);
1713
+ if (!selected)
1714
+ return json({ error: 'run not found' }, 404);
1715
+ if (selected.execution.owner.kind !== scope.principal.kind ||
1716
+ selected.execution.owner.id !== scope.principal.id)
1717
+ throw new AgentHostRequestError(404, 'run not found');
1718
+ if (selected.kind === 'initial')
1719
+ return json({ kind: 'initial', execution: selected.execution });
1720
+ const stored = await readRun(ref.runId);
1721
+ const value = await envelopeFor(scope, ref, stored?.principal ?? scope.principal, selected.summary);
1722
+ return json({
1723
+ kind: 'result',
1724
+ execution: selected.execution,
1725
+ value: publicAgentRunEnvelope(value, selected.execution, {
1726
+ ...ref,
1727
+ threadId: scope.threadId,
1728
+ }),
1729
+ });
1730
+ }
1282
1731
  if (url.searchParams.get('dispatch') === '1') {
1283
1732
  const key = ownerRecoveryKey(ref.runId);
1284
- const pending = await options
1285
- .stateStorage()
1286
- .get(key);
1287
- if (pending) {
1288
- await recoverOwner(scope.init.runtime, scope.threadId, key, pending, true);
1733
+ const pending = await options.stateStorage().get(key);
1734
+ if (pending !== undefined) {
1735
+ await recoverOwner(scope, key, pending);
1289
1736
  }
1290
1737
  return json(await statusFor(scope, ref));
1291
1738
  }
1292
- return json(await statusFor(scope, ref));
1739
+ return json(await statusFor(scope, ref, await publicAgentState(scope, ref)));
1293
1740
  }
1294
1741
  if (segments.length === 4 &&
1295
1742
  segments[3] === 'terminate' &&
1296
1743
  request.method === 'POST') {
1297
- const runtime = scope.init.runtime;
1744
+ const scopedRuntime = scope.init.runtime;
1298
1745
  const replayOnly = url.searchParams.get('replay') === '1';
1299
1746
  const storedRun = await readRun(ref.runId);
1300
1747
  if (storedRun && storedRun.agentId !== ref.agentId) {
1301
1748
  throw new AgentHostRequestError(404, 'run not found');
1302
1749
  }
1303
- await snapshotExecutionFor(scope, ref);
1750
+ await snapshotExecutionFor(scope, ref, replayOnly ? undefined : await publicAgentState(scope, ref));
1304
1751
  const preflightOwner = await options
1305
1752
  .resourceAccess()
1306
1753
  .owner('run', ref.runId);
1307
1754
  if (!replayOnly && !preflightedTermination) {
1308
- await runtime.cancelActiveExecution(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, 'cancelled', [scope.principal, preflightOwner ?? scope.principal]);
1755
+ await scopedRuntime.cancelActiveExecution(await workflowIdFor(scope, ref.agentId), ref.runId, 'cancelled', [scope.principal, preflightOwner ?? scope.principal]);
1309
1756
  }
1310
1757
  const owner = await options.resourceAccess().owner('run', ref.runId);
1311
1758
  if (replayOnly) {
1312
- const existing = await runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
1759
+ const existing = await scopedRuntime.status(await workflowIdFor(scope, ref.agentId), ref.runId);
1313
1760
  if (existing?.status !== 'cancelled' &&
1314
1761
  existing?.status !== 'timed_out') {
1315
1762
  throw new AgentHostRequestError(404, 'run not found');
1316
1763
  }
1317
1764
  }
1318
- const transition = await runtime.terminateAsPrincipal(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, scope.principal, owner ?? scope.principal);
1319
- let summary = transition.summary;
1320
- if (!transition.cleanup.cleanupCompleted) {
1321
- await abandonApprovalsForRun(options.approvalService(scope), DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, transition.cleanup.status, options.systemPrincipalId ?? 'flowsafe-system');
1322
- const dispatch = transition.cleanup.scheduleDispatch;
1323
- if (dispatch) {
1324
- if (!options.discardScheduleDispatch) {
1325
- throw new Error('scheduled agent termination requires a dispatch-discard hook');
1765
+ const transition = await scopedRuntime.terminateAsPrincipal(await workflowIdFor(scope, ref.agentId), ref.runId, scope.principal, owner ?? scope.principal);
1766
+ const selected = await selectedAgentState(scope, ref, {
1767
+ includeLegacy: true,
1768
+ });
1769
+ if (!selected || selected.kind === 'initial')
1770
+ throw new RunStartPendingError();
1771
+ const journal = await options
1772
+ .stateStorage()
1773
+ .get(ownerRecoveryKey(ref.runId));
1774
+ if (journal !== undefined) {
1775
+ if (selected.kind === 'legacy')
1776
+ throw new ExecutionFenceUnreadableError('legacy run cleanup is unresolved');
1777
+ const recovery = validateOwnerRecovery(scope.threadId, ownerRecoveryKey(ref.runId), journal);
1778
+ const summary = await finalizeOwnerRecovery(scope, recovery, selected);
1779
+ return json(await envelopeFor(scope, ref, storedRun?.principal ?? scope.principal, summary));
1780
+ }
1781
+ const legacy = selected.kind === 'legacy' ? selected : undefined;
1782
+ const workflowId = selected.kind === 'legacy'
1783
+ ? selected.address.workflowId
1784
+ : selected.execution.workflowId;
1785
+ const cleanup = legacy
1786
+ ? terminalCleanupFor(lifecycleFromRequestContext(legacy.snapshot.requestContext))
1787
+ : transition.cleanup;
1788
+ if (!cleanup ||
1789
+ (legacy &&
1790
+ (legacy.summary.status !== transition.summary.status ||
1791
+ cleanup.revision !== transition.cleanup.revision ||
1792
+ cleanup.status !== transition.cleanup.status ||
1793
+ cleanup.scheduleDispatch?.scheduleId !==
1794
+ transition.cleanup.scheduleDispatch?.scheduleId ||
1795
+ cleanup.scheduleDispatch?.dispatchId !==
1796
+ transition.cleanup.scheduleDispatch?.dispatchId ||
1797
+ (transition.cleanup.cleanupCompleted &&
1798
+ !cleanup.cleanupCompleted))))
1799
+ throw new ExecutionFenceUnreadableError('legacy run cleanup is unresolved');
1800
+ const finish = async () => {
1801
+ const guard = legacy
1802
+ ? () => assertLegacyTerminalCurrent(scope, ref, legacy, storedRun)
1803
+ : undefined;
1804
+ if (guard)
1805
+ await guard();
1806
+ if (selected.kind !== 'legacy')
1807
+ await scopedRuntime.settleStartExecution(selected);
1808
+ let summary = legacy?.summary ?? transition.summary;
1809
+ if (!cleanup.cleanupCompleted) {
1810
+ if (guard)
1811
+ await guard();
1812
+ await abandonApprovalsForRun(options.approvalService(scope), workflowId, ref.runId, cleanup.status, options.systemPrincipalId ?? 'flowsafe-system');
1813
+ const dispatch = cleanup.scheduleDispatch;
1814
+ if (dispatch) {
1815
+ if (!options.discardScheduleDispatch) {
1816
+ throw new Error('scheduled agent termination requires a dispatch-discard hook');
1817
+ }
1818
+ if (guard)
1819
+ await guard();
1820
+ await options.discardScheduleDispatch(dispatch.scheduleId, dispatch.dispatchId, ref.runId);
1326
1821
  }
1327
- await options.discardScheduleDispatch(dispatch.scheduleId, dispatch.dispatchId, ref.runId);
1328
- }
1329
- const released = await options
1330
- .resourceAccess()
1331
- .release('run', ref.runId, owner ?? scope.principal);
1332
- if (!released) {
1333
- const current = await options
1822
+ if (guard)
1823
+ await guard();
1824
+ const released = await options
1334
1825
  .resourceAccess()
1335
- .owner('run', ref.runId);
1336
- if (current) {
1337
- throw new Error(`run '${ref.runId}' ownership could not be released`);
1826
+ .release('run', ref.runId, owner ?? scope.principal);
1827
+ if (!released) {
1828
+ const current = await options
1829
+ .resourceAccess()
1830
+ .owner('run', ref.runId);
1831
+ if (current) {
1832
+ throw new Error(`run '${ref.runId}' ownership could not be released`);
1833
+ }
1338
1834
  }
1835
+ if (guard)
1836
+ await guard();
1837
+ summary = await scopedRuntime.completeTerminalCleanup(workflowId, ref.runId, cleanup.revision);
1339
1838
  }
1340
- }
1341
- await finalizeTerminalAgentState(scope.threadId, ref.runId, summary);
1342
- if (!transition.cleanup.cleanupCompleted) {
1343
- summary = await runtime.completeTerminalCleanup(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, transition.cleanup.revision);
1344
- }
1345
- return json(await envelopeFor(scope, ref, storedRun?.principal ?? scope.principal, summary));
1839
+ if (legacy) {
1840
+ if (guard)
1841
+ await guard();
1842
+ if (storedRun)
1843
+ await finalizeTerminalRecord(scope, ref.runId, storedRun, legacy);
1844
+ }
1845
+ else {
1846
+ await finalizeTerminalAgentState(scope, ref, selected, storedRun);
1847
+ }
1848
+ return json(await envelopeFor(scope, ref, storedRun?.principal ?? scope.principal, summary));
1849
+ };
1850
+ return legacy
1851
+ ? withBindingLock(() => withRecoveryLock(finish))
1852
+ : finish();
1346
1853
  }
1347
1854
  if (segments.length === 4 &&
1348
1855
  segments[3] === 'stream' &&
1349
1856
  request.method === 'GET') {
1350
- const run = await statusFor(scope, ref);
1857
+ const run = await statusFor(scope, ref, await publicAgentState(scope, ref));
1351
1858
  const offset = Number(url.searchParams.get('offset') ?? '0');
1352
1859
  if (!Number.isSafeInteger(offset) || offset < 0) {
1353
1860
  throw new AgentHostRequestError(400, 'invalid stream offset');