eve 0.24.2 → 0.24.4

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 (208) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/src/channel/adapter.d.ts +4 -2
  3. package/dist/src/channel/adapter.js +1 -1
  4. package/dist/src/channel/session.d.ts +5 -1
  5. package/dist/src/channel/types.d.ts +7 -6
  6. package/dist/src/chunks/{use-eve-agent-CFBTHlPx.js → use-eve-agent-BP9FpQsJ.js} +15 -4
  7. package/dist/src/chunks/{use-eve-agent-dEGV09g_.js → use-eve-agent-Dwa2j1wE.js} +15 -4
  8. package/dist/src/cli/dev/environment.d.ts +6 -0
  9. package/dist/src/cli/dev/environment.js +1 -1
  10. package/dist/src/cli/dev/tui/runner.d.ts +2 -2
  11. package/dist/src/cli/dev/tui/runner.js +1 -1
  12. package/dist/src/client/index.d.ts +1 -1
  13. package/dist/src/client/message-reducer.js +1 -1
  14. package/dist/src/client/open-stream.js +1 -1
  15. package/dist/src/client/session-utils.js +1 -1
  16. package/dist/src/client/session.d.ts +4 -2
  17. package/dist/src/client/session.js +1 -1
  18. package/dist/src/client/types.d.ts +3 -2
  19. package/dist/src/compiled/.vendor-stamp.json +2 -1
  20. package/dist/src/compiled/@chat-adapter/slack/index.js +12 -12
  21. package/dist/src/compiled/@chat-adapter/twilio/index.js +1 -1
  22. package/dist/src/compiled/@vercel/sandbox/index.js +19 -19
  23. package/dist/src/compiled/@workflow/world-local/index.d.ts +14 -0
  24. package/dist/src/compiled/_chunks/node/{auth-CWHn3Yve.js → auth-BuQkq4Gr.js} +2 -2
  25. package/dist/src/compiled/_chunks/node/{dist-BdTs18CF.js → chunk-BTyA9uPd.js} +1 -1
  26. package/dist/src/compiled/_chunks/node/{dist-W8yle6rh.js → dist-CdH_Yoxt.js} +5 -5
  27. package/dist/src/compiled/_chunks/node/{dist-RHRJZ03Q.js → dist-Drt-_JVK.js} +1 -1
  28. package/dist/src/compiled/_chunks/node/dist-DsNhwdzf.js +1 -0
  29. package/dist/src/compiled/_chunks/node/retry-DngYleaI.js +1 -0
  30. package/dist/src/compiled/_chunks/node/token-DabMnh8F.js +1 -0
  31. package/dist/src/compiled/_chunks/node/token-util-BoSJPKrG.js +1 -0
  32. package/dist/src/compiled/_chunks/node/token-util-DVigMYWS.js +1 -0
  33. package/dist/src/compiled/_chunks/node/virtual-loader-B8K8w9cr.js +1 -0
  34. package/dist/src/compiled/chat/index.js +1 -1
  35. package/dist/src/compiled/env-runner/LICENSE +21 -0
  36. package/dist/src/compiled/env-runner/index.d.ts +38 -0
  37. package/dist/src/compiled/env-runner/index.js +1 -0
  38. package/dist/src/compiled/env-runner/node-worker.d.ts +1 -0
  39. package/dist/src/compiled/env-runner/node-worker.js +12 -0
  40. package/dist/src/compiler/compile-agent.d.ts +4 -6
  41. package/dist/src/compiler/compile-agent.js +1 -1
  42. package/dist/src/discover/filesystem.js +1 -1
  43. package/dist/src/execution/create-session-step.d.ts +2 -2
  44. package/dist/src/execution/create-session-step.js +1 -1
  45. package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +1 -0
  46. package/dist/src/execution/durable-session-migrations/turn-workflow.js +1 -1
  47. package/dist/src/execution/next-driver-action.d.ts +7 -0
  48. package/dist/src/execution/settle-cancelled-turn-step.d.ts +16 -0
  49. package/dist/src/execution/settle-cancelled-turn-step.js +1 -0
  50. package/dist/src/execution/subagent-hitl-proxy.js +1 -1
  51. package/dist/src/execution/terminal-session-failure-step.d.ts +6 -0
  52. package/dist/src/execution/terminal-session-failure-step.js +1 -0
  53. package/dist/src/execution/turn-cancellation-control.d.ts +40 -0
  54. package/dist/src/execution/turn-cancellation-control.js +1 -0
  55. package/dist/src/execution/turn-dispatch.d.ts +14 -1
  56. package/dist/src/execution/turn-dispatch.js +1 -1
  57. package/dist/src/execution/turn-execution-cursor.d.ts +2 -1
  58. package/dist/src/execution/turn-execution-cursor.js +1 -1
  59. package/dist/src/execution/turn-workflow.d.ts +9 -1
  60. package/dist/src/execution/turn-workflow.js +1 -1
  61. package/dist/src/execution/workflow-entry.js +1 -1
  62. package/dist/src/execution/workflow-runtime.js +1 -1
  63. package/dist/src/execution/workflow-steps.d.ts +8 -6
  64. package/dist/src/execution/workflow-steps.js +1 -1
  65. package/dist/src/harness/active-turn-id.d.ts +11 -0
  66. package/dist/src/harness/active-turn-id.js +1 -0
  67. package/dist/src/harness/cancelled-turn-emission.d.ts +11 -0
  68. package/dist/src/harness/cancelled-turn-emission.js +1 -0
  69. package/dist/src/harness/emission.d.ts +4 -2
  70. package/dist/src/harness/emission.js +1 -1
  71. package/dist/src/harness/proxy-input-requests.d.ts +5 -0
  72. package/dist/src/harness/proxy-input-requests.js +1 -1
  73. package/dist/src/harness/session-limit-enforcement.js +1 -1
  74. package/dist/src/harness/tool-loop.js +2 -2
  75. package/dist/src/internal/application/compiled-artifacts.d.ts +13 -0
  76. package/dist/src/internal/application/compiled-artifacts.js +5 -3
  77. package/dist/src/internal/application/dev-environment.d.ts +4 -0
  78. package/dist/src/internal/application/dev-environment.js +1 -0
  79. package/dist/src/internal/application/optional-package-install.d.ts +2 -10
  80. package/dist/src/internal/application/optional-package-install.js +1 -1
  81. package/dist/src/internal/application/output-publication-lock.js +1 -1
  82. package/dist/src/internal/application/package.js +1 -1
  83. package/dist/src/internal/application/tsconfig-dependencies.js +1 -1
  84. package/dist/src/internal/authored-module-loader.d.ts +3 -9
  85. package/dist/src/internal/authored-module-loader.js +2 -2
  86. package/dist/src/internal/authored-package-boundary.d.ts +0 -2
  87. package/dist/src/internal/authored-package-boundary.js +1 -1
  88. package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
  89. package/dist/src/internal/bundler/nitro-rolldown.d.ts +18 -2
  90. package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
  91. package/dist/src/internal/compiled-manifest-fingerprint.d.ts +5 -0
  92. package/dist/src/internal/compiled-manifest-fingerprint.js +1 -0
  93. package/dist/src/internal/materialized-authored-modules.d.ts +0 -3
  94. package/dist/src/internal/materialized-authored-modules.js +1 -1
  95. package/dist/src/internal/nitro/dev-client-address.d.ts +22 -0
  96. package/dist/src/internal/nitro/dev-client-address.js +1 -0
  97. package/dist/src/internal/nitro/dev-runtime-artifacts-retention.d.ts +12 -0
  98. package/dist/src/internal/nitro/dev-runtime-artifacts-retention.js +1 -0
  99. package/dist/src/internal/nitro/dev-runtime-artifacts.d.ts +19 -1
  100. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  101. package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
  102. package/dist/src/internal/nitro/development-generation.d.ts +5 -1
  103. package/dist/src/internal/nitro/development-generation.js +1 -1
  104. package/dist/src/internal/nitro/host/artifacts-config.d.ts +2 -0
  105. package/dist/src/internal/nitro/host/artifacts-config.js +1 -1
  106. package/dist/src/internal/nitro/host/channel-routes.d.ts +1 -13
  107. package/dist/src/internal/nitro/host/channel-routes.js +3 -3
  108. package/dist/src/internal/nitro/host/configure-nitro-routes.d.ts +1 -2
  109. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  110. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +3 -5
  111. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  112. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.d.ts +32 -0
  113. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -0
  114. package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +4 -15
  115. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  116. package/dist/src/internal/nitro/host/dev-host-candidate.d.ts +16 -0
  117. package/dist/src/internal/nitro/host/dev-host-candidate.js +1 -0
  118. package/dist/src/internal/nitro/host/dev-host-fingerprint.d.ts +2 -0
  119. package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -0
  120. package/dist/src/internal/nitro/host/dev-host-workspace.d.ts +10 -0
  121. package/dist/src/internal/nitro/host/dev-host-workspace.js +1 -0
  122. package/dist/src/internal/nitro/host/dev-runner.d.ts +21 -0
  123. package/dist/src/internal/nitro/host/dev-runner.js +1 -0
  124. package/dist/src/internal/nitro/host/dev-server-http.d.ts +5 -0
  125. package/dist/src/internal/nitro/host/dev-server-http.js +1 -0
  126. package/dist/src/internal/nitro/host/dev-server-url.d.ts +6 -0
  127. package/dist/src/internal/nitro/host/dev-server-url.js +1 -0
  128. package/dist/src/internal/nitro/host/dev-workflow-world-setup.d.ts +9 -0
  129. package/dist/src/internal/nitro/host/dev-workflow-world-setup.js +1 -0
  130. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.js +1 -1
  131. package/dist/src/internal/nitro/host/drained-nitro-dev-server.d.ts +53 -0
  132. package/dist/src/internal/nitro/host/drained-nitro-dev-server.js +1 -0
  133. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +4 -5
  134. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  135. package/dist/src/internal/nitro/host/start-development-server.d.ts +2 -5
  136. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  137. package/dist/src/internal/nitro/host/types.d.ts +6 -0
  138. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  139. package/dist/src/internal/nitro/routes/runtime-artifacts.d.ts +7 -0
  140. package/dist/src/internal/nitro/routes/runtime-artifacts.js +1 -1
  141. package/dist/src/internal/nitro/routes/schedule-task.d.ts +9 -0
  142. package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
  143. package/dist/src/internal/workflow/development-generation-context.d.ts +8 -0
  144. package/dist/src/internal/workflow/development-generation-context.js +1 -0
  145. package/dist/src/internal/workflow/development-world-client.d.ts +29 -0
  146. package/dist/src/internal/workflow/development-world-client.js +1 -0
  147. package/dist/src/internal/workflow/development-world-codec.d.ts +11 -0
  148. package/dist/src/internal/workflow/development-world-codec.js +1 -0
  149. package/dist/src/internal/workflow/development-world-protocol.d.ts +31 -0
  150. package/dist/src/internal/workflow/development-world-protocol.js +1 -0
  151. package/dist/src/internal/workflow/development-world-server.d.ts +27 -0
  152. package/dist/src/internal/workflow/development-world-server.js +1 -0
  153. package/dist/src/internal/workflow/local-world-data-directory.d.ts +2 -0
  154. package/dist/src/internal/workflow/local-world-data-directory.js +1 -0
  155. package/dist/src/internal/workflow-bundle/builder-support.js +3 -3
  156. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  157. package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
  158. package/dist/src/protocol/message.d.ts +23 -3
  159. package/dist/src/protocol/message.js +2 -2
  160. package/dist/src/public/channels/discord/discordChannel.d.ts +1 -0
  161. package/dist/src/public/channels/eve.js +1 -1
  162. package/dist/src/public/channels/github/githubChannel.d.ts +1 -0
  163. package/dist/src/public/channels/linear/linearChannel.d.ts +1 -0
  164. package/dist/src/public/channels/slack/slackChannel.d.ts +1 -0
  165. package/dist/src/public/channels/teams/teamsChannel.d.ts +1 -0
  166. package/dist/src/public/channels/telegram/telegramChannel.d.ts +1 -0
  167. package/dist/src/public/channels/twilio/twilioChannel.d.ts +1 -0
  168. package/dist/src/public/definitions/channel.d.ts +5 -4
  169. package/dist/src/public/definitions/channel.js +1 -1
  170. package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
  171. package/dist/src/runtime/compiled-artifacts-source.d.ts +9 -0
  172. package/dist/src/runtime/compiled-artifacts-source.js +1 -1
  173. package/dist/src/runtime/durable-compiled-artifacts-source.d.ts +8 -0
  174. package/dist/src/runtime/durable-compiled-artifacts-source.js +1 -0
  175. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
  176. package/dist/src/services/dev-client/runtime-artifacts.d.ts +2 -2
  177. package/dist/src/services/dev-client.d.ts +10 -18
  178. package/dist/src/services/dev-client.js +1 -1
  179. package/dist/src/setup/scaffold/create/extension.js +0 -1
  180. package/dist/src/setup/scaffold/create/project.js +1 -3
  181. package/dist/src/shared/atomic-write-file.d.ts +1 -1
  182. package/dist/src/shared/atomic-write-file.js +1 -1
  183. package/dist/src/shared/continuation-token.d.ts +2 -0
  184. package/dist/src/shared/continuation-token.js +1 -0
  185. package/dist/src/shared/rename-with-retry.d.ts +5 -0
  186. package/dist/src/shared/rename-with-retry.js +1 -0
  187. package/dist/src/svelte/index.js +1 -1
  188. package/dist/src/svelte/use-eve-agent.js +1 -1
  189. package/dist/src/vue/index.js +1 -1
  190. package/dist/src/vue/use-eve-agent.js +1 -1
  191. package/docs/agent-config.md +2 -0
  192. package/docs/concepts/execution-model-and-durability.md +1 -1
  193. package/docs/concepts/sessions-runs-and-streaming.md +13 -4
  194. package/docs/guides/client/continuations.mdx +14 -1
  195. package/docs/guides/client/streaming.mdx +14 -1
  196. package/docs/guides/deployment.md +1 -1
  197. package/docs/reference/cli.md +1 -1
  198. package/package.json +2 -1
  199. package/dist/src/compiled/_chunks/node/retry-DkR2H1Y0.js +0 -1
  200. package/dist/src/compiled/_chunks/node/token-ORseRyWn.js +0 -1
  201. package/dist/src/internal/bundler/nitro-node-file-trace.d.ts +0 -10
  202. package/dist/src/internal/bundler/nitro-node-file-trace.js +0 -1
  203. package/dist/src/internal/materialize-authored-external-dependencies.d.ts +0 -10
  204. package/dist/src/internal/materialize-authored-external-dependencies.js +0 -2
  205. package/dist/src/internal/nitro/host/dev-live-virtual-modules.d.ts +0 -15
  206. package/dist/src/internal/nitro/host/dev-live-virtual-modules.js +0 -1
  207. package/dist/src/internal/nitro/host/server-external-packages.d.ts +0 -5
  208. package/dist/src/internal/nitro/host/server-external-packages.js +0 -1
