eve 0.82.0 → 0.83.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (528) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/NOTICE +1 -1
  3. package/dist/src/channel/pending-authorization.d.ts +5 -0
  4. package/dist/src/channel/pending-authorization.js +1 -1
  5. package/dist/src/channel/session.d.ts +2 -0
  6. package/dist/src/channel/session.js +1 -1
  7. package/dist/src/channel/types.d.ts +5 -0
  8. package/dist/src/chunks/{use-eve-agent-DTu78IAF.js → use-eve-agent-DnbG9c7c.js} +73 -14
  9. package/dist/src/chunks/{use-eve-agent-DlznYwQk.js → use-eve-agent-ZY7NQ2VW.js} +73 -14
  10. package/dist/src/cli/dev/local-server-child.js +1 -1
  11. package/dist/src/cli/dev/local-server-cleanup.js +1 -1
  12. package/dist/src/cli/dev/tui/question-panel.d.ts +4 -1
  13. package/dist/src/cli/dev/tui/question-panel.js +1 -1
  14. package/dist/src/cli/dev/tui/terminal-renderer.js +4 -4
  15. package/dist/src/cli/run.js +1 -1
  16. package/dist/src/client/eve-agent-store.d.ts +1 -1
  17. package/dist/src/client/eve-agent-store.js +1 -1
  18. package/dist/src/client/index.d.ts +1 -0
  19. package/dist/src/client/message-response.d.ts +18 -0
  20. package/dist/src/client/message-response.js +1 -1
  21. package/dist/src/client/session-controls.d.ts +6 -0
  22. package/dist/src/client/session-controls.js +1 -1
  23. package/dist/src/client/session.d.ts +4 -0
  24. package/dist/src/client/session.js +1 -1
  25. package/dist/src/compiled/.vendor-stamp.json +8 -8
  26. package/dist/src/compiled/@eve/catalog/index.js +1 -1
  27. package/dist/src/compiled/@workflow/core/events-consumer.d.ts +2 -0
  28. package/dist/src/compiled/@workflow/core/index.js +2 -2
  29. package/dist/src/compiled/@workflow/core/private.d.ts +5 -3
  30. package/dist/src/compiled/@workflow/core/private.js +1 -1
  31. package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +1 -37
  32. package/dist/src/compiled/@workflow/core/runtime/event-limit-warning.d.ts +32 -0
  33. package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +5 -6
  34. package/dist/src/compiled/@workflow/core/runtime/helpers.js +1 -1
  35. package/dist/src/compiled/@workflow/core/runtime/runs.d.ts +8 -0
  36. package/dist/src/compiled/@workflow/core/runtime/start.d.ts +16 -0
  37. package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +15 -18
  38. package/dist/src/compiled/@workflow/core/runtime/vm-mode.d.ts +20 -0
  39. package/dist/src/compiled/@workflow/core/runtime.js +4 -4
  40. package/dist/src/compiled/@workflow/core/seeded-nanoid.d.ts +2 -0
  41. package/dist/src/compiled/@workflow/core/serialization/compression.d.ts +14 -3
  42. package/dist/src/compiled/@workflow/core/serialization.d.ts +1 -1
  43. package/dist/src/compiled/@workflow/core/serialization.js +1 -1
  44. package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +0 -18
  45. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  46. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  47. package/dist/src/compiled/@workflow/errors/index.d.ts +48 -0
  48. package/dist/src/compiled/@workflow/errors/index.js +1 -1
  49. package/dist/src/compiled/@workflow/world/env-config.d.ts +24 -0
  50. package/dist/src/compiled/@workflow/world/events.d.ts +126 -7
  51. package/dist/src/compiled/@workflow/world/index.d.ts +3 -3
  52. package/dist/src/compiled/@workflow/world/interfaces.d.ts +59 -8
  53. package/dist/src/compiled/@workflow/world/queue.d.ts +71 -9
  54. package/dist/src/compiled/@workflow/world/recovery.d.ts +6 -0
  55. package/dist/src/compiled/@workflow/world/test-support/duplicate-event-fixtures.d.ts +3 -0
  56. package/dist/src/compiled/@workflow/world/test-support/in-band-fence-conformance.d.ts +46 -0
  57. package/dist/src/compiled/@workflow/world-local/index.js +5 -5
  58. package/dist/src/compiled/@workflow/world-vercel/index.js +18 -18
  59. package/dist/src/compiled/_chunks/workflow/{attribute-changes-BW-kbMMn.js → attribute-changes-7se_SE2q.js} +3 -3
  60. package/dist/src/compiled/_chunks/workflow/dist-CcnNPAp4.js +1 -0
  61. package/dist/src/compiled/_chunks/workflow/dist-S9cZRway.js +3 -0
  62. package/dist/src/compiled/_chunks/workflow/helpers-CxNRXH0a.js +1 -0
  63. package/dist/src/compiled/_chunks/workflow/private-DLYTSBbu.js +1 -0
  64. package/dist/src/compiled/_chunks/workflow/resume-hook-CPiIfe8r.js +1 -0
  65. package/dist/src/compiled/_chunks/workflow/{run-DzdAqdb1.js → run-BJSLCXR4.js} +6 -6
  66. package/dist/src/compiled/_chunks/workflow/serialization-B9gneT9Z.js +15 -0
  67. package/dist/src/compiled/_chunks/workflow/sleep-BL0oQs3R.js +1 -0
  68. package/dist/src/compiled/_chunks/workflow/{wait-until-xbRRDuUf.js → wait-until-BPou0RGO.js} +1 -1
  69. package/dist/src/compiled/_chunks/workflow/workflow-routes-BaljomCk.js +1 -0
  70. package/dist/src/compiled/{@ai-sdk/code-mode → run}/LICENSE +1 -1
  71. package/dist/src/compiled/run/index.d.ts +384 -0
  72. package/dist/src/compiled/run/index.js +650 -0
  73. package/dist/src/compiler/extension-compatibility.d.ts +21 -14
  74. package/dist/src/compiler/extension-compatibility.js +1 -1
  75. package/dist/src/compiler/manifest.js +1 -1
  76. package/dist/src/compiler/normalize-agent-config.js +1 -1
  77. package/dist/src/compiler/normalize-manifest.js +1 -1
  78. package/dist/src/compiler/normalize-sandbox.js +1 -1
  79. package/dist/src/compiler/workspace-resources.js +1 -1
  80. package/dist/src/context/build-callback-context.js +1 -1
  81. package/dist/src/context/build-dynamic-tools.js +1 -1
  82. package/dist/src/context/dynamic-skill-lifecycle.d.ts +2 -2
  83. package/dist/src/context/dynamic-skill-lifecycle.js +1 -1
  84. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  85. package/dist/src/context/prewarm.d.ts +27 -0
  86. package/dist/src/context/prewarm.js +1 -0
  87. package/dist/src/context/providers/sandbox.d.ts +7 -0
  88. package/dist/src/context/providers/sandbox.js +1 -1
  89. package/dist/src/context/run-step.js +1 -1
  90. package/dist/src/discover/extension-specifier.d.ts +1 -0
  91. package/dist/src/discover/extension-specifier.js +1 -1
  92. package/dist/src/discover/lib.d.ts +4 -3
  93. package/dist/src/discover/lib.js +1 -1
  94. package/dist/src/discover/named-source-directory.d.ts +3 -2
  95. package/dist/src/evals/cli/eval.d.ts +2 -0
  96. package/dist/src/evals/cli/eval.js +2 -2
  97. package/dist/src/evals/define-eval-config.d.ts +5 -4
  98. package/dist/src/evals/define-eval-config.js +1 -1
  99. package/dist/src/evals/index.d.ts +1 -1
  100. package/dist/src/evals/runner/artifacts.js +2 -2
  101. package/dist/src/evals/runner/attempt-label.d.ts +2 -0
  102. package/dist/src/evals/runner/attempt-label.js +1 -0
  103. package/dist/src/evals/runner/derive-run-facts.d.ts +12 -0
  104. package/dist/src/evals/runner/derive-run-facts.js +1 -1
  105. package/dist/src/evals/runner/execute-task.js +1 -1
  106. package/dist/src/evals/runner/reporters/braintrust.js +1 -1
  107. package/dist/src/evals/runner/reporters/console.js +1 -1
  108. package/dist/src/evals/runner/reporters/datadog.js +1 -1
  109. package/dist/src/evals/runner/reporters/junit.js +2 -2
  110. package/dist/src/evals/runner/reporters/types.d.ts +2 -0
  111. package/dist/src/evals/runner/run-evals.d.ts +5 -0
  112. package/dist/src/evals/runner/run-evals.js +1 -1
  113. package/dist/src/evals/session-manager.js +1 -1
  114. package/dist/src/evals/session.d.ts +4 -1
  115. package/dist/src/evals/session.js +2 -2
  116. package/dist/src/evals/types.d.ts +39 -2
  117. package/dist/src/eve-channel/index.js +1 -1
  118. package/dist/src/eve-channel/request.d.ts +0 -1
  119. package/dist/src/eve-channel/request.js +2 -2
  120. package/dist/src/execution/agent-sessions/context.d.ts +1 -1
  121. package/dist/src/execution/agent-sessions/context.js +1 -1
  122. package/dist/src/execution/coordination-dispatch-shared.d.ts +3 -0
  123. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  124. package/dist/src/execution/dynamic-workflow/program-step.d.ts +7 -7
  125. package/dist/src/execution/dynamic-workflow/program-step.js +1 -1
  126. package/dist/src/execution/dynamic-workflow/schema.d.ts +18 -11
  127. package/dist/src/execution/dynamic-workflow/schema.js +1 -1
  128. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  129. package/dist/src/execution/dynamic-workflow/workflow.js +1 -1
  130. package/dist/src/execution/eve-workflow-attributes.d.ts +3 -1
  131. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  132. package/dist/src/execution/invoke-tool.js +1 -1
  133. package/dist/src/execution/sandbox/abort-bound-session.js +1 -1
  134. package/dist/src/execution/sandbox/active-connections.d.ts +28 -0
  135. package/dist/src/execution/sandbox/active-connections.js +1 -0
  136. package/dist/src/execution/sandbox/bindings/docker-cli.d.ts +10 -2
  137. package/dist/src/execution/sandbox/bindings/docker-cli.js +2 -2
  138. package/dist/src/execution/sandbox/bindings/docker-connection.d.ts +15 -0
  139. package/dist/src/execution/sandbox/bindings/docker-connection.js +2 -0
  140. package/dist/src/execution/sandbox/bindings/docker-container.d.ts +2 -0
  141. package/dist/src/execution/sandbox/bindings/docker-container.js +1 -1
  142. package/dist/src/execution/sandbox/bindings/docker-network.d.ts +5 -0
  143. package/dist/src/execution/sandbox/bindings/docker-network.js +1 -1
  144. package/dist/src/execution/sandbox/bindings/docker-templates.js +1 -1
  145. package/dist/src/execution/sandbox/bindings/docker.d.ts +12 -15
  146. package/dist/src/execution/sandbox/bindings/docker.js +1 -1
  147. package/dist/src/execution/sandbox/bindings/just-bash-runtime.d.ts +19 -29
  148. package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
  149. package/dist/src/execution/sandbox/bindings/just-bash.d.ts +2 -4
  150. package/dist/src/execution/sandbox/bindings/just-bash.js +1 -1
  151. package/dist/src/execution/sandbox/bindings/local-provider-utils.d.ts +0 -20
  152. package/dist/src/execution/sandbox/bindings/local-provider-utils.js +1 -1
  153. package/dist/src/execution/sandbox/bindings/local.d.ts +4 -6
  154. package/dist/src/execution/sandbox/bindings/local.js +1 -1
  155. package/dist/src/execution/sandbox/bindings/vercel-base-runtime.d.ts +2 -0
  156. package/dist/src/execution/sandbox/bindings/vercel-base-runtime.js +2 -2
  157. package/dist/src/execution/sandbox/bindings/vercel-errors.js +2 -2
  158. package/dist/src/execution/sandbox/bindings/vercel-lifecycle.d.ts +7 -5
  159. package/dist/src/execution/sandbox/bindings/vercel-lifecycle.js +1 -1
  160. package/dist/src/execution/sandbox/bindings/vercel.d.ts +5 -11
  161. package/dist/src/execution/sandbox/bindings/vercel.js +1 -2
  162. package/dist/src/execution/sandbox/development-cleanup.d.ts +0 -1
  163. package/dist/src/execution/sandbox/development-cleanup.js +1 -1
  164. package/dist/src/execution/sandbox/development-lazy-prewarm.js +1 -1
  165. package/dist/src/execution/sandbox/development-run.d.ts +0 -2
  166. package/dist/src/execution/sandbox/development-run.js +1 -1
  167. package/dist/src/execution/sandbox/dockerfile.d.ts +0 -4
  168. package/dist/src/execution/sandbox/dockerfile.js +1 -1
  169. package/dist/src/execution/sandbox/ensure.d.ts +31 -11
  170. package/dist/src/execution/sandbox/ensure.js +1 -1
  171. package/dist/src/execution/sandbox/glob-tool.js +3 -3
  172. package/dist/src/execution/sandbox/grep-tool.js +1 -1
  173. package/dist/src/execution/sandbox/logging-session.js +1 -1
  174. package/dist/src/execution/sandbox/prewarm.d.ts +23 -3
  175. package/dist/src/execution/sandbox/prewarm.js +2 -1
  176. package/dist/src/execution/sandbox/read-file.js +1 -1
  177. package/dist/src/execution/sandbox/require-sandbox.d.ts +3 -2
  178. package/dist/src/execution/sandbox/require-sandbox.js +1 -1
  179. package/dist/src/execution/sandbox/ripgrep-probe.js +1 -1
  180. package/dist/src/execution/sandbox/session.d.ts +10 -20
  181. package/dist/src/execution/sandbox/session.js +2 -2
  182. package/dist/src/execution/session/admission.js +1 -1
  183. package/dist/src/execution/session/checkpoint-migrations.js +1 -1
  184. package/dist/src/execution/session/entry-input.d.ts +5 -4
  185. package/dist/src/execution/session/entry.js +1 -1
  186. package/dist/src/execution/session/handoff-state.d.ts +5 -0
  187. package/dist/src/execution/session/handoff-state.js +1 -0
  188. package/dist/src/execution/session/handoff-steps.d.ts +1 -5
  189. package/dist/src/execution/session/handoff-steps.js +1 -1
  190. package/dist/src/execution/session/handoff.d.ts +2 -1
  191. package/dist/src/execution/session/handoff.js +1 -1
  192. package/dist/src/execution/session/handover-tracing.d.ts +3 -0
  193. package/dist/src/execution/session/handover-tracing.js +1 -0
  194. package/dist/src/execution/session/input-queue.d.ts +3 -0
  195. package/dist/src/execution/session/input-queue.js +1 -1
  196. package/dist/src/execution/session/next-input.d.ts +3 -0
  197. package/dist/src/execution/session/next-input.js +1 -1
  198. package/dist/src/execution/session/prewarm-step.d.ts +13 -0
  199. package/dist/src/execution/session/prewarm-step.js +1 -0
  200. package/dist/src/execution/session/program.d.ts +4 -1
  201. package/dist/src/execution/session/program.js +1 -1
  202. package/dist/src/execution/session/state-cursor.d.ts +11 -0
  203. package/dist/src/execution/session/state-cursor.js +1 -1
  204. package/dist/src/execution/session/timeout-control.d.ts +4 -0
  205. package/dist/src/execution/session/timeout-control.js +1 -1
  206. package/dist/src/execution/session/turn-control.d.ts +5 -2
  207. package/dist/src/execution/session/turn-control.js +1 -1
  208. package/dist/src/execution/session/turn-step-types.d.ts +2 -0
  209. package/dist/src/execution/session/turn-step.js +1 -1
  210. package/dist/src/execution/session/turn.d.ts +1 -0
  211. package/dist/src/execution/session/turn.js +1 -1
  212. package/dist/src/execution/session-inbox/inbox.d.ts +17 -1
  213. package/dist/src/execution/session-inbox/inbox.js +1 -1
  214. package/dist/src/execution/session-inbox/protocol.d.ts +2 -1
  215. package/dist/src/execution/session-inbox/protocol.js +1 -1
  216. package/dist/src/execution/session-inbox/resume.d.ts +2 -1
  217. package/dist/src/execution/session-inbox/resume.js +1 -1
  218. package/dist/src/execution/session-prewarm.d.ts +8 -0
  219. package/dist/src/execution/session-prewarm.js +1 -0
  220. package/dist/src/execution/skills/instructions.js +1 -1
  221. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  222. package/dist/src/execution/tools/workflow/body.js +1 -1
  223. package/dist/src/execution/tools/workflow/step-context.d.ts +11 -0
  224. package/dist/src/execution/tools/workflow/step-execution.js +1 -1
  225. package/dist/src/execution/tools/workflow/step.js +1 -1
  226. package/dist/src/execution/workflow-runtime.js +1 -1
  227. package/dist/src/extensions/git/extension/lib/github-shell-schema.js +1 -1
  228. package/dist/src/framework/sources/modules/sandbox.d.ts +1 -1
  229. package/dist/src/harness/attachment-staging.d.ts +3 -7
  230. package/dist/src/harness/attachment-staging.js +1 -1
  231. package/dist/src/harness/hitl/index.d.ts +2 -1
  232. package/dist/src/harness/hitl/index.js +1 -1
  233. package/dist/src/harness/hitl/view.d.ts +1 -0
  234. package/dist/src/harness/hitl/view.js +1 -0
  235. package/dist/src/harness/model-call/run.js +1 -1
  236. package/dist/src/harness/semantic-errors/rules/sandbox.d.ts +3 -5
  237. package/dist/src/harness/semantic-errors/rules/sandbox.js +1 -1
  238. package/dist/src/harness/step/prompt.js +1 -1
  239. package/dist/src/harness/tool-history-repair.d.ts +9 -0
  240. package/dist/src/harness/tool-history-repair.js +1 -0
  241. package/dist/src/harness/tool-model-output.d.ts +19 -3
  242. package/dist/src/harness/tool-model-output.js +1 -1
  243. package/dist/src/internal/application/compiled-artifacts.js +8 -4
  244. package/dist/src/internal/application/optional-package-import.d.ts +10 -0
  245. package/dist/src/internal/application/optional-package-import.js +1 -1
  246. package/dist/src/internal/application/stamped-package-version.js +1 -1
  247. package/dist/src/internal/attachments/limited-read.d.ts +2 -2
  248. package/dist/src/internal/authored-module-build-options.d.ts +6 -0
  249. package/dist/src/internal/authored-module-build-options.js +1 -1
  250. package/dist/src/internal/authored-module-cache.d.ts +10 -0
  251. package/dist/src/internal/authored-module-cache.js +1 -0
  252. package/dist/src/internal/authored-module-graph.js +1 -1
  253. package/dist/src/internal/authored-module-loader.js +1 -1
  254. package/dist/src/internal/authored-relative-extension-resolver.js +1 -1
  255. package/dist/src/internal/bundler/nitro-rolldown.d.ts +3 -1
  256. package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
  257. package/dist/src/internal/bundler/pseudo-packages.d.ts +11 -0
  258. package/dist/src/internal/bundler/pseudo-packages.js +1 -0
  259. package/dist/src/internal/nitro/host/build-extension.d.ts +6 -0
  260. package/dist/src/internal/nitro/host/build-extension.js +2 -2
  261. package/dist/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.d.ts +3 -1
  262. package/dist/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.js +3 -5
  263. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +2 -3
  264. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  265. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.d.ts +2 -0
  266. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -1
  267. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  268. package/dist/src/internal/nitro/host/dev-build-host.d.ts +83 -0
  269. package/dist/src/internal/nitro/host/dev-build-host.js +1 -0
  270. package/dist/src/internal/nitro/host/dev-build-operations.d.ts +6 -0
  271. package/dist/src/internal/nitro/host/dev-build-operations.js +1 -0
  272. package/dist/src/internal/nitro/host/dev-build-process.d.ts +1 -0
  273. package/dist/src/internal/nitro/host/dev-build-process.js +1 -0
  274. package/dist/src/internal/nitro/host/development-runtime-prune-plugin.d.ts +4 -1
  275. package/dist/src/internal/nitro/host/development-runtime-prune-plugin.js +3 -2
  276. package/dist/src/internal/nitro/host/drained-nitro-dev-server.d.ts +13 -0
  277. package/dist/src/internal/nitro/host/drained-nitro-dev-server.js +1 -1
  278. package/dist/src/internal/nitro/host/optional-engine-dependency-plugin.js +1 -1
  279. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +3 -0
  280. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  281. package/dist/src/internal/nitro/host/sandbox-shutdown-plugin.js +1 -1
  282. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  283. package/dist/src/internal/nitro/host/start-production-server.js +3 -3
  284. package/dist/src/internal/nitro/host/workflow-sandbox-runtime-plugin.js +1 -1
  285. package/dist/src/internal/nitro/host.js +1 -1
  286. package/dist/src/internal/workflow/local-world-delivery-auth.d.ts +17 -0
  287. package/dist/src/internal/workflow/local-world-delivery-auth.js +1 -0
  288. package/dist/src/internal/workflow/queue-namespace.d.ts +2 -0
  289. package/dist/src/internal/workflow/queue-namespace.js +1 -1
  290. package/dist/src/internal/workflow-bundle/builder-support.d.ts +0 -1
  291. package/dist/src/internal/workflow-bundle/builder-support.js +2 -2
  292. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  293. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
  294. package/dist/src/internal/workflow-bundle/vercel-workflow-output.d.ts +1 -1
  295. package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
  296. package/dist/src/protocol/prewarm-session.d.ts +14 -0
  297. package/dist/src/protocol/prewarm-session.js +1 -0
  298. package/dist/src/protocol/routes.d.ts +2 -2
  299. package/dist/src/public/channels/discord/authorization.d.ts +45 -0
  300. package/dist/src/public/channels/discord/authorization.js +3 -0
  301. package/dist/src/public/channels/discord/defaults.d.ts +14 -3
  302. package/dist/src/public/channels/discord/defaults.js +2 -2
  303. package/dist/src/public/channels/discord/discordChannel.d.ts +15 -1
  304. package/dist/src/public/channels/discord/discordChannel.js +1 -1
  305. package/dist/src/public/channels/discord/gateway/connection.d.ts +26 -0
  306. package/dist/src/public/channels/discord/gateway/connection.js +1 -0
  307. package/dist/src/public/channels/discord/gateway/forwarder.d.ts +14 -0
  308. package/dist/src/public/channels/discord/gateway/forwarder.js +1 -0
  309. package/dist/src/public/channels/discord/gateway/index.d.ts +59 -0
  310. package/dist/src/public/channels/discord/gateway/index.js +1 -0
  311. package/dist/src/public/channels/discord/inbound.d.ts +10 -3
  312. package/dist/src/public/channels/discord/inbound.js +2 -2
  313. package/dist/src/public/channels/discord/index.d.ts +3 -2
  314. package/dist/src/public/channels/discord/index.js +1 -1
  315. package/dist/src/public/channels/discord/messages.d.ts +116 -0
  316. package/dist/src/public/channels/discord/messages.js +2 -0
  317. package/dist/src/public/channels/github/checkout.js +1 -1
  318. package/dist/src/public/channels/linq/linqChannel.d.ts +4 -1
  319. package/dist/src/public/channels/linq/linqChannel.js +1 -1
  320. package/dist/src/public/channels/photon/photonIMessageChannel.js +1 -1
  321. package/dist/src/public/channels/same-environment-oidc.d.ts +7 -0
  322. package/dist/src/public/channels/same-environment-oidc.js +1 -0
  323. package/dist/src/public/definitions/channel.js +1 -1
  324. package/dist/src/public/definitions/sandbox.d.ts +1 -1
  325. package/dist/src/public/next/server.js +1 -1
  326. package/dist/src/public/sandbox/docker-sandbox.d.ts +6 -1
  327. package/dist/src/public/sandbox/docker.d.ts +1 -8
  328. package/dist/src/public/sandbox/index.d.ts +3 -3
  329. package/dist/src/public/sandbox/just-bash-sandbox.d.ts +87 -7
  330. package/dist/src/public/sandbox/just-bash.d.ts +1 -1
  331. package/dist/src/public/sandbox/provider.d.ts +5 -1
  332. package/dist/src/public/sandbox/provider.js +1 -1
  333. package/dist/src/public/sandbox/vercel-sandbox.d.ts +16 -9
  334. package/dist/src/public/sandbox/vercel.d.ts +0 -1
  335. package/dist/src/public/sandbox/vercel.js +1 -1
  336. package/dist/src/public/tools/agent.d.ts +8 -1
  337. package/dist/src/public/tools/agent.js +1 -1
  338. package/dist/src/react/use-eve-agent.d.ts +1 -1
  339. package/dist/src/runtime/agent/resolve-model.js +1 -1
  340. package/dist/src/runtime/connections/openapi-client.d.ts +2 -0
  341. package/dist/src/runtime/connections/openapi-client.js +1 -1
  342. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  343. package/dist/src/runtime/resolve-agent.js +1 -1
  344. package/dist/src/runtime/resolve-channel.js +1 -1
  345. package/dist/src/runtime/resolve-sandbox.js +1 -1
  346. package/dist/src/runtime/sandbox/prepared-artifacts.js +1 -1
  347. package/dist/src/runtime/sandbox/registry.d.ts +2 -0
  348. package/dist/src/runtime/sandbox/registry.js +1 -1
  349. package/dist/src/runtime/subagents/workflow.d.ts +6 -0
  350. package/dist/src/runtime/subagents/workflow.js +1 -1
  351. package/dist/src/runtime/workspace/seed-files.d.ts +9 -12
  352. package/dist/src/runtime/workspace/seed-files.js +1 -1
  353. package/dist/src/runtime/workspace/spec.d.ts +1 -1
  354. package/dist/src/runtime/workspace/spec.js +1 -1
  355. package/dist/src/runtime/workspace/types.d.ts +2 -6
  356. package/dist/src/sandbox/provider.d.ts +185 -0
  357. package/dist/src/sandbox/provider.js +1 -0
  358. package/dist/src/sandbox/providers/default.d.ts +20 -19
  359. package/dist/src/sandbox/providers/default.js +1 -1
  360. package/dist/src/sandbox/providers/docker.d.ts +5 -2
  361. package/dist/src/sandbox/providers/docker.js +1 -1
  362. package/dist/src/sandbox/providers/just-bash.d.ts +4 -3
  363. package/dist/src/sandbox/providers/just-bash.js +1 -1
  364. package/dist/src/sandbox/providers/vercel.d.ts +4 -10
  365. package/dist/src/sandbox/providers/vercel.js +1 -1
  366. package/dist/src/sandbox/providers.d.ts +0 -1
  367. package/dist/src/sandbox/providers.js +1 -1
  368. package/dist/src/sandbox/state.d.ts +61 -0
  369. package/dist/src/sandbox/state.js +1 -1
  370. package/dist/src/self-modification/deployed-sandbox.d.ts +4 -9
  371. package/dist/src/self-modification/deployed-sandbox.js +1 -1
  372. package/dist/src/self-modification/filesystem.d.ts +3 -3
  373. package/dist/src/self-modification/remote/config.d.ts +2 -2
  374. package/dist/src/self-modification/remote/config.js +1 -1
  375. package/dist/src/self-modification/setup.d.ts +0 -1
  376. package/dist/src/self-modification/setup.js +8 -8
  377. package/dist/src/setup/integrations/discord/api.d.ts +7 -0
  378. package/dist/src/setup/integrations/discord/api.js +1 -1
  379. package/dist/src/setup/integrations/discord/daemon.d.ts +18 -0
  380. package/dist/src/setup/integrations/discord/daemon.js +21 -0
  381. package/dist/src/setup/integrations/discord/setup.d.ts +24 -4
  382. package/dist/src/setup/integrations/discord/setup.js +5 -4
  383. package/dist/src/setup/integrations/self-modification/setup.js +1 -1
  384. package/dist/src/setup/scaffold/create/project.js +1 -1
  385. package/dist/src/setup/scaffold/update/web-options.js +1 -1
  386. package/dist/src/setup/scaffold/version-tokens.d.ts +0 -1
  387. package/dist/src/setup/scaffold/version-tokens.js +1 -1
  388. package/dist/src/shared/agent-definition.d.ts +2 -0
  389. package/dist/src/shared/built-server-start-failure.d.ts +12 -0
  390. package/dist/src/shared/built-server-start-failure.js +3 -0
  391. package/dist/src/shared/framework-eve-server.d.ts +2 -0
  392. package/dist/src/shared/framework-eve-server.js +2 -2
  393. package/dist/src/shared/sandbox-environment.d.ts +4 -10
  394. package/dist/src/shared/sandbox-environment.js +1 -1
  395. package/dist/src/shared/sandbox-network-policy.d.ts +45 -9
  396. package/dist/src/shared/sandbox-provider.d.ts +0 -103
  397. package/dist/src/shared/sandbox-provider.js +1 -1
  398. package/dist/src/shared/sandbox-recorded-data-error.d.ts +4 -0
  399. package/dist/src/shared/sandbox-recorded-data-error.js +1 -0
  400. package/dist/src/shared/sandbox-session-gone-error.d.ts +12 -0
  401. package/dist/src/shared/sandbox-session-gone-error.js +1 -0
  402. package/dist/src/shared/sandbox-session.d.ts +97 -83
  403. package/dist/src/shared/sandbox-template-error.d.ts +19 -4
  404. package/dist/src/shared/sandbox-template-error.js +1 -1
  405. package/dist/src/shared/sandbox-tool-session-error.d.ts +4 -0
  406. package/dist/src/shared/sandbox-tool-session-error.js +1 -0
  407. package/dist/src/shared/skill-package.js +1 -1
  408. package/dist/src/shared/skill-paths.d.ts +4 -5
  409. package/dist/src/shared/skill-paths.js +2 -2
  410. package/dist/src/shared/workflow-sandbox.d.ts +4 -41
  411. package/dist/src/shared/workflow-sandbox.js +1 -1
  412. package/dist/src/svelte/index.js +1 -1
  413. package/dist/src/svelte/use-eve-agent.d.ts +1 -1
  414. package/dist/src/svelte/use-eve-agent.js +1 -1
  415. package/dist/src/tools/definition.js +1 -1
  416. package/dist/src/tools/durable-callbacks.d.ts +5 -1
  417. package/dist/src/tools/durable-callbacks.js +1 -1
  418. package/dist/src/tools/dynamic.d.ts +3 -3
  419. package/dist/src/tools/model-output.d.ts +23 -5
  420. package/dist/src/tools/model-output.js +1 -1
  421. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  422. package/dist/src/tools/provided/glob.js +1 -1
  423. package/dist/src/tools/provided/grep.js +1 -1
  424. package/dist/src/tools/provided/read-file.js +1 -1
  425. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  426. package/dist/src/tools/provided/workflow.js +1 -1
  427. package/dist/src/tools/provided/write-file.js +1 -1
  428. package/dist/src/tools/workflow-definition.d.ts +19 -4
  429. package/dist/src/vue/index.js +1 -1
  430. package/dist/src/vue/use-eve-agent.d.ts +1 -1
  431. package/dist/src/vue/use-eve-agent.js +1 -1
  432. package/docs/channels/custom.mdx +3 -3
  433. package/docs/channels/discord.mdx +279 -7
  434. package/docs/channels/eve.mdx +13 -2
  435. package/docs/channels/linq.mdx +2 -2
  436. package/docs/channels/mcp.mdx +2 -2
  437. package/docs/channels/overview.mdx +1 -1
  438. package/docs/channels/photon.mdx +1 -1
  439. package/docs/concepts/built-in-tools.md +31 -8
  440. package/docs/concepts/execution-model-and-durability.mdx +6 -101
  441. package/docs/concepts/security-model.md +2 -0
  442. package/docs/concepts/sessions-runs-and-streaming.md +44 -36
  443. package/docs/connections/openapi.mdx +2 -0
  444. package/docs/evals/overview.mdx +1 -1
  445. package/docs/evals/reporters.mdx +5 -5
  446. package/docs/evals/running.mdx +19 -1
  447. package/docs/guides/client/messages.mdx +1 -1
  448. package/docs/guides/deployment/overview.md +4 -4
  449. package/docs/guides/deployment/self-hosting.md +50 -1
  450. package/docs/guides/dev-tui.md +1 -1
  451. package/docs/guides/dynamic-capabilities.md +2 -2
  452. package/docs/guides/frontend/overview.mdx +34 -10
  453. package/docs/guides/instrumentation/agent-runs.mdx +16 -0
  454. package/docs/guides/instrumentation/otel.mdx +23 -0
  455. package/docs/guides/self-modification.md +1 -1
  456. package/docs/guides/session-context.md +1 -1
  457. package/docs/instructions.mdx +1 -1
  458. package/docs/meta.json +1 -0
  459. package/docs/reference/agent-files.md +4 -4
  460. package/docs/reference/cli.md +24 -17
  461. package/docs/reference/typescript-api.md +9 -3
  462. package/docs/sandbox/custom-providers.mdx +254 -0
  463. package/docs/sandbox/default.mdx +71 -4
  464. package/docs/sandbox/docker.mdx +15 -3
  465. package/docs/sandbox/index.mdx +32 -106
  466. package/docs/sandbox/just-bash.mdx +54 -0
  467. package/docs/sandbox/meta.json +9 -1
  468. package/docs/sandbox/troubleshooting.mdx +215 -0
  469. package/docs/sandbox/vercel.mdx +48 -7
  470. package/docs/skills.mdx +1 -1
  471. package/docs/subagents/index.mdx +2 -2
  472. package/docs/tools/overview.mdx +20 -1
  473. package/docs/tools/workflows.mdx +73 -5
  474. package/docs/tutorial/run-analysis.mdx +2 -2
  475. package/docs/use-cases.mdx +250 -0
  476. package/package.json +14 -20
  477. package/dist/src/compiled/@ai-sdk/code-mode/_run.d.ts +0 -1
  478. package/dist/src/compiled/@ai-sdk/code-mode/index.d.ts +0 -325
  479. package/dist/src/compiled/@ai-sdk/code-mode/index.js +0 -660
  480. package/dist/src/compiled/_chunks/workflow/dist-CyBgVS7g.js +0 -1
  481. package/dist/src/compiled/_chunks/workflow/dist-T5NnW-0k.js +0 -3
  482. package/dist/src/compiled/_chunks/workflow/helpers-DlLD3ov_.js +0 -1
  483. package/dist/src/compiled/_chunks/workflow/private-tQUuwBoQ.js +0 -1
  484. package/dist/src/compiled/_chunks/workflow/resume-hook-DMsV_b4n.js +0 -1
  485. package/dist/src/compiled/_chunks/workflow/serialization-DPdYS_w2.js +0 -16
  486. package/dist/src/compiled/_chunks/workflow/sleep-BY6leHh8.js +0 -1
  487. package/dist/src/compiled/_chunks/workflow/workflow-routes-CwqB063q.js +0 -1
  488. package/dist/src/execution/sandbox/active-handles.d.ts +0 -32
  489. package/dist/src/execution/sandbox/active-handles.js +0 -1
  490. package/dist/src/execution/sandbox/bindings/docker-session.d.ts +0 -6
  491. package/dist/src/execution/sandbox/bindings/docker-session.js +0 -2
  492. package/dist/src/execution/sandbox/bindings/immutable-resources.d.ts +0 -15
  493. package/dist/src/execution/sandbox/bindings/immutable-resources.js +0 -2
  494. package/dist/src/execution/sandbox/bindings/microsandbox-create.d.ts +0 -12
  495. package/dist/src/execution/sandbox/bindings/microsandbox-create.js +0 -1
  496. package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.d.ts +0 -42
  497. package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.js +0 -1
  498. package/dist/src/execution/sandbox/bindings/microsandbox-metadata.d.ts +0 -29
  499. package/dist/src/execution/sandbox/bindings/microsandbox-metadata.js +0 -1
  500. package/dist/src/execution/sandbox/bindings/microsandbox-network.d.ts +0 -18
  501. package/dist/src/execution/sandbox/bindings/microsandbox-network.js +0 -1
  502. package/dist/src/execution/sandbox/bindings/microsandbox-options.d.ts +0 -37
  503. package/dist/src/execution/sandbox/bindings/microsandbox-options.js +0 -1
  504. package/dist/src/execution/sandbox/bindings/microsandbox-platform.d.ts +0 -21
  505. package/dist/src/execution/sandbox/bindings/microsandbox-platform.js +0 -21
  506. package/dist/src/execution/sandbox/bindings/microsandbox-process.d.ts +0 -3
  507. package/dist/src/execution/sandbox/bindings/microsandbox-process.js +0 -1
  508. package/dist/src/execution/sandbox/bindings/microsandbox-provider-state.d.ts +0 -11
  509. package/dist/src/execution/sandbox/bindings/microsandbox-provider-state.js +0 -1
  510. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.d.ts +0 -82
  511. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +0 -1
  512. package/dist/src/execution/sandbox/bindings/microsandbox-templates.d.ts +0 -12
  513. package/dist/src/execution/sandbox/bindings/microsandbox-templates.js +0 -1
  514. package/dist/src/execution/sandbox/bindings/microsandbox.d.ts +0 -16
  515. package/dist/src/execution/sandbox/bindings/microsandbox.js +0 -1
  516. package/dist/src/execution/sandbox/provider-host-development.d.ts +0 -2
  517. package/dist/src/execution/sandbox/provider-host-development.js +0 -1
  518. package/dist/src/execution/sandbox/provider-host.d.ts +0 -2
  519. package/dist/src/execution/sandbox/provider-host.js +0 -1
  520. package/dist/src/execution/tool-session/sandbox.d.ts +0 -22
  521. package/dist/src/execution/tool-session/sandbox.js +0 -1
  522. package/dist/src/public/sandbox/microsandbox-sandbox.d.ts +0 -48
  523. package/dist/src/public/sandbox/microsandbox-sandbox.js +0 -1
  524. package/dist/src/public/sandbox/microsandbox.d.ts +0 -9
  525. package/dist/src/public/sandbox/microsandbox.js +0 -1
  526. package/dist/src/sandbox/providers/microsandbox.d.ts +0 -12
  527. package/dist/src/sandbox/providers/microsandbox.js +0 -1
  528. package/docs/sandbox/microsandbox.mdx +0 -31
