@proofoftech/flowsafe 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +68 -6
  3. package/deployment-identity-protocol.d.mts +70 -1
  4. package/deployment-identity-protocol.mjs +423 -5
  5. package/dist/agent-host/index.d.ts +1 -1
  6. package/dist/agent-host/index.d.ts.map +1 -1
  7. package/dist/agent-host/index.js.map +1 -1
  8. package/dist/agent-host/router.d.ts.map +1 -1
  9. package/dist/agent-host/router.js +17 -4
  10. package/dist/agent-host/router.js.map +1 -1
  11. package/dist/agent-host/thread-host.d.ts +14 -1
  12. package/dist/agent-host/thread-host.d.ts.map +1 -1
  13. package/dist/agent-host/thread-host.js +865 -308
  14. package/dist/agent-host/thread-host.js.map +1 -1
  15. package/dist/agent-host/thread-topology.d.ts +43 -1
  16. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  17. package/dist/agent-host/thread-topology.js +301 -28
  18. package/dist/agent-host/thread-topology.js.map +1 -1
  19. package/dist/agent-runner/durable-agent-runner.d.ts +107 -8
  20. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  21. package/dist/agent-runner/durable-agent-runner.js +427 -55
  22. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  23. package/dist/agent-runner/index.d.ts +1 -1
  24. package/dist/agent-runner/index.d.ts.map +1 -1
  25. package/dist/agent-runner/index.js.map +1 -1
  26. package/dist/approval-api/actor-context.d.ts +4 -0
  27. package/dist/approval-api/actor-context.d.ts.map +1 -1
  28. package/dist/approval-api/actor-context.js +53 -5
  29. package/dist/approval-api/actor-context.js.map +1 -1
  30. package/dist/approval-api/d1-store.d.ts.map +1 -1
  31. package/dist/approval-api/d1-store.js +6 -3
  32. package/dist/approval-api/d1-store.js.map +1 -1
  33. package/dist/approval-api/principal-identity.d.ts +32 -0
  34. package/dist/approval-api/principal-identity.d.ts.map +1 -0
  35. package/dist/approval-api/principal-identity.js +69 -0
  36. package/dist/approval-api/principal-identity.js.map +1 -0
  37. package/dist/approval-api/principal.d.ts +10 -13
  38. package/dist/approval-api/principal.d.ts.map +1 -1
  39. package/dist/approval-api/principal.js +10 -46
  40. package/dist/approval-api/principal.js.map +1 -1
  41. package/dist/approval-api/retention.d.ts +1 -2
  42. package/dist/approval-api/retention.d.ts.map +1 -1
  43. package/dist/approval-api/retention.js.map +1 -1
  44. package/dist/approval-api/router.d.ts.map +1 -1
  45. package/dist/approval-api/router.js +9 -1
  46. package/dist/approval-api/router.js.map +1 -1
  47. package/dist/approval-api/service.d.ts +29 -14
  48. package/dist/approval-api/service.d.ts.map +1 -1
  49. package/dist/approval-api/service.js +83 -25
  50. package/dist/approval-api/service.js.map +1 -1
  51. package/dist/approval-api/types.d.ts +12 -0
  52. package/dist/approval-api/types.d.ts.map +1 -1
  53. package/dist/approval-api/types.js +12 -0
  54. package/dist/approval-api/types.js.map +1 -1
  55. package/dist/audit-export/index.d.ts +2 -2
  56. package/dist/audit-export/index.js +2 -2
  57. package/dist/background-tasks/d1-storage.d.ts +4 -3
  58. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  59. package/dist/background-tasks/d1-storage.js +7 -13
  60. package/dist/background-tasks/d1-storage.js.map +1 -1
  61. package/dist/background-tasks/host.d.ts +127 -14
  62. package/dist/background-tasks/host.d.ts.map +1 -1
  63. package/dist/background-tasks/host.js +579 -50
  64. package/dist/background-tasks/host.js.map +1 -1
  65. package/dist/background-tasks/index.d.ts +2 -2
  66. package/dist/background-tasks/index.d.ts.map +1 -1
  67. package/dist/background-tasks/index.js +11 -6
  68. package/dist/background-tasks/index.js.map +1 -1
  69. package/dist/background-tasks/routes.d.ts +19 -2
  70. package/dist/background-tasks/routes.d.ts.map +1 -1
  71. package/dist/background-tasks/routes.js +4 -4
  72. package/dist/background-tasks/routes.js.map +1 -1
  73. package/dist/deployment-identity-protocol.d.ts +2 -2
  74. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  75. package/dist/deployment-identity-protocol.js +1 -1
  76. package/dist/deployment-identity-protocol.js.map +1 -1
  77. package/dist/do-runner/cause-chain.d.ts +53 -0
  78. package/dist/do-runner/cause-chain.d.ts.map +1 -0
  79. package/dist/do-runner/cause-chain.js +96 -0
  80. package/dist/do-runner/cause-chain.js.map +1 -0
  81. package/dist/do-runner/constants.d.ts +3 -0
  82. package/dist/do-runner/constants.d.ts.map +1 -0
  83. package/dist/do-runner/constants.js +3 -0
  84. package/dist/do-runner/constants.js.map +1 -0
  85. package/dist/do-runner/d1-storage.d.ts +47 -69
  86. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  87. package/dist/do-runner/d1-storage.js +972 -196
  88. package/dist/do-runner/d1-storage.js.map +1 -1
  89. package/dist/do-runner/deployment-identity.d.ts +29 -5
  90. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  91. package/dist/do-runner/deployment-identity.js +23 -6
  92. package/dist/do-runner/deployment-identity.js.map +1 -1
  93. package/dist/do-runner/do-error-response.d.ts +4 -23
  94. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  95. package/dist/do-runner/do-error-response.js +19 -24
  96. package/dist/do-runner/do-error-response.js.map +1 -1
  97. package/dist/do-runner/do-status-error.d.ts +37 -0
  98. package/dist/do-runner/do-status-error.d.ts.map +1 -0
  99. package/dist/do-runner/do-status-error.js +42 -0
  100. package/dist/do-runner/do-status-error.js.map +1 -0
  101. package/dist/do-runner/durable-object.d.ts +2 -1
  102. package/dist/do-runner/durable-object.d.ts.map +1 -1
  103. package/dist/do-runner/durable-object.js +617 -144
  104. package/dist/do-runner/durable-object.js.map +1 -1
  105. package/dist/do-runner/execution-admission.d.ts +114 -0
  106. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  107. package/dist/do-runner/execution-admission.js +206 -0
  108. package/dist/do-runner/execution-admission.js.map +1 -0
  109. package/dist/do-runner/execution-context.d.ts.map +1 -1
  110. package/dist/do-runner/execution-context.js +1 -0
  111. package/dist/do-runner/execution-context.js.map +1 -1
  112. package/dist/do-runner/execution-fence.d.ts +379 -0
  113. package/dist/do-runner/execution-fence.d.ts.map +1 -0
  114. package/dist/do-runner/execution-fence.js +1098 -0
  115. package/dist/do-runner/execution-fence.js.map +1 -0
  116. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  117. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  118. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  119. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  120. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  121. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  122. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  123. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  124. package/dist/do-runner/index.d.ts +20 -8
  125. package/dist/do-runner/index.d.ts.map +1 -1
  126. package/dist/do-runner/index.js +21 -4
  127. package/dist/do-runner/index.js.map +1 -1
  128. package/dist/do-runner/init.d.ts +82 -1
  129. package/dist/do-runner/init.d.ts.map +1 -1
  130. package/dist/do-runner/init.js +58 -3
  131. package/dist/do-runner/init.js.map +1 -1
  132. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  133. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  134. package/dist/do-runner/initial-admission-refusal.js +41 -0
  135. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  136. package/dist/do-runner/inventory.d.ts +295 -0
  137. package/dist/do-runner/inventory.d.ts.map +1 -0
  138. package/dist/do-runner/inventory.js +800 -0
  139. package/dist/do-runner/inventory.js.map +1 -0
  140. package/dist/do-runner/notification-predicate.d.ts +8 -0
  141. package/dist/do-runner/notification-predicate.d.ts.map +1 -0
  142. package/dist/do-runner/notification-predicate.js +136 -0
  143. package/dist/do-runner/notification-predicate.js.map +1 -0
  144. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  145. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  146. package/dist/do-runner/run-lifecycle.js +67 -13
  147. package/dist/do-runner/run-lifecycle.js.map +1 -1
  148. package/dist/do-runner/run-provenance.d.ts +38 -0
  149. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  150. package/dist/do-runner/run-provenance.js +152 -0
  151. package/dist/do-runner/run-provenance.js.map +1 -0
  152. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  153. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  154. package/dist/do-runner/run-storage-tables.js +4 -0
  155. package/dist/do-runner/run-storage-tables.js.map +1 -0
  156. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  157. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  158. package/dist/do-runner/run-terminal-state.js +105 -0
  159. package/dist/do-runner/run-terminal-state.js.map +1 -0
  160. package/dist/do-runner/runtime.d.ts +191 -46
  161. package/dist/do-runner/runtime.d.ts.map +1 -1
  162. package/dist/do-runner/runtime.js +994 -378
  163. package/dist/do-runner/runtime.js.map +1 -1
  164. package/dist/do-runner/start-idempotency.d.ts +285 -0
  165. package/dist/do-runner/start-idempotency.d.ts.map +1 -0
  166. package/dist/do-runner/start-idempotency.js +994 -0
  167. package/dist/do-runner/start-idempotency.js.map +1 -0
  168. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  169. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  170. package/dist/do-runner/start-reservation-contract.js +338 -0
  171. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  172. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  173. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  174. package/dist/do-runner/suspension-deadline.js +8 -12
  175. package/dist/do-runner/suspension-deadline.js.map +1 -1
  176. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  177. package/dist/do-runner/table-prefix.js +2 -1
  178. package/dist/do-runner/table-prefix.js.map +1 -1
  179. package/dist/do-runner/testing.d.ts +3 -0
  180. package/dist/do-runner/testing.d.ts.map +1 -0
  181. package/dist/do-runner/testing.js +3 -0
  182. package/dist/do-runner/testing.js.map +1 -0
  183. package/dist/do-runner/thread-do.d.ts +2 -1
  184. package/dist/do-runner/thread-do.d.ts.map +1 -1
  185. package/dist/do-runner/thread-do.js +14 -10
  186. package/dist/do-runner/thread-do.js.map +1 -1
  187. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  188. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  189. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  190. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  191. package/dist/goals/objective-routes.d.ts +15 -5
  192. package/dist/goals/objective-routes.d.ts.map +1 -1
  193. package/dist/goals/objective-routes.js +64 -64
  194. package/dist/goals/objective-routes.js.map +1 -1
  195. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  196. package/dist/host-kit/approval-bridge.js +10 -7
  197. package/dist/host-kit/approval-bridge.js.map +1 -1
  198. package/dist/host-kit/do-response.d.ts +16 -0
  199. package/dist/host-kit/do-response.d.ts.map +1 -1
  200. package/dist/host-kit/do-response.js +181 -0
  201. package/dist/host-kit/do-response.js.map +1 -1
  202. package/dist/host-kit/do-run-topology.d.ts +3 -0
  203. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  204. package/dist/host-kit/do-run-topology.js +36 -8
  205. package/dist/host-kit/do-run-topology.js.map +1 -1
  206. package/dist/host-kit/env-vars.d.ts.map +1 -1
  207. package/dist/host-kit/env-vars.js +5 -6
  208. package/dist/host-kit/env-vars.js.map +1 -1
  209. package/dist/host-kit/flowsafe-worker.d.ts +49 -6
  210. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  211. package/dist/host-kit/flowsafe-worker.js +409 -111
  212. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  213. package/dist/host-kit/host-approval-service.d.ts +24 -14
  214. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  215. package/dist/host-kit/host-approval-service.js +29 -40
  216. package/dist/host-kit/host-approval-service.js.map +1 -1
  217. package/dist/host-kit/index.d.ts +9 -3
  218. package/dist/host-kit/index.d.ts.map +1 -1
  219. package/dist/host-kit/index.js +5 -1
  220. package/dist/host-kit/index.js.map +1 -1
  221. package/dist/host-kit/run-route-error.d.ts +8 -4
  222. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  223. package/dist/host-kit/run-route-error.js +14 -11
  224. package/dist/host-kit/run-route-error.js.map +1 -1
  225. package/dist/host-kit/run-router.d.ts +63 -2
  226. package/dist/host-kit/run-router.d.ts.map +1 -1
  227. package/dist/host-kit/run-router.js +167 -45
  228. package/dist/host-kit/run-router.js.map +1 -1
  229. package/dist/host-kit/stream-router.d.ts.map +1 -1
  230. package/dist/host-kit/stream-router.js +18 -9
  231. package/dist/host-kit/stream-router.js.map +1 -1
  232. package/dist/host-kit/thread-topology.d.ts +1 -1
  233. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  234. package/dist/host-kit/thread-topology.js +7 -3
  235. package/dist/host-kit/thread-topology.js.map +1 -1
  236. package/dist/internal-error-response.d.ts.map +1 -1
  237. package/dist/internal-error-response.js +16 -6
  238. package/dist/internal-error-response.js.map +1 -1
  239. package/dist/schedules/index.d.ts +1 -0
  240. package/dist/schedules/index.d.ts.map +1 -1
  241. package/dist/schedules/index.js +1 -7
  242. package/dist/schedules/index.js.map +1 -1
  243. package/dist/schedules/mutation-contract.d.ts +38 -0
  244. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  245. package/dist/schedules/mutation-contract.js +21 -0
  246. package/dist/schedules/mutation-contract.js.map +1 -0
  247. package/dist/schedules/router.d.ts +15 -8
  248. package/dist/schedules/router.d.ts.map +1 -1
  249. package/dist/schedules/router.js +170 -59
  250. package/dist/schedules/router.js.map +1 -1
  251. package/dist/schedules/schedules-d1.d.ts +11 -5
  252. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  253. package/dist/schedules/schedules-d1.js +570 -143
  254. package/dist/schedules/schedules-d1.js.map +1 -1
  255. package/dist/schedules/storage.d.ts +0 -7
  256. package/dist/schedules/storage.d.ts.map +1 -1
  257. package/dist/schedules/storage.js +0 -27
  258. package/dist/schedules/storage.js.map +1 -1
  259. package/dist/schedules/tick.d.ts +13 -0
  260. package/dist/schedules/tick.d.ts.map +1 -1
  261. package/dist/schedules/tick.js +66 -40
  262. package/dist/schedules/tick.js.map +1 -1
  263. package/dist/signal-providers/host-do.d.ts +12 -1
  264. package/dist/signal-providers/host-do.d.ts.map +1 -1
  265. package/dist/signal-providers/host-do.js +28 -3
  266. package/dist/signal-providers/host-do.js.map +1 -1
  267. package/dist/signal-providers/webhook-route.d.ts +15 -1
  268. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  269. package/dist/signal-providers/webhook-route.js +126 -113
  270. package/dist/signal-providers/webhook-route.js.map +1 -1
  271. package/dist/signals/d1-shared.d.ts +11 -8
  272. package/dist/signals/d1-shared.d.ts.map +1 -1
  273. package/dist/signals/d1-shared.js +1 -6
  274. package/dist/signals/d1-shared.js.map +1 -1
  275. package/dist/signals/index.d.ts +1 -1
  276. package/dist/signals/index.d.ts.map +1 -1
  277. package/dist/signals/index.js +1 -1
  278. package/dist/signals/index.js.map +1 -1
  279. package/dist/signals/notification-dispatch.d.ts +109 -5
  280. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  281. package/dist/signals/notification-dispatch.js +430 -46
  282. package/dist/signals/notification-dispatch.js.map +1 -1
  283. package/dist/signals/notifications-d1.d.ts +14 -1
  284. package/dist/signals/notifications-d1.d.ts.map +1 -1
  285. package/dist/signals/notifications-d1.js +229 -18
  286. package/dist/signals/notifications-d1.js.map +1 -1
  287. package/dist/signals/router.d.ts +6 -4
  288. package/dist/signals/router.d.ts.map +1 -1
  289. package/dist/signals/router.js +49 -84
  290. package/dist/signals/router.js.map +1 -1
  291. package/dist/signals/thread-do-routes.d.ts +2 -0
  292. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  293. package/dist/signals/thread-do-routes.js +330 -83
  294. package/dist/signals/thread-do-routes.js.map +1 -1
  295. package/package.json +6 -3
  296. package/patches/@mastra__core@1.53.0.patch +54 -0
  297. package/scripts/seed-deployment-identity.mjs +34 -9