@@ -1,2 +1,2 @@
1
- import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{detectPackageManager}from"#setup/package-manager.js";import{eveDevArguments}from"#setup/primitives/index.js";import{toErrorMessage}from"#shared/errors.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{resolveDiscoveryProject}from"#discover/project.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{build,createDevServer,prepare}from"nitro/builder";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{isEveServerHealthy}from"#shared/eve-server-health.js";import{handleDevRuntimeArtifactsRequest}from"#internal/nitro/routes/dev-runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,WORKFLOW_LOCAL_BASE_URL_ENV=`WORKFLOW_LOCAL_BASE_URL`,PORT_ENV=`PORT`,DEFAULT_DEVELOPMENT_SERVER_HOST=`127.0.0.1`,IPV6_WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`]);function normalizeDevelopmentServerClientUrl(e){let t=new URL(e);return IPV6_WILDCARD_LISTEN_HOSTNAMES.has(t.hostname)?(t.hostname=`[::1]`,t.toString()):t.hostname===`0.0.0.0`?(t.hostname=DEFAULT_DEVELOPMENT_SERVER_HOST,t.toString()):e}async function isActiveDevelopmentServerForApp(e){try{let n=await new DevelopmentServerState(await resolveDiscoveryProject(e.appRoot)).read();return n===void 0||!isLoopbackServerUrl(n)||!await isEveServerHealthy(n)?!1:new URL(n).origin===new URL(normalizeDevelopmentServerClientUrl(e.serverUrl)).origin}catch{return!1}}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let n=await detectDevelopmentCommandPackageManager(e);return[n,...eveDevArguments(n),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
2
- `))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function installWorkflowLocalQueueEnvironment(e){let t=process.env[WORKFLOW_LOCAL_BASE_URL_ENV],n=process.env[PORT_ENV],r=new URL(normalizeDevelopmentServerClientUrl(e));return process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=r.origin,r.port&&(process.env[PORT_ENV]=r.port),()=>{t===void 0?delete process.env[WORKFLOW_LOCAL_BASE_URL_ENV]:process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=t,n===void 0?delete process.env[PORT_ENV]:process.env[PORT_ENV]=n}}function attachTemporarySocketErrorHandler(e){let onSocketError=()=>{};return e.once(`error`,onSocketError),()=>{e.off(`error`,onSocketError)}}function shouldProxyDevelopmentServerWebSocketUpgrades(e){return e.options.features.websocket===!0||e.options.experimental.websocket===!0}function guardDevelopmentServerWebSocketUpgrades(e,t){let n=t.upgrade.bind(t),r=shouldProxyDevelopmentServerWebSocketUpgrades(e);t.upgrade=async(e,t,i)=>{if(!r){t.destroyed||t.destroy();return}let a=attachTemporarySocketErrorHandler(t);try{await n(e,t,i)}catch{t.destroyed||t.destroy()}finally{a()}}}function addDevelopmentRuntimeArtifactsRebuildHandler(t){t.nitro.options.devHandlers.push({route:EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,handler:async e=>{let n=e.node?.req.url??``;return new URL(n,`http://localhost`).searchParams.get(`force`)===`1`?await t.watcher.rebuild():await t.watcher.flush(),handleDevRuntimeArtifactsRequest({appRoot:t.appRoot})}})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.devServer,i=r===void 0?!0:await attempt(()=>r.close()),a=e.nitro;return a!==void 0&&await attempt(()=>a.close()),await attempt(()=>stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(e.developmentSandboxRunId),devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:i}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,n){process.env[EVE_DEV_ENV_FLAG]??=`1`;let r=await resolveDiscoveryProject(e);loadDevelopmentEnvironmentFiles(r.appRoot);let i=readEnvironmentPort(),u=n.port??i,p=n.host!==void 0||n.port!==void 0||i!==void 0,m=new DevelopmentServerState(r),h=await m.read();if(h!==void 0&&isLoopbackServerUrl(h)&&await isEveServerHealthy(h)){if(n.existing===`attach-if-unconfigured`&&!p)return{handle:{kind:`existing`,appRoot:r.appRoot,url:h},close:void 0};throw await createDevelopmentServerAlreadyRunningError(r.appRoot,h)}let g=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],_=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=_;let v,y,b,x;try{let e=await devBootPhase(`compiling agent`,()=>prepareDevelopmentApplicationHost(r.appRoot),n.onBootProgress),t=resolveNitroCompiledArtifactsSource(createDevelopmentNitroArtifactsConfig({appRoot:e.appRoot}));startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:t}),pruneLocalSandboxTemplatesInBackground(e.appRoot);let i=await devBootPhase(`creating dev server`,()=>createDevelopmentApplicationNitro(e),n.onBootProgress);v=i,y=createDevServer(i);let a=y;guardDevelopmentServerWebSocketUpgrades(i,y);let o=n.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,s=u===void 0,c=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:a,host:o,port:u,retryOnAddressInUse:s}),n.onBootProgress);if(!c.url)throw Error(`Nitro dev server did not expose a URL.`);let l=normalizeDevelopmentServerClientUrl(c.url);b=installWorkflowLocalQueueEnvironment(l),await devBootPhase(`building dev bundle`,async()=>{await prepare(i),await build(i)},n.onBootProgress),x=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({nitro:i,preparedHost:e})},n.onBootProgress),addDevelopmentRuntimeArtifactsRebuildHandler({appRoot:r.appRoot,nitro:i,watcher:x}),await m.write(l);let d=b;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);let f=x,p=y,h=i,S;return{handle:{kind:`started`,appRoot:r.appRoot,url:l},close:()=>(S??=(async()=>{let e=await closeDevelopmentServerResources({authoredSourceWatcher:f,devServer:p,developmentSandboxRunId:_,nitro:h});e.listenerClosed&&await m.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{clearInitializedDevelopmentSandboxBackendNames(_),d(),restoreDevelopmentSandboxRunId(g)}})(),S)}}catch(e){let t=await closeDevelopmentServerResources({authoredSourceWatcher:x,devServer:y,developmentSandboxRunId:_,nitro:v}),n=[...t.errors];throw b?.(),clearInitializedDevelopmentSandboxBackendNames(_),t.listenerClosed&&await m.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(g),n.length>0?createDevelopmentServerStartupCleanupError(e,n):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,isActiveDevelopmentServerForApp,normalizeDevelopmentServerClientUrl};
1
+ import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{detectPackageManager}from"#setup/package-manager.js";import{eveDevArguments}from"#setup/primitives/index.js";import{toErrorMessage}from"#shared/errors.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{randomBytes}from"node:crypto";import{resolveDiscoveryProject}from"#discover/project.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{buildDevelopmentHostCandidate}from"#internal/nitro/host/dev-host-candidate.js";import{removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import{DrainedNitroDevServer}from"#internal/nitro/host/drained-nitro-dev-server.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{DEFAULT_DEVELOPMENT_SERVER_HOST,normalizeDevelopmentServerClientUrl}from"#internal/nitro/host/dev-server-url.js";import{createDevelopmentAuthoredRebuildCoordinator}from"#internal/nitro/host/dev-authored-rebuild-coordinator.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{isEveServerHealthy}from"#shared/eve-server-health.js";import{handleDevRuntimeArtifactsRequest}from"#internal/nitro/routes/dev-runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";import{createDevelopmentWorkflowWorld,installWorkflowLocalQueueEnvironment,installWorkflowTransportEnvironment}from"#internal/nitro/host/dev-workflow-world-setup.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,PORT_ENV=`PORT`;async function isActiveDevelopmentServerForApp(e){try{let t=await new DevelopmentServerState(await resolveDiscoveryProject(e.appRoot)).read();return t===void 0||!isLoopbackServerUrl(t)||!await isEveServerHealthy(t)?!1:new URL(t).origin===new URL(normalizeDevelopmentServerClientUrl(e.serverUrl)).origin}catch{return!1}}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let n=await detectDevelopmentCommandPackageManager(e);return[n,...eveDevArguments(n),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
2
+ `))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function addDevelopmentControlHandler(n){n.devServer.setControlHandler(async r=>{let i=await n.workflowWorld?.handleRequest(r);if(i!==void 0)return i;let a=new URL(r.url);if(a.pathname===EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH&&r.method===`GET`)return handleDevRuntimeArtifactsRequest({appRoot:n.appRoot});if(a.pathname!==EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH||r.method!==`GET`)return;let o=n.getWatcher();return o===void 0?Response.json({error:`The development server is still starting.`},{status:503}):(a.searchParams.get(`force`)===`1`?await o.rebuild():await o.flush(),handleDevRuntimeArtifactsRequest({appRoot:n.appRoot}))})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.devServer,i=r===void 0?!0:await attempt(()=>r.close()),a=e.workflowWorld;a!==void 0&&await attempt(()=>a.close());let o=e.nitro;return o!==void 0&&await attempt(()=>o.close()),await attempt(()=>stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(e.developmentSandboxRunId),devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:i}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,t){process.env[EVE_DEV_ENV_FLAG]??=`1`;let r=await resolveDiscoveryProject(e);loadDevelopmentEnvironmentFiles(r.appRoot);let i=readEnvironmentPort(),a=t.port??i,d=t.host!==void 0||t.port!==void 0||i!==void 0,h=new DevelopmentServerState(r),g=await h.read();if(g!==void 0&&isLoopbackServerUrl(g)&&await isEveServerHealthy(g)){if(t.existing===`attach-if-unconfigured`&&!d)return{handle:{kind:`existing`,appRoot:r.appRoot,url:g},close:void 0};throw await createDevelopmentServerAlreadyRunningError(r.appRoot,g)}let _=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],v=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=v;let y,b,x,S,C,w,T,E=!1,D=!1;try{let e=await devBootPhase(`compiling agent`,()=>prepareDevelopmentApplicationHost(r.appRoot),t.onBootProgress);T=e;let n=resolveNitroCompiledArtifactsSource(createDevelopmentNitroArtifactsConfig({appRoot:e.appRoot,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));pruneLocalSandboxTemplatesInBackground(e.appRoot);let i=await devBootPhase(`creating dev server`,()=>createDevelopmentApplicationNitro(e),t.onBootProgress);y=i,b=new DrainedNitroDevServer(i.logger);let o=b,s=randomBytes(32).toString(`base64url`);o.setClientAddressSecret(s),S=installWorkflowTransportEnvironment(r.appRoot,s),C=createDevelopmentWorkflowWorld({appRoot:r.appRoot,preparedHost:e,transportSecret:s}),addDevelopmentControlHandler({appRoot:r.appRoot,devServer:o,getWatcher:()=>w,workflowWorld:C});let c=t.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,l=a===void 0,u=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:o,host:c,port:a,retryOnAddressInUse:l}),t.onBootProgress);if(!u.url)throw Error(`Nitro dev server did not expose a URL.`);let d=normalizeDevelopmentServerClientUrl(u.url);x=installWorkflowLocalQueueEnvironment(d),await devBootPhase(`building dev bundle`,async()=>{let t=await buildDevelopmentHostCandidate({host:e,nitro:i});y=void 0;let n=e.workspace;D=!0,await o.replaceWorker({dispose:async()=>await removeDevelopmentHostWorkspace(n),entry:t.entry,workerData:t.workerData}),await activateDevelopmentGeneration({appRoot:e.appRoot,generation:e.generation}),E=!0},t.onBootProgress),await C?.start(),startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:n});let f=await createDevelopmentAuthoredRebuildCoordinator({devServer:o,initialHost:e});w=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({coordinator:f,preparedHost:e})},t.onBootProgress),await h.write(d);let p=x;if(p===void 0)throw Error(`Workflow local queue environment was not initialized.`);let m=w,g=b,O=C,k=S,A;return{handle:{kind:`started`,appRoot:r.appRoot,url:d},close:()=>(A??=(async()=>{let e=await closeDevelopmentServerResources({authoredSourceWatcher:m,devServer:g,developmentSandboxRunId:v,nitro:void 0,workflowWorld:O});e.listenerClosed&&await h.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{clearInitializedDevelopmentSandboxBackendNames(v),p(),k?.(),restoreDevelopmentSandboxRunId(_)}})(),A)}}catch(e){let t=await closeDevelopmentServerResources({authoredSourceWatcher:w,devServer:b,developmentSandboxRunId:v,nitro:y,workflowWorld:C}),n=[...t.errors];throw T!==void 0&&!E&&await discardDevelopmentGeneration(T.generation).catch(e=>{n.push(e)}),T!==void 0&&!D&&await removeDevelopmentHostWorkspace(T.workspace).catch(e=>{n.push(e)}),x?.(),S?.(),clearInitializedDevelopmentSandboxBackendNames(v),t.listenerClosed&&await h.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(_),n.length>0?createDevelopmentServerStartupCleanupError(e,n):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,isActiveDevelopmentServerForApp,normalizeDevelopmentServerClientUrl};
@@ -3,6 +3,8 @@ import type { ScheduleRegistration } from "#runtime/schedules/register.js";
3
3
  import type { ResolvedScheduleDefinition } from "#runtime/types.js";
4
4
  import type { GeneratedCompiledArtifactsFiles } from "#internal/application/compiled-artifacts.js";
5
5
  import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
6
+ import type { DevelopmentGeneration } from "#internal/nitro/development-generation.js";
7
+ import type { DevelopmentHostWorkspace } from "#internal/nitro/host/dev-host-workspace.js";
6
8
  /**
7
9
  * Route surface included in one programmatic Nitro host build.
8
10
  */
@@ -65,3 +67,7 @@ export interface PreparedApplicationHost {
65
67
  schedules: readonly ResolvedScheduleDefinition[];
66
68
  workflowBuildDir: string;
67
69
  }
70
+ export interface PreparedDevelopmentApplicationHost extends PreparedApplicationHost {
71
+ generation: DevelopmentGeneration;
72
+ workspace: DevelopmentHostWorkspace;
73
+ }
@@ -1 +1 @@
1
- import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{attachAgentInfoRouteResponse}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),c;try{c=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),c}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,c=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,c.args));return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,s,c){let l=readVercelRequestId(t.req.headers),u=extractSocketIp(t),d=[],f=t.context.params??{},p={};for(let[e,t]of Object.entries(f))p[e]=decodeURIComponent(t);let waitUntil=e=>{d.push(e)},m=n.channels.find(e=>e.name===s)?.adapter??{kind:`channel`};return{agent:createRouteAgent(n.runtime,l),args:attachAgentInfoRouteResponse({send:createSendFn(n.runtime,m,s,{requestId:l}),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:p,waitUntil,requestIp:u},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(c)}),backgroundTasks:d}}function createRouteAgent(e,t){return{async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
1
+ import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{attachAgentInfoRouteResponse}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),s;try{s=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),s}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,s=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,s.args));return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,o,s){let c=readVercelRequestId(t.req.headers),l=extractRequestIp(t,s),u=[],d=t.context.params??{},f={};for(let[e,t]of Object.entries(d))f[e]=decodeURIComponent(t);let waitUntil=e=>{u.push(e)},p=n.channels.find(e=>e.name===o)?.adapter??{kind:`channel`};return{agent:createRouteAgent(n.runtime,c),args:attachAgentInfoRouteResponse({send:createSendFn(n.runtime,p,o,{requestId:c}),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:f,waitUntil,requestIp:l},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(s)}),backgroundTasks:u}}function createRouteAgent(e,t){return{async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
@@ -7,6 +7,13 @@ import { type RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts
7
7
  export interface DevelopmentNitroArtifactsConfig {
8
8
  readonly appRoot: string;
9
9
  readonly devRuntimeArtifactsPointerPath: string;
10
+ /**
11
+ * Set when durable Workflow payloads may store a logical generation
12
+ * selector instead of this source's exact snapshot path. Only true when
13
+ * the parent-owned dev World delivers the queue, because only those
14
+ * deliveries install the context that resolves the selector.
15
+ */
16
+ readonly durableArtifactsReference?: "development-generation";
10
17
  readonly kind: "development";
11
18
  readonly moduleMapLoaderPath: string;
12
19
  }
@@ -1 +1 @@
1
- import{createBundledRuntimeCompiledArtifactsSource,createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{readBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";import{readDevelopmentRuntimeArtifactsSnapshotRoot}from"#internal/nitro/dev-runtime-artifacts.js";function resolveNitroCompiledArtifactsSource(e){if(e.kind===`development`)return createDiskRuntimeCompiledArtifactsSource(readDevelopmentRuntimeArtifactsSnapshotRoot(e.devRuntimeArtifactsPointerPath)??e.appRoot,{moduleMapLoaderPath:e.moduleMapLoaderPath,sandboxAppRoot:e.appRoot});if(readBundledCompiledArtifacts()!==null)return createBundledRuntimeCompiledArtifactsSource();throw Error(`eve Nitro production requires bundled artifacts.`)}export{resolveNitroCompiledArtifactsSource};
1
+ import{createBundledRuntimeCompiledArtifactsSource,createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{readBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";import{readDevelopmentRuntimeArtifactsSnapshotRoot}from"#internal/nitro/dev-runtime-artifacts.js";function resolveNitroCompiledArtifactsSource(e){if(e.kind===`development`)return createDiskRuntimeCompiledArtifactsSource(readDevelopmentRuntimeArtifactsSnapshotRoot(e.devRuntimeArtifactsPointerPath)??e.appRoot,{durableReference:e.durableArtifactsReference,moduleMapLoaderPath:e.moduleMapLoaderPath,sandboxAppRoot:e.appRoot});if(readBundledCompiledArtifacts()!==null)return createBundledRuntimeCompiledArtifactsSource();throw Error(`eve Nitro production requires bundled artifacts.`)}export{resolveNitroCompiledArtifactsSource};
@@ -1,4 +1,5 @@
1
1
  import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
2
+ import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
2
3
  /**
3
4
  * Dispatches one eve authored schedule via the execution engine.
4
5
  *
@@ -10,3 +11,11 @@ export declare function dispatchScheduleTask(taskName: string, config: NitroArti
10
11
  scheduleId: string;
11
12
  sessionIds: readonly string[];
12
13
  }>;
14
+ /**
15
+ * Variant of {@link dispatchScheduleTask} for callers that already resolved
16
+ * an artifact source and need the dispatch to stay on that generation.
17
+ */
18
+ export declare function dispatchScheduleTaskFromArtifacts(taskName: string, compiledArtifactsSource: RuntimeCompiledArtifactsSource): Promise<{
19
+ scheduleId: string;
20
+ sessionIds: readonly string[];
21
+ }>;
@@ -1 +1 @@
1
- import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{loadResolvedCompiledScheduleByTaskName}from"#runtime/schedules/resolve-schedule.js";import{ScheduleDispatcher,expectScheduleRun}from"#channel/schedule.js";import{loadResolvedModuleExport}from"#runtime/resolve-helpers.js";async function dispatchScheduleTask(r,i){let a=resolveNitroCompiledArtifactsSource(i),o=await loadResolvedCompiledScheduleByTaskName(r,{compiledArtifactsSource:a}),s=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:a}),c=new ScheduleDispatcher({runtime:createWorkflowRuntime({compiledArtifactsSource:a}),channels:s.graph.root.channels}),l={scheduleId:o.name};o.hasRun&&(l.run=await loadScheduleRun(o,s.moduleMap)),o.markdown!==void 0&&(l.markdown=o.markdown);let u=await c.trigger(l);return u.waitUntilTasks.length>0&&await Promise.allSettled(u.waitUntilTasks),{scheduleId:o.name,sessionIds:u.sessions.map(e=>e.id)}}async function loadScheduleRun(e,t){if(e.sourceKind!==`module`)throw Error(`Schedule "${e.name}" claims hasRun but is not a module-backed schedule.`);let n=e;return expectScheduleRun(await loadResolvedModuleExport({definition:{exportName:n.exportName,logicalPath:n.logicalPath,sourceId:n.sourceId},kindLabel:`schedule`,moduleMap:t,nodeId:void 0}),n.logicalPath,n.exportName)}export{dispatchScheduleTask};
1
+ import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{loadResolvedCompiledScheduleByTaskName}from"#runtime/schedules/resolve-schedule.js";import{ScheduleDispatcher,expectScheduleRun}from"#channel/schedule.js";import{loadResolvedModuleExport}from"#runtime/resolve-helpers.js";async function dispatchScheduleTask(e,t){return await dispatchScheduleTaskFromArtifacts(e,resolveNitroCompiledArtifactsSource(t))}async function dispatchScheduleTaskFromArtifacts(n,r){let i=await loadResolvedCompiledScheduleByTaskName(n,{compiledArtifactsSource:r}),a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:r}),o=new ScheduleDispatcher({runtime:createWorkflowRuntime({compiledArtifactsSource:r}),channels:a.graph.root.channels}),s={scheduleId:i.name};i.hasRun&&(s.run=await loadScheduleRun(i,a.moduleMap)),i.markdown!==void 0&&(s.markdown=i.markdown);let c=await o.trigger(s);return c.waitUntilTasks.length>0&&await Promise.allSettled(c.waitUntilTasks),{scheduleId:i.name,sessionIds:c.sessions.map(e=>e.id)}}async function loadScheduleRun(e,t){if(e.sourceKind!==`module`)throw Error(`Schedule "${e.name}" claims hasRun but is not a module-backed schedule.`);let n=e;return expectScheduleRun(await loadResolvedModuleExport({definition:{exportName:n.exportName,logicalPath:n.logicalPath,sourceId:n.sourceId},kindLabel:`schedule`,moduleMap:t,nodeId:void 0}),n.logicalPath,n.exportName)}export{dispatchScheduleTask,dispatchScheduleTaskFromArtifacts};
@@ -0,0 +1,8 @@
1
+ import type { RuntimeDiskCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
2
+ interface DevelopmentGenerationContext {
3
+ readonly generationId: string;
4
+ readonly source: RuntimeDiskCompiledArtifactsSource;
5
+ }
6
+ export declare function getDevelopmentWorkflowGeneration(): DevelopmentGenerationContext | undefined;
7
+ export declare function withDevelopmentWorkflowGeneration<T>(context: DevelopmentGenerationContext, operation: () => Promise<T>): Promise<T>;
8
+ export {};
@@ -0,0 +1 @@
1
+ import{ContextContainer,contextStorage}from"#context/container.js";import{ContextKey}from"#context/key.js";const DevelopmentGenerationKey=new ContextKey(`eve.internal.developmentGeneration`);function getDevelopmentWorkflowGeneration(){return contextStorage.getStore()?.get(DevelopmentGenerationKey)}async function withDevelopmentWorkflowGeneration(e,t){let n=new ContextContainer;return n.setVirtualContext(DevelopmentGenerationKey,e),await contextStorage.run(n,t)}export{getDevelopmentWorkflowGeneration,withDevelopmentWorkflowGeneration};
@@ -0,0 +1,29 @@
1
+ import type { World } from "#compiled/@workflow/world/index.js";
2
+ /**
3
+ * Raised when a delivery's recorded generation no longer exists on disk.
4
+ * This never heals on retry, so the queue handler acknowledges and drops
5
+ * the delivery instead of letting the queue redeliver it for its full
6
+ * retry budget.
7
+ */
8
+ export declare class MissingDevelopmentGenerationError extends Error {
9
+ constructor(generationId: string, cause?: unknown);
10
+ }
11
+ /**
12
+ * Worker-side Workflow World: an interface-faithful shim whose every method
13
+ * forwards to the real local World in the CLI parent process.
14
+ *
15
+ * Why: a dev worker is disposed on every structural reload, so nothing with
16
+ * run lifetime may live inside it. The `World` interface is already fully
17
+ * async because production Worlds are remote services — inserting HTTP
18
+ * between the runtime and the World changes topology, not semantics, and
19
+ * makes development match production's compute/state split. The runtime
20
+ * cannot observe the difference, so `@workflow/core` needs no changes and
21
+ * this file is deletable the day a multi-process local World ships upstream.
22
+ *
23
+ * Two members are not simple forwards. `streams.get` must return a live
24
+ * `ReadableStream`, so it uses a dedicated route and hands back the response
25
+ * body. `createQueueHandler` points the other way entirely: it returns the
26
+ * HTTP handler that the parent's queue posts deliveries into, and is where a
27
+ * delivery gets pinned to the generation its run started on.
28
+ */
29
+ export declare function createDevelopmentWorkflowWorld(): World;
@@ -0,0 +1 @@
1
+ import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{basename,join}from"node:path";import{readFile}from"node:fs/promises";import{turnWorkflowReference}from"#execution/workflow-runtime.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{DEVELOPMENT_WORKER_APP_ROOT_ENV,DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_SECRET_ENV,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldJson,decodeDevelopmentWorldValue,deserializeDevelopmentWorldError,encodeDevelopmentWorldValue}from"#internal/workflow/development-world-codec.js";import{getDevelopmentWorkflowGeneration,withDevelopmentWorkflowGeneration}from"#internal/workflow/development-generation-context.js";import{LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}from"#internal/workflow/local-world-data-directory.js";var MissingDevelopmentGenerationError=class extends Error{constructor(e,t){super(`Workflow run references missing development generation "${e}". Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard the app's active local Workflow runs.`,t===void 0?void 0:{cause:t}),this.name=`MissingDevelopmentGenerationError`}};async function call(e,t=[]){return decodeDevelopmentWorldValue(await(await fetchDevelopmentWorld(DEVELOPMENT_WORKFLOW_WORLD_ROUTE,{body:encodeDevelopmentWorldValue({arguments:t,operation:e}),method:`POST`})).text())}function createDevelopmentWorkflowWorld(){let e=buildForwardedOperations();return{specVersion:5,processExitTriggersQueueRedelivery:!1,async getDeploymentId(){return getDevelopmentWorkflowGeneration()?.generationId??await call(`getDeploymentId`)},resolveLatestDeploymentId:e.topLevel.resolveLatestDeploymentId,queue:e.topLevel.queue,createQueueHandler,runs:e.groups.runs,steps:e.groups.steps,events:e.groups.events,hooks:e.groups.hooks,streams:{...e.groups.streams,get:async(e,t,n)=>{let r=new URL(resolveDevelopmentWorldBaseUrl());r.pathname=DEVELOPMENT_WORKFLOW_STREAM_ROUTE,r.searchParams.set(`runId`,e),r.searchParams.set(`name`,t),n!==void 0&&r.searchParams.set(`startIndex`,String(n));let i=await fetchDevelopmentWorld(r,{method:`GET`});if(i.body===null)throw Error(`Development Workflow stream response had no body.`);return i.body}},async start(){},async close(){}}}function buildForwardedOperations(){let e={},t={};for(let n of DEVELOPMENT_WORLD_OPERATIONS){let forward=async(...e)=>await call(n,e),r=n.indexOf(`.`);r===-1?t[n]=forward:(e[n.slice(0,r)]??={})[n.slice(r+1)]=forward}return{groups:e,topLevel:t}}function createQueueHandler(t,n){return async r=>{let i=readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV),c=r.headers.get(DEVELOPMENT_WORKFLOW_DELIVERY_HEADER);if(c===null||!timingSafeEqualStrings(c,i))return Response.json({error:`Workflow delivery is not trusted.`},{status:401});let l=r.headers.get(`x-vqs-queue-name`),u=r.headers.get(`x-vqs-message-id`),d=Number(r.headers.get(`x-vqs-message-attempt`));if(l===null||!l.startsWith(t)||u===null||!Number.isInteger(d)||d<1||r.body===null)return Response.json({error:`Workflow delivery is malformed.`},{status:400});let f=decodeDevelopmentWorldJson(await r.text());try{let t=readRequiredEnvironment(DEVELOPMENT_WORKER_APP_ROOT_ENV),r=await resolveDeliveryGenerationId(f),i=await withDevelopmentWorkflowGeneration({generationId:r,source:createDiskRuntimeCompiledArtifactsSource(await readGenerationRuntimeAppRoot(t,r),{durableReference:`development-generation`,moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:t})},async()=>await n(f,{attempt:d,messageId:u,queueName:l}));return Response.json(i===void 0?{ok:!0}:{timeoutSeconds:i.timeoutSeconds})}catch(e){return e instanceof MissingDevelopmentGenerationError?(console.error(`[eve:dev] ${e.message}`),Response.json({ok:!0})):Response.json(String(e),{status:500})}}}async function resolveDeliveryGenerationId(e){if(!isRecord(e))return await call(`resolveLatestDeploymentId`);let t=isRecord(e.runInput)?e.runInput:void 0;if(t!==void 0)return t.workflowName===turnWorkflowReference.workflowId&&typeof t.deploymentId==`string`?t.deploymentId:await call(`resolveLatestDeploymentId`);let n=typeof e.runId==`string`?e.runId:typeof e.workflowRunId==`string`?e.workflowRunId:void 0;if(n===void 0)return await call(`resolveLatestDeploymentId`);let r=await call(`runs.get`,[n,{resolveData:`none`}]);return r.workflowName===turnWorkflowReference.workflowId?r.deploymentId:await call(`resolveLatestDeploymentId`)}async function readGenerationRuntimeAppRoot(e,i){if(i.length===0||i===`.`||i===`..`||basename(i)!==i)throw Error(`Workflow run references invalid development generation "${i}".`);let a=join(e,`.eve`,`dev-runtime`,`snapshots`,i,`generation.json`),o;try{o=await readFile(a,`utf8`)}catch(e){throw isFileNotFoundError(e)?new MissingDevelopmentGenerationError(i,e):e}let s;try{s=JSON.parse(o)}catch(e){throw Error(`Development generation "${i}" has invalid metadata.`,{cause:e})}if(!isRecord(s)||typeof s.runtimeAppRoot!=`string`)throw Error(`Development generation "${i}" has invalid metadata.`);return s.runtimeAppRoot}function isFileNotFoundError(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function fetchDevelopmentWorld(e,t){let n=e instanceof URL?e:new URL(e,resolveDevelopmentWorldBaseUrl()),r=new Headers(t.headers);r.set(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV));let i=await fetch(n,{...t,headers:r});if(!i.ok){let e=await i.text(),t=readDevelopmentWorldError(e);throw t===void 0?Error(`Development Workflow World request failed (${String(i.status)}): ${e}`):t}return i}function readDevelopmentWorldError(e){try{return deserializeDevelopmentWorldError(decodeDevelopmentWorldValue(e))}catch{return}}function resolveDevelopmentWorldBaseUrl(){return readRequiredEnvironment(`WORKFLOW_LOCAL_BASE_URL`)}function readRequiredEnvironment(e){let t=process.env[e];if(t===void 0||t.length===0)throw Error(`Development Workflow transport is missing ${e}.`);return t}export{MissingDevelopmentGenerationError,createDevelopmentWorkflowWorld};
@@ -0,0 +1,11 @@
1
+ export interface SerializedDevelopmentWorldError {
2
+ readonly details: Readonly<Record<string, unknown>>;
3
+ readonly message: string;
4
+ readonly name: string;
5
+ readonly stack?: string;
6
+ }
7
+ export declare function encodeDevelopmentWorldValue(value: unknown): string;
8
+ export declare function decodeDevelopmentWorldValue(source: string): unknown;
9
+ export declare function decodeDevelopmentWorldJson(source: string): unknown;
10
+ export declare function serializeDevelopmentWorldError(error: unknown): SerializedDevelopmentWorldError;
11
+ export declare function deserializeDevelopmentWorldError(value: unknown): Error | undefined;
@@ -0,0 +1 @@
1
+ const VALUE_TYPE_KEY=`__eveDevelopmentWorldType`,DATE_MARKER=`date`,OBJECT_MARKER=`object`,UINT8_ARRAY_MARKER=`uint8-array`,UNDEFINED_MARKER=`undefined`;function encodeDevelopmentWorldValue(e){return JSON.stringify({value:encodeValue(e)})}function decodeDevelopmentWorldValue(e){let t=JSON.parse(e);return isRecord(t)?decodeTransportValue(t.value):void 0}function decodeDevelopmentWorldJson(e){return decodeWorkflowJsonValue(JSON.parse(e))}function serializeDevelopmentWorldError(e){return e instanceof Error?{details:Object.fromEntries(Object.entries(e)),message:e.message,name:e.name,stack:e.stack}:{details:{},message:String(e),name:`Error`}}function deserializeDevelopmentWorldError(e){if(!isRecord(e)||!isRecord(e.details)||typeof e.message!=`string`||typeof e.name!=`string`)return;let t=Error(e.message);return t.name=e.name,typeof e.stack==`string`&&(t.stack=e.stack),Object.assign(t,e.details),t}function encodeValue(n){return n===void 0?{[VALUE_TYPE_KEY]:UNDEFINED_MARKER}:n instanceof Date?{[VALUE_TYPE_KEY]:DATE_MARKER,data:n.toISOString()}:n instanceof Uint8Array?{[VALUE_TYPE_KEY]:UINT8_ARRAY_MARKER,data:Buffer.from(n).toString(`base64`)}:Array.isArray(n)?n.map(e=>encodeValue(e)):isRecord(n)?{[VALUE_TYPE_KEY]:OBJECT_MARKER,data:Object.fromEntries(Object.entries(n).map(([e,t])=>[e,encodeValue(t)]))}:n}function decodeTransportValue(n){if(Array.isArray(n))return n.map(e=>decodeTransportValue(e));if(!isRecord(n))return n;if(n[VALUE_TYPE_KEY]!==UNDEFINED_MARKER){if(n[VALUE_TYPE_KEY]===DATE_MARKER&&typeof n.data==`string`)return new Date(n.data);if(n[VALUE_TYPE_KEY]===UINT8_ARRAY_MARKER&&typeof n.data==`string`)return Uint8Array.from(Buffer.from(n.data,`base64`));if(n[VALUE_TYPE_KEY]===OBJECT_MARKER&&isRecord(n.data))return Object.fromEntries(Object.entries(n.data).map(([e,t])=>[e,decodeTransportValue(t)]));throw Error(`Development Workflow World transport contained an invalid encoded value.`)}}function decodeWorkflowJsonValue(e){return Array.isArray(e)?e.map(e=>decodeWorkflowJsonValue(e)):isRecord(e)?Object.keys(e).length===2&&e.__type===`Uint8Array`&&typeof e.data==`string`?Uint8Array.from(Buffer.from(e.data,`base64`)):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,decodeWorkflowJsonValue(t)])):e}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{decodeDevelopmentWorldJson,decodeDevelopmentWorldValue,deserializeDevelopmentWorldError,encodeDevelopmentWorldValue,serializeDevelopmentWorldError};
@@ -0,0 +1,31 @@
1
+ import type { AgentWorkflowWorldDefinition } from "#shared/agent-definition.js";
2
+ export declare const DEVELOPMENT_WORKFLOW_WORLD_ROUTE = "/eve/v1/dev/internal/workflow-world";
3
+ /**
4
+ * Whether development serves this app's Workflow World from the CLI parent.
5
+ * The parent's world creation and the generated worker plugin must agree on
6
+ * this predicate: a worker wired for the parent RPC client fails every World
7
+ * call when the parent never created a World to serve it. An explicit
8
+ * `world: "local"` resolves to the same vendored world as an absent config,
9
+ * so both take the parent-owned path.
10
+ */
11
+ export declare function usesParentDevelopmentWorkflowWorld(configuredWorld: AgentWorkflowWorldDefinition | undefined): boolean;
12
+ export declare const DEVELOPMENT_WORKFLOW_SECRET_ENV = "EVE_DEV_WORKFLOW_TRANSPORT_SECRET";
13
+ export declare const DEVELOPMENT_WORKER_APP_ROOT_ENV = "EVE_DEV_WORKER_APP_ROOT";
14
+ export declare const DEVELOPMENT_WORKFLOW_STREAM_ROUTE = "/eve/v1/dev/internal/workflow-world/stream";
15
+ export declare const DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER = "x-eve-dev-workflow-transport";
16
+ export declare const DEVELOPMENT_WORKFLOW_DELIVERY_HEADER = "x-eve-dev-workflow-delivery";
17
+ /**
18
+ * The single source of truth for World operations forwarded over the dev
19
+ * RPC: the worker client generates its method forwards from this list and
20
+ * the parent dispatches by walking the same dot-path on the real world, so
21
+ * adapting to a vendored-world interface change is one entry here. The
22
+ * members NOT listed are the deliberate exceptions — `streams.get` returns
23
+ * a live stream over its own route, `createQueueHandler` runs entirely in
24
+ * the worker, and `start`/`close` belong to the parent's lifecycle.
25
+ */
26
+ export declare const DEVELOPMENT_WORLD_OPERATIONS: readonly ["events.create", "events.get", "events.list", "events.listByCorrelationId", "hooks.get", "hooks.getByToken", "hooks.list", "getDeploymentId", "queue", "resolveLatestDeploymentId", "runs.experimentalSetAttributes", "runs.get", "runs.list", "steps.get", "steps.list", "streams.close", "streams.getChunks", "streams.getInfo", "streams.list", "streams.write", "streams.writeMulti"];
27
+ export type DevelopmentWorldOperation = (typeof DEVELOPMENT_WORLD_OPERATIONS)[number];
28
+ export interface DevelopmentWorldCall {
29
+ readonly arguments: readonly unknown[];
30
+ readonly operation: DevelopmentWorldOperation;
31
+ }
@@ -0,0 +1 @@
1
+ import{getWorldImport}from"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/world-target.js";import"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/index.js";const DEVELOPMENT_WORKFLOW_WORLD_ROUTE=`/eve/v1/dev/internal/workflow-world`;function usesParentDevelopmentWorkflowWorld(e){return getWorldImport({WORKFLOW_TARGET_WORLD:e??`local`})===`@workflow/world-local`}const DEVELOPMENT_WORKFLOW_SECRET_ENV=`EVE_DEV_WORKFLOW_TRANSPORT_SECRET`,DEVELOPMENT_WORKER_APP_ROOT_ENV=`EVE_DEV_WORKER_APP_ROOT`,DEVELOPMENT_WORKFLOW_STREAM_ROUTE=`${DEVELOPMENT_WORKFLOW_WORLD_ROUTE}/stream`,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER=`x-eve-dev-workflow-transport`,DEVELOPMENT_WORKFLOW_DELIVERY_HEADER=`x-eve-dev-workflow-delivery`,DEVELOPMENT_WORLD_OPERATIONS=[`events.create`,`events.get`,`events.list`,`events.listByCorrelationId`,`hooks.get`,`hooks.getByToken`,`hooks.list`,`getDeploymentId`,`queue`,`resolveLatestDeploymentId`,`runs.experimentalSetAttributes`,`runs.get`,`runs.list`,`steps.get`,`steps.list`,`streams.close`,`streams.getChunks`,`streams.getInfo`,`streams.list`,`streams.write`,`streams.writeMulti`];export{DEVELOPMENT_WORKER_APP_ROOT_ENV,DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_SECRET_ENV,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS,usesParentDevelopmentWorkflowWorld};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The application's one local Workflow World, owned by the CLI parent.
3
+ *
4
+ * Why the parent: run records, the queue, and stream state must outlive the
5
+ * Nitro dev worker, which is disposed on every structural reload. The parent
6
+ * is the only process whose lifetime matches the run data, so it holds the
7
+ * real (stock, vendored) world-local instance and serves it to workers over
8
+ * an RPC route on the public listener; workers hold only an
9
+ * interface-faithful client. Deliveries are not served here — the queue
10
+ * posts them through the public listener to the active worker like any
11
+ * other request, so drained replacement covers them automatically.
12
+ *
13
+ * `handleRequest` must be reachable before `start()` runs: starting the
14
+ * world begins queue redelivery immediately, and a delivery's first World
15
+ * call arrives back on the listener within milliseconds.
16
+ */
17
+ export interface ParentDevelopmentWorkflowWorld {
18
+ close(): Promise<void>;
19
+ handleRequest(request: Request): Promise<Response | undefined>;
20
+ start(): Promise<void>;
21
+ }
22
+ export declare function createParentDevelopmentWorkflowWorld(input: {
23
+ readonly agentName: string;
24
+ readonly appRoot: string;
25
+ readonly resolveActiveGenerationId: () => string;
26
+ readonly transportSecret: string;
27
+ }): ParentDevelopmentWorkflowWorld;
@@ -0,0 +1 @@
1
+ import{existsSync}from"node:fs";import{basename,join}from"node:path";import{turnWorkflowReference}from"#execution/workflow-runtime.js";import{DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldValue,encodeDevelopmentWorldValue,serializeDevelopmentWorldError}from"#internal/workflow/development-world-codec.js";import{LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH,resolveLocalWorkflowWorldDataDirectory}from"#internal/workflow/local-world-data-directory.js";import{createWorld}from"#compiled/@workflow/world-local/index.js";function createParentDevelopmentWorkflowWorld(e){return new LocalParentDevelopmentWorkflowWorld(e)}var LocalParentDevelopmentWorkflowWorld=class{#e;#t;#n;#r;#i;#a=!1;#o=!1;constructor(e){if(e.transportSecret.length<16)throw Error(`Development Workflow transport secret is too short to be trusted.`);this.#e=e.agentName,this.#t=e.appRoot,this.#n=e.resolveActiveGenerationId,this.#r=e.transportSecret,this.#i=createWorld({dataDir:resolveLocalWorkflowWorldDataDirectory(e.appRoot),recoverActiveRuns:!1})}async start(){if(this.#o)return;let e=await this.#s(),t=new Set;for(let n of e)this.#p(n)||t.add(n);t.size>0&&console.error(`[eve:dev] ${String(t.size)} active local Workflow run(s) reference development generations that no longer exist (${[...t].join(`, `)}). Their deliveries are quarantined; remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard the app's active local Workflow runs.`),await this.#i.start?.(),this.#o=!0,await reenqueueActiveDevelopmentRuns({enqueue:this.#u.bind(this),prefix:deriveEveWorkflowQueuePrefix(this.#e),quarantinedGenerationIds:t,world:this.#i})}async close(){this.#a||(this.#a=!0,this.#o=!1,await this.#i.close?.())}async handleRequest(e){let t=new URL(e.url);if(t.pathname===DEVELOPMENT_WORKFLOW_WORLD_ROUTE)return await this.#c(e);if(t.pathname===DEVELOPMENT_WORKFLOW_STREAM_ROUTE)return await this.#l(e,t)}async#s(){let e=new Set;for(let t of[`pending`,`running`]){let n;do{let i;try{i=await this.#i.runs.list({pagination:{cursor:n,limit:1e3},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard them.`,{cause:e})}for(let t of i.data)t.workflowName===turnWorkflowReference.workflowId&&e.add(t.deploymentId);n=i.hasMore?i.cursor??void 0:void 0}while(n!==void 0)}return e}async#c(e){if(!this.#f(e)||e.method!==`POST`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});try{let t=decodeDevelopmentWorldValue(await e.text()),n=await this.#d(t);return new Response(encodeDevelopmentWorldValue(n))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#l(e,t){if(!this.#f(e)||e.method!==`GET`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});let n=t.searchParams.get(`runId`),r=t.searchParams.get(`name`),i=t.searchParams.get(`startIndex`);if(n===null||r===null)return Response.json({error:`Workflow stream request is malformed.`},{status:400});let a=i===null||i===``?void 0:Number(i);if(i===``||a!==void 0&&!Number.isInteger(a))return Response.json({error:`Workflow stream start index is invalid.`},{status:400});try{return new Response(await this.#i.streams.get(n,r,a))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#u(...e){let[t,n,r]=e;return await this.#i.queue(t,n,{...r,headers:{...r?.headers,[DEVELOPMENT_WORKFLOW_DELIVERY_HEADER]:this.#r}})}async#d(e){if(!isDevelopmentWorldCall(e))throw Error(`Development Workflow World call is malformed.`);let t=[...e.arguments];if(e.operation===`getDeploymentId`||e.operation===`resolveLatestDeploymentId`)return this.#n();if(e.operation===`queue`)return await this.#u(...t);if(e.operation===`streams.writeMulti`&&this.#i.streams.writeMulti===void 0){for(let e of t[2])await this.#i.streams.write(t[0],t[1],e);return}let n=e.operation.indexOf(`.`),r=this.#i[e.operation.slice(0,n)],i=typeof r==`object`&&r?r[e.operation.slice(n+1)]:void 0;if(typeof i==`function`)return await Reflect.apply(i,r,t)}#f(e){let t=e.headers.get(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER);return t!==null&&timingSafeEqualStrings(t,this.#r)}#p(t){return isValidGenerationId(t)?existsSync(join(this.#t,`.eve`,`dev-runtime`,`snapshots`,t,`generation.json`)):!1}};function isValidGenerationId(e){return e.length>0&&e!==`.`&&e!==`..`&&basename(e)===e}const DEVELOPMENT_WORLD_OPERATION_SET=new Set(DEVELOPMENT_WORLD_OPERATIONS);function isDevelopmentWorldCall(e){return isObject(e)&&typeof e.operation==`string`&&DEVELOPMENT_WORLD_OPERATION_SET.has(e.operation)&&Array.isArray(e.arguments)}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function reenqueueActiveDevelopmentRuns(e){for(let t of[`pending`,`running`]){let n;do{let r;try{r=await e.world.runs.list({pagination:{cursor:n},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard them.`,{cause:e})}for(let t of r.data)e.quarantinedGenerationIds.has(t.deploymentId)||await e.enqueue(`${e.prefix}${t.workflowName}`,{runId:t.runId});n=r.hasMore?r.cursor??void 0:void 0}while(n!==void 0)}}export{createParentDevelopmentWorkflowWorld};
@@ -0,0 +1,2 @@
1
+ export declare const LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH = ".eve/.workflow-data";
2
+ export declare function resolveLocalWorkflowWorldDataDirectory(appRoot: string): string;
@@ -0,0 +1 @@
1
+ import{join}from"node:path";const LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH=`.eve/.workflow-data`;function resolveLocalWorkflowWorldDataDirectory(e){return join(e,LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH)}export{LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH,resolveLocalWorkflowWorldDataDirectory};
@@ -1,9 +1,9 @@
1
- import{builtinModules}from"node:module";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{mkdir,readFile,readdir}from"node:fs/promises";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{applyWorkflowTransform,getImportPath}from"#internal/workflow-bundle/workflow-builders.js";const WORKFLOW_VIRTUAL_ENTRY_ID=`\0eve-workflow-entry`,PSEUDO_PACKAGES=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]),NODE_BUILTIN_MODULES=new Set([...builtinModules,...builtinModules.map(e=>`node:${e}`)]),WORKFLOW_INPUT_EXTENSIONS=new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),IGNORED_INPUT_DIRECTORIES=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function collectWorkflowInputFiles(e){let t=[];async function visit(e){let n;try{n=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let r of n){if(r.isDirectory()){IGNORED_INPUT_DIRECTORIES.has(r.name)||await visit(join(e,r.name));continue}if(!r.isFile())continue;let n=r.name.match(/\.[^.]+$/)?.[0];n!==void 0&&WORKFLOW_INPUT_EXTENSIONS.has(n)&&t.push(join(e,r.name))}}return await visit(e),t}function createWorkflowImport(e,t){let{importPath:n,isPackage:r}=getImportPath(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(toRelativeImportSpecifier(t,e))};`}function createWorkflowVirtualEntryPlugin(e){return{name:`eve-workflow-virtual-entry`,resolveId(e){if(e===`\0eve-workflow-entry`)return{id:e}},load(t){if(t===`\0eve-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function createWorkflowPseudoPackagePlugin(){return{name:`eve-workflow-pseudo-packages`,resolveId(e){if(PSEUDO_PACKAGES.has(e))return{id:`\0eve-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0eve-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function createWorkflowRuntimeAliasPlugin(){return{name:`eve-workflow-runtime-aliases`,resolveId(e){if(!(e!==`workflow`&&!e.startsWith(`workflow/`)))return resolveWorkflowModulePath(e)}}}function createEvePackageImportsPlugin(e,t={}){return{name:`eve-package-imports`,resolveId(n){let r=n.match(/^#compiled\/(.+)$/)?.[1];if(r!==void 0)return t.workflowCondition===!0&&r===`@workflow/core/index.js`?resolveFirstExistingPath([join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)]):resolveFirstExistingPath([join(e,`.generated`,`compiled`,r),join(e,`dist`,`src`,`compiled`,r)]);let a=n.match(/^#(.+)\.js$/)?.[1];if(a!==void 0)return resolveFirstExistingPath([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`].flatMap(t=>[join(e,`src`,`${a}${t}`),join(e,`dist`,`src`,`${a}${t}`)]))}}}function createWorkflowTransformPlugin(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`eve-workflow-transform`,async load(n){if(!isJavaScriptLikePath(n))return;let r=await readFile(n,`utf8`),i=await applyWorkflowTransform(createManifestRelativeFilepath(e.workingDir,n),r.replace(/require\(\s*(['"])server-only\1\s*\)/g,`void 0`).replace(/require\(\s*(['"])client-only\1\s*\)/g,`void 0`),e.mode??`workflow`,n,e.projectRoot);return mergeWorkflowManifest(e.manifest,i.workflowManifest),{code:i.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function bundleWorkflowStepRegistrations(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i={},a=[createWorkflowImport(e.builtinsPath,e.workingDir),...t.map(t=>createWorkflowImport(t,e.workingDir)),...r.map(t=>createWorkflowImport(t,e.workingDir)),`export const __steps_registered = true;`].join(`
2
- `),o=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:isWorkflowStepExternalPackage,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(a),createWorkflowPseudoPackagePlugin(),createWorkflowRuntimeAliasPlugin(),createEvePackageImportsPlugin(e.workingDir),createWorkflowTransformPlugin({manifest:i,mode:`step`,projectRoot:e.projectRoot,sideEffectFiles:[...t,...r],workingDir:e.workingDir})],resolve:{conditionNames:[`eve-source`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,write:!1,output:{codeSplitting:!1,comments:!1,format:`esm`,sourcemap:`inline`}}),`step registrations bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,o.code)}function isWorkflowStepExternalPackage(e){return WORKFLOW_STEP_EXTERNAL_PACKAGES.some(t=>e===t||e.startsWith(`${t}/`))}function createWorkflowNodeBuiltinGuardPlugin(){return{name:`eve-workflow-node-builtins`,resolveId(e,t){let n=e.startsWith(`node:`)?e.slice(5):e;if(!NODE_BUILTIN_MODULES.has(e)&&!NODE_BUILTIN_MODULES.has(n))return;let r=t?` (imported by "${t}")`:``;throw Error(`Workflow bundle cannot import Node.js builtin "${e}"${r}. Move Node.js APIs behind a "use step" function, or keep the importing module out of the workflow driver body (only reachable through a "use step").`)}}}async function bundleFinalWorkflowOutput(e){let n=e.code.endsWith(`
1
+ import{builtinModules}from"node:module";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{mkdir,readFile,readdir}from"node:fs/promises";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{applyWorkflowTransform,getImportPath}from"#internal/workflow-bundle/workflow-builders.js";const WORKFLOW_VIRTUAL_ENTRY_ID=`\0eve-workflow-entry`,PSEUDO_PACKAGES=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]),NODE_BUILTIN_MODULES=new Set([...builtinModules,...builtinModules.map(e=>`node:${e}`)]),WORKFLOW_INPUT_EXTENSIONS=new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),IGNORED_INPUT_DIRECTORIES=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function collectWorkflowInputFiles(e){let t=[];async function visit(e){let n;try{n=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let r of n){if(r.isDirectory()){IGNORED_INPUT_DIRECTORIES.has(r.name)||await visit(join(e,r.name));continue}if(!r.isFile())continue;let n=r.name.match(/\.[^.]+$/)?.[0];n!==void 0&&WORKFLOW_INPUT_EXTENSIONS.has(n)&&t.push(join(e,r.name))}}return await visit(e),t}function createWorkflowImport(e,t){let{importPath:n,isPackage:r}=getImportPath(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(toRelativeImportSpecifier(t,e))};`}function createWorkflowVirtualEntryPlugin(e){return{name:`eve-workflow-virtual-entry`,resolveId(e){if(e===`\0eve-workflow-entry`)return{id:e}},load(t){if(t===`\0eve-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function createWorkflowPseudoPackagePlugin(){return{name:`eve-workflow-pseudo-packages`,resolveId(e){if(PSEUDO_PACKAGES.has(e))return{id:`\0eve-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0eve-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function createWorkflowRuntimeAliasPlugin(){return{name:`eve-workflow-runtime-aliases`,resolveId(e){if(!(e!==`workflow`&&!e.startsWith(`workflow/`)))return resolveWorkflowModulePath(e)}}}function createEvePackageImportsPlugin(e,t={}){return{name:`eve-package-imports`,resolveId(n){let r=n.match(/^#compiled\/(.+)$/)?.[1];if(r!==void 0)return t.workflowCondition===!0&&r===`@workflow/core/index.js`?resolveFirstExistingPath([join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)]):resolveFirstExistingPath([join(e,`.generated`,`compiled`,r),join(e,`dist`,`src`,`compiled`,r)]);let a=n.match(/^#(.+)\.js$/)?.[1];if(a!==void 0)return resolveFirstExistingPath([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`].flatMap(t=>[join(e,`src`,`${a}${t}`),join(e,`dist`,`src`,`${a}${t}`)]))}}}function createWorkflowTransformPlugin(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`eve-workflow-transform`,async load(n){if(!isJavaScriptLikePath(n))return;let r=await readFile(n,`utf8`),i=await applyWorkflowTransform(createManifestRelativeFilepath(e.workingDir,n),r.replace(/require\(\s*(['"])server-only\1\s*\)/g,`void 0`).replace(/require\(\s*(['"])client-only\1\s*\)/g,`void 0`),e.mode??`workflow`,n,e.projectRoot);return mergeWorkflowManifest(e.manifest,i.workflowManifest),{code:i.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function bundleWorkflowStepRegistrations(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i={},a=[createWorkflowImport(e.builtinsPath,e.workingDir),...t.map(t=>createWorkflowImport(t,e.workingDir)),...r.map(t=>createWorkflowImport(t,e.workingDir)),`export const __steps_registered = true;`].join(`
2
+ `),o=await buildSingleRolldownChunk(`step registrations bundle for "${e.outfile}"`,{cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:isWorkflowStepExternalPackage,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(a),createWorkflowPseudoPackagePlugin(),createWorkflowRuntimeAliasPlugin(),createEvePackageImportsPlugin(e.workingDir),createWorkflowTransformPlugin({manifest:i,mode:`step`,projectRoot:e.projectRoot,sideEffectFiles:[...t,...r],workingDir:e.workingDir})],resolve:{conditionNames:[`eve-source`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,output:{comments:!1,format:`esm`,sourcemap:`inline`}});await writeWorkflowBundleAtomically(e.outfile,o.code)}function isWorkflowStepExternalPackage(e){return WORKFLOW_STEP_EXTERNAL_PACKAGES.some(t=>e===t||e.startsWith(`${t}/`))}function createWorkflowNodeBuiltinGuardPlugin(){return{name:`eve-workflow-node-builtins`,resolveId(e,t){let n=e.startsWith(`node:`)?e.slice(5):e;if(!NODE_BUILTIN_MODULES.has(e)&&!NODE_BUILTIN_MODULES.has(n))return;let r=t?` (imported by "${t}")`:``;throw Error(`Workflow bundle cannot import Node.js builtin "${e}"${r}. Move Node.js APIs behind a "use step" function, or keep the importing module out of the workflow driver body (only reachable through a "use step").`)}}}async function bundleFinalWorkflowOutput(e){let n=e.code.endsWith(`
3
3
  `)?e.code:`${e.code}\n`,r=resolveWorkflowModulePath(`workflow/runtime`).replaceAll(`\\`,`/`),i=`// biome-ignore-all lint: generated file
4
4
  /* eslint-disable */
5
5
  import { workflowEntrypoint } from ${JSON.stringify(r)};
6
6
 
7
7
  const workflowCode = \`${n.replace(/[\\`$]/g,`\\$&`)}\`;
8
8
 
9
- export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(e.queueNamespace)} });`;if(!e.bundleFinalOutput){await writeWorkflowBundleAtomically(e.outfile,i);return}let a=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(i)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,a.code)}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0}),await atomicWriteFile(e,t)}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=relative(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function isJavaScriptLikePath(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}export{WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,bundleWorkflowStepRegistrations,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowRuntimeAliasPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin};
9
+ export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(e.queueNamespace)} });`;if(!e.bundleFinalOutput){await writeWorkflowBundleAtomically(e.outfile,i);return}let a=await buildSingleRolldownChunk(`final workflow bundle for "${e.outfile}"`,{cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(i)],output:{comments:!1,format:e.format,sourcemap:!1}});await writeWorkflowBundleAtomically(e.outfile,a.code)}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0}),await atomicWriteFile(e,t)}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=relative(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function isJavaScriptLikePath(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}export{WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,bundleWorkflowStepRegistrations,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowRuntimeAliasPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin};
@@ -1,3 +1,3 @@
1
- import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative,resolve}from"node:path";import{cp,mkdir,readFile,rm,writeFile}from"node:fs/promises";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES,copyNitroFunctionDirectory,createWorkflowFunctionEnvironment,retargetNitroFunctionDirectoryToWorkflowRoute}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{createEveWorkflowQueueTrigger,detectWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{Buffer}from"node:buffer";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;#r;config;#i=new WeakMap;constructor(t){let n=[resolvePackageSourceDirectoryPath(`src/execution`)];t.includeTestFixtures===!0&&n.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:n,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:t.appRoot,watch:t.watch,workingDir:t.rootDir},this.#e=t.agentName,this.#t=t.compiledArtifactsBootstrapPath,this.#n=t.outDir,this.#r=deriveEveWorkflowQueueNamespace(t.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#a(e))}async#a(i){await prepareEveVersionedCacheDirectory(this.#n);let a=await this.#o();if(a.length===0)throw Error(`Expected the execution workflow source file under "${resolvePackageSourceDirectoryPath(`src/execution`)}".`);let o=await this.findTsConfigPath();await mkdir(this.#n,{recursive:!0});let c=await this.discoverEntries(a,this.#n,o),l=join(this.#n,`workflows.mjs`),{manifest:u}=await this.createWorkflowsBundle({discoveredEntries:c,keepInterimBundleContext:!1,outfile:l,bundleFinalOutput:!1,format:`esm`,inputFiles:a,tsconfigPath:o}),d=join(this.#n,`steps.mjs`),f=await writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:c,outfile:d,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),p=i.nitroStepOutfile;p!==void 0&&p!==d&&await writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:c,outfile:p,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),await addStepRegistrationsImport(l,d),await rewriteWorkflowRuntimeImports(l),await rewriteWorkflowCodeLiteral(l,this.#r);let m=i.nitroWorkflowOutfile;m!==void 0&&m!==l&&(await mkdir(dirname(m),{recursive:!0}),await mirrorFileBypassingUnlink(l,m),p!==void 0&&(await addStepRegistrationsImport(m,p),await rewriteWorkflowRuntimeImports(m),await rewriteWorkflowCodeLiteral(m,this.#r))),await this.createManifest({workflowBundlePath:join(this.#n,`workflows.mjs`),manifestDir:this.#n,manifest:{steps:{...f.steps,...u.steps},workflows:{...f.workflows,...u.workflows},classes:{...f.classes,...u.classes}}}),await writeEveVersionedCacheMetadata(this.#n)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.config.workingDir;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e,t,n){let r=this.#i.get(e);if(r!==void 0)return r;let i={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]};for(let t of e){let e=detectWorkflowPatterns(await readFile(t,`utf8`));e.hasUseStep&&i.discoveredSteps.push(t),e.hasUseWorkflow&&i.discoveredWorkflows.push(t),e.hasSerde&&i.discoveredSerdeFiles.push(t)}return this.#i.set(e,i),i}async createWorkflowsBundle({bundleFinalOutput:e=!0,discoveredEntries:t,format:r=`cjs`,inputFiles:i,keepInterimBundleContext:a=this.config.watch,outfile:o,tsconfigPath:s}){let c=t??await this.discoverEntries(i,dirname(o),s),l=[...c.discoveredWorkflows].sort(),u=new Set(l),d=[...c.discoveredSerdeFiles].sort().filter(e=>!u.has(e)),f={},h=[...l.map(e=>createWorkflowImport(e,this.config.workingDir)),...d.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
2
- `);return await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:getSingleRolldownChunk(await buildWithNitroRolldown({cwd:this.config.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,platform:`neutral`,plugins:[createWorkflowVirtualEntryPlugin(h),createWorkflowPseudoPackagePlugin(),createEvePackageImportsPlugin(this.config.workingDir,{workflowCondition:!0}),createWorkflowTransformPlugin({manifest:f,projectRoot:this.transformProjectRoot,sideEffectFiles:[...l,...d],workingDir:this.config.workingDir}),createWorkflowNodeBuiltinGuardPlugin()],resolve:{conditionNames:[`eve-source`,`workflow`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:s??!1,write:!1,output:{banner:`globalThis.__private_workflows = new Map();`,codeSplitting:!1,comments:!1,format:`cjs`,sourcemap:`inline`}}),`intermediate workflow bundle for "${o}"`).code,format:r,outfile:o,queueNamespace:this.#r,workingDir:this.config.workingDir}),a?{bundleFinal:async t=>{await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:t,format:r,outfile:o,queueNamespace:this.#r,workingDir:this.config.workingDir})},interimBundleCtx:void 0,manifest:f}:{manifest:f}}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:convertStepsManifest(e.steps),workflows:convertWorkflowsManifest(e.workflows),classes:convertClassesManifest(e.classes)},i=JSON.stringify(n,null,2);return await mkdir(t,{recursive:!0}),await writeFile(join(t,`manifest.json`),i),i}async buildVercelOutput(e){await this.build();let t=join(this.#n,`vercel-build-output`,`functions`,`.well-known`,`workflow`,`v1`),n=join(t,`flow.func`),i=join(e.outputDir,`functions`,`.well-known`,`workflow`,`v1`),a=join(e.flowNitroOutputDir,`functions`,`__server.func`),c=join(e.flowNitroOutputDir,`functions`,`.well-known`,`workflow`,`v1`,`flow.func`),u=join(i,`flow.func`),d=join(i,`step.func`),f=join(i,`webhook`,`[token].func`);await copyNitroFunctionDirectory({fallbackPath:a,sourcePath:c,targetPath:n}),await Promise.all([this.#s(n,{experimentalTriggers:[createEveWorkflowQueueTrigger(this.#e)],maxDuration:`max`,runtime:e.runtime??null,shouldAddHelpers:!1}),cp(join(this.#n,`manifest.json`),join(t,`manifest.json`))]),await retargetNitroFunctionDirectoryToWorkflowRoute({functionDirectoryPath:n,workflowRoutePath:`/.well-known/workflow/v1/flow`}),await Promise.all([rm(u,{force:!0,recursive:!0}),rm(d,{force:!0,recursive:!0}),rm(f,{force:!0,recursive:!0})]),await mkdir(i,{recursive:!0}),await Promise.all([cp(n,u,{recursive:!0}),cp(join(t,`manifest.json`),join(i,`manifest.json`))])}async#o(){return await this.getInputFiles()}async#s(e,t){let n=join(e,`.vc-config.json`),i=await this.#c(n),a={...i};a.environment=createWorkflowFunctionEnvironment(i.environment),t.runtime!==null&&(a.runtime=t.runtime),t.maxDuration!==void 0&&(a.maxDuration=t.maxDuration),t.shouldAddHelpers!==void 0&&(a.shouldAddHelpers=t.shouldAddHelpers),t.shouldAddSourcemapSupport!==void 0&&(a.shouldAddSourcemapSupport=t.shouldAddSourcemapSupport),t.experimentalTriggers!==void 0&&(a.experimentalTriggers=[...t.experimentalTriggers]),await writeFile(n,`${JSON.stringify(a,null,2)}\n`)}async#c(e){try{let t=JSON.parse(await readFile(e,`utf8`));if(typeof t==`object`&&t)return t}catch{}return{}}};async function addStepRegistrationsImport(e,t){let r=await readTextFileIfPresent(e);if(r===null||r.includes(`__eveWorkflowStepsRegistered`))return;let i=createRelativeImportSpecifier(dirname(e),t),a=[`import { __steps_registered as __eveWorkflowStepsRegistered } from ${JSON.stringify(i)};`,`void __eveWorkflowStepsRegistered;`,``].join(`
1
+ import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative,resolve}from"node:path";import{cp,mkdir,readFile,rm,writeFile}from"node:fs/promises";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES,copyNitroFunctionDirectory,createWorkflowFunctionEnvironment,retargetNitroFunctionDirectoryToWorkflowRoute}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{createEveWorkflowQueueTrigger,detectWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{Buffer}from"node:buffer";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;#r;config;#i=new WeakMap;constructor(t){let n=[resolvePackageSourceDirectoryPath(`src/execution`)];t.includeTestFixtures===!0&&n.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:n,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:t.appRoot,watch:t.watch,workingDir:t.rootDir},this.#e=t.agentName,this.#t=t.compiledArtifactsBootstrapPath,this.#n=t.outDir,this.#r=deriveEveWorkflowQueueNamespace(t.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#a(e))}async#a(i){await prepareEveVersionedCacheDirectory(this.#n);let a=await this.#o();if(a.length===0)throw Error(`Expected the execution workflow source file under "${resolvePackageSourceDirectoryPath(`src/execution`)}".`);let o=await this.findTsConfigPath();await mkdir(this.#n,{recursive:!0});let c=await this.discoverEntries(a,this.#n,o),l=join(this.#n,`workflows.mjs`),{manifest:u}=await this.createWorkflowsBundle({discoveredEntries:c,keepInterimBundleContext:!1,outfile:l,bundleFinalOutput:!1,format:`esm`,inputFiles:a,tsconfigPath:o}),d=join(this.#n,`steps.mjs`),f=await writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:c,outfile:d,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),p=i.nitroStepOutfile;p!==void 0&&p!==d&&await writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:c,outfile:p,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),await addStepRegistrationsImport(l,d),await rewriteWorkflowRuntimeImports(l),await rewriteWorkflowCodeLiteral(l,this.#r);let h=i.nitroWorkflowOutfile;h!==void 0&&h!==l&&(await mkdir(dirname(h),{recursive:!0}),await mirrorFileBypassingUnlink(l,h),p!==void 0&&(await addStepRegistrationsImport(h,p),await rewriteWorkflowRuntimeImports(h),await rewriteWorkflowCodeLiteral(h,this.#r))),await this.createManifest({workflowBundlePath:join(this.#n,`workflows.mjs`),manifestDir:this.#n,manifest:{steps:{...f.steps,...u.steps},workflows:{...f.workflows,...u.workflows},classes:{...f.classes,...u.classes}}}),await writeEveVersionedCacheMetadata(this.#n)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.config.workingDir;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e,t,n){let r=this.#i.get(e);if(r!==void 0)return r;let i={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]};for(let t of e){let e=detectWorkflowPatterns(await readFile(t,`utf8`));e.hasUseStep&&i.discoveredSteps.push(t),e.hasUseWorkflow&&i.discoveredWorkflows.push(t),e.hasSerde&&i.discoveredSerdeFiles.push(t)}return this.#i.set(e,i),i}async createWorkflowsBundle({bundleFinalOutput:e=!0,discoveredEntries:t,format:r=`cjs`,inputFiles:i,keepInterimBundleContext:a=this.config.watch,outfile:o,tsconfigPath:s}){let c=t??await this.discoverEntries(i,dirname(o),s),l=[...c.discoveredWorkflows].sort(),u=new Set(l),d=[...c.discoveredSerdeFiles].sort().filter(e=>!u.has(e)),f={},m=[...l.map(e=>createWorkflowImport(e,this.config.workingDir)),...d.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
2
+ `);return await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:(await buildSingleRolldownChunk(`intermediate workflow bundle for "${o}"`,{cwd:this.config.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,platform:`neutral`,plugins:[createWorkflowVirtualEntryPlugin(m),createWorkflowPseudoPackagePlugin(),createEvePackageImportsPlugin(this.config.workingDir,{workflowCondition:!0}),createWorkflowTransformPlugin({manifest:f,projectRoot:this.transformProjectRoot,sideEffectFiles:[...l,...d],workingDir:this.config.workingDir}),createWorkflowNodeBuiltinGuardPlugin()],resolve:{conditionNames:[`eve-source`,`workflow`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:s??!1,output:{banner:`globalThis.__private_workflows = new Map();`,comments:!1,format:`cjs`,sourcemap:`inline`}})).code,format:r,outfile:o,queueNamespace:this.#r,workingDir:this.config.workingDir}),a?{bundleFinal:async t=>{await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:t,format:r,outfile:o,queueNamespace:this.#r,workingDir:this.config.workingDir})},interimBundleCtx:void 0,manifest:f}:{manifest:f}}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:convertStepsManifest(e.steps),workflows:convertWorkflowsManifest(e.workflows),classes:convertClassesManifest(e.classes)},i=JSON.stringify(n,null,2);return await mkdir(t,{recursive:!0}),await writeFile(join(t,`manifest.json`),i),i}async buildVercelOutput(e){await this.build();let t=join(this.#n,`vercel-build-output`,`functions`,`.well-known`,`workflow`,`v1`),n=join(t,`flow.func`),i=join(e.outputDir,`functions`,`.well-known`,`workflow`,`v1`),a=join(e.flowNitroOutputDir,`functions`,`__server.func`),c=join(e.flowNitroOutputDir,`functions`,`.well-known`,`workflow`,`v1`,`flow.func`),u=join(i,`flow.func`),d=join(i,`step.func`),f=join(i,`webhook`,`[token].func`);await copyNitroFunctionDirectory({fallbackPath:a,sourcePath:c,targetPath:n}),await Promise.all([this.#s(n,{experimentalTriggers:[createEveWorkflowQueueTrigger(this.#e)],maxDuration:`max`,runtime:e.runtime??null,shouldAddHelpers:!1}),cp(join(this.#n,`manifest.json`),join(t,`manifest.json`))]),await retargetNitroFunctionDirectoryToWorkflowRoute({functionDirectoryPath:n,workflowRoutePath:`/.well-known/workflow/v1/flow`}),await Promise.all([rm(u,{force:!0,recursive:!0}),rm(d,{force:!0,recursive:!0}),rm(f,{force:!0,recursive:!0})]),await mkdir(i,{recursive:!0}),await Promise.all([cp(n,u,{recursive:!0}),cp(join(t,`manifest.json`),join(i,`manifest.json`))])}async#o(){return await this.getInputFiles()}async#s(e,t){let n=join(e,`.vc-config.json`),i=await this.#c(n),a={...i};a.environment=createWorkflowFunctionEnvironment(i.environment),t.runtime!==null&&(a.runtime=t.runtime),t.maxDuration!==void 0&&(a.maxDuration=t.maxDuration),t.shouldAddHelpers!==void 0&&(a.shouldAddHelpers=t.shouldAddHelpers),t.shouldAddSourcemapSupport!==void 0&&(a.shouldAddSourcemapSupport=t.shouldAddSourcemapSupport),t.experimentalTriggers!==void 0&&(a.experimentalTriggers=[...t.experimentalTriggers]),await writeFile(n,`${JSON.stringify(a,null,2)}\n`)}async#c(e){try{let t=JSON.parse(await readFile(e,`utf8`));if(typeof t==`object`&&t)return t}catch{}return{}}};async function addStepRegistrationsImport(e,t){let r=await readTextFileIfPresent(e);if(r===null||r.includes(`__eveWorkflowStepsRegistered`))return;let i=createRelativeImportSpecifier(dirname(e),t),a=[`import { __steps_registered as __eveWorkflowStepsRegistered } from ${JSON.stringify(i)};`,`void __eveWorkflowStepsRegistered;`,``].join(`
3
3
  `),o=r.match(/^import\s.+?;\n/m);if(o===null||o.index===void 0){await atomicWriteFile(e,`${a}${r}`);return}let s=o.index+o[0].length;await atomicWriteFile(e,`${r.slice(0,s)}${a}${r.slice(s)}`)}async function rewriteWorkflowRuntimeImports(e){let n=await readTextFileIfPresent(e);if(n===null)return;let r=n;for(let e of[`workflow`,`workflow/api`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`]){let n=normalizeImportSpecifierPath(resolveWorkflowModulePath(e));r=replaceStringLiteralSpecifier(r,e,n)}r!==n&&await atomicWriteFile(e,r)}async function rewriteWorkflowCodeLiteral(e,t){let n=await readTextFileIfPresent(e);if(n===null)return;let r=`;\n\nexport const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(t)} });`,i=n.indexOf(`const workflowCode = `),a=n.lastIndexOf(r);if(i===-1||a===-1||a<=i)return;let o=i+21,s=n.slice(o,a);if(!s.trimStart().startsWith("`"))return;let c=decodeWorkflowCodeTemplateLiteral(s,e),l=`${n.slice(0,o)}${encodeWorkflowCodeLiteral(c)}${n.slice(a)}`;l!==n&&await atomicWriteFile(e,l)}function encodeWorkflowCodeLiteral(e){let t=Buffer.from(e,`utf8`).toString(`base64`).match(/.{1,16384}/g)??[``];return`Buffer.from(${JSON.stringify(t)}.join(""), "base64").toString("utf8")`}function decodeWorkflowCodeTemplateLiteral(e,t){let n=e.trim();if(!n.startsWith("`")||!n.endsWith("`"))throw Error(`Expected generated workflow code literal in "${t}" to be a template.`);let r=n.slice(1,-1),i=``;for(let e=0;e<r.length;e+=1){let t=r[e];if(t!==`\\`){i+=t;continue}let n=r[e+1];if(n===`\\`||n==="`"||n===`$`){i+=n,e+=1;continue}i+=t}return i}function replaceStringLiteralSpecifier(e,t,n){return e.replaceAll(JSON.stringify(t),JSON.stringify(n)).replaceAll(`'${t}'`,JSON.stringify(n))}function normalizeImportSpecifierPath(e){return normalizeEsmImportSpecifier(e)}function createRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function readTextFileIfPresent(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function readBinaryFileIfPresent(e){try{return await readFile(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function mirrorFileBypassingUnlink(e,t){let n=await readFile(e),r=await readBinaryFileIfPresent(t);r!==null&&r.equals(n)||await atomicWriteFile(t,n)}export{WorkflowBundleBuilder};
@@ -1,3 +1,3 @@
1
- import{basename,dirname,extname,join,relative}from"node:path";import{cp,mkdir,readFile,readdir,realpath,rename,rm,symlink,writeFile}from"node:fs/promises";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{EVE_SHARED_SERVER_FUNCTION_PATH,isEveVercelFunctionPath,normalizeEveVercelRoutes}from"#internal/workflow-bundle/eve-service-route-output.js";const WORKFLOW_STEP_EXTERNAL_PACKAGES=[`@mongodb-js/zstd`,`just-bash`,`microsandbox`,`node-liblzma`],WORKFLOW_BUILDER_DEFERRED_PACKAGES=[`@chat-adapter/slack`,`chat`];function createWorkflowFunctionEnvironment(e){let t={};return isRecord(e)&&Object.assign(t,e),t.NODE_OPTIONS=`--experimental-require-module`,t}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function prepareVercelFunctionDirectory(e){await rm(e,{force:!0,recursive:!0}),await mkdir(e,{recursive:!0})}async function resolveNitroFunctionDirectory(e){try{return await realpath(e.sourcePath)}catch{return await realpath(e.fallbackPath)}}async function copyNitroFunctionDirectory(e){let t=await resolveNitroFunctionDirectory({fallbackPath:e.fallbackPath,sourcePath:e.sourcePath});await prepareVercelFunctionDirectory(e.targetPath),await cp(t,e.targetPath,{dereference:!0,recursive:!0})}async function normalizeEveVercelFunctionOutput(e,t={}){let n=join(e,`functions`),i=await prepareSharedEveServerFunction(n);i!==null&&await repointEveFunctionSymlinksInDirectory(n,i),await pruneNonEveFunctionEntries(n,n),await pruneNonEveVercelRoutes(e,t.servicePrefix)}async function prepareSharedEveServerFunction(e){let n=join(e,`__server.func`),i=join(e,EVE_SHARED_SERVER_FUNCTION_PATH),s;try{s=await realpath(n)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}let c=`${i}.eve-staging`;return await mkdir(dirname(i),{recursive:!0}),await rm(c,{force:!0,recursive:!0}),await cp(s,c,{dereference:!0,recursive:!0}),await rm(i,{force:!0,recursive:!0}),await rename(c,i),i}async function repointEveFunctionSymlinksInDirectory(e,t,n=e){let a;try{a=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(a.map(async a=>{let o=join(e,a.name),s=normalizeVercelOutputPath(relative(n,o));if(a.isSymbolicLink()){a.name.endsWith(`.func`)&&isEveVercelFunctionPath(s)&&await repointFunctionSymlink(o,t);return}a.isDirectory()&&!a.name.endsWith(`.func`)&&await repointEveFunctionSymlinksInDirectory(o,t,n)}))}async function repointFunctionSymlink(e,n){await rm(e,{force:!0,recursive:!0}),await symlink(normalizeVercelOutputPath(relative(dirname(e),n)),e,`dir`)}async function pruneNonEveFunctionEntries(e,t){let n;try{n=await readdir(t,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(n.map(async n=>{let a=join(t,n.name),o=normalizeVercelOutputPath(relative(e,a));if(n.name.endsWith(`.func`)){isEveVercelFunctionPath(o)||await rm(a,{force:!0,recursive:!0});return}n.isDirectory()&&await pruneNonEveFunctionEntries(e,a)}))}async function pruneNonEveVercelRoutes(e,t){let n=join(e,`config.json`),i;try{i=JSON.parse(await readFile(n,`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}!isRecord(i)||!Array.isArray(i.routes)||(i.routes=normalizeEveVercelRoutes(i.routes,t),await writeFile(n,`${JSON.stringify(i,null,2)}\n`))}function normalizeVercelOutputPath(e){return e.replaceAll(`\\`,`/`)}async function emitBundledWorkflowFunctionDirectory(e){await prepareVercelFunctionDirectory(e.targetPath);let n=await emitBundledWorkflowPluginModules({build:buildWithNitroRolldown,pluginPaths:e.pluginPaths??[],targetPath:e.targetPath}),i=join(dirname(e.bundlePath),`__eve_workflow_function_entry.js`),a=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:dirname(e.bundlePath),input:i,platform:`node`,plugins:[createVirtualModulePlugin({id:i,moduleType:`js`,source:createWorkflowFunctionEntrypointSource({bundlePath:e.bundlePath,pluginModulePaths:n})})],write:!1,output:{codeSplitting:!1,comments:!1,format:`cjs`,sourcemap:!1}}),`Vercel workflow function for "${e.bundlePath}"`);await Promise.all([writeFile(join(e.targetPath,`index.js`),a.code),writeFile(join(e.targetPath,`package.json`),`${JSON.stringify({type:`commonjs`},null,2)}\n`),writeFile(join(e.targetPath,`.vc-config.json`),`${JSON.stringify({environment:createWorkflowFunctionEnvironment(),handler:`index.js`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`)])}async function emitBundledWorkflowPluginModules(e){return await Promise.all(e.pluginPaths.map(async(t,n)=>{let i=getSingleRolldownChunk(await e.build({input:t,platform:`node`,write:!1,output:{codeSplitting:!1,comments:!1,format:`esm`,sourcemap:!1}}),`workflow plugin for "${t}"`),a=`__eve_workflow_plugin_${n}.mjs`;return await writeFile(join(e.targetPath,a),i.code),`./${a}`}))}function createVirtualModulePlugin(e){return{name:`eve-virtual-module`,resolveId(t){return t===e.id?e.id:void 0},load(t){return t===e.id?{code:e.source,moduleType:e.moduleType}:void 0}}}function toRelativeImportPath(e){let t=relative(e.fromDirectoryPath,e.toFilePath).replaceAll(`\\`,`/`);return t.startsWith(`.`)?t:`./${t}`}function normalizeImportSpecifierPath(e){return e.replaceAll(`\\`,`/`)}function createWorkflowFunctionEntrypointSource(t){let n=t.pluginModulePaths.map(e=>normalizeImportSpecifierPath(e)),r=n.length>0;return[`const { POST } = require(${JSON.stringify(`./${basename(t.bundlePath)}`)});`,...r?[`const workflowPluginModulePaths = ${JSON.stringify(n)};`,``,`let workflowPluginPromise;`,``,`async function loadWorkflowPlugins() {`,` if (workflowPluginPromise == null) {`,` workflowPluginPromise = (async () => {`,` for (const pluginPath of workflowPluginModulePaths) {`,` await import(pluginPath);`,` }`,` })();`,` }`,` return await workflowPluginPromise;`,`}`]:[],``,`const DEFAULT_WORKFLOW_REQUEST_ORIGIN = "https://workflow.invalid";`,``,`function getHeader(headers, name) {`,` if (headers === null || headers === undefined) {`,` return undefined;`,` }`,` if (typeof headers.get === "function") {`,` const value = headers.get(name);`,` return typeof value === "string" && value.length > 0 ? value : undefined;`,` }`,` if (typeof headers !== "object") {`,` return undefined;`,` }`,` const record = headers;`,` const lowerName = name.toLowerCase();`,` for (const [key, value] of Object.entries(record)) {`,` if (key.toLowerCase() !== lowerName || value === undefined) {`,` continue;`,` }`,` if (Array.isArray(value)) {`,` return value.find((item) => typeof item === "string" && item.length > 0);`,` }`,` return typeof value === "string" && value.length > 0 ? value : undefined;`,` }`,` return undefined;`,`}`,``,`function createHeaders(headers) {`,` const normalized = new Headers();`,` if (headers === null || headers === undefined) {`,` return normalized;`,` }`,` if (headers instanceof Headers) {`,` return headers;`,` }`,` if (typeof headers.forEach === "function" && typeof headers.entries === "function") {`,` for (const [key, value] of headers.entries()) {`,` normalized.append(key, value);`,` }`,` return normalized;`,` }`,` for (const [key, value] of Object.entries(headers)) {`,` if (value === undefined) {`,` continue;`,` }`,` if (Array.isArray(value)) {`,` for (const item of value) {`,` normalized.append(key, String(item));`,` }`,` continue;`,` }`,` normalized.set(key, String(value));`,` }`,` return normalized;`,`}`,``,`function toAbsoluteWorkflowUrl(request) {`,` const url = typeof request?.url === "string" ? request.url : "/";`,` if (/^https?:\\/\\//.test(url)) {`,` return url;`,` }`,` const host = getHeader(request?.headers, "x-forwarded-host") ?? getHeader(request?.headers, "host");`,` const protocolHeader = getHeader(request?.headers, "x-forwarded-proto");`,` const protocol = protocolHeader === "http" || protocolHeader === "https" ? protocolHeader : "https";`,` const origin = typeof host === "string" && host.length > 0 ? protocol + "://" + host : DEFAULT_WORKFLOW_REQUEST_ORIGIN;`,` return new URL(url, origin).toString();`,`}`,``,`function normalizeWorkflowRequest(request) {`,` if (request instanceof Request) {`,` if (/^https?:\\/\\//.test(request.url)) {`,` return request;`,` }`,` return new Request(toAbsoluteWorkflowUrl(request), request);`,` }`,` const method = typeof request?.method === "string" ? request.method : "GET";`,` const headers = createHeaders(request?.headers);`,` const init = {`,` headers,`,` method,`,` };`,` if (method !== "GET" && method !== "HEAD") {`,` const body = request?.body ?? (request !== null && typeof request === "object" && typeof request.pipe === "function" ? request : undefined);`,` if (body !== undefined) {`,` init.body = body;`,` init.duplex = "half";`,` }`,` }`,` return new Request(toAbsoluteWorkflowUrl(request), init);`,`}`,``,`module.exports = async function handleWorkflowFunctionRequest(requestContext) {`,` const request =`,` requestContext !== null && typeof requestContext === "object" && "req" in requestContext`,` ? requestContext.req`,` : requestContext;`,...r?[` await loadWorkflowPlugins();`]:[],` return await POST(normalizeWorkflowRequest(request));`,`};`,``].join(`
1
+ import{basename,dirname,extname,join,relative}from"node:path";import{cp,mkdir,readFile,readdir,realpath,rename,rm,symlink,writeFile}from"node:fs/promises";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{EVE_SHARED_SERVER_FUNCTION_PATH,isEveVercelFunctionPath,normalizeEveVercelRoutes}from"#internal/workflow-bundle/eve-service-route-output.js";const WORKFLOW_STEP_EXTERNAL_PACKAGES=[`@mongodb-js/zstd`,`just-bash`,`microsandbox`,`node-liblzma`],WORKFLOW_BUILDER_DEFERRED_PACKAGES=[`@chat-adapter/slack`,`chat`];function createWorkflowFunctionEnvironment(e){let t={};return isRecord(e)&&Object.assign(t,e),t.NODE_OPTIONS=`--experimental-require-module`,t}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function prepareVercelFunctionDirectory(e){await rm(e,{force:!0,recursive:!0}),await mkdir(e,{recursive:!0})}async function resolveNitroFunctionDirectory(e){try{return await realpath(e.sourcePath)}catch{return await realpath(e.fallbackPath)}}async function copyNitroFunctionDirectory(e){let t=await resolveNitroFunctionDirectory({fallbackPath:e.fallbackPath,sourcePath:e.sourcePath});await prepareVercelFunctionDirectory(e.targetPath),await cp(t,e.targetPath,{dereference:!0,recursive:!0})}async function normalizeEveVercelFunctionOutput(e,t={}){let n=join(e,`functions`),i=await prepareSharedEveServerFunction(n);i!==null&&await repointEveFunctionSymlinksInDirectory(n,i),await pruneNonEveFunctionEntries(n,n),await pruneNonEveVercelRoutes(e,t.servicePrefix)}async function prepareSharedEveServerFunction(e){let n=join(e,`__server.func`),i=join(e,EVE_SHARED_SERVER_FUNCTION_PATH),s;try{s=await realpath(n)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}let c=`${i}.eve-staging`;return await mkdir(dirname(i),{recursive:!0}),await rm(c,{force:!0,recursive:!0}),await cp(s,c,{dereference:!0,recursive:!0}),await rm(i,{force:!0,recursive:!0}),await rename(c,i),i}async function repointEveFunctionSymlinksInDirectory(e,t,n=e){let a;try{a=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(a.map(async a=>{let o=join(e,a.name),s=normalizeVercelOutputPath(relative(n,o));if(a.isSymbolicLink()){a.name.endsWith(`.func`)&&isEveVercelFunctionPath(s)&&await repointFunctionSymlink(o,t);return}a.isDirectory()&&!a.name.endsWith(`.func`)&&await repointEveFunctionSymlinksInDirectory(o,t,n)}))}async function repointFunctionSymlink(e,n){await rm(e,{force:!0,recursive:!0}),await symlink(normalizeVercelOutputPath(relative(dirname(e),n)),e,`dir`)}async function pruneNonEveFunctionEntries(e,t){let n;try{n=await readdir(t,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(n.map(async n=>{let a=join(t,n.name),o=normalizeVercelOutputPath(relative(e,a));if(n.name.endsWith(`.func`)){isEveVercelFunctionPath(o)||await rm(a,{force:!0,recursive:!0});return}n.isDirectory()&&await pruneNonEveFunctionEntries(e,a)}))}async function pruneNonEveVercelRoutes(e,t){let n=join(e,`config.json`),i;try{i=JSON.parse(await readFile(n,`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}!isRecord(i)||!Array.isArray(i.routes)||(i.routes=normalizeEveVercelRoutes(i.routes,t),await writeFile(n,`${JSON.stringify(i,null,2)}\n`))}function normalizeVercelOutputPath(e){return e.replaceAll(`\\`,`/`)}async function emitBundledWorkflowFunctionDirectory(e){await prepareVercelFunctionDirectory(e.targetPath);let n=await emitBundledWorkflowPluginModules({pluginPaths:e.pluginPaths??[],targetPath:e.targetPath}),i=join(dirname(e.bundlePath),`__eve_workflow_function_entry.js`),a=await buildSingleRolldownChunk(`Vercel workflow function for "${e.bundlePath}"`,{cwd:dirname(e.bundlePath),input:i,platform:`node`,plugins:[createVirtualModulePlugin({id:i,moduleType:`js`,source:createWorkflowFunctionEntrypointSource({bundlePath:e.bundlePath,pluginModulePaths:n})})],output:{comments:!1,format:`cjs`,sourcemap:!1}});await Promise.all([writeFile(join(e.targetPath,`index.js`),a.code),writeFile(join(e.targetPath,`package.json`),`${JSON.stringify({type:`commonjs`},null,2)}\n`),writeFile(join(e.targetPath,`.vc-config.json`),`${JSON.stringify({environment:createWorkflowFunctionEnvironment(),handler:`index.js`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`)])}async function emitBundledWorkflowPluginModules(e){return await Promise.all(e.pluginPaths.map(async(t,n)=>{let i=await buildSingleRolldownChunk(`workflow plugin for "${t}"`,{input:t,platform:`node`,output:{comments:!1,format:`esm`,sourcemap:!1}}),a=`__eve_workflow_plugin_${n}.mjs`;return await writeFile(join(e.targetPath,a),i.code),`./${a}`}))}function createVirtualModulePlugin(e){return{name:`eve-virtual-module`,resolveId(t){return t===e.id?e.id:void 0},load(t){return t===e.id?{code:e.source,moduleType:e.moduleType}:void 0}}}function toRelativeImportPath(e){let t=relative(e.fromDirectoryPath,e.toFilePath).replaceAll(`\\`,`/`);return t.startsWith(`.`)?t:`./${t}`}function normalizeImportSpecifierPath(e){return e.replaceAll(`\\`,`/`)}function createWorkflowFunctionEntrypointSource(t){let n=t.pluginModulePaths.map(e=>normalizeImportSpecifierPath(e)),r=n.length>0;return[`const { POST } = require(${JSON.stringify(`./${basename(t.bundlePath)}`)});`,...r?[`const workflowPluginModulePaths = ${JSON.stringify(n)};`,``,`let workflowPluginPromise;`,``,`async function loadWorkflowPlugins() {`,` if (workflowPluginPromise == null) {`,` workflowPluginPromise = (async () => {`,` for (const pluginPath of workflowPluginModulePaths) {`,` await import(pluginPath);`,` }`,` })();`,` }`,` return await workflowPluginPromise;`,`}`]:[],``,`const DEFAULT_WORKFLOW_REQUEST_ORIGIN = "https://workflow.invalid";`,``,`function getHeader(headers, name) {`,` if (headers === null || headers === undefined) {`,` return undefined;`,` }`,` if (typeof headers.get === "function") {`,` const value = headers.get(name);`,` return typeof value === "string" && value.length > 0 ? value : undefined;`,` }`,` if (typeof headers !== "object") {`,` return undefined;`,` }`,` const record = headers;`,` const lowerName = name.toLowerCase();`,` for (const [key, value] of Object.entries(record)) {`,` if (key.toLowerCase() !== lowerName || value === undefined) {`,` continue;`,` }`,` if (Array.isArray(value)) {`,` return value.find((item) => typeof item === "string" && item.length > 0);`,` }`,` return typeof value === "string" && value.length > 0 ? value : undefined;`,` }`,` return undefined;`,`}`,``,`function createHeaders(headers) {`,` const normalized = new Headers();`,` if (headers === null || headers === undefined) {`,` return normalized;`,` }`,` if (headers instanceof Headers) {`,` return headers;`,` }`,` if (typeof headers.forEach === "function" && typeof headers.entries === "function") {`,` for (const [key, value] of headers.entries()) {`,` normalized.append(key, value);`,` }`,` return normalized;`,` }`,` for (const [key, value] of Object.entries(headers)) {`,` if (value === undefined) {`,` continue;`,` }`,` if (Array.isArray(value)) {`,` for (const item of value) {`,` normalized.append(key, String(item));`,` }`,` continue;`,` }`,` normalized.set(key, String(value));`,` }`,` return normalized;`,`}`,``,`function toAbsoluteWorkflowUrl(request) {`,` const url = typeof request?.url === "string" ? request.url : "/";`,` if (/^https?:\\/\\//.test(url)) {`,` return url;`,` }`,` const host = getHeader(request?.headers, "x-forwarded-host") ?? getHeader(request?.headers, "host");`,` const protocolHeader = getHeader(request?.headers, "x-forwarded-proto");`,` const protocol = protocolHeader === "http" || protocolHeader === "https" ? protocolHeader : "https";`,` const origin = typeof host === "string" && host.length > 0 ? protocol + "://" + host : DEFAULT_WORKFLOW_REQUEST_ORIGIN;`,` return new URL(url, origin).toString();`,`}`,``,`function normalizeWorkflowRequest(request) {`,` if (request instanceof Request) {`,` if (/^https?:\\/\\//.test(request.url)) {`,` return request;`,` }`,` return new Request(toAbsoluteWorkflowUrl(request), request);`,` }`,` const method = typeof request?.method === "string" ? request.method : "GET";`,` const headers = createHeaders(request?.headers);`,` const init = {`,` headers,`,` method,`,` };`,` if (method !== "GET" && method !== "HEAD") {`,` const body = request?.body ?? (request !== null && typeof request === "object" && typeof request.pipe === "function" ? request : undefined);`,` if (body !== undefined) {`,` init.body = body;`,` init.duplex = "half";`,` }`,` }`,` return new Request(toAbsoluteWorkflowUrl(request), init);`,`}`,``,`module.exports = async function handleWorkflowFunctionRequest(requestContext) {`,` const request =`,` requestContext !== null && typeof requestContext === "object" && "req" in requestContext`,` ? requestContext.req`,` : requestContext;`,...r?[` await loadWorkflowPlugins();`]:[],` return await POST(normalizeWorkflowRequest(request));`,`};`,``].join(`
2
2
  `)}function createRoutedNitroEntrypoint(e){return[`import nitroHandler from ${JSON.stringify(e.delegateImportPath)};`,``,`function invokeNitroHandler(request, context) {`,` if (typeof nitroHandler === "function") {`,` return nitroHandler(request, context);`,` }`,``,` if (nitroHandler !== null && typeof nitroHandler === "object" && "fetch" in nitroHandler) {`,` const fetch = nitroHandler.fetch;`,` if (typeof fetch === "function") {`,` return fetch.call(nitroHandler, request, context);`,` }`,` }`,``,` throw new TypeError("Expected Nitro handler to export a function or an object with fetch(request, context).");`,`}`,``,`const workflowRoutePath = ${JSON.stringify(e.workflowRoutePath)};`,``,`function rewriteRequestToWorkflowRoute(request) {`,` const sourceUrl = new URL(request.url);`,` const routedUrl = new URL(workflowRoutePath, sourceUrl);`,` routedUrl.search = sourceUrl.search;`,` return new Request(routedUrl, request);`,`}`,``,`export default {`,` fetch(request, context) {`,` return invokeNitroHandler(rewriteRequestToWorkflowRoute(request), context);`,` },`,`};`,``].join(`
3
3
  `)}async function readVercelHandlerPath(e){try{let t=JSON.parse(await readFile(join(e,`.vc-config.json`),`utf8`));if(typeof t.handler==`string`&&t.handler.length>0)return t.handler}catch{}return`index.mjs`}async function retargetNitroFunctionDirectoryToWorkflowRoute(e){let i=await readVercelHandlerPath(e.functionDirectoryPath),a=join(e.functionDirectoryPath,i),o=dirname(a),s=extname(i),c=join(o,`__eve_nitro_handler__${s.length>0?s:`.mjs`}`),l=toRelativeImportPath({fromDirectoryPath:o,toFilePath:c});await rename(a,c),await writeFile(a,createRoutedNitroEntrypoint({delegateImportPath:l,workflowRoutePath:e.workflowRoutePath}))}export{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES,copyNitroFunctionDirectory,createWorkflowFunctionEnvironment,emitBundledWorkflowFunctionDirectory,normalizeEveVercelFunctionOutput,prepareVercelFunctionDirectory,retargetNitroFunctionDirectoryToWorkflowRoute};
@@ -8,7 +8,7 @@ export declare const EVE_STREAM_FORMAT_HEADER = "x-eve-stream-format";
8
8
  export declare const EVE_STREAM_VERSION_HEADER = "x-eve-stream-version";
9
9
  export declare const EVE_MESSAGE_STREAM_CONTENT_TYPE = "application/x-ndjson; charset=utf-8";
10
10
  export declare const EVE_MESSAGE_STREAM_FORMAT = "ndjson";
11
- export declare const EVE_MESSAGE_STREAM_VERSION = "18";
11
+ export declare const EVE_MESSAGE_STREAM_VERSION = "19";
12
12
  /**
13
13
  * eve-owned finish reason for one completed assistant step.
14
14
  *
@@ -397,6 +397,19 @@ export interface TurnFailedStreamEvent {
397
397
  };
398
398
  type: "turn.failed";
399
399
  }
400
+ /**
401
+ * Stream event emitted when one turn is cancelled before reaching a
402
+ * terminal outcome. Cancellation is not failure: the turn ends without
403
+ * `turn.failed`/`session.failed`, is followed by `session.waiting`, and
404
+ * the session accepts the next message normally.
405
+ */
406
+ export interface TurnCancelledStreamEvent {
407
+ data: {
408
+ sequence: number;
409
+ turnId: string;
410
+ };
411
+ type: "turn.cancelled";
412
+ }
400
413
  /**
401
414
  * Stream event emitted when the workflow decides to compact the current
402
415
  * visible session history before the next model fragment runs.
@@ -480,6 +493,8 @@ export interface AuthorizationCompletedStreamEvent {
480
493
  */
481
494
  export interface SessionWaitingStreamEvent {
482
495
  data: {
496
+ /** Channel-owned resume handle for the next user turn. */
497
+ continuationToken: string;
483
498
  wait: "next-user-message";
484
499
  };
485
500
  type: "session.waiting";
@@ -505,7 +520,7 @@ export interface SessionCompletedStreamEvent {
505
520
  /**
506
521
  * Serializable stream event union for the durable message session flow.
507
522
  */
508
- export type HandleMessageStreamEvent = (CompactionCompletedStreamEvent | CompactionRequestedStreamEvent | AuthorizationCompletedStreamEvent | AuthorizationRequiredStreamEvent | MessageAppendedStreamEvent | MessageCompletedStreamEvent | MessageReceivedStreamEvent | ReasoningAppendedStreamEvent | SessionCompletedStreamEvent | SessionFailedStreamEvent | SessionStartedStreamEvent | SessionWaitingStreamEvent | ResultCompletedStreamEvent | SubagentCalledStreamEvent | SubagentChildEventStreamEvent | SubagentCompletedStreamEvent | SubagentStartedStreamEvent | ActionsRequestedStreamEvent | InputRequestedStreamEvent | ActionResultStreamEvent | ReasoningCompletedStreamEvent | StepCompletedStreamEvent | StepFailedStreamEvent | StepStartedStreamEvent | TurnCompletedStreamEvent | TurnFailedStreamEvent | TurnStartedStreamEvent) & {
523
+ export type HandleMessageStreamEvent = (CompactionCompletedStreamEvent | CompactionRequestedStreamEvent | AuthorizationCompletedStreamEvent | AuthorizationRequiredStreamEvent | MessageAppendedStreamEvent | MessageCompletedStreamEvent | MessageReceivedStreamEvent | ReasoningAppendedStreamEvent | SessionCompletedStreamEvent | SessionFailedStreamEvent | SessionStartedStreamEvent | SessionWaitingStreamEvent | ResultCompletedStreamEvent | SubagentCalledStreamEvent | SubagentChildEventStreamEvent | SubagentCompletedStreamEvent | SubagentStartedStreamEvent | ActionsRequestedStreamEvent | InputRequestedStreamEvent | ActionResultStreamEvent | ReasoningCompletedStreamEvent | StepCompletedStreamEvent | StepFailedStreamEvent | StepStartedStreamEvent | TurnCancelledStreamEvent | TurnCompletedStreamEvent | TurnFailedStreamEvent | TurnStartedStreamEvent) & {
509
524
  readonly meta?: HandleMessageStreamEventMeta;
510
525
  };
511
526
  /**
@@ -739,6 +754,11 @@ export declare function createTurnFailedEvent(input: {
739
754
  readonly sequence: number;
740
755
  readonly turnId: string;
741
756
  }): TurnFailedStreamEvent;
757
+ /** Creates the `turn.cancelled` event for one cancelled turn. */
758
+ export declare function createTurnCancelledEvent(input: {
759
+ readonly sequence: number;
760
+ readonly turnId: string;
761
+ }): TurnCancelledStreamEvent;
742
762
  /**
743
763
  * Creates the `compaction.requested` event for one runtime compaction pass.
744
764
  */
@@ -762,7 +782,7 @@ export declare function createCompactionCompletedEvent(input: {
762
782
  * Creates the `session.waiting` event for the only supported between-turn
763
783
  * wait.
764
784
  */
765
- export declare function createSessionWaitingEvent(): SessionWaitingStreamEvent;
785
+ export declare function createSessionWaitingEvent(namespacedContinuationToken: string): SessionWaitingStreamEvent;
766
786
  /**
767
787
  * Creates the `session.failed` event for one terminal session failure.
768
788
  */