@@ -13,7 +13,7 @@ import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.
13
13
  * A newer successor must always accept older checkpoints: every bump adds the
14
14
  * upgrade from the previous version in `checkpoint-migrations.ts`.
15
15
  */
16
- export declare const SESSION_CHECKPOINT_VERSION = 16;
16
+ export declare const SESSION_CHECKPOINT_VERSION = 17;
17
17
  /** Everything a successor needs to continue an idle session. Hooks are derived from the state. */
18
18
  export interface SessionCheckpoint {
19
19
  readonly admittedDeliveryKeys: readonly string[];
@@ -115,6 +115,7 @@ export declare class SessionHandoff {
115
115
  * parks until the next one arrives.
116
116
  */
117
117
  tryCompactionTransfer(state: SessionTransferState): Promise<SessionTransferOutcome>;
118
+ tryPrewarmTransfer(state: SessionTransferState, targetDeploymentId: string, sessionTimeoutDeadline: Date | undefined): Promise<SessionTransferOutcome>;
118
119
  private transfer;
119
120
  /**
120
121
  * The session was taken over while no attempt was open. This run leaves as
@@ -1 +1 @@
1
- import{isObject}from"#shared/guards.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{hasRunEndedStep,reportHandoverPartStuckStep,reportSessionHandoffRetainedStep,reportSessionTakenOverOutsideAttemptStep,sendSessionHandoverPartStep,startSuccessorStep}from"#execution/session/handoff-steps.js";import{abandonHandoverIfRunEnds,watchRunEnd}from"#execution/session/run-watch.js";import{readAcceptedDeploymentId}from"#execution/session/accepted-deployment.js";const SESSION_CHECKPOINT_VERSION=16;function sessionAnchorToken(e){return`${e}:anchor`}function handoffLeaseToken(e){return`eve:handoff:lease:${e}`}const HANDOFF_LEASE_RETENTION=`7d`;function verdictRunId(e){return e.kind===`verdict`&&e.verdict.kind!==`active`?e.verdict.runId:void 0}async function sendSessionHandover(e){let{attemptKey:t,sessionId:n}=e,r=e.payloads.filter(e=>e.kind!==`handover`);for(let[e,i]of r.entries())if(await sendHandoverPart({attemptKey:t,index:e,payloads:[i]},n)===`session-ended`)return;await sendHandoverPart({attemptKey:t,final:!0,index:r.length,payloads:[]},n)}async function sendHandoverPart(e,t){for(let n=1,r=1;;n++)try{return await sendSessionHandoverPartStep({part:e,sessionId:t})}catch(i){n===HANDOVER_PART_FAILURES_BEFORE_REPORT&&await reportHandoverPartStuckStep({attemptKey:e.attemptKey,error:isObject(i)&&typeof i.message==`string`?i.message:void 0,failures:n,index:e.index,sessionId:t}).catch(()=>{}),await sleep(r*1e3),r=Math.min(r*2,60)}}const HANDOVER_PART_FAILURES_BEFORE_REPORT=5;var SessionHandoff=class{input;anchor;incompatibleTargetDeploymentIds=new Set;attempts=0;worldUnsupported=!1;constructor(e){this.input=e}async tryTransfer(e,t){let{delivery:n}=e,r=readAcceptedDeploymentId(n);return r===void 0?{kind:`retained`,reason:`missing-deployment`}:r===this.input.deploymentId?{kind:`retained`,reason:`same-deployment`}:this.incompatibleTargetDeploymentIds.has(r)?{kind:`retained`,reason:`known-incompatible`}:e.handoffEligible?await this.transfer(t,r,{delivery:n}):{kind:`retained`,reason:`busy`}}async tryCompactionTransfer(e){let{deploymentId:t}=this.input;return this.incompatibleTargetDeploymentIds.has(t)?{kind:`retained`,reason:`known-incompatible`}:await this.transfer(e,t,{reason:`compaction`})}async transfer(e,t,n){let{inbox:r}=this.input;if(this.worldUnsupported)return{kind:`retained`,reason:`unsupported-world`};if(r.awaitingHandover)return{kind:`retained`,reason:`busy`};let i=getWorkflowMetadata().workflowRunId,a=this.attempts++,o=`${i}:${String(a)}`,s=r.claimedTokens,c=createHook({token:`${i}:handoff:${String(a)}`});this.ensureAnchor();let l=new AbortController,u=Date.now();try{let a;try{let r=await startSuccessorStep({...n,activationToken:c.token,anchorRunId:this.input.sessionId,attemptKey:o,checkpoint:{...this.input.checkpoint,...e,version:16},hookTokens:s,sourceRunId:i,targetDeploymentId:t});if(r.kind===`not-idle`)return{kind:`retained`,reason:`not-idle`};if(r.kind===`unsupported`)return this.worldUnsupported=!0,{kind:`retained`,reason:`unsupported-world`};a=r.runId}catch(e){let n=await this.fenceAttempt(o);if(n.kind!==`live`)return n.kind===`done`&&await this.holdEveryToken(s),await this.reportRetained(`activation-failed`,t,e),{kind:`retained`,reason:`activation-failed`};a=n.runId}let d=r.whenTakenOver(l.signal).then(()=>({kind:`taken-over`})),f,p;for(;;){if(f===void 0&&p===void 0&&r.hasPending()){let e=u+3e5-Date.now();p=sleep(Math.max(0,e)).then(()=>({kind:`deadline`}))}let e;try{e=await Promise.race([d,c.then(e=>({kind:`verdict`,verdict:e})),f===void 0?p??r.whenArrival().then(()=>({kind:`arrival`})):f.ended.then(()=>({kind:`candidate-ended`}))])}finally{f?.stop()}if(e.kind===`taken-over`)return await this.handOver(o);if(e.kind===`arrival`)continue;let n=e.kind===`candidate-ended`?a:verdictRunId(e),i=await this.fenceAttempt(o,n);if(i.kind===`live`){a=i.runId,f=watchRunEnd(a);continue}i.kind===`done`&&i.runId!==verdictRunId(e)&&await this.holdEveryToken(s);let l=e.kind===`verdict`?await this.recover(e.verdict,{attemptKey:o,candidateRunId:a,hookTokens:s,targetDeploymentId:t}):this.recoverFromSilentCandidate(e.kind);return await this.reportRetained(l.reason,t,l.error),{kind:`retained`,reason:l.reason}}}finally{l.abort(),await disposeHook(c)}}async adoptTakeover(){return await reportSessionTakenOverOutsideAttemptStep({sessionId:this.input.sessionId}),this.ensureAnchor(),{kind:`transferred`}}async fenceAttempt(e,t){let n=createHook({experimental_minRetention:`7d`,token:handoffLeaseToken(e)});try{await claimHookOwnership(n)}catch(e){if(!isHookConflictError(e)||typeof e.conflictingRunId!=`string`)throw e;let n=e.conflictingRunId;return n===t||await hasRunEndedStep({runId:n})?{kind:`done`,runId:n}:{kind:`live`,runId:n}}return{kind:`won`}}async handOver(e){return await sendSessionHandover({attemptKey:e,payloads:this.input.inbox.drain(),sessionId:this.input.sessionId}),{kind:`transferred`}}async holdEveryToken(e){await this.input.inbox.claimSessionHooks(e,{force:!0})}recoverFromSilentCandidate(e){return{error:Error(e===`deadline`?`The successor run did not report within 5 minutes.`:`The successor run ended before the handoff settled.`),reason:`activation-failed`}}async recover(e,t){let{inbox:n}=this.input;switch(e.kind){case`active`:return{error:Error(`Successor reported active without a takeover.`),reason:`activation-failed`};case`incompatible`:return this.incompatibleTargetDeploymentIds.add(t.targetDeploymentId),e.payloads.length>0&&n.restore(e.payloads),{reason:`checkpoint-incompatible`};case`failed`:return e.claimedHooks===!0?(await n.claimSessionHooks(t.hookTokens,{force:!0,handover:t.attemptKey}),abandonHandoverIfRunEnds(n,{attemptKey:t.attemptKey,sourceRunId:e.runId??t.candidateRunId})):isHookConflictError(e.error)&&this.incompatibleTargetDeploymentIds.add(t.targetDeploymentId),e.payloads.length>0&&n.restore(e.payloads),{error:e.error,reason:`activation-failed`}}}ensureAnchor(){this.input.isInitialOwner&&this.anchor===void 0&&(this.anchor=createHook({token:sessionAnchorToken(this.input.sessionId)}))}async awaitAnchoredResult(){if(this.anchor===void 0)throw Error(`Session anchor was never claimed.`);try{return await this.anchor}finally{await this.disposeAnchor()}}async disposeAnchor(){if(this.anchor===void 0)return;let e=this.anchor;this.anchor=void 0,await disposeHook(e)}async reportRetained(e,t,n){let r=isObject(n)&&typeof n.message==`string`?n.message:void 0;await reportSessionHandoffRetainedStep({error:r,reason:e,sessionId:this.input.sessionId,sourceDeploymentId:this.input.deploymentId,targetDeploymentId:t})}};export{HANDOFF_LEASE_RETENTION,SESSION_CHECKPOINT_VERSION,SessionHandoff,handoffLeaseToken,sendSessionHandover,sessionAnchorToken};
1
+ import{isObject}from"#shared/guards.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{hasRunEndedStep,reportHandoverPartStuckStep,reportSessionHandoffRetainedStep,reportSessionTakenOverOutsideAttemptStep,sendSessionHandoverPartStep,startSuccessorStep}from"#execution/session/handoff-steps.js";import{abandonHandoverIfRunEnds,watchRunEnd}from"#execution/session/run-watch.js";import{isSessionStateIdleForHandoff}from"#execution/session/handoff-state.js";import{readAcceptedDeploymentId}from"#execution/session/accepted-deployment.js";const SESSION_CHECKPOINT_VERSION=17;function sessionAnchorToken(e){return`${e}:anchor`}function handoffLeaseToken(e){return`eve:handoff:lease:${e}`}const HANDOFF_LEASE_RETENTION=`7d`;function verdictRunId(e){return e.kind===`verdict`&&e.verdict.kind!==`active`?e.verdict.runId:void 0}async function sendSessionHandover(e){let{attemptKey:t,sessionId:n}=e,r=e.payloads.filter(e=>e.kind!==`handover`);for(let[e,i]of r.entries())if(await sendHandoverPart({attemptKey:t,index:e,payloads:[i]},n,r.length)===`session-ended`)return;await sendHandoverPart({attemptKey:t,final:!0,index:r.length,payloads:[]},n,r.length)}async function sendHandoverPart(e,t,n){for(let r=1,i=1;;r++)try{return await sendSessionHandoverPartStep({bufferedPayloadCount:n,part:e,sessionId:t})}catch(n){r===HANDOVER_PART_FAILURES_BEFORE_REPORT&&await reportHandoverPartStuckStep({attemptKey:e.attemptKey,error:isObject(n)&&typeof n.message==`string`?n.message:void 0,failures:r,index:e.index,sessionId:t}).catch(()=>{}),await sleep(i*1e3),i=Math.min(i*2,60)}}const HANDOVER_PART_FAILURES_BEFORE_REPORT=5;var SessionHandoff=class{input;anchor;incompatibleTargetDeploymentIds=new Set;attempts=0;worldUnsupported=!1;constructor(e){this.input=e}async tryTransfer(e,t){let{delivery:n}=e,r=readAcceptedDeploymentId(n);return r===void 0?{kind:`retained`,reason:`missing-deployment`}:r===this.input.deploymentId?{kind:`retained`,reason:`same-deployment`}:this.incompatibleTargetDeploymentIds.has(r)?{kind:`retained`,reason:`known-incompatible`}:e.handoffEligible?await this.transfer(t,r,{delivery:n}):{kind:`retained`,reason:`busy`}}async tryCompactionTransfer(e){let{deploymentId:t}=this.input;return this.incompatibleTargetDeploymentIds.has(t)?{kind:`retained`,reason:`known-incompatible`}:await this.transfer(e,t,{reason:`compaction`})}async tryPrewarmTransfer(e,t,n){return t===this.input.deploymentId?{kind:`retained`,reason:`same-deployment`}:this.incompatibleTargetDeploymentIds.has(t)?{kind:`retained`,reason:`known-incompatible`}:await this.transfer(e,t,{reason:`prewarm`,sessionTimeoutDeadline:n})}async transfer(e,t,n){let{inbox:r}=this.input;if(this.worldUnsupported)return{kind:`retained`,reason:`unsupported-world`};if(r.awaitingHandover)return{kind:`retained`,reason:`busy`};if(!isSessionStateIdleForHandoff(e))return{kind:`retained`,reason:`not-idle`};let i=getWorkflowMetadata().workflowRunId,a=this.attempts++,o=`${i}:${String(a)}`,s=r.claimedTokens,c=createHook({token:`${i}:handoff:${String(a)}`});this.ensureAnchor();let l=new AbortController,u=Date.now();try{let a;try{let r=await startSuccessorStep({...n,activationToken:c.token,anchorRunId:this.input.sessionId,attemptKey:o,checkpoint:{...this.input.checkpoint,...e,version:17},hookTokens:s,sourceRunId:i,targetDeploymentId:t});if(r.kind===`not-idle`)return{kind:`retained`,reason:`not-idle`};if(r.kind===`unsupported`)return this.worldUnsupported=!0,{kind:`retained`,reason:`unsupported-world`};a=r.runId}catch(e){let n=await this.fenceAttempt(o);if(n.kind!==`live`)return n.kind===`done`&&await this.holdEveryToken(s),await this.reportRetained(`activation-failed`,t,e),{kind:`retained`,reason:`activation-failed`};a=n.runId}let d=r.whenTakenOver(l.signal).then(()=>({kind:`taken-over`})),f,p;for(;;){if(f===void 0&&p===void 0&&r.hasPending()){let e=u+3e5-Date.now();p=sleep(Math.max(0,e)).then(()=>({kind:`deadline`}))}let e;try{e=await Promise.race([d,c.then(e=>({kind:`verdict`,verdict:e})),f===void 0?p??r.whenArrival().then(()=>({kind:`arrival`})):f.ended.then(()=>({kind:`candidate-ended`}))])}finally{f?.stop()}if(e.kind===`taken-over`)return await this.handOver(o);if(e.kind===`arrival`)continue;let n=e.kind===`candidate-ended`?a:verdictRunId(e),i=await this.fenceAttempt(o,n);if(i.kind===`live`){a=i.runId,f=watchRunEnd(a);continue}i.kind===`done`&&i.runId!==verdictRunId(e)&&await this.holdEveryToken(s);let l=e.kind===`verdict`?await this.recover(e.verdict,{attemptKey:o,candidateRunId:a,hookTokens:s,targetDeploymentId:t}):this.recoverFromSilentCandidate(e.kind);return await this.reportRetained(l.reason,t,l.error),{kind:`retained`,reason:l.reason}}}finally{l.abort(),await disposeHook(c)}}async adoptTakeover(){return await reportSessionTakenOverOutsideAttemptStep({sessionId:this.input.sessionId}),this.ensureAnchor(),{kind:`transferred`}}async fenceAttempt(e,t){let n=createHook({experimental_minRetention:`7d`,token:handoffLeaseToken(e)});try{await claimHookOwnership(n)}catch(e){if(!isHookConflictError(e)||typeof e.conflictingRunId!=`string`)throw e;let n=e.conflictingRunId;return n===t||await hasRunEndedStep({runId:n})?{kind:`done`,runId:n}:{kind:`live`,runId:n}}return{kind:`won`}}async handOver(e){return await sendSessionHandover({attemptKey:e,payloads:this.input.inbox.drain(),sessionId:this.input.sessionId}),{kind:`transferred`}}async holdEveryToken(e){await this.input.inbox.claimSessionHooks(e,{force:!0})}recoverFromSilentCandidate(e){return{error:Error(e===`deadline`?`The successor run did not report within 5 minutes.`:`The successor run ended before the handoff settled.`),reason:`activation-failed`}}async recover(e,t){let{inbox:n}=this.input;switch(e.kind){case`active`:return{error:Error(`Successor reported active without a takeover.`),reason:`activation-failed`};case`incompatible`:return this.incompatibleTargetDeploymentIds.add(t.targetDeploymentId),e.payloads.length>0&&n.restore(e.payloads),{reason:`checkpoint-incompatible`};case`failed`:return e.claimedHooks===!0?(await n.claimSessionHooks(t.hookTokens,{force:!0,handover:t.attemptKey}),abandonHandoverIfRunEnds(n,{attemptKey:t.attemptKey,sourceRunId:e.runId??t.candidateRunId})):isHookConflictError(e.error)&&this.incompatibleTargetDeploymentIds.add(t.targetDeploymentId),e.payloads.length>0&&n.restore(e.payloads),{error:e.error,reason:`activation-failed`}}}ensureAnchor(){this.input.isInitialOwner&&this.anchor===void 0&&(this.anchor=createHook({token:sessionAnchorToken(this.input.sessionId)}))}async awaitAnchoredResult(){if(this.anchor===void 0)throw Error(`Session anchor was never claimed.`);try{return await this.anchor}finally{await this.disposeAnchor()}}async disposeAnchor(){if(this.anchor===void 0)return;let e=this.anchor;this.anchor=void 0,await disposeHook(e)}async reportRetained(e,t,n){let r=isObject(n)&&typeof n.message==`string`?n.message:void 0;await reportSessionHandoffRetainedStep({error:r,reason:e,sessionId:this.input.sessionId,sourceDeploymentId:this.input.deploymentId,targetDeploymentId:t})}};export{HANDOFF_LEASE_RETENTION,SESSION_CHECKPOINT_VERSION,SessionHandoff,handoffLeaseToken,sendSessionHandover,sessionAnchorToken};
@@ -0,0 +1,3 @@
1
+ import { type Attributes } from "#compiled/@opentelemetry/api/index.js";
2
+ /** Called only from existing host steps; workflow bodies cannot export host spans. */
3
+ export declare function traceSessionHandover(phase: "forwarding_started" | "part_submitted" | "final_submitted" | "inbox_unblocked", sessionId: string, attemptKey: string, attributes: Attributes): void;
@@ -0,0 +1 @@
1
+ import{getStepMetadata,getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{trace}from"#compiled/@opentelemetry/api/index.js";function traceSessionHandover(e,t,n,r){try{let i=trace.getActiveSpan();if(i===void 0)return;let a=getStepMetadata(),o={"eve.session.id":t,"eve.handoff.attempt_key":n,"workflow.run.id":getWorkflowMetadata().workflowRunId,"workflow.step.id":a.stepId,"eve.handoff.step_attempt":a.attempt,...r};for(let[e,t]of Object.entries(o))t!==void 0&&i.setAttribute(e,t);i.addEvent(`eve.session.handover.${e}`,o)}catch{}}export{traceSessionHandover};
@@ -29,6 +29,9 @@ export declare class SessionInputQueue {
29
29
  private readonly entries;
30
30
  private readonly admittedKeys;
31
31
  private nextSequence;
32
+ private prewarmDeploymentId;
33
+ prepareOnDeployment(deploymentId: string): void;
34
+ takePrewarmDeployment(): string | undefined;
32
35
  constructor(admittedDeliveryKeys: readonly string[]);
33
36
  get admittedDeliveryKeys(): readonly string[];
34
37
  isDuplicate(delivery: DeliverHookPayload): boolean;
@@ -1 +1 @@
1
- import{DELIVERY_IDEMPOTENCY_WINDOW}from"#channel/delivery-idempotency.js";import{coalesceDeliveries}from"#harness/messages.js";import{ANONYMOUS_PRINCIPAL,principalOf}from"#execution/session/principal.js";var SessionInputQueue=class{entries=[];admittedKeys;nextSequence=0;constructor(e){this.admittedKeys=new Set(e)}get admittedDeliveryKeys(){return[...this.admittedKeys]}isDuplicate(e){return e.idempotencyKey!==void 0&&this.admittedKeys.has(e.idempotencyKey)}get pendingCount(){return this.entries.length}get nextAdmission(){return this.nextSequence}enqueueDelivery(e){if(this.isDuplicate(e))return;e.idempotencyKey!==void 0&&(this.admittedKeys.add(e.idempotencyKey),this.admittedKeys.size>DELIVERY_IDEMPOTENCY_WINDOW&&this.admittedKeys.delete(this.admittedKeys.values().next().value));let t={delivery:e,sequence:this.nextSequence++};return this.entries.push({...t,kind:`delivery`}),t}enqueueControl(e){this.entries.push({control:e,kind:`control`,sequence:this.nextSequence++})}enqueueAuthorization(e){for(let t of e){let e=authorizationAttemptId(t);e!==void 0&&(this.entries.some(t=>t.kind===`authorization`&&t.attemptId===e)||this.entries.push({attemptId:e,kind:`authorization`,payload:t,sequence:this.nextSequence++}))}}takeAuthorizations(e){let t=this.entries.filter(t=>t.kind===`authorization`&&e.has(t.attemptId));if(!(t.length===0||new Set(t.map(e=>e.attemptId)).size<e.size))return this.retain(e=>!t.includes(e)),t.map(e=>e.payload)}delivery(e){return this.entries.find(t=>t.kind===`delivery`&&t.sequence===e)?.delivery}replaceDelivery(e,t){let n=this.entries.findIndex(t=>t.kind===`delivery`&&t.sequence===e);if(!(n<0)){if(t===void 0){this.entries.splice(n,1);return}this.entries[n]={delivery:t,kind:`delivery`,sequence:e}}}takeSteering(e,t,n){let r=this.entries.filter(r=>r.kind===`delivery`&&e.has(r.sequence)&&isSteeringDelivery(r.delivery,t,{heldOnPerson:n?.heldSince!==void 0&&r.sequence>=n.heldSince}));if(r.length!==0)return this.retain(e=>e.kind!==`delivery`||!r.includes(e)),{delivery:combine(r),handoffEligible:!1,kind:`turn`,sequences:r.map(({sequence:e})=>e)}}takeNext(e){this.retain(e=>e.kind!==`authorization`);let t=this.entries.shift();if(t===void 0)return;if(t.kind===`control`)return{control:t.control,kind:`control`};let n=[t,...this.takeFollowingDeliveriesFrom(t)],r=n.map(({sequence:e})=>e),i=combine(n);return{delivery:i,handoffEligible:r.length===1&&r[0]===e?.freshSequence&&i.caller===void 0&&this.entries.length===0,kind:`turn`,sequences:r}}takeFollowingDeliveriesFrom(e){let t=principalOf(e.delivery.auth),n=[],r=e.delivery.caller?.callId;for(;;){let e=this.entries[0];if(e?.kind!==`delivery`||t===ANONYMOUS_PRINCIPAL||principalOf(e.delivery.auth)!==t||r!==void 0&&e.delivery.caller!==void 0&&e.delivery.caller.callId!==r)break;n.push(e),this.entries.shift(),r??=e.delivery.caller?.callId}return n}retain(e){let t=this.entries.filter(e);this.entries.splice(0,this.entries.length,...t)}};function isSteeringDelivery(e,t,n){return(n?.heldOnPerson===!0||(e.turnPolicy??`steer`)===`steer`)&&(e.caller===void 0||e.caller.callId===t.callerCallId)&&(e.auth===void 0||principalOf(e.auth)===t.principal)}function isSteeringMessage(e,t){return isSteeringDelivery(e,t)&&e.payloads.some(e=>e.message!==void 0&&e.inputResponses===void 0)}function combine(e){return e.length===1?e[0].delivery:coalesceDeliveries(e.map(({delivery:e})=>e))}function authorizationAttemptId(e){let t=e.authorizationCallback;return typeof t?.attemptId==`string`?t.attemptId:void 0}export{SessionInputQueue,isSteeringDelivery,isSteeringMessage};
1
+ import{DELIVERY_IDEMPOTENCY_WINDOW}from"#channel/delivery-idempotency.js";import{coalesceDeliveries}from"#harness/messages.js";import{ANONYMOUS_PRINCIPAL,principalOf}from"#execution/session/principal.js";var SessionInputQueue=class{entries=[];admittedKeys;nextSequence=0;prewarmDeploymentId;prepareOnDeployment(e){this.prewarmDeploymentId=e}takePrewarmDeployment(){let e=this.prewarmDeploymentId;return this.prewarmDeploymentId=void 0,e}constructor(e){this.admittedKeys=new Set(e)}get admittedDeliveryKeys(){return[...this.admittedKeys]}isDuplicate(e){return e.idempotencyKey!==void 0&&this.admittedKeys.has(e.idempotencyKey)}get pendingCount(){return this.entries.length}get nextAdmission(){return this.nextSequence}enqueueDelivery(e){if(this.isDuplicate(e))return;e.idempotencyKey!==void 0&&(this.admittedKeys.add(e.idempotencyKey),this.admittedKeys.size>DELIVERY_IDEMPOTENCY_WINDOW&&this.admittedKeys.delete(this.admittedKeys.values().next().value)),this.prewarmDeploymentId=void 0;let t={delivery:e,sequence:this.nextSequence++};return this.entries.push({...t,kind:`delivery`}),t}enqueueControl(e){this.entries.push({control:e,kind:`control`,sequence:this.nextSequence++})}enqueueAuthorization(e){for(let t of e){let e=authorizationAttemptId(t);e!==void 0&&(this.entries.some(t=>t.kind===`authorization`&&t.attemptId===e)||this.entries.push({attemptId:e,kind:`authorization`,payload:t,sequence:this.nextSequence++}))}}takeAuthorizations(e){let t=this.entries.filter(t=>t.kind===`authorization`&&e.has(t.attemptId));if(!(t.length===0||new Set(t.map(e=>e.attemptId)).size<e.size))return this.retain(e=>!t.includes(e)),t.map(e=>e.payload)}delivery(e){return this.entries.find(t=>t.kind===`delivery`&&t.sequence===e)?.delivery}replaceDelivery(e,t){let n=this.entries.findIndex(t=>t.kind===`delivery`&&t.sequence===e);if(!(n<0)){if(t===void 0){this.entries.splice(n,1);return}this.entries[n]={delivery:t,kind:`delivery`,sequence:e}}}takeSteering(e,t,n){let r=this.entries.filter(r=>r.kind===`delivery`&&e.has(r.sequence)&&isSteeringDelivery(r.delivery,t,{heldOnPerson:n?.heldSince!==void 0&&r.sequence>=n.heldSince}));if(r.length!==0)return this.retain(e=>e.kind!==`delivery`||!r.includes(e)),{delivery:combine(r),handoffEligible:!1,kind:`turn`,sequences:r.map(({sequence:e})=>e)}}takeNext(e){this.retain(e=>e.kind!==`authorization`);let t=this.entries.shift();if(t===void 0)return;if(t.kind===`control`)return{control:t.control,kind:`control`};let n=[t,...this.takeFollowingDeliveriesFrom(t)],r=n.map(({sequence:e})=>e),i=combine(n);return{delivery:i,handoffEligible:r.length===1&&r[0]===e?.freshSequence&&i.caller===void 0&&this.entries.length===0,kind:`turn`,sequences:r}}takeFollowingDeliveriesFrom(e){let t=principalOf(e.delivery.auth),n=[],r=e.delivery.caller?.callId;for(;;){let e=this.entries[0];if(e?.kind!==`delivery`||t===ANONYMOUS_PRINCIPAL||principalOf(e.delivery.auth)!==t||r!==void 0&&e.delivery.caller!==void 0&&e.delivery.caller.callId!==r)break;n.push(e),this.entries.shift(),r??=e.delivery.caller?.callId}return n}retain(e){let t=this.entries.filter(e);this.entries.splice(0,this.entries.length,...t)}};function isSteeringDelivery(e,t,n){return(n?.heldOnPerson===!0||(e.turnPolicy??`steer`)===`steer`)&&(e.caller===void 0||e.caller.callId===t.callerCallId)&&(e.auth===void 0||principalOf(e.auth)===t.principal)}function isSteeringMessage(e,t){return isSteeringDelivery(e,t)&&e.payloads.some(e=>e.message!==void 0&&e.inputResponses===void 0)}function combine(e){return e.length===1?e[0].delivery:coalesceDeliveries(e.map(({delivery:e})=>e))}function authorizationAttemptId(e){let t=e.authorizationCallback;return typeof t?.attemptId==`string`?t.attemptId:void 0}export{SessionInputQueue,isSteeringDelivery,isSteeringMessage};
@@ -3,6 +3,9 @@ import type { SessionInboxReader } from "#execution/session-inbox/inbox.js";
3
3
  import type { SessionStateCursor } from "#execution/session/state-cursor.js";
4
4
  import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
5
5
  export type NextTurnInstruction = {
6
+ readonly kind: "prewarm";
7
+ readonly targetDeploymentId: string;
8
+ } | {
6
9
  readonly kind: "workflow";
7
10
  readonly message: WorkflowToolRunMessage;
8
11
  } | {
@@ -1 +1 @@
1
- import{openInputs}from"#protocol/session-projection.js";import{storedProjection}from"#harness/session-machine/view.js";import{admitSessionInboxPayload}from"#execution/session/admission.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";async function nextTurnDelivery(e){let{inbox:t,cursor:n,queue:r}=e,i;for(;;){let a=r.takeNext({freshSequence:t.hasPending()?void 0:i});if(a?.kind===`control`)return{kind:a.control};if(a?.kind===`turn`){let e=await routeSelectedDelivery(a,n);if(e.kind===`cancel-turn`)return e;if(e.kind===`consumed`)continue;return e}let o=r.pendingCount===0,s=await t.next();if(s===void 0)return{kind:`closed`};let c=await admitSessionInboxPayload(s,e);if(i=o&&c.kind===`delivery`?c.admission.sequence:void 0,c.kind===`workflow`)return{kind:`workflow`,message:c.message};if(c.kind===`cancel`&&openInputs(storedProjection(n.sessionState.snapshot.session.state)).some(e=>e.request.kind===`session-limit`))return{kind:`cancel-turn`};if(c.kind===`cancel`&&e.hasWorkingTasks())return{kind:`cancel-working-tasks`}}}export{nextTurnDelivery};
1
+ import{openInputs}from"#protocol/session-projection.js";import{storedProjection}from"#harness/session-machine/view.js";import{admitSessionInboxPayload}from"#execution/session/admission.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";async function nextTurnDelivery(e){let{inbox:t,cursor:n,queue:r}=e,i;for(;;){let a=r.takeNext({freshSequence:t.hasPending()?void 0:i});if(a?.kind===`control`)return{kind:a.control};if(a?.kind===`turn`){let e=await routeSelectedDelivery(a,n);if(e.kind===`cancel-turn`)return e;if(e.kind===`consumed`)continue;return e}if(!t.hasPending()){let e=r.takePrewarmDeployment();if(e!==void 0)return{kind:`prewarm`,targetDeploymentId:e}}let o=r.pendingCount===0,s=await t.next();if(s===void 0)return{kind:`closed`};let c=await admitSessionInboxPayload(s,e);if(i=o&&c.kind===`delivery`?c.admission.sequence:void 0,c.kind===`workflow`)return{kind:`workflow`,message:c.message};if(c.kind===`cancel`&&openInputs(storedProjection(n.sessionState.snapshot.session.state)).some(e=>e.request.kind===`session-limit`))return{kind:`cancel-turn`};if(c.kind===`cancel`&&e.hasWorkingTasks())return{kind:`cancel-working-tasks`}}}export{nextTurnDelivery};
@@ -0,0 +1,13 @@
1
+ import { type DurableSessionState } from "#execution/durable-session-store.js";
2
+ import { type SessionStateTransition } from "#execution/session/state-delta.js";
3
+ interface SessionPrewarmInput {
4
+ readonly serializedContext: Record<string, unknown>;
5
+ readonly sessionState: DurableSessionState;
6
+ }
7
+ /**
8
+ * Starts the session prewarmers for a session started without a message and
9
+ * records what they prepared, such as the sandbox state, once their work
10
+ * settles. Runs beside the wait for the first message and never fails.
11
+ */
12
+ export declare function prewarmSessionStep(input: SessionPrewarmInput): Promise<SessionStateTransition>;
13
+ export {};
@@ -0,0 +1 @@
1
+ import{createLogger}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{withContextScope}from"#context/run-step.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{hydrateDurableSession,projectToDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{startSessionPrewarmers}from"#context/prewarm.js";const log=createLogger(`execution.session.prewarm`);async function prewarmSessionStep(e){"use step";return await withSessionStateDelta(e,prewarmSession)}async function prewarmSession(e){try{let t=await deserializeContext(e.serializedContext),n=resolveEffectiveAgentRuntime(t.require(BundleKey),t),r=hydrateDurableSession({compactionOverrides:{thresholdPercent:n.thresholdPercent},durable:readDurableSession(e.sessionState),turnAgent:n.turnAgent}),i=await withContextScope(t,r,async e=>(startSessionPrewarmers(t,`session`),{result:void 0,session:e}));return{serializedContext:serializeContext(t),sessionState:replaceDurableSessionSnapshot({session:projectToDurableSession(i.session),state:e.sessionState})}}catch(t){return log.warn(`session prewarm failed; the first turn does this work instead`,{error:t,sessionId:e.sessionState.sessionId}),{}}}export{prewarmSessionStep};
@@ -25,7 +25,10 @@ export type SessionStart =
25
25
  readonly kind: "turn";
26
26
  readonly input: DeliverHookPayload | undefined;
27
27
  }
28
- /** A prewarmed session parks on the inbox before any session-scoped lifecycle work. */
28
+ /**
29
+ * A prewarmed session parks on the inbox before any turn, session event, or
30
+ * session hook, while its session prewarmers run beside the wait.
31
+ */
29
32
  | {
30
33
  readonly kind: "first-message";
31
34
  }
@@ -1 +1 @@
1
- import{STUB_CONTEXT_KEY}from"#tool-stubs/types.js";import{workingTasks}from"#execution/tasks/table.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{signalSessionAnchorStep}from"#execution/session/handoff-steps.js";import{SessionInputQueue}from"#execution/session/input-queue.js";import{createTurnControl}from"#execution/session/turn-control.js";import{SessionHandoff,sessionAnchorToken}from"#execution/session/handoff.js";import{notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{withStubPlayback}from"#execution/tool-stubs/playback.js";import{nextTurnDelivery}from"#execution/session/next-input.js";import{SessionExecution}from"#execution/session/turn.js";import{SessionStateCursor}from"#execution/session/state-cursor.js";import{cancelWorkingTasks,sessionTaskTable}from"#execution/tasks/session.js";import{finalizeSession}from"#execution/session/finalization.js";function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runPreparedSession(e,t){let n=e.serializedContext[STUB_CONTEXT_KEY];n!==void 0&&n.rootSessionId===void 0&&(e.serializedContext[STUB_CONTEXT_KEY]={...n,rootSessionId:e.sessionId});let r=new SessionStateCursor({history:e.history,inbox:t,sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),i={caller:e.caller,terminalEmitted:!1},a=new SessionHandoff({checkpoint:{capabilities:e.capabilities,retention:e.retention,sessionTimeoutMs:e.sessionTimeoutMs},deploymentId:e.deploymentId,inbox:t,isInitialOwner:e.anchor.kind===`self`,sessionId:e.sessionId}),o={output:``,isError:!0},s;try{return o=await withStubPlayback(n,e.sessionId,async()=>{try{s=await runSessionLoop(e,{cursor:r,handoff:a,inbox:t,progress:i})}finally{await t.dispose()}return s.kind===`transferred`?e.anchor.kind===`self`?(o=await a.awaitAnchoredResult(),o):{output:``}:(o=await finalizeSession(s.outcome,{caller:i.caller,cursor:r,sessionWritable:e.sessionWritable}),i.terminalEmitted=!0,o)}),o}catch(t){throw i.terminalEmitted||await finalizeSession({error:t,kind:`failed`,turnId:i.turnId},{caller:i.caller,cursor:r,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}finally{await t.dispose(),await reportResultToAnchor(e,o,a,s)}}async function failSession(e){let t;try{t=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext})}catch{}throw await finalizeSession({error:e.error,kind:`failed`},{caller:t,cursor:{serializedContext:e.serializedContext,sessionState:e.sessionState},sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}async function reportResultToAnchor(e,t,n,r){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:if(r?.kind===`transferred`)return;await signalSessionAnchorStep({result:t,token:sessionAnchorToken(e.sessionId)});return}}async function runSessionLoop(e,t){let{cursor:n,handoff:r,inbox:i,progress:a}=t,o=new SessionInputQueue(e.admittedDeliveryKeys),s=new SessionExecution({capabilities:e.capabilities,cursor:n,inbox:i,queue:o,sessionId:e.sessionId}),c=e.sessionTimeoutControl,nextParkedActivity=async()=>{for(;;){let e=await nextTurnDelivery({cursor:n,hasWorkingTasks:()=>workingTasks(sessionTaskTable(n)).length>0,inbox:i,queue:o});if(e.kind===`workflow`){await s.handleWorkflowMessage(e.message);continue}if(e.kind===`cancel-working-tasks`){await cancelWorkingTasks(n,`turn_cancelled`);continue}if(!(e.kind===`expired`&&c!==void 0&&((o.pendingCount>0||i.hasPending())&&c.recordActivity(),await c.handleTimerElapsed()===`extended`)))return e}},l=e.initialTurnControl??(e.anchor.kind===`self`?createTurnControl():void 0),u=0,d=!1,runTurn=async e=>{let t=a.caller,n=l;l=void 0,a.turnId=`turn_${String(u++)}`;let r=await s.runTurn(e,{caller:t,control:n});return c?.recordActivity(),r.caller!==void 0&&(a.caller=r.caller),r.compacted===!0&&(d=!0),r},transferState=()=>({admittedDeliveryKeys:o.admittedDeliveryKeys,history:n.history,serializedContext:n.serializedContext,sessionState:n.sessionState}),compactionHandoffReady=()=>d&&a.caller===void 0&&workingTasks(sessionTaskTable(n)).length===0,tryCompactionHandoff=async()=>{if(!compactionHandoffReady()||o.pendingCount>0||i.hasPending())return;let e=await r.tryCompactionTransfer(transferState());return e.kind===`transferred`?e:void 0},runDeliveredTurn=async e=>{let t=await r.tryTransfer(e,transferState());return t.kind===`transferred`?t:(e.delivery.caller!==void 0&&(a.caller=e.delivery.caller),{action:await runTurn({delivery:e.delivery}),kind:`action`})},settleCancelledTurn=async e=>{let t=await n.advanceWithHistory(t=>settleCancelledTurnStep({...t,reportUsage:e}));return a.caller=void 0,t},awaitPrewarmedAction=async()=>{for(;;){let e=await nextParkedActivity();switch(e.kind){case`closed`:return i.takenOver?await r.adoptTakeover():{kind:`terminal`,outcome:{kind:`expired`}};case`expired`:case`reset`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:continue;case`turn`:return await runDeliveredTurn(e);case`cancel-turn`:continue}}},runInitialAction=async()=>{switch(e.start.kind){case`first-message`:return await awaitPrewarmedAction();case`parked`:return{action:{kind:`park`},kind:`action`};case`turn`:{let{input:t}=e.start;return{action:await runTurn(t===void 0?void 0:{delivery:t}),kind:`action`}}}};try{let[t,n]=await Promise.allSettled([runInitialAction(),c?.start()]);if(n.status===`rejected`)throw n.reason;if(t.status===`rejected`)throw t.reason;let o=t.value;if(o.kind!==`action`)return o;let l=o.action;for(;;){if(l.kind===`done`)return{kind:`terminal`,outcome:{action:l,kind:`done`}};if(l.cancelled===!0){let{caller:t}=a,n=await settleCancelledTurn(t!==void 0);if(t!==void 0){let r={caller:t,sessionId:e.sessionId};await notifyCancelledTaskCallerStep(n.usage===void 0?r:{...r,usage:n.usage})}}else l.settled!==void 0&&(a.caller!==void 0&&await notifyTurnCallerStep({caller:a.caller,lifecycle:`parked`,sessionId:e.sessionId,settled:l.settled}),a.caller=void 0);let t=await tryCompactionHandoff();if(t!==void 0)return t;let n=await nextParkedActivity();switch(n.kind){case`closed`:return i.takenOver?await r.adoptTakeover():{kind:`terminal`,outcome:{kind:`expired`}};case`expired`:case`reset`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:l=await runTurn({control:n.kind});continue;case`cancel-turn`:await s.cancelTurnWork(),await settleCancelledTurn(!1),c?.recordActivity(),l={...l,settled:void 0};continue;case`turn`:{let e=await runDeliveredTurn(n);if(e.kind!==`action`)return e;l=e.action;continue}}}}finally{l?.dispose(),await c?.dispose()}}export{failSession,runPreparedSession};
1
+ import{STUB_CONTEXT_KEY}from"#tool-stubs/types.js";import{workingTasks}from"#execution/tasks/table.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{signalSessionAnchorStep}from"#execution/session/handoff-steps.js";import{SessionInputQueue}from"#execution/session/input-queue.js";import{createTurnControl}from"#execution/session/turn-control.js";import{SessionHandoff,sessionAnchorToken}from"#execution/session/handoff.js";import{notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{withStubPlayback}from"#execution/tool-stubs/playback.js";import{nextTurnDelivery}from"#execution/session/next-input.js";import{SessionExecution}from"#execution/session/turn.js";import{SessionStateCursor}from"#execution/session/state-cursor.js";import{cancelWorkingTasks,sessionTaskTable}from"#execution/tasks/session.js";import{finalizeSession}from"#execution/session/finalization.js";import{prewarmSessionStep}from"#execution/session/prewarm-step.js";function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runPreparedSession(e,t){let n=e.serializedContext[STUB_CONTEXT_KEY];n!==void 0&&n.rootSessionId===void 0&&(e.serializedContext[STUB_CONTEXT_KEY]={...n,rootSessionId:e.sessionId});let r=new SessionStateCursor({history:e.history,inbox:t,sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),i={caller:e.caller,terminalEmitted:!1},a=new SessionHandoff({checkpoint:{capabilities:e.capabilities,retention:e.retention,sessionTimeoutMs:e.sessionTimeoutMs},deploymentId:e.deploymentId,inbox:t,isInitialOwner:e.anchor.kind===`self`,sessionId:e.sessionId}),o={output:``,isError:!0},s;try{return o=await withStubPlayback(n,e.sessionId,async()=>{try{s=await runSessionLoop(e,{cursor:r,handoff:a,inbox:t,progress:i})}finally{await t.dispose()}return s.kind===`transferred`?e.anchor.kind===`self`?(o=await a.awaitAnchoredResult(),o):{output:``}:(o=await finalizeSession(s.outcome,{caller:i.caller,cursor:r,sessionWritable:e.sessionWritable}),i.terminalEmitted=!0,o)}),o}catch(t){throw i.terminalEmitted||await finalizeSession({error:t,kind:`failed`,turnId:i.turnId},{caller:i.caller,cursor:r,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}finally{await t.dispose(),await reportResultToAnchor(e,o,a,s)}}async function failSession(e){let t;try{t=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext})}catch{}throw await finalizeSession({error:e.error,kind:`failed`},{caller:t,cursor:{serializedContext:e.serializedContext,sessionState:e.sessionState},sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}async function reportResultToAnchor(e,t,n,r){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:if(r?.kind===`transferred`)return;await signalSessionAnchorStep({result:t,token:sessionAnchorToken(e.sessionId)});return}}async function runSessionLoop(e,t){let{cursor:n,handoff:r,inbox:i,progress:a}=t,o=new SessionInputQueue(e.admittedDeliveryKeys),s=new SessionExecution({capabilities:e.capabilities,cursor:n,inbox:i,queue:o,sessionId:e.sessionId}),c=e.sessionTimeoutControl,l=Promise.resolve(),u=!0,d=!1,nextParkedActivity=async()=>{for(;;){let e=await nextTurnDelivery({cursor:n,hasWorkingTasks:()=>workingTasks(sessionTaskTable(n)).length>0,inbox:i,queue:o});if(e.kind===`prewarm`){if(u&&a.caller===void 0&&workingTasks(sessionTaskTable(n)).length===0&&o.pendingCount===0&&!i.hasPending()){let t=c?.getDeadline(),n=await r.tryPrewarmTransfer(transferState(),e.targetDeploymentId,t);if(n.kind===`transferred`)return n}continue}if(e.kind===`workflow`){await s.handleWorkflowMessage(e.message);continue}if(e.kind===`cancel-working-tasks`){await cancelWorkingTasks(n,`turn_cancelled`);continue}if(!(e.kind===`expired`&&c!==void 0&&((o.pendingCount>0||i.hasPending())&&c.recordActivity(),await c.handleTimerElapsed()===`extended`)))return e}},f=e.initialTurnControl??(e.anchor.kind===`self`?createTurnControl():void 0),p=0,m=!1,runTurn=async e=>{let t=a.caller,n=f;f=void 0,a.turnId=`turn_${String(p++)}`;let r=await s.runTurn(e,{caller:t,control:n});return c?.recordActivity(),r.caller!==void 0&&(a.caller=r.caller),r.compacted===!0&&(m=!0),r},transferState=()=>({admittedDeliveryKeys:o.admittedDeliveryKeys,history:n.history,serializedContext:n.serializedContext,sessionState:n.sessionState}),compactionHandoffReady=()=>m&&a.caller===void 0&&workingTasks(sessionTaskTable(n)).length===0,tryCompactionHandoff=async()=>{if(!compactionHandoffReady()||o.pendingCount>0||i.hasPending())return;let e=await r.tryCompactionTransfer(transferState());return e.kind===`transferred`?e:void 0},runDeliveredTurn=async e=>{let t=await r.tryTransfer(e,transferState());return t.kind===`transferred`?t:(e.delivery.caller!==void 0&&(a.caller=e.delivery.caller),{action:await runTurn({delivery:e.delivery}),kind:`action`})},settleCancelledTurn=async e=>{let t=await n.advanceWithHistory(t=>settleCancelledTurnStep({...t,reportUsage:e}));return a.caller=void 0,t},awaitPrewarmedAction=async()=>{for(;;){let e=await nextParkedActivity();switch(d=!1,e.kind){case`closed`:return i.takenOver?await r.adoptTakeover():{kind:`terminal`,outcome:{kind:`expired`}};case`transferred`:return e;case`expired`:case`reset`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:continue;case`turn`:return await runDeliveredTurn(e);case`cancel-turn`:continue}}},runInitialAction=async()=>{switch(e.start.kind){case`first-message`:return d=!0,u=!1,l=n.advanceBeside(({serializedContext:e,sessionState:t})=>prewarmSessionStep({serializedContext:e,sessionState:t}),()=>d).then(()=>void 0,()=>void 0).finally(()=>{u=!0}),await awaitPrewarmedAction();case`parked`:return{action:{kind:`park`},kind:`action`};case`turn`:{let{input:t}=e.start;return{action:await runTurn(t===void 0?void 0:{delivery:t}),kind:`action`}}}};try{let[t,n]=await Promise.allSettled([runInitialAction(),c?.start()]);if(n.status===`rejected`)throw n.reason;if(t.status===`rejected`)throw t.reason;let o=t.value;if(o.kind!==`action`)return o;let l=o.action;for(;;){if(l.kind===`done`)return{kind:`terminal`,outcome:{action:l,kind:`done`}};if(l.cancelled===!0){let{caller:t}=a,n=await settleCancelledTurn(t!==void 0);if(t!==void 0){let r={caller:t,sessionId:e.sessionId};await notifyCancelledTaskCallerStep(n.usage===void 0?r:{...r,usage:n.usage})}}else l.settled!==void 0&&(a.caller!==void 0&&await notifyTurnCallerStep({caller:a.caller,lifecycle:`parked`,sessionId:e.sessionId,settled:l.settled}),a.caller=void 0);let t=await tryCompactionHandoff();if(t!==void 0)return t;f??=createTurnControl();let n=await nextParkedActivity();switch(n.kind){case`closed`:return i.takenOver?await r.adoptTakeover():{kind:`terminal`,outcome:{kind:`expired`}};case`transferred`:return n;case`expired`:case`reset`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:l=await runTurn({control:n.kind});continue;case`cancel-turn`:await s.cancelTurnWork(),await settleCancelledTurn(!1),c?.recordActivity(),l={...l,settled:void 0};continue;case`turn`:{let e=await runDeliveredTurn(n);if(e.kind!==`action`)return e;l=e.action;continue}}}}finally{d=!1,await l,await c?.dispose()}}export{failSession,runPreparedSession};
@@ -14,6 +14,9 @@ export declare class SessionStateCursor {
14
14
  readonly sessionWritable: WritableStream<Uint8Array>;
15
15
  private readonly inbox;
16
16
  private values;
17
+ /** Session steps adopted so far, and those still running. */
18
+ private adopted;
19
+ private running;
17
20
  constructor(input: SessionStateValues & {
18
21
  readonly inbox: Pick<SessionInboxOwnership, "claimSessionHooks">;
19
22
  readonly sessionWritable: WritableStream<Uint8Array>;
@@ -30,6 +33,14 @@ export declare class SessionStateCursor {
30
33
  advance<T extends SessionStateTransition>(step: (state: SessionStepState) => Promise<T>): Promise<T>;
31
34
  /** {@link advance} for a step that reads or changes the history, such as a turn. */
32
35
  advanceWithHistory<T extends SessionStateTransition>(step: (state: SessionHistoryStepState) => Promise<T>): Promise<T>;
36
+ /**
37
+ * Runs a step beside the session's own steps, which do not wait for it.
38
+ * Its delta applies only while `wanted()` holds, no other step ran or is
39
+ * running meanwhile, and it adds no session address; otherwise it is
40
+ * dropped and this returns `false`. A step run this way must leave nothing
41
+ * that dropping its delta would lose for good.
42
+ */
43
+ advanceBeside<T extends SessionStateTransition>(step: (state: SessionStepState) => Promise<T>, wanted: () => boolean): Promise<boolean>;
33
44
  /**
34
45
  * A delta describes a change to exactly the values its step was given, so
35
46
  * values that another step changed in the meantime are a sequencing bug,
@@ -1 +1 @@
1
- import{applySessionStateDelta}from"#execution/session/state-delta.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";var SessionStateCursor=class{sessionWritable;inbox;values;constructor(e){this.inbox=e.inbox,this.sessionWritable=e.sessionWritable,this.values={history:e.history,serializedContext:e.serializedContext,sessionState:e.sessionState}}get serializedContext(){return this.values.serializedContext}get sessionState(){return this.values.sessionState}get history(){return this.values.history}async advance(e){let{serializedContext:t,sessionState:n}=this.values;return await this.adopt(()=>e({serializedContext:t,sessionState:n,sessionWritable:this.sessionWritable}),{withHistory:!1})}async advanceWithHistory(e){return await this.adopt(()=>e({...this.values,sessionWritable:this.sessionWritable}),{withHistory:!0})}async adopt(e,t){let n=this.values,r=await e();if(!t.withHistory&&r.stateDelta.history!==void 0)throw Error(`A session step that was not given the history cannot change it.`);let i=applySessionStateDelta(n,r.stateDelta);if(await this.inbox.claimSessionHooks(sessionHookTokens(i)),this.values!==n)throw Error(`Session state changed while a step ran, so its state delta cannot apply.`);return this.values=i,r}};export{SessionStateCursor};
1
+ import{applySessionStateDelta}from"#execution/session/state-delta.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";var SessionStateCursor=class{sessionWritable;inbox;values;adopted=0;running=0;constructor(e){this.inbox=e.inbox,this.sessionWritable=e.sessionWritable,this.values={history:e.history,serializedContext:e.serializedContext,sessionState:e.sessionState}}get serializedContext(){return this.values.serializedContext}get sessionState(){return this.values.sessionState}get history(){return this.values.history}async advance(e){let{serializedContext:t,sessionState:n}=this.values;return await this.adopt(()=>e({serializedContext:t,sessionState:n,sessionWritable:this.sessionWritable}),{withHistory:!1})}async advanceWithHistory(e){return await this.adopt(()=>e({...this.values,sessionWritable:this.sessionWritable}),{withHistory:!0})}async advanceBeside(e,t){let n=this.values,r=this.adopted,i=await e({serializedContext:n.serializedContext,sessionState:n.sessionState,sessionWritable:this.sessionWritable});if(!t()||this.adopted!==r||this.running>0)return!1;if(i.stateDelta.history!==void 0)throw Error(`A session step that was not given the history cannot change it.`);let a=applySessionStateDelta(n,i.stateDelta),o=new Set(sessionHookTokens(n));return!sessionHookTokens(a).some(e=>!o.has(e))&&(this.values=a,this.adopted++,!0)}async adopt(e,t){let n=this.values;this.running++;try{let r=await e();if(!t.withHistory&&r.stateDelta.history!==void 0)throw Error(`A session step that was not given the history cannot change it.`);let i=applySessionStateDelta(n,r.stateDelta);if(await this.inbox.claimSessionHooks(sessionHookTokens(i)),this.values!==n)throw Error(`Session state changed while a step ran, so its state delta cannot apply.`);return this.values=i,this.adopted++,r}finally{this.running--}}};export{SessionStateCursor};
@@ -6,6 +6,8 @@
6
6
  * per turn.
7
7
  */
8
8
  export interface SessionTimeoutControl {
9
+ /** Current idle deadline, including activity since the durable timer was armed. */
10
+ getDeadline(): Date;
9
11
  dispose(): Promise<void>;
10
12
  /**
11
13
  * Answers this owner's elapsed timer: `expired` once the session has been
@@ -19,6 +21,8 @@ export interface SessionTimeoutControl {
19
21
  }
20
22
  /** Creates the idle timeout for one owner run, or `undefined` when timeouts are disabled. */
21
23
  export declare function createSessionTimeoutControl(input: {
24
+ /** Preserve the idle window when proactively moving an existing session. */
25
+ readonly deadline?: Date;
22
26
  readonly sessionId: string;
23
27
  readonly timeoutMs: number | false;
24
28
  }): SessionTimeoutControl | undefined;
@@ -1 +1 @@
1
- import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{cancelSessionTimeoutStep,startSessionTimeoutStep}from"#execution/session/timeout-steps.js";function createSessionTimeoutControl(e){let{sessionId:t,timeoutMs:n}=e;if(n===!1)return;let r=Date.now(),i,a,arm=async()=>{a??=(async()=>{i=await startSessionTimeoutStep({deadline:new Date(r+n),ownerRunId:getWorkflowMetadata().workflowRunId,token:sessionCommandHookToken(t)})})(),await a};return{async dispose(){try{await a}catch{}if(i===void 0)return;let e=i;i=void 0,await cancelSessionTimeoutStep({runId:e.runId})},async handleTimerElapsed(){return Date.now()>=r+n?`expired`:(i=void 0,a=void 0,await arm(),`extended`)},recordActivity(){r=Date.now()},start:arm}}export{createSessionTimeoutControl};
1
+ import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{cancelSessionTimeoutStep,startSessionTimeoutStep}from"#execution/session/timeout-steps.js";function createSessionTimeoutControl(e){let{sessionId:t,timeoutMs:n}=e;if(n===!1)return;let r=e.deadline===void 0?Date.now():e.deadline.getTime()-n,i,a,arm=async()=>{a??=(async()=>{i=await startSessionTimeoutStep({deadline:new Date(r+n),ownerRunId:getWorkflowMetadata().workflowRunId,token:sessionCommandHookToken(t)})})(),await a};return{getDeadline(){return new Date(r+n)},async dispose(){try{await a}catch{}if(i===void 0)return;let e=i;i=void 0,await cancelSessionTimeoutStep({runId:e.runId})},async handleTimerElapsed(){return Date.now()>=r+n?`expired`:(i=void 0,a=void 0,await arm(),`extended`)},recordActivity(){r=Date.now()},start:arm}}export{createSessionTimeoutControl};
@@ -1,7 +1,10 @@
1
- /** Workflow-owned abort controls prepared before a turn begins. */
1
+ /**
2
+ * Workflow-owned abort controls prepared before a turn begins. One that no
3
+ * turn uses is left open, as a finished turn's are: nothing listens to it,
4
+ * so aborting it would only add Workflow writes.
5
+ */
2
6
  export interface TurnControl {
3
7
  readonly cancellation: AbortController;
4
8
  readonly steering: AbortController;
5
- dispose(): void;
6
9
  }
7
10
  export declare function createTurnControl(): TurnControl;
@@ -1 +1 @@
1
- function createTurnControl(){let e=new AbortController,t=new AbortController;return{cancellation:e,steering:t,dispose(){e.abort(),t.abort()}}}export{createTurnControl};
1
+ function createTurnControl(){return{cancellation:new AbortController,steering:new AbortController}}export{createTurnControl};
@@ -6,6 +6,7 @@ import type { HarnessModelMessage } from "#harness/messages.js";
6
6
  import type { SettledTurn } from "#harness/types.js";
7
7
  import type { RuntimeActionResult } from "#shared/action-types.js";
8
8
  import type { TokenUsage } from "#shared/token-usage.js";
9
+ import type { SessionHandoverObservation } from "#execution/session-inbox/inbox.js";
9
10
  /** Trusted runtime-action results collected by the session owner. */
10
11
  export interface RuntimeActionResultStepInput {
11
12
  readonly acceptedAtMsByCallId?: Readonly<Record<string, number>>;
@@ -25,6 +26,7 @@ export interface TurnStepPayload {
25
26
  }
26
27
  /** Input for one atomic, session-owner-executed turn step. */
27
28
  export interface TurnStepInput {
29
+ readonly handover?: SessionHandoverObservation;
28
30
  readonly abortSignal?: AbortSignal;
29
31
  /** The delegated caller to bind into the context before the step runs; sent on a turn's first step. */
30
32
  readonly caller?: TurnCaller;
@@ -1 +1 @@
1
- import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{currentProjection,enterSessionProjection,saveSessionProjection}from"#harness/session-machine/current.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,OccurrenceIdKey,ParentSessionKey,ScheduleIdKey,ScheduleInstanceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TurnDeliveryIdsKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,validateHarnessModelMessages}from"#harness/messages.js";import{activeTurnId,isBetweenTurns,storedProjection,turnPosition}from"#harness/session-machine/view.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{createDurableSessionValues,readDurableSession}from"#execution/durable-session-store.js";import{runStep}from"#context/run-step.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{readHitlState}from"#harness/hitl/index.js";import*as agentTraceState from"#tracing/eve/agent-trace-context-store.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey}from"#harness/authorization.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime,resolveSessionUsageLimit}from"#execution/effective-agent-config.js";import{openSessionEventPublisher}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{matchSignIns}from"#harness/session-machine/transitions.js";import{readPendingHistory,withoutPendingHistory}from"#execution/session/pending-history.js";import{dropClosedRecords,saveTransition,sessionView}from"#harness/session-machine/commit.js";import{sessionStartedForResolvers,turnStartedForResolvers}from"#harness/session-machine/resolver-events.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{createTurnEventHandler}from"#execution/session/turn-event-handler.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{bindTurnCallerContext}from"#subagents/parent-notification.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{recoverDynamicConnectionRehydration}from"#execution/dynamic-connection-recovery.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{attributeAnswers}from"#execution/session/answer-caller.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return await withSessionStateDelta(e,e=>runSessionStep({...e,serializedContext:bindTurnCallerContext(e.caller,e.serializedContext)}))}async function runSessionStep(e){let t={};try{return await runSessionStepBody(e,t)}finally{await t.title}}async function runSessionStepBody(e,t){let n=e.input?.delivery,r=n,i=e.input?.runtimeResults,a=readDurableSession(e.sessionState);for(let e of i?.delegatedUsage??[])a=countRunUsage(a,e);let o=await deserializeContext(e.serializedContext);enterSessionProjection(o,a.state);let s=o.require(ChannelKey),c=o.require(BundleKey),l=resolveEffectiveAgentRuntime(c,o);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&o.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let{signIns:u}=readHitlState(a.state),d;if(u.length>0&&r!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(u,r.payloads);if(r={...r,payloads:t},e.length>0){let n=e.map(e=>e.result.attemptId),i=e.map(e=>e.result);o.set(PendingAuthorizationResultKey,i);let s=sessionView(storedProjection(a.state),a.state),c=matchSignIns(s,{attemptIds:n});if(c.events.length!==0)throw Error(`matchSignIns must not emit events.`);a=saveTransition(a,c),d=e,t.length===0&&(r=void 0)}}r?.payloads.some(e=>e.message!==void 0)&&(o.delete(ScheduleIdKey),o.delete(ScheduleInstanceKey),o.delete(OccurrenceIdKey),r.schedule!==void 0&&(o.set(ScheduleIdKey,r.schedule.definition),r.schedule.instance!==void 0&&o.set(ScheduleInstanceKey,r.schedule.instance),r.schedule.occurrenceId!==void 0&&o.set(OccurrenceIdKey,r.schedule.occurrenceId)));let f=o.get(AuthKey),p=o.has(InitiatorAuthKey);r?.auth!==void 0&&(o.set(AuthKey,r.auth??null),o.has(InitiatorAuthKey)||o.set(InitiatorAuthKey,r.auth??null));let m=r===void 0?d?.find(({challenge:e})=>e.candidateId===void 0)?.challenge.requester:void 0;m!==void 0&&o.set(AuthKey,m);let h=r?.payloads.some(e=>e.message!==void 0)===!0?readPendingHistory(a.state):[],g={...hydrateDurableSession({compactionOverrides:{thresholdPercent:l.thresholdPercent},durable:a,turnAgent:l.turnAgent}),history:validateHarnessModelMessages(e.history)},_=createExecutionHistoryView(g),v=bindSessionInstrumentation({agentName:l.turnAgent.id,ctx:o,rootSessionId:g.rootSessionId??g.sessionId,sessionId:g.sessionId}),y=turnPosition(currentProjection(o)),b=isBetweenTurns(currentProjection(o));if(!y.sessionStarted&&!o.has(SessionTitleKey)&&!o.has(ParentSessionKey)){let e=n?.payloads.find(e=>e.message!==void 0)?.message,r=deriveSessionTitle(n?.title??e);r!==void 0&&(o.set(SessionTitleKey,r),t.title=setEveAttributes({"$eve.title":r}))}n!==void 0&&(await contextStorage.run(o,()=>v?.preparePreamble({sequence:y.sequence,sessionStarted:y.sessionStarted})),await contextStorage.run(o,()=>v?.instrumentChannelDelivery({agentName:c.turnAgent.id,ctx:o,delivery:n,rootSessionId:g.rootSessionId??g.sessionId,sequence:y.sequence,sessionId:g.sessionId,turnId:activeTurnId(y)})));let failChannelDeliveries=async e=>{await contextStorage.run(o,()=>v?.instrumentChannelDelivery({ctx:o,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await v?.flush()},x=openSessionEventPublisher({ctx:o,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:S}=x.dispatcher,C=new AbortController,w=e.abortSignal===void 0?C.signal:AbortSignal.any([e.abortSignal,C.signal]);try{let u=bindDynamicConnections(o,c.resolvedAgent),m={...c.graph.root,turnAgent:l.turnAgent},T=resolveSessionUsageLimit(c),E=!1,D=createTurnEventHandler({abortSignal:w,bundle:c,canCancelTurn:e.input?.control===void 0,hookCancellation:C,ctx:o,dynamicConnections:u,effectiveAgent:l,effectiveNode:m,instrumentation:v,publisher:x}),handleEvent=async(e,t)=>{e.type===`compaction.completed`&&(E=!0),await D(e,t)},O=r!==void 0&&!b?structuredClone(S.state):void 0,k;if(r!==void 0){let e=[];try{for(let t of r.payloads){let n=s.deliver?await s.deliver(t,S):defaultDeliverResult(t);if(n!=null){let r=[...e.length===0?h:[],...t.history??[]];e.push(r.length===0?n:{...n,history:r})}}}catch(e){throw await failChannelDeliveries(e),e}e.length>0&&h.length>0&&(g={...g,state:withoutPendingHistory(g.state)}),k=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let A=r?.auth===void 0?void 0:attributeAnswers({responder:r.auth,state:a.state,stepInput:k});if(A!==void 0&&(k=A,f===void 0?o.delete(AuthKey):o.set(AuthKey,f),p||o.delete(InitiatorAuthKey)),r!==void 0&&k===void 0&&!b)f===void 0?o.delete(AuthKey):o.set(AuthKey,f),S.state=O;else if(n?.payloads.some(e=>e.message!==void 0)){let e=n.deliveryMetadata?.map(e=>e.deliveryId)??[];o.set(TurnDeliveryIdsKey,y.turnId?[...new Set([...o.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!y.sessionStarted&&o.get(ChannelDeliveryKey)!==void 0&&o.set(TurnDeliveryIdsKey,[o.require(ChannelDeliveryKey).deliveryId]);if(i!==void 0&&(i.acceptedAtMsByCallId!==void 0&&o.set(RuntimeActionSettlementTimesKey,i.acceptedAtMsByCallId),k={...k,runtimeActionResults:i.results}),n!==void 0){let e={...s,state:{...S.state}};setChannelContext(o,e)}if(r!==void 0&&k===void 0&&b){await contextStorage.run(o,()=>v?.instrumentChannelDelivery({ctx:o,includeTurn:!1,outcome:`completed`})),await v?.flush();let t=saveSessionProjection(reconcileSessionContinuationToken(o,g),o),n=serializeContext(o),r=t===g?{history:e.history,sessionState:e.sessionState}:createDurableSessionValues(t);return{action:`park`,...derivePendingState(t,currentProjection(o)),serializedContext:n,...r}}let j=c.subagentRegistry.dynamicResolvers??[],M=c.resolvedAgent.dynamicToolResolvers??[],N=buildRuntimeIdentity(m);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(c.compiledArtifactsSource),n=y.sessionStarted;if(o.setVirtualContext(StaticModelReferenceKey,l.turnAgent.model??null),!n)o.set(SessionDynamicSubagentRuntimeRevisionKey,t),o.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=sessionStartedForResolvers(N);await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:o,resolvers:j,event:e,messages:_.initial.messages,runtimeRevision:t}),contextStorage.run(o,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:o,resolvers:M,event:e,messages:_.initial.messages,runtimeRevision:t}))]),b||await rebindMissingCompiledDynamicToolCallbacks({ctx:o,event:turnStartedForResolvers({sequence:y.sequence,turnId:activeTurnId(y)}),messages:_.initial.messages,resolvers:M})}}catch(e){throw await failChannelDeliveries(e),e}let P=c.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,F=o.get(CapabilitiesKey),runHarnessStep=async(n,r,i)=>{let a=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:l.thresholdPercent},session:n,turnAgent:l.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:w,capabilities:F,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent,prepareApprovalTurn:e=>u.dispatch(turnStartedForResolvers(e)),signInCompletions:i,historyProjector:_.projector,historyView:_.prepare(a),instrumentation:v,modelResolutionScope:{moduleMap:c.moduleMap,nodeId:c.nodeId},node:m,sessionUsageLimit:T,titleAttributeWrite:t.title})(a,r)},I,L;try{throwIfTurnAborted(w),L=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:k,initialSession:g,modelCallsPerStep:P,runStep:async({firstCall:e,session:t,stepInput:n})=>{let r=await runStep(o,t,async t=>{o.setVirtualContext(HandleEventKey,handleEvent),o.setVirtualContext(StaticModelReferenceKey,l.turnAgent.model??null);let r=e&&k?.outputSchema!==void 0?{...t,outputSchema:k.outputSchema}:t,i=turnPosition(currentProjection(o));try{await u.rehydrate(i,N,isBetweenTurns(currentProjection(o))?void 0:{sequence:i.sequence,turnId:activeTurnId(i)})}catch(e){let t=await recoverDynamicConnectionRehydration({emit:handleEvent,error:e,projection:currentProjection(o),session:r});if(t!==void 0)return t;throw e}let a=e&&d!==void 0?d.map(({challenge:e})=>e):void 0;return runHarnessStep(r,n,a)});r.settledTurn===void 0&&throwIfTurnAborted(w);let i={...r,session:saveSessionProjection(r.session,o)};return I={result:i,serializedContext:serializeContext(o)},i}})}catch(t){if(!isTurnCancellation(t)&&!w.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:I,ctx:o,initialSession:g,stepInput:k})}let R=saveSessionProjection(dropClosedRecords(reconcileSessionContinuationToken(o,L.session),currentProjection(o)),o);agentTraceState.pruneAgentTraceState(o,R.sessionId,R.state);let z=serializeContext(o);L={...L,session:R};let B=resolveSessionStepResult(L,z);return B.action===`done`&&await x.writer.close(),E?{...B,compacted:!0}:B}finally{x.writer.release()}}export{turnStep};
1
+ import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{currentProjection,enterSessionProjection,saveSessionProjection}from"#harness/session-machine/current.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,OccurrenceIdKey,ParentSessionKey,ScheduleIdKey,ScheduleInstanceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TurnDeliveryIdsKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,validateHarnessModelMessages}from"#harness/messages.js";import{activeTurnId,isBetweenTurns,storedProjection,turnPosition}from"#harness/session-machine/view.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{createDurableSessionValues,readDurableSession}from"#execution/durable-session-store.js";import{runStep}from"#context/run-step.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{readHitlState}from"#harness/hitl/index.js";import*as agentTraceState from"#tracing/eve/agent-trace-context-store.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey}from"#harness/authorization.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime,resolveSessionUsageLimit}from"#execution/effective-agent-config.js";import{openSessionEventPublisher}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{matchSignIns}from"#harness/session-machine/transitions.js";import{readPendingHistory,withoutPendingHistory}from"#execution/session/pending-history.js";import{dropClosedRecords,saveTransition,sessionView}from"#harness/session-machine/commit.js";import{sessionStartedForResolvers,turnStartedForResolvers}from"#harness/session-machine/resolver-events.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{createTurnEventHandler}from"#execution/session/turn-event-handler.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{bindTurnCallerContext}from"#subagents/parent-notification.js";import{traceSessionHandover}from"#execution/session/handover-tracing.js";import{startSessionPrewarmers}from"#context/prewarm.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{recoverDynamicConnectionRehydration}from"#execution/dynamic-connection-recovery.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{attributeAnswers}from"#execution/session/answer-caller.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return e.handover!==void 0&&traceSessionHandover(`inbox_unblocked`,e.sessionState.sessionId,e.handover.attemptKey,{"eve.handoff.buffered_payload_count":e.handover.payloadCount,"eve.handoff.applied_at_ms":e.handover.appliedAtMs,"eve.handoff.applied_at_clock":`workflow`}),await withSessionStateDelta(e,e=>runSessionStep({...e,serializedContext:bindTurnCallerContext(e.caller,e.serializedContext)}))}async function runSessionStep(e){let t={};try{return await runSessionStepBody(e,t)}finally{await t.title}}async function runSessionStepBody(e,t){let n=e.input?.delivery,r=n,i=e.input?.runtimeResults,a=readDurableSession(e.sessionState);for(let e of i?.delegatedUsage??[])a=countRunUsage(a,e);let o=await deserializeContext(e.serializedContext);enterSessionProjection(o,a.state);let s=o.require(ChannelKey),c=o.require(BundleKey),l=resolveEffectiveAgentRuntime(c,o);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&o.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let{signIns:u}=readHitlState(a.state),d;if(u.length>0&&r!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(u,r.payloads);if(r={...r,payloads:t},e.length>0){let n=e.map(e=>e.result.attemptId),i=e.map(e=>e.result);o.set(PendingAuthorizationResultKey,i);let s=sessionView(storedProjection(a.state),a.state),c=matchSignIns(s,{attemptIds:n});if(c.events.length!==0)throw Error(`matchSignIns must not emit events.`);a=saveTransition(a,c),d=e,t.length===0&&(r=void 0)}}r?.payloads.some(e=>e.message!==void 0)&&(o.delete(ScheduleIdKey),o.delete(ScheduleInstanceKey),o.delete(OccurrenceIdKey),r.schedule!==void 0&&(o.set(ScheduleIdKey,r.schedule.definition),r.schedule.instance!==void 0&&o.set(ScheduleInstanceKey,r.schedule.instance),r.schedule.occurrenceId!==void 0&&o.set(OccurrenceIdKey,r.schedule.occurrenceId)));let f=o.get(AuthKey),p=o.has(InitiatorAuthKey);r?.auth!==void 0&&(o.set(AuthKey,r.auth??null),o.has(InitiatorAuthKey)||o.set(InitiatorAuthKey,r.auth??null));let m=r===void 0?d?.find(({challenge:e})=>e.candidateId===void 0)?.challenge.requester:void 0;m!==void 0&&o.set(AuthKey,m);let h=r?.payloads.some(e=>e.message!==void 0)===!0?readPendingHistory(a.state):[],g={...hydrateDurableSession({compactionOverrides:{thresholdPercent:l.thresholdPercent},durable:a,turnAgent:l.turnAgent}),history:validateHarnessModelMessages(e.history)},_=createExecutionHistoryView(g),v=bindSessionInstrumentation({agentName:l.turnAgent.id,ctx:o,rootSessionId:g.rootSessionId??g.sessionId,sessionId:g.sessionId}),y=turnPosition(currentProjection(o)),b=isBetweenTurns(currentProjection(o));if(!y.sessionStarted&&!o.has(SessionTitleKey)&&!o.has(ParentSessionKey)){let e=n?.payloads.find(e=>e.message!==void 0)?.message,r=deriveSessionTitle(n?.title??e);r!==void 0&&(o.set(SessionTitleKey,r),t.title=setEveAttributes({"$eve.title":r}))}n!==void 0&&(await contextStorage.run(o,()=>v?.preparePreamble({sequence:y.sequence,sessionStarted:y.sessionStarted})),await contextStorage.run(o,()=>v?.instrumentChannelDelivery({agentName:c.turnAgent.id,ctx:o,delivery:n,rootSessionId:g.rootSessionId??g.sessionId,sequence:y.sequence,sessionId:g.sessionId,turnId:activeTurnId(y)})));let failChannelDeliveries=async e=>{await contextStorage.run(o,()=>v?.instrumentChannelDelivery({ctx:o,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await v?.flush()},x=openSessionEventPublisher({ctx:o,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:S}=x.dispatcher,C=new AbortController,w=e.abortSignal===void 0?C.signal:AbortSignal.any([e.abortSignal,C.signal]);try{let u=bindDynamicConnections(o,c.resolvedAgent),m={...c.graph.root,turnAgent:l.turnAgent},T=resolveSessionUsageLimit(c),E=!1,D=createTurnEventHandler({abortSignal:w,bundle:c,canCancelTurn:e.input?.control===void 0,hookCancellation:C,ctx:o,dynamicConnections:u,effectiveAgent:l,effectiveNode:m,instrumentation:v,publisher:x}),handleEvent=async(e,t)=>{e.type===`compaction.completed`&&(E=!0),await D(e,t)},O=r!==void 0&&!b?structuredClone(S.state):void 0,k;if(r!==void 0){let e=[];try{for(let t of r.payloads){let n=s.deliver?await s.deliver(t,S):defaultDeliverResult(t);if(n!=null){let r=[...e.length===0?h:[],...t.history??[]];e.push(r.length===0?n:{...n,history:r})}}}catch(e){throw await failChannelDeliveries(e),e}e.length>0&&h.length>0&&(g={...g,state:withoutPendingHistory(g.state)}),k=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let A=r?.auth===void 0?void 0:attributeAnswers({responder:r.auth,state:a.state,stepInput:k});if(A!==void 0&&(k=A,f===void 0?o.delete(AuthKey):o.set(AuthKey,f),p||o.delete(InitiatorAuthKey)),r!==void 0&&k===void 0&&!b)f===void 0?o.delete(AuthKey):o.set(AuthKey,f),S.state=O;else if(n?.payloads.some(e=>e.message!==void 0)){let e=n.deliveryMetadata?.map(e=>e.deliveryId)??[];o.set(TurnDeliveryIdsKey,y.turnId?[...new Set([...o.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!y.sessionStarted&&o.get(ChannelDeliveryKey)!==void 0&&o.set(TurnDeliveryIdsKey,[o.require(ChannelDeliveryKey).deliveryId]);if(i!==void 0&&(i.acceptedAtMsByCallId!==void 0&&o.set(RuntimeActionSettlementTimesKey,i.acceptedAtMsByCallId),k={...k,runtimeActionResults:i.results}),n!==void 0){let e={...s,state:{...S.state}};setChannelContext(o,e)}if(r!==void 0&&k===void 0&&b){await contextStorage.run(o,()=>v?.instrumentChannelDelivery({ctx:o,includeTurn:!1,outcome:`completed`})),await v?.flush();let t=saveSessionProjection(reconcileSessionContinuationToken(o,g),o),n=serializeContext(o),r=t===g?{history:e.history,sessionState:e.sessionState}:createDurableSessionValues(t);return{action:`park`,...derivePendingState(t,currentProjection(o)),serializedContext:n,...r}}let j=c.subagentRegistry.dynamicResolvers??[],M=c.resolvedAgent.dynamicToolResolvers??[],N=buildRuntimeIdentity(m);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(c.compiledArtifactsSource),n=y.sessionStarted;if(o.setVirtualContext(StaticModelReferenceKey,l.turnAgent.model??null),!n)o.set(SessionDynamicSubagentRuntimeRevisionKey,t),o.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=sessionStartedForResolvers(N);await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:o,resolvers:j,event:e,messages:_.initial.messages,runtimeRevision:t}),contextStorage.run(o,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:o,resolvers:M,event:e,messages:_.initial.messages,runtimeRevision:t}))]),b||await rebindMissingCompiledDynamicToolCallbacks({ctx:o,event:turnStartedForResolvers({sequence:y.sequence,turnId:activeTurnId(y)}),messages:_.initial.messages,resolvers:M})}}catch(e){throw await failChannelDeliveries(e),e}let P=c.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,F=o.get(CapabilitiesKey),runHarnessStep=async(n,r,i)=>{let a=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:l.thresholdPercent},session:n,turnAgent:l.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:w,capabilities:F,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent,prepareApprovalTurn:e=>u.dispatch(turnStartedForResolvers(e)),signInCompletions:i,historyProjector:_.projector,historyView:_.prepare(a),instrumentation:v,modelResolutionScope:{moduleMap:c.moduleMap,nodeId:c.nodeId},node:m,sessionUsageLimit:T,titleAttributeWrite:t.title})(a,r)},I,L;try{throwIfTurnAborted(w),L=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:k,initialSession:g,modelCallsPerStep:P,runStep:async({firstCall:t,session:n,stepInput:r})=>{let i=await runStep(o,n,async n=>{t&&e.input?.control===void 0&&startSessionPrewarmers(o,`turn`),o.setVirtualContext(HandleEventKey,handleEvent),o.setVirtualContext(StaticModelReferenceKey,l.turnAgent.model??null);let i=t&&k?.outputSchema!==void 0?{...n,outputSchema:k.outputSchema}:n,a=turnPosition(currentProjection(o));try{await u.rehydrate(a,N,isBetweenTurns(currentProjection(o))?void 0:{sequence:a.sequence,turnId:activeTurnId(a)})}catch(e){let t=await recoverDynamicConnectionRehydration({emit:handleEvent,error:e,projection:currentProjection(o),session:i});if(t!==void 0)return t;throw e}let s=t&&d!==void 0?d.map(({challenge:e})=>e):void 0;return runHarnessStep(i,r,s)});i.settledTurn===void 0&&throwIfTurnAborted(w);let a={...i,session:saveSessionProjection(i.session,o)};return I={result:a,serializedContext:serializeContext(o)},a}})}catch(t){if(!isTurnCancellation(t)&&!w.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:I,ctx:o,initialSession:g,stepInput:k})}let R=saveSessionProjection(dropClosedRecords(reconcileSessionContinuationToken(o,L.session),currentProjection(o)),o);agentTraceState.pruneAgentTraceState(o,R.sessionId,R.state);let z=serializeContext(o);L={...L,session:R};let B=resolveSessionStepResult(L,z);return B.action===`done`&&await x.writer.close(),E?{...B,compacted:!0}:B}finally{x.writer.release()}}export{turnStep};
@@ -23,6 +23,7 @@ export interface SessionExecutionInput {
23
23
  */
24
24
  export declare class SessionExecution {
25
25
  private readonly input;
26
+ private observedHandoverAttemptKey;
26
27
  constructor(input: SessionExecutionInput);
27
28
  get cursor(): SessionStateCursor;
28
29
  runTurn(delivery: TurnStepPayload | undefined, options?: {
@@ -1 +1 @@
1
- import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{TASK_WAIT_TOOL_NAME}from"#protocol/task-tools.js";import{renderTaskWaitResult}from"#execution/tasks/render.js";import{sleep}from"#compiled/@workflow/core/index.js";import{findBlockingWorkflowToolRun,getBlockingWorkflowToolRuns,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{taskWaitResult}from"#execution/tasks/table.js";import{handleWorkflowToolRunMessage,isAppliedRunMessage,takeLeadingAppliedRunMessages}from"#execution/session-workflow-tool-run.js";import{resolveTurnPrincipal}from"#execution/session/principal.js";import{answerTaskCancel,cancelWorkingTasks,sessionTaskTable}from"#execution/tasks/session.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchCoordinationStep,publishTaskStartedStep}from"#execution/coordination-dispatch-step.js";import{taskToolResult}from"#execution/tasks/calls.js";import{publishTurnWaitingStep}from"#execution/session/turn-waiting-step.js";import{applyRunMessagesStep}from"#execution/tools/workflow/apply-run-messages-step.js";import{interruptWorkflowToolRun}from"#execution/tools/workflow/interrupt.js";import{turnStep}from"#execution/session/turn-step.js";import{ActiveTurn}from"#execution/session/active-turn.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";import{startTaskToolCallsStep,traceTaskToolCallStep}from"#execution/session/task-tool-tracing-step.js";function hasDelegatedCallerContext(e){if(e[`eve.sessionCallback`]!==void 0)return!0;let t=e[`eve.channel`];return typeof t==`object`&&!!t&&Reflect.get(t,`kind`)===`subagent`}var SessionExecution=class{input;constructor(e){this.input=e}get cursor(){return this.input.cursor}async runTurn(e,t={}){let n;try{n=new ActiveTurn(this.input,{caller:t.caller,principal:resolveTurnPrincipal(e,this.input.cursor.serializedContext)},t.control)}catch(e){throw t.control?.dispose(),e}try{let t=await this.runTurnSteps(n,e);return await this.handleBoundaryMessages(n.takeBoundaryMessages(),t.kind===`done`),t.kind===`park`&&t.settled!==void 0&&await cancelWorkingTasks(this.input.cursor,`turn_ended`),{...t,...n.caller!==void 0&&{caller:n.caller},...n.compacted&&{compacted:!0}}}finally{n.dispose()}}async handleBoundaryMessages(e,t=!1,n){let r=[];for(let i of e)isAppliedRunMessage(i)?(!t||i.kind!==`agent-started`)&&r.push(i):(await this.applyRunMessages(r,n),r=[],await handleWorkflowToolRunMessage({cursor:this.input.cursor,message:i}));await this.applyRunMessages(r,n)}async applyRunMessages(e,t){if(e.length===0)return;let{cancelled:n}=await this.input.cursor.advance(n=>applyRunMessagesStep({...n,canCancelTurn:t!==void 0,messages:e}));n&&t?.abort()}async runTurnSteps(e,t){let n=t,r=e.caller;for(;;){let{cursor:t}=this.input,i=r;r=void 0;let a=await t.advanceWithHistory(t=>turnStep({...t,abortSignal:e.signal,caller:i,input:n,steeringSignal:e.steeringSignal}));a.compacted===!0&&(e.compacted=!0);let o=a.action===`park`?a.pendingCoordinationCallIds:void 0,s=a.action===`park`&&a.settled!==void 0,c=this.input.queue.nextAdmission;await e.admitBoundary();let l=a.action===`done`;if(await this.handleBoundaryMessages(e.takeBoundaryMessages(),l,l?void 0:e),a.action===`cancelled`||!s&&e.signal.aborted&&o===void 0)return await this.finishCancelledTurn(e);if(a.action===`done`)return{isError:a.isError,kind:`done`,output:a.output??``,usage:a.usage,usageDelta:a.usageDelta};if(a.action===`held`&&a.hold===`request`){if(a.hasPendingInputBatch&&this.input.capabilities?.requestInput!==!0&&!hasDelegatedCallerContext(this.input.cursor.serializedContext))throw Error(`This session cannot request human input, so it cannot wait for a tool approval or question. Configure unattended tools with an approval policy that does not require human input.`);let t=await this.waitForHeldRequest(e,a,c);if(t===`cancelled`)return await this.finishCancelledTurn(e);n={delivery:t};continue}if(a.action===`held`){if(await this.waitForHeldTurn(e)===`cancelled`)return await this.finishCancelledTurn(e);let t=await e.takeSteering();n=t===void 0?void 0:{delivery:t};continue}if(o!==void 0&&a.action===`park`){let t=a.hasRunsToDispatch===!1?[]:await this.dispatchRuns(),r=t.length===0?void 0:Date.now(),i=await this.waitForRuntimeActionResults({initialAcceptedAtMs:r,initialResults:t,taskToolCalls:a.pendingTaskToolCalls??[],pendingCallIds:o,turn:e});if(i===`cancelled`)return await this.finishCancelledTurn(e);n={delivery:await e.takeSteering(),runtimeResults:i};continue}if(a.action===`park`)return{kind:`park`,settled:a.settled};let u=await e.takeSteering();n=u===void 0?void 0:{delivery:u}}}async dispatchRuns(){let{cursor:e}=this.input,t=await e.advance(({serializedContext:e,sessionState:t})=>dispatchCoordinationStep({action:`park`,serializedContext:e,sessionState:t,workflowToolRunOwner:{inbox:sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId))}}));return t.started.length>0&&await e.advance(e=>publishTaskStartedStep({...e,started:t.started})),t.results}async handleWorkflowMessage(e,t){if(isAppliedRunMessage(e)){let n=t?.takeAppliedRunMessages()??takeLeadingAppliedRunMessages(this.input.inbox);await this.applyRunMessages([e,...n],t);return}return await handleWorkflowToolRunMessage({cursor:this.input.cursor,message:e})}async cancelTurnWork(){let{cursor:e}=this.input;mayWaitOnWorkflowToolRuns(e.sessionState)&&await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState}),await cancelWorkingTasks(e,`turn_cancelled`)}async finishCancelledTurn(e){return await this.handleBoundaryMessages(e.takeBoundaryMessages(`agent-started`)),await this.cancelTurnWork(),{cancelled:!0,kind:`park`}}async waitForHeldTurn(e){let t=!1;for(;;){let n={interrupted:t,timedOut:!1};if(taskWaitResult(sessionTaskTable(this.input.cursor),n)!==void 0)return`woke`;let r=await e.nextRuntimeEvent([]);if(r===`cancelled`)return r;switch(r.kind){case`steering`:t=!0;continue;case`workflow`:await this.handleWorkflowMessage(r.message,e);continue;case`input`:case`runtime-action-result`:case`timeout`:continue}}}async waitForHeldRequest(e,t,n){let r=new Set(t.authorizationAttemptIds),i=new Set(t.inputRequestIds);for(;;){let t=this.input.queue.takeAuthorizations(r);if(t!==void 0)return{kind:`deliver`,payloads:t};let a=await e.takeInputResponses(i);if(a!==void 0)return a;let o=await e.takeSteering({heldSince:n});if(o!==void 0)return o;let s=await e.nextRuntimeEvent([]);if(s===`cancelled`)return s;s.kind===`workflow`&&await this.handleWorkflowMessage(s.message,e)}}async waitForRuntimeActionResults(e){let t=[...e.initialResults],n=!1,r=new Map,i=new Map;if(e.initialAcceptedAtMs!==void 0)for(let n of t)r.set(n.callId,e.initialAcceptedAtMs);let accept=e=>{t.push(e),r.set(e.callId,Date.now())},a=await this.answerTaskToolCalls(e.taskToolCalls,accept);try{for(;;){a=await this.resolveTaskWaits(a,n,accept);let o=resolveRuntimeActionResultsForCallIds({pendingCallIds:e.pendingCallIds,results:t});if(o!==void 0){let e=o.flatMap(e=>{let t=i.get(e.callId);return t===void 0?[]:[t]});return{acceptedAtMsByCallId:Object.fromEntries(o.map(e=>[e.callId,r.get(e.callId)])),...e.length>0&&{delegatedUsage:e},results:o}}let s=a.flatMap(e=>e.timer===void 0?[]:[e.timer]),c=await e.turn.nextRuntimeEvent(s);if(c===`cancelled`)return c;if(c.kind===`timeout`){for(let e of a)e.callId===c.callId&&(e.timedOut=!0);continue}if(c.kind===`input`)continue;if(c.kind===`steering`){n||await this.interruptWaitedWorkflowCalls(e.pendingCallIds,t),n=!0;continue}if(c.kind===`runtime-action-result`){let e=this.input.cursor.sessionState.snapshot.session.state,n=c.results.filter(t=>t.kind===`tool-result`&&isInboxToolResultFromRecordedWorkflowToolRun(e,t));if(n.length>0){let e=Date.now();t.push(...n);for(let t of n)r.set(t.callId,e)}continue}let l=await this.handleWorkflowMessage(c.message,e.turn);l!==void 0&&(accept(l),c.message.kind===`outcome`&&c.message.usage!==void 0&&i.set(l.callId,c.message.usage))}}finally{for(let e of a)await this.traceTaskWait(e,void 0,!0)}}async resolveTaskWaits(e,t,n){let r=sessionTaskTable(this.input.cursor),i=[];for(let a of e){let e=taskWaitResult(r,{interrupted:t,timedOut:a.timedOut});if(e===void 0){i.push(a);continue}let o=renderTaskWaitResult(e,Date.now()-a.startedAtMs);await this.traceTaskWait(a,o,t),n(taskToolResult(a.callId,TASK_WAIT_TOOL_NAME,o))}return i}async answerTaskToolCalls(e,t){let n=[],r=e.length===0?0:await startTaskToolCallsStep();for(let i of e)if(i.kind===TASK_WAIT_TOOL_NAME)n.push(startTaskWait(i,r));else{let e;try{e=await answerTaskCancel(this.input.cursor,i)}catch(e){throw await this.input.cursor.advance(e=>traceTaskToolCallStep(e,{callId:i.callId,toolName:i.kind,startedAtMs:r,completedAtMs:Date.now(),input:{taskId:i.taskId},failed:!0})),e}await this.input.cursor.advance(t=>traceTaskToolCallStep(t,{callId:i.callId,toolName:i.kind,startedAtMs:r,completedAtMs:Date.now(),input:{taskId:i.taskId},output:e.output})),t(e)}let i=await this.resolveTaskWaits(n,!1,t);return i.length>0&&await this.input.cursor.advance(publishTurnWaitingStep),i}async traceTaskWait(e,t,n=!1){await this.input.cursor.advance(r=>traceTaskToolCallStep(r,{callId:e.callId,toolName:TASK_WAIT_TOOL_NAME,startedAtMs:e.startedAtMs,completedAtMs:Date.now(),input:e.input,output:t,failed:n}))}async interruptWaitedWorkflowCalls(e,t){let n=this.input.cursor.sessionState.snapshot.session.state,r=new Set(t.map(e=>e.callId)),i=e.filter(e=>!r.has(e)).flatMap(e=>{let t=findBlockingWorkflowToolRun(n,e);return t===void 0?[]:[t.address]});await Promise.all(i.map(e=>interruptWorkflowToolRun(e)))}};function startTaskWait(e,t){let{callId:n,timeoutMs:r}=e,i=r===void 0?void 0:sleep(r).then(()=>n);return{callId:n,startedAtMs:t,input:r===void 0?{}:{timeoutSeconds:r/1e3},timedOut:r===0,timer:i}}function mayWaitOnWorkflowToolRuns(e){try{return getBlockingWorkflowToolRuns(e.snapshot?.session?.state).length>0}catch{return!0}}export{SessionExecution,hasDelegatedCallerContext};
1
+ import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{TASK_WAIT_TOOL_NAME}from"#protocol/task-tools.js";import{renderTaskWaitResult}from"#execution/tasks/render.js";import{sleep}from"#compiled/@workflow/core/index.js";import{findBlockingWorkflowToolRun,getBlockingWorkflowToolRuns,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{taskWaitResult}from"#execution/tasks/table.js";import{handleWorkflowToolRunMessage,isAppliedRunMessage,takeLeadingAppliedRunMessages}from"#execution/session-workflow-tool-run.js";import{resolveTurnPrincipal}from"#execution/session/principal.js";import{answerTaskCancel,cancelWorkingTasks,sessionTaskTable}from"#execution/tasks/session.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchCoordinationStep,publishTaskStartedStep}from"#execution/coordination-dispatch-step.js";import{taskToolResult}from"#execution/tasks/calls.js";import{publishTurnWaitingStep}from"#execution/session/turn-waiting-step.js";import{applyRunMessagesStep}from"#execution/tools/workflow/apply-run-messages-step.js";import{interruptWorkflowToolRun}from"#execution/tools/workflow/interrupt.js";import{turnStep}from"#execution/session/turn-step.js";import{ActiveTurn}from"#execution/session/active-turn.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";import{startTaskToolCallsStep,traceTaskToolCallStep}from"#execution/session/task-tool-tracing-step.js";function hasDelegatedCallerContext(e){if(e[`eve.sessionCallback`]!==void 0)return!0;let t=e[`eve.channel`];return typeof t==`object`&&!!t&&Reflect.get(t,`kind`)===`subagent`}var SessionExecution=class{input;observedHandoverAttemptKey;constructor(e){this.input=e}get cursor(){return this.input.cursor}async runTurn(e,t={}){let n=new ActiveTurn(this.input,{caller:t.caller,principal:resolveTurnPrincipal(e,this.input.cursor.serializedContext)},t.control);try{let t=await this.runTurnSteps(n,e);return await this.handleBoundaryMessages(n.takeBoundaryMessages(),t.kind===`done`),t.kind===`park`&&t.settled!==void 0&&await cancelWorkingTasks(this.input.cursor,`turn_ended`),{...t,...n.caller!==void 0&&{caller:n.caller},...n.compacted&&{compacted:!0}}}finally{n.dispose()}}async handleBoundaryMessages(e,t=!1,n){let r=[];for(let i of e)isAppliedRunMessage(i)?(!t||i.kind!==`agent-started`)&&r.push(i):(await this.applyRunMessages(r,n),r=[],await handleWorkflowToolRunMessage({cursor:this.input.cursor,message:i}));await this.applyRunMessages(r,n)}async applyRunMessages(e,t){if(e.length===0)return;let{cancelled:n}=await this.input.cursor.advance(n=>applyRunMessagesStep({...n,canCancelTurn:t!==void 0,messages:e}));n&&t?.abort()}async runTurnSteps(e,t){let n=t,r=e.caller;for(;;){let{cursor:t}=this.input,i=r;r=void 0;let a=this.input.inbox.handoverObservation,o=a?.attemptKey===this.observedHandoverAttemptKey?void 0:a,s=await t.advanceWithHistory(t=>turnStep({...t,handover:o,abortSignal:e.signal,caller:i,input:n,steeringSignal:e.steeringSignal}));o!==void 0&&(this.observedHandoverAttemptKey=o.attemptKey),s.compacted===!0&&(e.compacted=!0);let c=s.action===`park`?s.pendingCoordinationCallIds:void 0,l=s.action===`park`&&s.settled!==void 0,u=this.input.queue.nextAdmission;await e.admitBoundary();let d=s.action===`done`;if(await this.handleBoundaryMessages(e.takeBoundaryMessages(),d,d?void 0:e),s.action===`cancelled`||!l&&e.signal.aborted&&c===void 0)return await this.finishCancelledTurn(e);if(s.action===`done`)return{isError:s.isError,kind:`done`,output:s.output??``,usage:s.usage,usageDelta:s.usageDelta};if(s.action===`held`&&s.hold===`request`){if(s.hasPendingInputBatch&&this.input.capabilities?.requestInput!==!0&&!hasDelegatedCallerContext(this.input.cursor.serializedContext))throw Error(`This session cannot request human input, so it cannot wait for a tool approval or question. Configure unattended tools with an approval policy that does not require human input.`);let t=await this.waitForHeldRequest(e,s,u);if(t===`cancelled`)return await this.finishCancelledTurn(e);n={delivery:t};continue}if(s.action===`held`){if(await this.waitForHeldTurn(e)===`cancelled`)return await this.finishCancelledTurn(e);let t=await e.takeSteering();n=t===void 0?void 0:{delivery:t};continue}if(c!==void 0&&s.action===`park`){let t=s.hasRunsToDispatch===!1?[]:await this.dispatchRuns(),r=t.length===0?void 0:Date.now(),i=await this.waitForRuntimeActionResults({initialAcceptedAtMs:r,initialResults:t,taskToolCalls:s.pendingTaskToolCalls??[],pendingCallIds:c,turn:e});if(i===`cancelled`)return await this.finishCancelledTurn(e);n={delivery:await e.takeSteering(),runtimeResults:i};continue}if(s.action===`park`)return{kind:`park`,settled:s.settled};let f=await e.takeSteering();n=f===void 0?void 0:{delivery:f}}}async dispatchRuns(){let{cursor:e}=this.input,t=await e.advance(({serializedContext:e,sessionState:t})=>dispatchCoordinationStep({action:`park`,serializedContext:e,sessionState:t,workflowToolRunOwner:{inbox:sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId))}}));return t.started.length>0&&await e.advance(e=>publishTaskStartedStep({...e,started:t.started})),t.results}async handleWorkflowMessage(e,t){if(isAppliedRunMessage(e)){let n=t?.takeAppliedRunMessages()??takeLeadingAppliedRunMessages(this.input.inbox);await this.applyRunMessages([e,...n],t);return}return await handleWorkflowToolRunMessage({cursor:this.input.cursor,message:e})}async cancelTurnWork(){let{cursor:e}=this.input;mayWaitOnWorkflowToolRuns(e.sessionState)&&await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState}),await cancelWorkingTasks(e,`turn_cancelled`)}async finishCancelledTurn(e){return await this.handleBoundaryMessages(e.takeBoundaryMessages(`agent-started`)),await this.cancelTurnWork(),{cancelled:!0,kind:`park`}}async waitForHeldTurn(e){let t=!1;for(;;){let n={interrupted:t,timedOut:!1};if(taskWaitResult(sessionTaskTable(this.input.cursor),n)!==void 0)return`woke`;let r=await e.nextRuntimeEvent([]);if(r===`cancelled`)return r;switch(r.kind){case`steering`:t=!0;continue;case`workflow`:await this.handleWorkflowMessage(r.message,e);continue;case`input`:case`runtime-action-result`:case`timeout`:continue}}}async waitForHeldRequest(e,t,n){let r=new Set(t.authorizationAttemptIds),i=new Set(t.inputRequestIds);for(;;){let t=this.input.queue.takeAuthorizations(r);if(t!==void 0)return{kind:`deliver`,payloads:t};let a=await e.takeInputResponses(i);if(a!==void 0)return a;let o=await e.takeSteering({heldSince:n});if(o!==void 0)return o;let s=await e.nextRuntimeEvent([]);if(s===`cancelled`)return s;s.kind===`workflow`&&await this.handleWorkflowMessage(s.message,e)}}async waitForRuntimeActionResults(e){let t=[...e.initialResults],n=!1,r=new Map,i=new Map;if(e.initialAcceptedAtMs!==void 0)for(let n of t)r.set(n.callId,e.initialAcceptedAtMs);let accept=e=>{t.push(e),r.set(e.callId,Date.now())},a=await this.answerTaskToolCalls(e.taskToolCalls,accept);try{for(;;){a=await this.resolveTaskWaits(a,n,accept);let o=resolveRuntimeActionResultsForCallIds({pendingCallIds:e.pendingCallIds,results:t});if(o!==void 0){let e=o.flatMap(e=>{let t=i.get(e.callId);return t===void 0?[]:[t]});return{acceptedAtMsByCallId:Object.fromEntries(o.map(e=>[e.callId,r.get(e.callId)])),...e.length>0&&{delegatedUsage:e},results:o}}let s=a.flatMap(e=>e.timer===void 0?[]:[e.timer]),c=await e.turn.nextRuntimeEvent(s);if(c===`cancelled`)return c;if(c.kind===`timeout`){for(let e of a)e.callId===c.callId&&(e.timedOut=!0);continue}if(c.kind===`input`)continue;if(c.kind===`steering`){n||await this.interruptWaitedWorkflowCalls(e.pendingCallIds,t),n=!0;continue}if(c.kind===`runtime-action-result`){let e=this.input.cursor.sessionState.snapshot.session.state,n=c.results.filter(t=>t.kind===`tool-result`&&isInboxToolResultFromRecordedWorkflowToolRun(e,t));if(n.length>0){let e=Date.now();t.push(...n);for(let t of n)r.set(t.callId,e)}continue}let l=await this.handleWorkflowMessage(c.message,e.turn);l!==void 0&&(accept(l),c.message.kind===`outcome`&&c.message.usage!==void 0&&i.set(l.callId,c.message.usage))}}finally{for(let e of a)await this.traceTaskWait(e,void 0,!0)}}async resolveTaskWaits(e,t,n){let r=sessionTaskTable(this.input.cursor),i=[];for(let a of e){let e=taskWaitResult(r,{interrupted:t,timedOut:a.timedOut});if(e===void 0){i.push(a);continue}let o=renderTaskWaitResult(e,Date.now()-a.startedAtMs);await this.traceTaskWait(a,o,t),n(taskToolResult(a.callId,TASK_WAIT_TOOL_NAME,o))}return i}async answerTaskToolCalls(e,t){let n=[],r=e.length===0?0:await startTaskToolCallsStep();for(let i of e)if(i.kind===TASK_WAIT_TOOL_NAME)n.push(startTaskWait(i,r));else{let e;try{e=await answerTaskCancel(this.input.cursor,i)}catch(e){throw await this.input.cursor.advance(e=>traceTaskToolCallStep(e,{callId:i.callId,toolName:i.kind,startedAtMs:r,completedAtMs:Date.now(),input:{taskId:i.taskId},failed:!0})),e}await this.input.cursor.advance(t=>traceTaskToolCallStep(t,{callId:i.callId,toolName:i.kind,startedAtMs:r,completedAtMs:Date.now(),input:{taskId:i.taskId},output:e.output})),t(e)}let i=await this.resolveTaskWaits(n,!1,t);return i.length>0&&await this.input.cursor.advance(publishTurnWaitingStep),i}async traceTaskWait(e,t,n=!1){await this.input.cursor.advance(r=>traceTaskToolCallStep(r,{callId:e.callId,toolName:TASK_WAIT_TOOL_NAME,startedAtMs:e.startedAtMs,completedAtMs:Date.now(),input:e.input,output:t,failed:n}))}async interruptWaitedWorkflowCalls(e,t){let n=this.input.cursor.sessionState.snapshot.session.state,r=new Set(t.map(e=>e.callId)),i=e.filter(e=>!r.has(e)).flatMap(e=>{let t=findBlockingWorkflowToolRun(n,e);return t===void 0?[]:[t.address]});await Promise.all(i.map(e=>interruptWorkflowToolRun(e)))}};function startTaskWait(e,t){let{callId:n,timeoutMs:r}=e,i=r===void 0?void 0:sleep(r).then(()=>n);return{callId:n,startedAtMs:t,input:r===void 0?{}:{timeoutSeconds:r/1e3},timedOut:r===0,timer:i}}function mayWaitOnWorkflowToolRuns(e){try{return getBlockingWorkflowToolRuns(e.snapshot?.session?.state).length>0}catch{return!0}}export{SessionExecution,hasDelegatedCallerContext};
@@ -1,3 +1,4 @@
1
+ import type { SessionPrewarmPayload } from "#execution/session-prewarm.js";
1
2
  import type { DeliverPayload, HookPayload, SessionCommand } from "#channel/types.js";
2
3
  import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
3
4
  /** All session addresses accept the same protocol. Callback routes construct
@@ -26,12 +27,20 @@ export interface SessionHandoverPayload {
26
27
  readonly final?: true;
27
28
  readonly payloads: readonly Exclude<SessionInboxPayload, SessionHandoverPayload>[];
28
29
  }
29
- export type SessionInboxPayload = SessionFailurePayload | SessionHandoverPayload | HookPayload | SessionCommand | WorkflowToolRunMessage | AuthorizationCallbackPayload;
30
+ /** Replay-stable evidence that every buffered part and the final marker were applied. */
31
+ export interface SessionHandoverObservation {
32
+ readonly attemptKey: string;
33
+ readonly payloadCount: number;
34
+ /** Workflow event time, not the host wall clock when replay reached this point. */
35
+ readonly appliedAtMs: number;
36
+ }
37
+ export type SessionInboxPayload = SessionPrewarmPayload | SessionFailurePayload | SessionHandoverPayload | HookPayload | SessionCommand | WorkflowToolRunMessage | AuthorizationCallbackPayload;
30
38
  /**
31
39
  * While a handover is awaited (see {@link SessionHookBatchClaimOptions.handover}),
32
40
  * reads expose nothing; interrupt handlers still fire on arrival.
33
41
  */
34
42
  export interface SessionInboxReader {
43
+ readonly handoverObservation?: SessionHandoverObservation;
35
44
  /**
36
45
  * Waits for and removes the next accepted payload in arrival order, or
37
46
  * `undefined` once no hook can deliver any more (released or taken over).
@@ -69,6 +78,13 @@ export interface SessionHookClaimOptions {
69
78
  * token this inbox already holds is claimed again on a fresh hook.
70
79
  */
71
80
  readonly force?: boolean;
81
+ /**
82
+ * Creates the hook at once but confirms its registration only after this
83
+ * settles. While a registration is awaited, Workflow queues every step
84
+ * started beside it instead of running it inline, so a claim made next to a
85
+ * step confirms after that step; the hook still commits alongside it.
86
+ */
87
+ readonly confirmAfter?: Promise<unknown>;
72
88
  }
73
89
  export interface SessionHookBatchClaimOptions extends SessionHookClaimOptions {
74
90
  /**
@@ -1 +1 @@
1
- import{sessionInboxHookToken}from"#execution/session-inbox/address.js";import{createHook,getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookForceClaimedError}from"#execution/hook-ownership.js";import{releaseSessionHooksStep}from"#execution/session-inbox/release-step.js";function isInterrupt(e){return e.kind===`cancel`||e.kind===`reset`||e.kind===`session-timeout`||e.kind===`session-failure`}function isDelivery(e){return e.kind===`send`||e.kind===`deliver`}function createSessionInbox(e){let t=[],n=[],r=new Set,i=new Set,a=new Set,o,s,c=new Set,l=new Set,u=!1,d=!1,notify=()=>{for(let e of r)e();r.clear()},wait=()=>new Promise(e=>r.add(e)),closed=()=>t.every(e=>e.closed||e.stopping),gated=()=>s!==void 0&&t.length>0,hasReadable=()=>!gated()&&n.length>0,throwIfFailed=()=>{if(o!==void 0)throw o.error},observe=(e,t,n)=>{for(let r of t)if(n(r))for(let t of e)t(r)},openHandover=()=>{s=void 0,observe(a,n,isDelivery),notify()},blockedOnHandover=()=>{if(gated()){for(let e of c)e();c.clear()}},acceptHandover=e=>{let t=s;if(t===void 0||e.attemptKey!==t.attemptKey||e.index<t.nextPart||t.parts.has(e.index))return;t.parts.set(e.index,e);let r=[];for(;;){let e=t.parts.get(t.nextPart);if(e===void 0)break;if(e.final===!0){observe(i,r,isInterrupt),openHandover();return}t.parts.delete(t.nextPart),t.nextPart+=1,n.splice(t.index,0,...e.payloads),t.index+=e.payloads.length,r.push(...e.payloads)}observe(i,r,isInterrupt),notify()},pump=async e=>{let r=e.hook[Symbol.asyncIterator]();try{for(;!e.stopping;){let e=await r.next();if(e.done)break;let t=e.value;for(let e of l)e();if(l.clear(),t.kind===`workflow-batch`){n.push(...t.messages),notify();continue}if(t.kind===`handover`){acceptHandover(t);continue}n.push(t),gated()||observe(a,[t],isDelivery),observe(i,[t],isInterrupt),notify()}}catch(n){if(e.stopping||e.replaced)return;isHookForceClaimedError(n)?(t.splice(t.indexOf(e),1),u=!0):o={error:n}}finally{e.closed=!0,notify()}},stop=async()=>{let e=t.splice(0);s=void 0,u=!1,d=!0;for(let t of e)t.stopping=!0;notify(),await Promise.all(e.map(({hook:e})=>disposeHook(e)));let r=n.splice(0);return notify(),r},claimSessionHook=async(n,r={})=>{if(!n)throw Error(`A session alias requires a nonempty continuation token.`);let i=r.force===!0,a=t.find(e=>e.token===n);if(a!==void 0&&!i)return await a.registered;if(a===void 0&&t.length>=256)throw Error(`A session may claim at most 256 addresses.`);let o={token:n,hook:createHook({token:sessionInboxHookToken(n),metadata:{sessionId:e},...i&&{experimental_force:!0}}),stopping:!1,closed:!1,replaced:!1};a===void 0?t.push(o):(a.replaced=!0,t.splice(t.indexOf(a),1,o)),d=!1;try{o.registered=claimHookOwnership(o.hook),await o.registered,u=!1,pump(o)}catch(e){throw a===void 0||a.closed?t.splice(t.indexOf(o),1):(a.replaced=!1,t.splice(t.indexOf(o),1,a)),e}};return{get claimedTokens(){return t.map(({token:e})=>e)},get awaitingHandover(){return s!==void 0},async whenHandoverSettled(){for(;s!==void 0;)await wait()},abandonHandover(e){s?.attemptKey===e&&openHandover()},whenBlockedOnHandover(){return new Promise(e=>c.add(e))},whenArrival(){return new Promise(e=>l.add(e))},get takenOver(){return u&&t.length===0},claimSessionHook,async claimSessionHooks(e,t={}){t.handover!==void 0&&(s={attemptKey:t.handover,index:n.length,nextPart:0,parts:new Map});let r=await Promise.allSettled([...new Set(e)].map(e=>claimSessionHook(e,t)));for(let e of r)if(e.status===`rejected`)throw e.reason},async whenTakenOver(e){for(e?.addEventListener(`abort`,notify,{once:!0});t.length>0||!u;){if(throwIfFailed(),d)throw Error(`The session inbox was released before a takeover.`);if(e?.aborted===!0)throw e.reason;await wait()}},async next(){for(;;){if(throwIfFailed(),hasReadable())return n.shift();if(closed())return;blockedOnHandover(),await wait()}},drain(){return throwIfFailed(),gated()?[]:n.splice(0)},takeLeading(e){throwIfFailed();let t=[];if(gated())return t;for(let r=n[0];r!==void 0&&e(r);r=n[0])t.push(r),n.shift();return t},hasPending(){return throwIfFailed(),hasReadable()},async whenPending(){for(;o===void 0&&!hasReadable()&&!closed();)blockedOnHandover(),await wait()},onInterrupt(e){return i.add(e),()=>i.delete(e)},onDelivery(e){if(a.add(e),!gated())for(let t of n)isDelivery(t)&&e(t);return()=>a.delete(e)},restore(e){if(t.length===0)throw Error(`Cannot restore session commands before reclaiming the session hooks.`);n.unshift(...e),s!==void 0&&(s.index+=e.length),notify()},async dispose(){await stop()},async release(){return t.length>0&&await releaseSessionHooksStep({ownerRunId:getWorkflowMetadata().workflowRunId,tokens:t.map(({hook:e})=>e.token)}),await stop()}}}function isWorkflowMessage(e){return e.kind===`agent-started`||e.kind===`started`||e.kind===`report`||e.kind===`reply`||e.kind===`request`||e.kind===`withdraw`||e.kind===`usage`||e.kind===`outcome`}export{createSessionInbox,isInterrupt,isWorkflowMessage};
1
+ import{sessionInboxHookToken}from"#execution/session-inbox/address.js";import{createHook,getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookForceClaimedError}from"#execution/hook-ownership.js";import{releaseSessionHooksStep}from"#execution/session-inbox/release-step.js";function isInterrupt(e){return e.kind===`cancel`||e.kind===`reset`||e.kind===`session-timeout`||e.kind===`session-failure`}function isDelivery(e){return e.kind===`send`||e.kind===`deliver`}function createSessionInbox(e){let t=[],n=[],r=new Set,i=new Set,a=new Set,o,s,c,l=new Set,u=new Set,d=!1,f=!1,notify=()=>{for(let e of r)e();r.clear()},wait=()=>new Promise(e=>r.add(e)),closed=()=>t.every(e=>e.closed||e.stopping),gated=()=>s!==void 0&&t.length>0,hasReadable=()=>!gated()&&n.length>0,throwIfFailed=()=>{if(o!==void 0)throw o.error},observe=(e,t,n)=>{for(let r of t)if(n(r))for(let t of e)t(r)},openHandover=()=>{s=void 0,observe(a,n,isDelivery),notify()},blockedOnHandover=()=>{if(gated()){for(let e of l)e();l.clear()}},acceptHandover=e=>{let t=s;if(t===void 0||e.attemptKey!==t.attemptKey||e.index<t.nextPart||t.parts.has(e.index))return;t.parts.set(e.index,e);let r=[];for(;;){let e=t.parts.get(t.nextPart);if(e===void 0)break;if(e.final===!0){c={attemptKey:t.attemptKey,payloadCount:t.nextPart,appliedAtMs:Date.now()},observe(i,r,isInterrupt),openHandover();return}t.parts.delete(t.nextPart),t.nextPart+=1,n.splice(t.index,0,...e.payloads),t.index+=e.payloads.length,r.push(...e.payloads)}observe(i,r,isInterrupt),notify()},pump=async e=>{let r=e.hook[Symbol.asyncIterator]();try{for(;!e.stopping;){let e=await r.next();if(e.done)break;let t=e.value;for(let e of u)e();if(u.clear(),t.kind===`workflow-batch`){n.push(...t.messages),notify();continue}if(t.kind===`handover`){acceptHandover(t);continue}n.push(t),gated()||observe(a,[t],isDelivery),observe(i,[t],isInterrupt),notify()}}catch(n){if(e.stopping||e.replaced)return;isHookForceClaimedError(n)?(t.splice(t.indexOf(e),1),d=!0):o={error:n}}finally{e.closed=!0,notify()}},stop=async()=>{let e=t.splice(0);s=void 0,d=!1,f=!0;for(let t of e)t.stopping=!0;notify(),await Promise.all(e.map(({hook:e})=>disposeHook(e)));let r=n.splice(0);return notify(),r},claimSessionHook=async(n,r={})=>{if(!n)throw Error(`A session alias requires a nonempty continuation token.`);let i=r.force===!0,a=t.find(e=>e.token===n);if(a!==void 0&&!i)return await a.registered;if(a===void 0&&t.length>=256)throw Error(`A session may claim at most 256 addresses.`);let o={token:n,hook:createHook({token:sessionInboxHookToken(n),metadata:{sessionId:e},...i&&{experimental_force:!0}}),stopping:!1,closed:!1,replaced:!1};a===void 0?t.push(o):(a.replaced=!0,t.splice(t.indexOf(a),1,o)),f=!1;try{let confirm=()=>claimHookOwnership(o.hook);o.registered=r.confirmAfter?.then(confirm,confirm)??confirm(),await o.registered,d=!1,pump(o)}catch(e){throw a===void 0||a.closed?t.splice(t.indexOf(o),1):(a.replaced=!1,t.splice(t.indexOf(o),1,a)),e}};return{get handoverObservation(){return c},get claimedTokens(){return t.map(({token:e})=>e)},get awaitingHandover(){return s!==void 0},async whenHandoverSettled(){for(;s!==void 0;)await wait()},abandonHandover(e){s?.attemptKey===e&&openHandover()},whenBlockedOnHandover(){return new Promise(e=>l.add(e))},whenArrival(){return new Promise(e=>u.add(e))},get takenOver(){return d&&t.length===0},claimSessionHook,async claimSessionHooks(e,t={}){t.handover!==void 0&&(s={attemptKey:t.handover,index:n.length,nextPart:0,parts:new Map});let r=await Promise.allSettled([...new Set(e)].map(e=>claimSessionHook(e,t)));for(let e of r)if(e.status===`rejected`)throw e.reason},async whenTakenOver(e){for(e?.addEventListener(`abort`,notify,{once:!0});t.length>0||!d;){if(throwIfFailed(),f)throw Error(`The session inbox was released before a takeover.`);if(e?.aborted===!0)throw e.reason;await wait()}},async next(){for(;;){if(throwIfFailed(),hasReadable())return n.shift();if(closed())return;blockedOnHandover(),await wait()}},drain(){return throwIfFailed(),gated()?[]:n.splice(0)},takeLeading(e){throwIfFailed();let t=[];if(gated())return t;for(let r=n[0];r!==void 0&&e(r);r=n[0])t.push(r),n.shift();return t},hasPending(){return throwIfFailed(),hasReadable()},async whenPending(){for(;o===void 0&&!hasReadable()&&!closed();)blockedOnHandover(),await wait()},onInterrupt(e){return i.add(e),()=>i.delete(e)},onDelivery(e){if(a.add(e),!gated())for(let t of n)isDelivery(t)&&e(t);return()=>a.delete(e)},restore(e){if(t.length===0)throw Error(`Cannot restore session commands before reclaiming the session hooks.`);n.unshift(...e),s!==void 0&&(s.index+=e.length),notify()},async dispose(){await stop()},async release(){return t.length>0&&await releaseSessionHooksStep({ownerRunId:getWorkflowMetadata().workflowRunId,tokens:t.map(({hook:e})=>e.token)}),await stop()}}}function isWorkflowMessage(e){return e.kind===`agent-started`||e.kind===`started`||e.kind===`report`||e.kind===`reply`||e.kind===`request`||e.kind===`withdraw`||e.kind===`usage`||e.kind===`outcome`}export{createSessionInbox,isInterrupt,isWorkflowMessage};
@@ -1,5 +1,6 @@
1
1
  import type { DeliverHookPayload, SessionCommand, SessionTimeoutHookPayload } from "#channel/types.js";
2
- type DecodedSessionInbox = DeliverHookPayload | SessionTimeoutHookPayload | Extract<SessionCommand, {
2
+ import type { SessionPrewarmPayload } from "#execution/session-prewarm.js";
3
+ type DecodedSessionInbox = SessionPrewarmPayload | DeliverHookPayload | SessionTimeoutHookPayload | Extract<SessionCommand, {
3
4
  readonly kind: "cancel" | "clear" | "compact" | "reset";
4
5
  }>;
5
6
  /** Invalid current-generation inbox payload. Historical wire shapes are not accepted. */
@@ -1 +1 @@
1
- import{validateDeliveryIdempotencyKey}from"#channel/delivery-idempotency.js";var SessionInboxPayloadError=class extends Error{constructor(e){super(e),this.name=`SessionInboxPayloadError`}};function decodeSessionInboxPayload(e){if(typeof e!=`object`||!e||!(`kind`in e))throw new SessionInboxPayloadError(`Session inbox payload must be an object with a kind.`);let t=e;if(t.kind===`send`||t.kind===`deliver`)try{validateDeliveryIdempotencyKey(t.idempotencyKey)}catch(e){throw new SessionInboxPayloadError(e.message)}switch(t.kind){case`send`:{if(t.payload===null||typeof t.payload!=`object`)throw new SessionInboxPayloadError(`Session send payload must be an object.`);let n=e;return{idempotencyKey:n.idempotencyKey,auth:n.auth,schedule:n.schedule,title:n.title,caller:n.caller,deliveryMetadata:n.delivery===void 0?void 0:[{...n.delivery,payloadIndex:0}],kind:`deliver`,payloads:[n.payload],requestId:n.requestId,turnPolicy:n.turnPolicy}}case`deliver`:if(!Array.isArray(t.payloads))throw new SessionInboxPayloadError(`Session delivery payloads must be an array.`);return e;case`cancel`:case`clear`:case`compact`:case`reset`:case`session-timeout`:return e;default:throw new SessionInboxPayloadError(`Unsupported session inbox payload kind ${JSON.stringify(t.kind)}.`)}}export{SessionInboxPayloadError,decodeSessionInboxPayload};
1
+ import{validateDeliveryIdempotencyKey}from"#channel/delivery-idempotency.js";var SessionInboxPayloadError=class extends Error{constructor(e){super(e),this.name=`SessionInboxPayloadError`}};function decodeSessionInboxPayload(e){if(typeof e!=`object`||!e||!(`kind`in e))throw new SessionInboxPayloadError(`Session inbox payload must be an object with a kind.`);let t=e;if(t.kind===`send`||t.kind===`deliver`)try{validateDeliveryIdempotencyKey(t.idempotencyKey)}catch(e){throw new SessionInboxPayloadError(e.message)}switch(t.kind){case`send`:{if(t.payload===null||typeof t.payload!=`object`)throw new SessionInboxPayloadError(`Session send payload must be an object.`);let n=e;return{idempotencyKey:n.idempotencyKey,auth:n.auth,schedule:n.schedule,title:n.title,caller:n.caller,deliveryMetadata:n.delivery===void 0?void 0:[{...n.delivery,payloadIndex:0}],kind:`deliver`,payloads:[n.payload],requestId:n.requestId,turnPolicy:n.turnPolicy}}case`deliver`:if(!Array.isArray(t.payloads))throw new SessionInboxPayloadError(`Session delivery payloads must be an array.`);return e;case`session-prewarm`:if(typeof t.expectedOwnerRunId!=`string`||typeof t.targetDeploymentId!=`string`||t.targetDeploymentId.length===0||t.targetDeploymentId===`latest`)throw new SessionInboxPayloadError(`Invalid session prewarm hint.`);return e;case`cancel`:case`clear`:case`compact`:case`reset`:case`session-timeout`:return e;default:throw new SessionInboxPayloadError(`Unsupported session inbox payload kind ${JSON.stringify(t.kind)}.`)}}export{SessionInboxPayloadError,decodeSessionInboxPayload};
@@ -1,3 +1,4 @@
1
+ import type { SessionPrewarmPayload } from "#execution/session-prewarm.js";
1
2
  import type { SessionFailurePayload } from "#execution/session-inbox/inbox.js";
2
3
  import type { DeliverHookPayload, SessionCommand, SessionTimeoutHookPayload } from "#channel/types.js";
3
4
  import { type SessionInboxAddress } from "#execution/session-inbox/address.js";
@@ -15,7 +16,7 @@ export interface ResumedSessionInboxHook {
15
16
  * The retry window bounds this request, not the handoff: a marker that
16
17
  * outlives it throws {@link SessionHandoffPendingError}.
17
18
  */
18
- export declare function resumeSessionInbox(address: string | SessionInboxAddress, command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload | SessionFailurePayload): Promise<ResumedSessionInboxHook>;
19
+ export declare function resumeSessionInbox(address: string | SessionInboxAddress, command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload | SessionFailurePayload | SessionPrewarmPayload): Promise<ResumedSessionInboxHook>;
19
20
  /**
20
21
  * The address's owner is still handing off after the request's retry window.
21
22
  * Nothing was delivered. The address is not unowned, so callers must not start
@@ -1 +1 @@
1
- import{isObject}from"#shared/guards.js";import{SESSION_INBOX_SESSION_ID_METADATA_KEY,isSessionInboxAddress,sessionCommandHookToken,sessionHandoffMarkerToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{getHookByToken}from"#internal/workflow/runtime.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{assertRunnableSessionOwner,lookupSessionOwnerHook,resumeRunnableHook}from"#execution/session-inbox/owner.js";import{UnsupportedLegacySessionError,resolveLegacyInbox,resumeLegacyInbox}from"#execution/legacy-session/inbox.js";async function resumeSessionInbox(e,t){let n=logicalSessionToken(e),r=typeof e==`string`?void 0:e.sessionId,i=Date.now()+5e3;for(;;){let e;try{e=await resumeRunnableHook(sessionInboxHookToken(n),t)}catch(e){if(!HookNotFoundError.is(e))throw e;if(await waitWhileHandoffInProgress(n,i))continue;if(t.kind===`session-failure`)throw e;return await resumeLegacyInbox(n,t).catch(rethrowUnsupportedAsNotFound)}let a;return{ownerRunId:e.runId,get sessionId(){return a??=(async()=>{try{return r??requireSessionId(await e.metadata)}catch(e){throw new AcceptedSessionIdentityError(e)}})()}}}}var SessionHandoffPendingError=class extends Error{constructor(e){super(`Session address "${e}" is still changing owners. Nothing was delivered; retry the request.`),this.name=`SessionHandoffPendingError`}},AcceptedSessionIdentityError=class extends Error{constructor(e){super(`Session command accepted, but its session identity could not be resolved.`,{cause:e}),this.name=`AcceptedSessionIdentityError`}};function requireSessionId(e){let t=isObject(e)?e[SESSION_INBOX_SESSION_ID_METADATA_KEY]:void 0;if(typeof t!=`string`||t.length===0)throw Error(`Session hook metadata is missing its session ID.`);return t}async function resolveSessionInbox(e){try{return{sessionId:requireSessionId(await(await getHookByToken(sessionInboxHookToken(e))).metadata)}}catch(t){if(!HookNotFoundError.is(t))throw t;return{sessionId:(await resolveLegacyInbox(e)).sessionId}}}function rethrowUnsupportedAsNotFound(e){throw e instanceof UnsupportedLegacySessionError?new HookNotFoundError(e.message):e}function logicalSessionToken(e){if(typeof e==`string`)return e;if(!isSessionInboxAddress(e))throw Error(`Session inbox target has an invalid address.`);return sessionCommandHookToken(e.sessionId)}async function waitWhileHandoffInProgress(e,t){let n;try{n=await lookupSessionOwnerHook(sessionHandoffMarkerToken(e))}catch(e){if(HookNotFoundError.is(e))return!1;throw e}if(Date.now()>=t)throw await assertRunnableSessionOwner(n),new SessionHandoffPendingError(e);return await new Promise(e=>setTimeout(e,20)),!0}export{AcceptedSessionIdentityError,SessionHandoffPendingError,logicalSessionToken,requireSessionId,resolveSessionInbox,resumeSessionInbox};
1
+ import{isObject}from"#shared/guards.js";import{SESSION_INBOX_SESSION_ID_METADATA_KEY,isSessionInboxAddress,sessionCommandHookToken,sessionHandoffMarkerToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{getHookByToken}from"#internal/workflow/runtime.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{assertRunnableSessionOwner,lookupSessionOwnerHook,resumeRunnableHook}from"#execution/session-inbox/owner.js";import{UnsupportedLegacySessionError,resolveLegacyInbox,resumeLegacyInbox}from"#execution/legacy-session/inbox.js";async function resumeSessionInbox(e,t){let n=logicalSessionToken(e),r=typeof e==`string`?void 0:e.sessionId,i=Date.now()+5e3;for(;;){let e;try{e=await resumeRunnableHook(sessionInboxHookToken(n),t)}catch(e){if(!HookNotFoundError.is(e))throw e;if(await waitWhileHandoffInProgress(n,i))continue;if(t.kind===`session-failure`||t.kind===`session-prewarm`)throw e;return await resumeLegacyInbox(n,t).catch(rethrowUnsupportedAsNotFound)}let a;return{ownerRunId:e.runId,get sessionId(){return a??=(async()=>{try{return r??requireSessionId(await e.metadata)}catch(e){throw new AcceptedSessionIdentityError(e)}})()}}}}var SessionHandoffPendingError=class extends Error{constructor(e){super(`Session address "${e}" is still changing owners. Nothing was delivered; retry the request.`),this.name=`SessionHandoffPendingError`}},AcceptedSessionIdentityError=class extends Error{constructor(e){super(`Session command accepted, but its session identity could not be resolved.`,{cause:e}),this.name=`AcceptedSessionIdentityError`}};function requireSessionId(e){let t=isObject(e)?e[SESSION_INBOX_SESSION_ID_METADATA_KEY]:void 0;if(typeof t!=`string`||t.length===0)throw Error(`Session hook metadata is missing its session ID.`);return t}async function resolveSessionInbox(e){try{return{sessionId:requireSessionId(await(await getHookByToken(sessionInboxHookToken(e))).metadata)}}catch(t){if(!HookNotFoundError.is(t))throw t;return{sessionId:(await resolveLegacyInbox(e)).sessionId}}}function rethrowUnsupportedAsNotFound(e){throw e instanceof UnsupportedLegacySessionError?new HookNotFoundError(e.message):e}function logicalSessionToken(e){if(typeof e==`string`)return e;if(!isSessionInboxAddress(e))throw Error(`Session inbox target has an invalid address.`);return sessionCommandHookToken(e.sessionId)}async function waitWhileHandoffInProgress(e,t){let n;try{n=await lookupSessionOwnerHook(sessionHandoffMarkerToken(e))}catch(e){if(HookNotFoundError.is(e))return!1;throw e}if(Date.now()>=t)throw await assertRunnableSessionOwner(n),new SessionHandoffPendingError(e);return await new Promise(e=>setTimeout(e,20)),!0}export{AcceptedSessionIdentityError,SessionHandoffPendingError,logicalSessionToken,requireSessionId,resolveSessionInbox,resumeSessionInbox};
@@ -0,0 +1,8 @@
1
+ import type { PrewarmSessionResult } from "#protocol/prewarm-session.js";
2
+ /** Internal hint, scoped to the owner inspected by ingress to avoid stale transfers. */
3
+ export interface SessionPrewarmPayload {
4
+ readonly kind: "session-prewarm";
5
+ readonly expectedOwnerRunId: string;
6
+ readonly targetDeploymentId: string;
7
+ }
8
+ export declare function prewarmWorkflowSession(sessionId: string, targetDeploymentId: string | undefined): Promise<PrewarmSessionResult>;
@@ -0,0 +1 @@
1
+ import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{getHookByToken,getWorld}from"#internal/workflow/runtime.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{EVE_PREWARM_ATTRIBUTE}from"#execution/eve-workflow-attributes.js";async function prewarmWorkflowSession(e,t){if(t===void 0||t.length===0||t===`latest`)return{status:`unsupported`};let n=await getWorld();if(n.capabilities?.deploymentAffinity!==!0)return{status:`unsupported`};let r;try{r=await getHookByToken(sessionInboxHookToken(sessionCommandHookToken(e)))}catch(e){if(HookNotFoundError.is(e))return{status:`no_active_session`};throw e}let i=await n.runs.get(r.runId,{resolveData:`none`});return i.status!==`running`&&i.status!==`pending`?{status:`no_active_session`}:i.deploymentId===t?{status:`ready`}:i.attributes[EVE_PREWARM_ATTRIBUTE]===`1`?(await resumeSessionInbox({sessionId:e},{kind:`session-prewarm`,expectedOwnerRunId:r.runId,targetDeploymentId:t}),{status:`accepted`}):{status:`unsupported`}}export{prewarmWorkflowSession};
@@ -1,2 +1,2 @@
1
- import{SKILL_TOOL_NAME}from"#protocol/catalog-tools.js";import{FALLBACK_SKILL_ROOT,MODEL_SKILL_ROOT}from"#shared/skill-paths.js";const ANNOUNCEMENT_KEY=`skills`;function formatAvailableSkillsSection(e){return e.length===0?null:[`Available skills`,`Listed skills are available in this run. Do not claim a listed skill is inaccessible unless activation or workspace inspection actually fails.`,`Dynamic skill announcements replace earlier dynamic skills and override static skills with the same name. Static skills omitted from a dynamic announcement remain available.`,`If the user names a skill or the request clearly matches one of the descriptions below, load it with ${SKILL_TOOL_NAME}({ name }) before proceeding.`,`If multiple skills match, activate the minimal set that covers the task. After activation, follow the returned instructions instead of improvising around them.`,`If activation fails, say so briefly and continue with the best available alternative.`,`Skill files live under \`${MODEL_SKILL_ROOT}/<skill>/\`, with \`${FALLBACK_SKILL_ROOT}/<skill>/\` as the fallback when \`$HOME\` is unavailable.`,"When a loaded SKILL.md mentions sibling files such as `references/foo.md`, resolve them relative to the directory containing that specific SKILL.md.",...e.map(formatAvailableSkillLine)].join(`
1
+ import{SKILL_TOOL_NAME}from"#protocol/catalog-tools.js";import{MODEL_SKILL_ROOT}from"#shared/skill-paths.js";const ANNOUNCEMENT_KEY=`skills`;function formatAvailableSkillsSection(e){return e.length===0?null:[`Available skills`,`Listed skills are available in this run. Do not claim a listed skill is inaccessible unless activation or workspace inspection actually fails.`,`Dynamic skill announcements replace earlier dynamic skills and override static skills with the same name. Static skills omitted from a dynamic announcement remain available.`,`If the user names a skill or the request clearly matches one of the descriptions below, load it with ${SKILL_TOOL_NAME}({ name }) before proceeding.`,`If multiple skills match, activate the minimal set that covers the task. After activation, follow the returned instructions instead of improvising around them.`,`If activation fails, say so briefly and continue with the best available alternative.`,`Skill files live under \`${MODEL_SKILL_ROOT}/<skill>/\`, with \`skills/<skill>/\` under the workspace root as the fallback when \`$HOME\` is unavailable.`,"When a loaded SKILL.md mentions sibling files such as `references/foo.md`, resolve them relative to the directory containing that specific SKILL.md.",...e.map(formatAvailableSkillLine)].join(`
2
2
  `)}function dynamicSkillAnnouncements(e,t){let n=Object.values(e??{}).flat().filter(e=>e.deferred!==!0);if(n.length===0&&t?.[ANNOUNCEMENT_KEY]===void 0)return{};let r=formatAvailableSkillsSection(n.map(({description:e,name:t,revision:n})=>({description:e,hasFiles:n!==void 0,name:t})))??`Available skills: none`;return{[ANNOUNCEMENT_KEY]:{value:r,render:()=>r}}}function formatAvailableSkillLine(e){let t=`- ${e.name}: ${e.description}`;return e.hasFiles===!1?t:`${t} (path: ${skillFilePath(e.name)})`}function skillFilePath(e){return`${MODEL_SKILL_ROOT}/${e}/SKILL.md`}export{dynamicSkillAnnouncements,formatAvailableSkillsSection,skillFilePath};
@@ -1 +1 @@
1
- import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{message:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.82.0//runAgentRouterTask`;export{runAgentRouterTask};
1
+ import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{message:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.83.1//runAgentRouterTask`;export{runAgentRouterTask};