@@ -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,6 +246,9 @@ export function createThreadAgentHost(options) {
219
246
  const withBindingLock = createFifoLock();
220
247
  const withDispatchLock = createFifoLock();
221
248
  const withRecoveryLock = createFifoLock();
249
+ /** Claim durability does not establish current run liveness. */
250
+ const startsInFlight = new Set();
251
+ const unwoundExecutions = new WeakSet();
222
252
  const instanceScopeFor = (scope) => {
223
253
  if (stableScope) {
224
254
  if (stableScope.threadId !== scope.threadId ||
@@ -245,13 +275,14 @@ export function createThreadAgentHost(options) {
245
275
  return catalogPromise;
246
276
  };
247
277
  const runtimeFor = async (scope) => {
278
+ instanceScopeFor(scope);
279
+ const catalog = await catalogFor(scope);
248
280
  if (runtime) {
249
281
  if (runtime.scopeRuntime !== scope.init.runtime) {
250
282
  throw new Error('thread agent host cannot be shared across DO instances');
251
283
  }
252
284
  return runtime;
253
285
  }
254
- const catalog = await catalogFor(scope);
255
286
  const mastra = new Mastra({
256
287
  storage: options.storage(instanceScopeFor(scope)),
257
288
  // Preserve ordinary key lookup, but remap Object.prototype collisions in
@@ -411,25 +442,34 @@ export function createThreadAgentHost(options) {
411
442
  };
412
443
  const readBinding = () => readAgentThreadBinding(options.stateStorage());
413
444
  const readRun = (runId) => readAgentRunRecord(options.stateStorage(), runId);
414
- const findBlockingRun = async (scopeRuntime) => {
445
+ const findBlockingRun = async (scope) => {
415
446
  const storage = options.stateStorage();
416
447
  const records = await storage.list({
417
448
  prefix: AGENT_RUN_STORAGE_KEY_PREFIX,
418
449
  });
450
+ if (records.size === 0)
451
+ return undefined;
419
452
  for (const key of records.keys()) {
420
453
  const runId = key.slice(AGENT_RUN_STORAGE_KEY_PREFIX.length);
421
454
  const record = await readRun(runId);
422
455
  if (!record)
423
456
  continue;
424
- const summary = await scopeRuntime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, runId);
425
- if (executions.has(runId) ||
426
- (summary !== null && !isTerminalRunStatus(summary.status))) {
457
+ if (executions.has(runId))
427
458
  return { runId, principal: record.principal };
428
- }
429
- const recovery = await storage.get(AGENT_OWNER_RECOVERY_PREFIX + runId);
430
- if (recovery)
459
+ const state = await selectedAgentState(scope, {
460
+ agentId: record.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: record.principal };
469
+ const recovery = await storage.get(ownerRecoveryKey(runId));
470
+ if (recovery !== undefined)
431
471
  return { runId, principal: record.principal };
432
- await deleteAgentRunRecord(storage, runId);
472
+ await withRecoveryLock(() => finalizeTerminalRecord(scope, runId, record, state));
433
473
  }
434
474
  return undefined;
435
475
  };
@@ -498,8 +538,10 @@ export function createThreadAgentHost(options) {
498
538
  const storage = options.stateStorage();
499
539
  const key = ownerRecoveryKey(recovery.runId);
500
540
  const current = await storage.get(key);
501
- if (current?.token === recovery.token)
502
- 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);
503
545
  });
504
546
  const releaseEphemeralOwnerClaims = async (recovery) => {
505
547
  const ownership = options.resourceAccess();
@@ -515,58 +557,340 @@ export function createThreadAgentHost(options) {
515
557
  release('thread', recovery.threadId),
516
558
  ]);
517
559
  };
518
- const finalizeOwnerRecovery = (recovery, summary) => withRecoveryLock(async () => {
519
- const storage = options.stateStorage();
520
- await options.resourceAccess().settleReservation(recovery.token, []);
521
- if (!recovery.threaded && !isTerminalRunStatus(summary.status)) {
522
- await ensureOwnerRecoveryAlarm(storage);
523
- return;
524
- }
525
- if (!recovery.threaded) {
526
- await releaseEphemeralOwnerClaims(recovery);
527
- }
528
- const key = ownerRecoveryKey(recovery.runId);
529
- const current = await storage.get(key);
530
- if (current?.token === recovery.token)
531
- await storage.delete(key);
532
- });
533
- const finalizeOwnerRecoveryBestEffort = async (recovery, summary) => {
560
+ const validateOwnerRecovery = (threadId, key, value) => {
534
561
  try {
535
- 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 };
536
632
  }
537
- catch (error) {
538
- 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');
539
660
  try {
540
- await withRecoveryLock(() => ensureOwnerRecoveryAlarm(options.stateStorage()));
661
+ await storage.put(key, prepared);
541
662
  }
542
- catch (alarmError) {
543
- 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;
544
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;
545
699
  }
546
700
  };
547
- const validateOwnerRecovery = (threadId, key, stored) => {
548
- if (stored?.version !== 1 ||
549
- stored.threadId !== threadId ||
550
- !isPathSafeId(stored.agentId) ||
551
- !isPathSafeId(stored.resourceId) ||
552
- !isPathSafeId(stored.runId) ||
553
- !isPathSafeId(stored.token) ||
554
- ownerRecoveryKey(stored.runId) !== key ||
555
- typeof stored.threaded !== 'boolean' ||
556
- typeof stored.bindingPreexisting !== 'boolean') {
557
- 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;
558
767
  }
559
- 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);
560
790
  };
561
- const finalizeTerminalAgentState = async (threadId, runId, summary) => {
562
- const storage = options.stateStorage();
563
- const key = ownerRecoveryKey(runId);
564
- const recovery = await storage.get(key);
565
- if (recovery) {
566
- validateOwnerRecovery(threadId, key, recovery);
567
- 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;
568
796
  }
569
- 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
+ }));
570
894
  };
571
895
  const withExecution = async (execution, operation) => {
572
896
  if (executions.has(execution.runId)) {
@@ -577,13 +901,13 @@ export function createThreadAgentHost(options) {
577
901
  return await operation();
578
902
  }
579
903
  finally {
580
- executions.delete(execution.runId);
904
+ if (executions.get(execution.runId) === execution)
905
+ executions.delete(execution.runId);
581
906
  }
582
907
  };
583
908
  // Reconciling approvals is trusted platform work with no person behind it.
584
- // It used to mint role:'operator', which is why an approval bridge looked
585
- // indistinguishable from a human operator in the audit trail. The bridge
586
- // 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.
587
911
  const systemPrincipalId = options.systemPrincipalId ?? 'flowsafe-system';
588
912
  // Deliberately NOT vouched. Its only consumer projects it to an ApprovalActor
589
913
  // for a role-gated READ, which grants nothing an automated principal does not
@@ -607,7 +931,7 @@ export function createThreadAgentHost(options) {
607
931
  throw new Error('suspended agent run has no durable requester provenance');
608
932
  }
609
933
  const service = options.approvalService(instanceScopeFor(scope));
610
- await reconcileApprovalsForSummary(service, DURABLE_AGENTIC_LOOP_WORKFLOW_ID, summary, systemPrincipalId, {
934
+ await reconcileApprovalsForSummary(service, await workflowIdFor(scope, agentId), summary, systemPrincipalId, {
611
935
  kind: 'agent-thread',
612
936
  agentId,
613
937
  threadId: scope.threadId,
@@ -615,7 +939,7 @@ export function createThreadAgentHost(options) {
615
939
  principal,
616
940
  }, summary.requestedBy);
617
941
  const records = await service.list({
618
- workflowId: DURABLE_AGENTIC_LOOP_WORKFLOW_ID,
942
+ workflowId: await workflowIdFor(scope, agentId),
619
943
  runId: summary.runId,
620
944
  }, principalActor(systemPrincipal()));
621
945
  const keys = new Set((summary.suspended ?? []).map((path) => path.join('.')));
@@ -655,127 +979,166 @@ export function createThreadAgentHost(options) {
655
979
  approvals,
656
980
  };
657
981
  };
658
- const snapshotExecutionFor = async (scope, ref) => {
659
- const workflows = await options
660
- .storage(instanceScopeFor(scope))
661
- .getStore('workflows');
662
- const snapshot = await workflows?.loadWorkflowSnapshot({
663
- workflowName: DURABLE_AGENTIC_LOOP_WORKFLOW_ID,
664
- runId: ref.runId,
665
- });
666
- const input = snapshot?.context.input;
667
- const requestContext = snapshot?.requestContext;
668
- const correlation = requestContext?.['breakwater.auditContext'];
669
- const memory = input?.messageListState?.memoryInfo;
670
- const memoryMatches = memory === null ||
671
- (memory?.threadId === scope.threadId &&
672
- memory.resourceId === ref.resourceId);
673
- if (input?.agentId !== ref.agentId ||
674
- requestContext?.runId !== ref.runId ||
675
- requestContext.threadId !== scope.threadId ||
676
- requestContext.resourceId !== ref.resourceId ||
677
- correlation?.agentId !== ref.agentId ||
678
- correlation.threadId !== scope.threadId ||
679
- correlation.resourceId !== ref.resourceId ||
680
- !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)
681
987
  throw new AgentHostRequestError(404, 'run not found');
682
- }
988
+ if (state.kind === 'initial')
989
+ throw new RunStartPendingError();
683
990
  return {
684
- threaded: memory !== null,
685
- safeContext: sanitizeStoredAgentContext(requestContext),
991
+ state,
992
+ threaded: state.threaded,
993
+ safeContext: sanitizeStoredAgentContext(state.snapshot.requestContext),
686
994
  };
687
995
  };
688
- let recoverOwner;
689
- const statusFor = async (scope, ref, knownThreaded) => {
690
- const binding = await readBinding();
691
- const current = await runtimeFor(scope);
692
- if (!current.catalog.get(ref.agentId)) {
693
- throw new AgentHostRequestError(404, 'agent not found');
694
- }
695
- const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
696
- 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)
697
1002
  throw new AgentHostRequestError(404, 'run not found');
698
- 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();
699
1007
  const bindingMatches = binding?.agentId === ref.agentId && binding.resourceId === ref.resourceId;
700
- if ((threaded && !bindingMatches) || (!threaded && binding)) {
1008
+ if ((selected.threaded && !bindingMatches) ||
1009
+ (!selected.threaded && binding))
701
1010
  throw new AgentHostRequestError(404, 'run not found');
702
- }
703
- const stored = await readRun(ref.runId);
704
- if (stored && stored.agentId !== ref.agentId) {
1011
+ if (stored && stored.agentId !== ref.agentId)
705
1012
  throw new AgentHostRequestError(404, 'run not found');
706
- }
707
- if (summary.status === 'suspended' && !stored) {
1013
+ if (summary.status === 'suspended' && !stored)
708
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
+ }
709
1076
  }
710
- const principal = stored?.principal ?? scope.principal;
711
- const result = await envelopeFor(scope, ref, principal, summary);
712
- if (isTerminalRunStatus(summary.status) && stored) {
713
- await deleteAgentRunRecord(options.stateStorage(), ref.runId);
714
- }
715
- if (isTerminalRunStatus(summary.status)) {
716
- const key = ownerRecoveryKey(ref.runId);
717
- const recovery = await options
718
- .stateStorage()
719
- .get(key);
720
- if (recovery) {
721
- 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;
722
1085
  }
1086
+ else {
1087
+ await assertRecoveryCurrent(stored);
1088
+ await options.resourceAccess().settleReservation(stored.token, []);
1089
+ clear = await finalizeJournalBookkeeping(stored, summary);
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');
723
1111
  }
724
- return result;
725
- };
726
- recoverOwner = async (scopeRuntime, threadId, key, stored, ignoreActive = false) => withBindingLock(() => withRecoveryLock(async () => {
727
- validateOwnerRecovery(threadId, key, stored);
728
1112
  const storage = options.stateStorage();
729
- const currentRecovery = await storage.get(key);
730
- if (currentRecovery?.token !== stored.token)
731
- return 'pending';
732
- if (!ignoreActive && executions.has(stored.runId))
733
- return 'pending';
734
- const summary = await scopeRuntime.recoverStartAttempt(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, stored.runId, stored.token);
735
- const [binding, record] = await Promise.all([
736
- readBinding(),
737
- readRun(stored.runId),
738
- ]);
739
- const bindingMatches = binding?.agentId === stored.agentId &&
1113
+ const binding = await readBinding(), record = await readRun(stored.runId);
1114
+ await assertRecoveryCurrent(stored);
1115
+ const matches = binding?.agentId === stored.agentId &&
740
1116
  binding.resourceId === stored.resourceId;
741
- if (record && (!summary || isTerminalRunStatus(summary.status))) {
1117
+ if (record && !sameRunRecord(record, stored.runRecord))
1118
+ throw new Error('agent run record changed');
1119
+ if (record)
742
1120
  await deleteAgentRunRecord(storage, stored.runId);
743
- }
744
- if (!summary && !stored.bindingPreexisting && bindingMatches) {
1121
+ if (!stored.bindingPreexisting && matches)
745
1122
  await deleteAgentThreadBinding(storage, {
746
1123
  agentId: stored.agentId,
747
1124
  resourceId: stored.resourceId,
748
1125
  });
749
- }
750
- if (summary) {
751
- await options.resourceAccess().settleReservation(stored.token, []);
752
- if (!stored.threaded && !isTerminalRunStatus(summary.status)) {
753
- await ensureOwnerRecoveryAlarm(storage);
754
- return 'pending';
755
- }
756
- if (!stored.threaded)
757
- await releaseEphemeralOwnerClaims(stored);
758
- const current = await storage.get(key);
759
- if (current?.token === stored.token)
760
- await storage.delete(key);
761
- return 'cleared';
762
- }
763
1126
  const release = [{ kind: 'run', resourceId: stored.runId }];
764
- const retainThread = stored.threaded && stored.bindingPreexisting && bindingMatches;
765
- if (!retainThread) {
1127
+ if (!(stored.threaded && stored.bindingPreexisting && matches))
766
1128
  release.push({ kind: 'resource', resourceId: stored.resourceId }, { kind: 'thread', resourceId: stored.threadId });
767
- }
768
1129
  await options.resourceAccess().settleReservation(stored.token, release);
769
- const current = await storage.get(key);
770
- if (current?.token === stored.token)
771
- await storage.delete(key);
772
- 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;
773
1135
  }));
774
1136
  const host = {
775
1137
  requestContextForRun: (base) => async (workflowId, runId, leg) => {
776
1138
  const values = base ? await base(workflowId, runId, leg) : undefined;
777
1139
  const execution = executions.get(runId);
778
- return execution && workflowId === DURABLE_AGENTIC_LOOP_WORKFLOW_ID
1140
+ return execution &&
1141
+ workflowId === runtime?.agents.get(execution.agentId)?.getWorkflow().id
779
1142
  ? {
780
1143
  ...execution.safeContext,
781
1144
  ...values,
@@ -784,55 +1147,113 @@ export function createThreadAgentHost(options) {
784
1147
  : values;
785
1148
  },
786
1149
  serializeDispatch: withDispatchLock,
787
- blockingRun: (scope) => findBlockingRun(scope.init.runtime),
1150
+ blockingRun: (scope) => withBindingLock(() => findBlockingRun(instanceScopeFor(scope))),
788
1151
  scheduleDispatchStatus: async (scope, input) => {
789
1152
  const ref = runRef(scope, {
790
1153
  ...input,
791
1154
  threadId: scope.threadId,
792
1155
  });
793
1156
  const key = ownerRecoveryKey(ref.runId);
794
- const recovery = await options
795
- .stateStorage()
796
- .get(key);
797
- if (recovery) {
798
- 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);
799
1160
  }
800
- const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
801
- if (!summary)
1161
+ const selected = await selectedAgentState(scope, ref, {
1162
+ includeLegacy: true,
1163
+ });
1164
+ if (!selected)
802
1165
  return undefined;
803
- return (await statusFor(scope, ref)).summary;
1166
+ if (selected.kind === 'initial')
1167
+ throw new RunStartPendingError();
1168
+ return (await statusFor(scope, ref, selected)).summary;
804
1169
  },
805
- recoverOwnership: (scopeRuntime, threadId) => withDispatchLock(async () => {
806
- const storage = options.stateStorage();
807
- try {
808
- const pending = await storage.list({
809
- prefix: AGENT_OWNER_RECOVERY_PREFIX,
810
- });
811
- for (const [key, stored] of pending) {
812
- await recoverOwner(scopeRuntime, threadId, key, stored);
813
- }
814
- await withRecoveryLock(async () => {
815
- 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({
816
1176
  prefix: AGENT_OWNER_RECOVERY_PREFIX,
817
1177
  });
818
- if (remaining.size > 0) {
819
- await ensureOwnerRecoveryAlarm(storage);
1178
+ for (const [key, stored] of pending) {
1179
+ await recoverOwner(scope, key, stored);
820
1180
  }
821
- else {
822
- await storage.deleteAlarm();
823
- }
824
- });
825
- }
826
- catch (error) {
827
- await withRecoveryLock(() => ensureOwnerRecoveryAlarm(storage));
828
- throw error;
829
- }
830
- }),
831
- start: async (scope, input) => {
832
- 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));
833
1241
  const entry = entryPath(input.entryPath);
834
1242
  const threaded = input.threaded !== false;
835
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
+ });
836
1257
  const hasPrompt = source.target === undefined && input.prompt !== undefined;
837
1258
  const hasMessages = source.target === undefined && input.messages !== undefined;
838
1259
  if ((source.target === undefined && hasPrompt === hasMessages) ||
@@ -853,7 +1274,6 @@ export function createThreadAgentHost(options) {
853
1274
  const resolvedProviderOptions = source.target
854
1275
  ? source.target.providerOptions
855
1276
  : input.providerOptions;
856
- const owner = source.owner;
857
1277
  const { current, module, principalPermissions } = await authorize(scope, ref.agentId, entry, scope.principal);
858
1278
  if (ref.resourceId !== resourceIdFromKey(scope.threadId)) {
859
1279
  throw new AgentHostRequestError(404, 'run not found');
@@ -874,16 +1294,14 @@ export function createThreadAgentHost(options) {
874
1294
  const durable = current.agents.get(module.meta.id);
875
1295
  if (!durable)
876
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
+ }
877
1302
  return withExecution(execution, async () => {
878
- const recoveryKey = ownerRecoveryKey(ref.runId);
879
- const pending = await options
880
- .stateStorage()
881
- .get(recoveryKey);
882
- if (pending) {
883
- await recoverOwner(scope.init.runtime, scope.threadId, recoveryKey, pending, true);
884
- }
885
1303
  const existingRecord = await readRun(ref.runId);
886
- 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);
887
1305
  if (existingRecord || existingSummary) {
888
1306
  throw new AgentHostRequestError(409, `run '${ref.runId}' already exists`);
889
1307
  }
@@ -898,7 +1316,10 @@ export function createThreadAgentHost(options) {
898
1316
  principal: scope.principal,
899
1317
  originEntryPath: entry,
900
1318
  };
901
- 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}'`);
902
1323
  const existing = await readBinding();
903
1324
  if (!threaded && existing) {
904
1325
  throw new AgentHostRequestError(409, 'unthreaded starts require an unbound object');
@@ -915,12 +1336,11 @@ export function createThreadAgentHost(options) {
915
1336
  throw new AgentHostRequestError(409, 'thread is bound to another agent');
916
1337
  }
917
1338
  }
918
- const blocking = await findBlockingRun(scope.init.runtime);
919
- if (blocking && blocking.runId !== ref.runId) {
920
- throw new AgentHostRequestError(409, `thread is blocked by run '${blocking.runId}'`);
921
- }
922
1339
  const recovery = {
923
- version: 1,
1340
+ version: 2,
1341
+ phase: 'preparing',
1342
+ runRecord: stored,
1343
+ ...(startReservation ? { startReservation } : {}),
924
1344
  agentId: ref.agentId,
925
1345
  threadId: scope.threadId,
926
1346
  resourceId: ref.resourceId,
@@ -931,7 +1351,9 @@ export function createThreadAgentHost(options) {
931
1351
  bindingPreexisting: existing !== undefined,
932
1352
  };
933
1353
  if (!threaded &&
934
- (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)) {
935
1357
  throw new AgentHostRequestError(404, 'run not found');
936
1358
  }
937
1359
  await armOwnerRecovery(recovery);
@@ -954,11 +1376,15 @@ export function createThreadAgentHost(options) {
954
1376
  await writeAgentRunRecord(options.stateStorage(), ref.runId, stored);
955
1377
  return recovery;
956
1378
  });
1379
+ // From here to the finally below, this object IS the run's execution.
1380
+ // Registered BEFORE the stream so the window a replaying start asks
1381
+ // about — the one before core has persisted anything — is covered too.
1382
+ startsInFlight.add(ref.runId);
957
1383
  try {
958
1384
  const streamOptions = {
959
1385
  runId: ref.runId,
960
1386
  requestContext: createTrustedAgentRequestContext(execution),
961
- ...(input.threaded !== false
1387
+ ...(threaded
962
1388
  ? {
963
1389
  memory: {
964
1390
  thread: scope.threadId,
@@ -978,57 +1404,53 @@ export function createThreadAgentHost(options) {
978
1404
  input.scheduleDispatchLease === 'executing'
979
1405
  ? { scheduleId: input.scheduleId, dispatchId: input.dispatchId }
980
1406
  : undefined;
981
- await durable.streamUntilPersisted(messages, streamOptions, scope.principal.id, scope.principal.kind, recovery.token, ...(scheduleDispatch ? [scheduleDispatch] : []));
982
- const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
983
- if (!summary)
984
- throw new Error('agent run did not persist a summary');
985
- const result = await envelopeFor(scope, ref, scope.principal, summary);
986
- if (isTerminalRunStatus(result.summary.status)) {
987
- 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);
988
1421
  }
989
- 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);
990
1427
  return result;
991
1428
  }
992
1429
  catch (error) {
993
- let summary;
1430
+ unwoundExecutions.add(execution);
994
1431
  try {
995
- summary = await scope.init.runtime.recoverStartAttempt(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, recovery.token);
996
- }
997
- catch (recoverError) {
998
- // Unknown authoritative state: retain metadata and fail closed —
999
- // and logged, never swallowed silently, because this read is the
1000
- // only thing that could tell an interrupted start apart from a
1001
- // failed one, and its own failure is why the journal is left
1002
- // armed for a wake that can read. The caller still sees the
1003
- // ORIGINAL start error.
1004
- console.error('interrupted start could not read authoritative state', recoverError);
1005
- }
1006
- if (summary === null ||
1007
- (summary && isTerminalRunStatus(summary.status))) {
1008
- await deleteAgentRunRecord(options.stateStorage(), ref.runId);
1009
- }
1010
- if (summary) {
1011
- await finalizeOwnerRecoveryBestEffort(recovery, summary);
1012
- return envelopeFor(scope, ref, scope.principal, summary);
1013
- }
1014
- else if (summary === null) {
1015
- try {
1016
- await recoverOwner(scope.init.runtime, scope.threadId, recoveryKey, recovery, true);
1017
- }
1018
- catch (recoveryError) {
1019
- console.error('agent owner recovery failed', recoveryError);
1432
+ const current = await options.stateStorage().get(recoveryKey);
1433
+ if (current !== undefined) {
1434
+ const latest = validateOwnerRecovery(scope.threadId, recoveryKey, current);
1435
+ if (!sameOwnerRecovery(latest, recovery))
1436
+ throw new Error('agent owner recovery changed');
1437
+ const summary = await recoverOwner(scope, recoveryKey, latest, execution, error);
1438
+ if (summary)
1439
+ return envelopeFor(scope, ref, scope.principal, summary);
1020
1440
  }
1021
1441
  }
1022
- else {
1023
- try {
1024
- await withRecoveryLock(() => ensureOwnerRecoveryAlarm(options.stateStorage()));
1025
- }
1026
- catch (alarmError) {
1027
- console.error('agent owner recovery rearm failed', alarmError);
1028
- }
1442
+ catch (recoveryError) {
1443
+ console.error('agent owner recovery failed', recoveryError);
1444
+ await withRecoveryLock(() => ensureOwnerRecoveryAlarm(options.stateStorage()));
1029
1445
  }
1030
1446
  throw error;
1031
1447
  }
1448
+ finally {
1449
+ // Unconditional: an entry left behind would answer every later probe
1450
+ // "live" for the lifetime of the isolate, turning a crashed start's
1451
+ // honest UNRESOLVABLE into an endless PENDING.
1452
+ startsInFlight.delete(ref.runId);
1453
+ }
1032
1454
  });
1033
1455
  },
1034
1456
  resolveBoundAgent: async (scope, input) => {
@@ -1058,6 +1480,41 @@ export function createThreadAgentHost(options) {
1058
1480
  ? preflightUrl.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length)
1059
1481
  : '';
1060
1482
  const preflightSegments = preflightSuffix.split('/').filter(Boolean);
1483
+ // The start holds the dispatch lock while its liveness probe must remain responsive.
1484
+ if (request.method === 'GET' &&
1485
+ preflightSegments.length === 4 &&
1486
+ preflightSegments[0] === 'runs' &&
1487
+ preflightSegments[3] === 'start-liveness') {
1488
+ instanceScopeFor(scope);
1489
+ const agentId = decode(preflightSegments[1]);
1490
+ const runId = decode(preflightSegments[2]);
1491
+ return json({
1492
+ live: agentId !== undefined &&
1493
+ runId !== undefined &&
1494
+ (startsInFlight.has(runId) ||
1495
+ executions.has(runId) ||
1496
+ (runtime?.agents.get(agentId)?.isRunLive(runId) ??
1497
+ globalRunRegistry.has(runId))),
1498
+ });
1499
+ }
1500
+ if (request.method === 'GET' &&
1501
+ preflightSegments.length === 3 &&
1502
+ preflightSegments[0] === 'runs' &&
1503
+ preflightUrl.searchParams.get('replay') === '1') {
1504
+ const ref = runRef(scope, {
1505
+ agentId: decode(preflightSegments[1]),
1506
+ runId: decode(preflightSegments[2]),
1507
+ threadId: scope.threadId,
1508
+ resourceId: preflightUrl.searchParams.get('resourceId'),
1509
+ });
1510
+ const state = await selectedAgentState(scope, ref);
1511
+ if (state &&
1512
+ (state.execution.owner.kind !== scope.principal.kind ||
1513
+ state.execution.owner.id !== scope.principal.id))
1514
+ throw new AgentHostRequestError(404, 'run not found');
1515
+ if (state?.kind === 'initial')
1516
+ return json({ kind: 'initial', execution: state.execution });
1517
+ }
1061
1518
  if (request.method === 'POST' &&
1062
1519
  preflightSegments.length === 4 &&
1063
1520
  preflightSegments[0] === 'runs' &&
@@ -1078,10 +1535,12 @@ export function createThreadAgentHost(options) {
1078
1535
  if (storedRun && storedRun.agentId !== ref.agentId) {
1079
1536
  throw new AgentHostRequestError(404, 'run not found');
1080
1537
  }
1081
- await snapshotExecutionFor(scope, ref);
1538
+ await snapshotExecutionFor(scope, ref, preflightUrl.searchParams.get('replay') === '1'
1539
+ ? undefined
1540
+ : await publicAgentState(scope, ref));
1082
1541
  const owner = await options.resourceAccess().owner('run', ref.runId);
1083
1542
  if (preflightUrl.searchParams.get('replay') !== '1') {
1084
- await scope.init.runtime.cancelActiveExecution(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, 'cancelled', [scope.principal, owner ?? scope.principal]);
1543
+ await scope.init.runtime.cancelActiveExecution(await workflowIdFor(scope, ref.agentId), ref.runId, 'cancelled', [scope.principal, owner ?? scope.principal]);
1085
1544
  preflightedTermination = true;
1086
1545
  }
1087
1546
  }
@@ -1105,9 +1564,24 @@ export function createThreadAgentHost(options) {
1105
1564
  if (request.method === 'POST' &&
1106
1565
  url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/start`) {
1107
1566
  const body = await objectBody(request);
1108
- if ('resourceOwner' in body || 'requestedBy' in body) {
1567
+ if ('resourceOwner' in body ||
1568
+ 'requestedBy' in body ||
1569
+ [
1570
+ 'mutationEpoch',
1571
+ 'startIdentity',
1572
+ 'agentStart',
1573
+ 'execution',
1574
+ 'tablePrefix',
1575
+ 'startToken',
1576
+ 'attemptToken',
1577
+ 'runOwnerGuard',
1578
+ 'onPreparedStartIdentity',
1579
+ ].some((key) => Object.hasOwn(body, key))) {
1109
1580
  throw new AgentHostRequestError(400, 'start owner and requester are derived from trusted provenance');
1110
1581
  }
1582
+ const startReservation = body.startReservation === undefined
1583
+ ? undefined
1584
+ : captureReservation(body.startReservation, 'started');
1111
1585
  const ref = runRef(scope, body);
1112
1586
  const requestedEntry = entryPath(body.entryPath);
1113
1587
  if (requestedEntry !== 'schedule.fire' &&
@@ -1116,6 +1590,7 @@ export function createThreadAgentHost(options) {
1116
1590
  }
1117
1591
  return json(await host.start(scope, {
1118
1592
  ...ref,
1593
+ startReservation,
1119
1594
  ...(typeof body.prompt === 'string'
1120
1595
  ? { prompt: body.prompt }
1121
1596
  : {}),
@@ -1123,6 +1598,17 @@ export function createThreadAgentHost(options) {
1123
1598
  threaded: body.threaded !== false,
1124
1599
  safeContext: safeContext(body.safeContext),
1125
1600
  providerOptions: providerOptions(body.providerOptions),
1601
+ // Validated, not trusted: this body is JSON, and the same string
1602
+ // reaches the execution fence's proof-only comparison.
1603
+ ...(body.idempotencyKey === undefined
1604
+ ? {}
1605
+ : {
1606
+ idempotencyKey: isPathSafeId(body.idempotencyKey)
1607
+ ? body.idempotencyKey
1608
+ : (() => {
1609
+ throw new AgentHostRequestError(400, 'idempotencyKey must be a URL-path-safe identifier');
1610
+ })(),
1611
+ }),
1126
1612
  ...(body.scheduleId !== undefined
1127
1613
  ? {
1128
1614
  scheduleId: isPathSafeId(body.scheduleId)
@@ -1148,7 +1634,7 @@ export function createThreadAgentHost(options) {
1148
1634
  const body = await objectBody(request);
1149
1635
  const ref = runRef(scope, body);
1150
1636
  const snapshotExecution = await snapshotExecutionFor(scope, ref);
1151
- await statusFor(scope, ref, snapshotExecution.threaded);
1637
+ await statusFor(scope, ref, snapshotExecution.state);
1152
1638
  const stored = await readRun(ref.runId);
1153
1639
  if (!stored ||
1154
1640
  stored.agentId !== ref.agentId ||
@@ -1199,15 +1685,8 @@ export function createThreadAgentHost(options) {
1199
1685
  });
1200
1686
  });
1201
1687
  const result = await envelopeFor(scope, ref, stored.principal, summary);
1202
- if (isTerminalRunStatus(summary.status)) {
1203
- await deleteAgentRunRecord(options.stateStorage(), ref.runId);
1204
- const recovery = await options
1205
- .stateStorage()
1206
- .get(ownerRecoveryKey(ref.runId));
1207
- if (recovery) {
1208
- await finalizeOwnerRecoveryBestEffort(recovery, summary);
1209
- }
1210
- }
1688
+ if (isTerminalRunStatus(summary.status))
1689
+ await finalizeTerminalAgentState(scope, ref, undefined, stored);
1211
1690
  return json(result);
1212
1691
  }
1213
1692
  const suffix = url.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length);
@@ -1227,17 +1706,35 @@ export function createThreadAgentHost(options) {
1227
1706
  runId,
1228
1707
  });
1229
1708
  if (segments.length === 3 && request.method === 'GET') {
1709
+ if (url.searchParams.get('replay') === '1') {
1710
+ const selected = await selectedAgentState(scope, ref);
1711
+ if (!selected)
1712
+ return json({ error: 'run not found' }, 404);
1713
+ if (selected.execution.owner.kind !== scope.principal.kind ||
1714
+ selected.execution.owner.id !== scope.principal.id)
1715
+ throw new AgentHostRequestError(404, 'run not found');
1716
+ if (selected.kind === 'initial')
1717
+ return json({ kind: 'initial', execution: selected.execution });
1718
+ const stored = await readRun(ref.runId);
1719
+ const value = await envelopeFor(scope, ref, stored?.principal ?? scope.principal, selected.summary);
1720
+ return json({
1721
+ kind: 'result',
1722
+ execution: selected.execution,
1723
+ value: publicAgentRunEnvelope(value, selected.execution, {
1724
+ ...ref,
1725
+ threadId: scope.threadId,
1726
+ }),
1727
+ });
1728
+ }
1230
1729
  if (url.searchParams.get('dispatch') === '1') {
1231
1730
  const key = ownerRecoveryKey(ref.runId);
1232
- const pending = await options
1233
- .stateStorage()
1234
- .get(key);
1235
- if (pending) {
1236
- await recoverOwner(scope.init.runtime, scope.threadId, key, pending, true);
1731
+ const pending = await options.stateStorage().get(key);
1732
+ if (pending !== undefined) {
1733
+ await recoverOwner(scope, key, pending);
1237
1734
  }
1238
1735
  return json(await statusFor(scope, ref));
1239
1736
  }
1240
- return json(await statusFor(scope, ref));
1737
+ return json(await statusFor(scope, ref, await publicAgentState(scope, ref)));
1241
1738
  }
1242
1739
  if (segments.length === 4 &&
1243
1740
  segments[3] === 'terminate' &&
@@ -1248,54 +1745,114 @@ export function createThreadAgentHost(options) {
1248
1745
  if (storedRun && storedRun.agentId !== ref.agentId) {
1249
1746
  throw new AgentHostRequestError(404, 'run not found');
1250
1747
  }
1251
- await snapshotExecutionFor(scope, ref);
1748
+ await snapshotExecutionFor(scope, ref, replayOnly ? undefined : await publicAgentState(scope, ref));
1252
1749
  const preflightOwner = await options
1253
1750
  .resourceAccess()
1254
1751
  .owner('run', ref.runId);
1255
1752
  if (!replayOnly && !preflightedTermination) {
1256
- await runtime.cancelActiveExecution(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, 'cancelled', [scope.principal, preflightOwner ?? scope.principal]);
1753
+ await runtime.cancelActiveExecution(await workflowIdFor(scope, ref.agentId), ref.runId, 'cancelled', [scope.principal, preflightOwner ?? scope.principal]);
1257
1754
  }
1258
1755
  const owner = await options.resourceAccess().owner('run', ref.runId);
1259
1756
  if (replayOnly) {
1260
- const existing = await runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
1757
+ const existing = await runtime.status(await workflowIdFor(scope, ref.agentId), ref.runId);
1261
1758
  if (existing?.status !== 'cancelled' &&
1262
1759
  existing?.status !== 'timed_out') {
1263
1760
  throw new AgentHostRequestError(404, 'run not found');
1264
1761
  }
1265
1762
  }
1266
- const transition = await runtime.terminateAsPrincipal(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, scope.principal, owner ?? scope.principal);
1267
- let summary = transition.summary;
1268
- if (!transition.cleanup.cleanupCompleted) {
1269
- await abandonApprovalsForRun(options.approvalService(scope), DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, transition.cleanup.status, options.systemPrincipalId ?? 'flowsafe-system');
1270
- const dispatch = transition.cleanup.scheduleDispatch;
1271
- if (dispatch) {
1272
- if (!options.discardScheduleDispatch) {
1273
- throw new Error('scheduled agent termination requires a dispatch-discard hook');
1763
+ const transition = await runtime.terminateAsPrincipal(await workflowIdFor(scope, ref.agentId), ref.runId, scope.principal, owner ?? scope.principal);
1764
+ const selected = await selectedAgentState(scope, ref, {
1765
+ includeLegacy: true,
1766
+ });
1767
+ if (!selected || selected.kind === 'initial')
1768
+ throw new RunStartPendingError();
1769
+ const journal = await options
1770
+ .stateStorage()
1771
+ .get(ownerRecoveryKey(ref.runId));
1772
+ if (journal !== undefined) {
1773
+ if (selected.kind === 'legacy')
1774
+ throw new ExecutionFenceUnreadableError('legacy run cleanup is unresolved');
1775
+ const recovery = validateOwnerRecovery(scope.threadId, ownerRecoveryKey(ref.runId), journal);
1776
+ const summary = await finalizeOwnerRecovery(scope, recovery, selected);
1777
+ return json(await envelopeFor(scope, ref, storedRun?.principal ?? scope.principal, summary));
1778
+ }
1779
+ const legacy = selected.kind === 'legacy' ? selected : undefined;
1780
+ const workflowId = selected.kind === 'legacy'
1781
+ ? selected.address.workflowId
1782
+ : selected.execution.workflowId;
1783
+ const cleanup = legacy
1784
+ ? terminalCleanupFor(lifecycleFromRequestContext(legacy.snapshot.requestContext))
1785
+ : transition.cleanup;
1786
+ if (!cleanup ||
1787
+ (legacy &&
1788
+ (legacy.summary.status !== transition.summary.status ||
1789
+ cleanup.revision !== transition.cleanup.revision ||
1790
+ cleanup.status !== transition.cleanup.status ||
1791
+ cleanup.scheduleDispatch?.scheduleId !==
1792
+ transition.cleanup.scheduleDispatch?.scheduleId ||
1793
+ cleanup.scheduleDispatch?.dispatchId !==
1794
+ transition.cleanup.scheduleDispatch?.dispatchId ||
1795
+ (transition.cleanup.cleanupCompleted &&
1796
+ !cleanup.cleanupCompleted))))
1797
+ throw new ExecutionFenceUnreadableError('legacy run cleanup is unresolved');
1798
+ const finish = async () => {
1799
+ const guard = legacy
1800
+ ? () => assertLegacyTerminalCurrent(scope, ref, legacy, storedRun)
1801
+ : undefined;
1802
+ if (guard)
1803
+ await guard();
1804
+ if (selected.kind !== 'legacy')
1805
+ await runtime.settleStartExecution(selected);
1806
+ let summary = legacy?.summary ?? transition.summary;
1807
+ if (!cleanup.cleanupCompleted) {
1808
+ if (guard)
1809
+ await guard();
1810
+ await abandonApprovalsForRun(options.approvalService(scope), workflowId, ref.runId, cleanup.status, options.systemPrincipalId ?? 'flowsafe-system');
1811
+ const dispatch = cleanup.scheduleDispatch;
1812
+ if (dispatch) {
1813
+ if (!options.discardScheduleDispatch) {
1814
+ throw new Error('scheduled agent termination requires a dispatch-discard hook');
1815
+ }
1816
+ if (guard)
1817
+ await guard();
1818
+ await options.discardScheduleDispatch(dispatch.scheduleId, dispatch.dispatchId, ref.runId);
1274
1819
  }
1275
- await options.discardScheduleDispatch(dispatch.scheduleId, dispatch.dispatchId, ref.runId);
1276
- }
1277
- const released = await options
1278
- .resourceAccess()
1279
- .release('run', ref.runId, owner ?? scope.principal);
1280
- if (!released) {
1281
- const current = await options
1820
+ if (guard)
1821
+ await guard();
1822
+ const released = await options
1282
1823
  .resourceAccess()
1283
- .owner('run', ref.runId);
1284
- if (current) {
1285
- throw new Error(`run '${ref.runId}' ownership could not be released`);
1824
+ .release('run', ref.runId, owner ?? scope.principal);
1825
+ if (!released) {
1826
+ const current = await options
1827
+ .resourceAccess()
1828
+ .owner('run', ref.runId);
1829
+ if (current) {
1830
+ throw new Error(`run '${ref.runId}' ownership could not be released`);
1831
+ }
1286
1832
  }
1833
+ if (guard)
1834
+ await guard();
1835
+ summary = await runtime.completeTerminalCleanup(workflowId, ref.runId, cleanup.revision);
1287
1836
  }
1288
- }
1289
- await finalizeTerminalAgentState(scope.threadId, ref.runId, summary);
1290
- if (!transition.cleanup.cleanupCompleted) {
1291
- summary = await runtime.completeTerminalCleanup(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId, transition.cleanup.revision);
1292
- }
1293
- return json(await envelopeFor(scope, ref, storedRun?.principal ?? scope.principal, summary));
1837
+ if (legacy) {
1838
+ if (guard)
1839
+ await guard();
1840
+ if (storedRun)
1841
+ await finalizeTerminalRecord(scope, ref.runId, storedRun, legacy);
1842
+ }
1843
+ else {
1844
+ await finalizeTerminalAgentState(scope, ref, selected, storedRun);
1845
+ }
1846
+ return json(await envelopeFor(scope, ref, storedRun?.principal ?? scope.principal, summary));
1847
+ };
1848
+ return legacy
1849
+ ? withBindingLock(() => withRecoveryLock(finish))
1850
+ : finish();
1294
1851
  }
1295
1852
  if (segments.length === 4 &&
1296
1853
  segments[3] === 'stream' &&
1297
1854
  request.method === 'GET') {
1298
- const run = await statusFor(scope, ref);
1855
+ const run = await statusFor(scope, ref, await publicAgentState(scope, ref));
1299
1856
  const offset = Number(url.searchParams.get('offset') ?? '0');
1300
1857
  if (!Number.isSafeInteger(offset) || offset < 0) {
1301
1858
  throw new AgentHostRequestError(400, 'invalid stream offset');