eve 0.24.1 → 0.24.3

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 (147) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/src/cli/dev/environment.d.ts +6 -0
  3. package/dist/src/cli/dev/environment.js +1 -1
  4. package/dist/src/cli/run.js +2 -2
  5. package/dist/src/cli/vercel-service-output.d.ts +4 -0
  6. package/dist/src/cli/vercel-service-output.js +1 -0
  7. package/dist/src/compiled/.vendor-stamp.json +2 -1
  8. package/dist/src/compiled/@chat-adapter/slack/index.js +12 -12
  9. package/dist/src/compiled/@chat-adapter/twilio/index.js +1 -1
  10. package/dist/src/compiled/@vercel/sandbox/index.js +19 -19
  11. package/dist/src/compiled/@workflow/world-local/index.d.ts +14 -0
  12. package/dist/src/compiled/_chunks/node/{auth-CWHn3Yve.js → auth-BuQkq4Gr.js} +2 -2
  13. package/dist/src/compiled/_chunks/node/{dist-BdTs18CF.js → chunk-BTyA9uPd.js} +1 -1
  14. package/dist/src/compiled/_chunks/node/{dist-W8yle6rh.js → dist-CdH_Yoxt.js} +5 -5
  15. package/dist/src/compiled/_chunks/node/{dist-RHRJZ03Q.js → dist-Drt-_JVK.js} +1 -1
  16. package/dist/src/compiled/_chunks/node/dist-DsNhwdzf.js +1 -0
  17. package/dist/src/compiled/_chunks/node/retry-DngYleaI.js +1 -0
  18. package/dist/src/compiled/_chunks/node/token-DabMnh8F.js +1 -0
  19. package/dist/src/compiled/_chunks/node/token-util-BoSJPKrG.js +1 -0
  20. package/dist/src/compiled/_chunks/node/token-util-DVigMYWS.js +1 -0
  21. package/dist/src/compiled/_chunks/node/virtual-loader-B8K8w9cr.js +1 -0
  22. package/dist/src/compiled/chat/index.js +1 -1
  23. package/dist/src/compiled/env-runner/LICENSE +21 -0
  24. package/dist/src/compiled/env-runner/index.d.ts +38 -0
  25. package/dist/src/compiled/env-runner/index.js +1 -0
  26. package/dist/src/compiled/env-runner/node-worker.d.ts +1 -0
  27. package/dist/src/compiled/env-runner/node-worker.js +12 -0
  28. package/dist/src/compiler/compile-agent.d.ts +4 -6
  29. package/dist/src/compiler/compile-agent.js +1 -1
  30. package/dist/src/execution/create-session-step.d.ts +2 -2
  31. package/dist/src/execution/create-session-step.js +1 -1
  32. package/dist/src/execution/workflow-runtime.js +1 -1
  33. package/dist/src/harness/compaction-prompt.d.ts +16 -0
  34. package/dist/src/harness/compaction-prompt.js +24 -0
  35. package/dist/src/harness/compaction.d.ts +2 -1
  36. package/dist/src/harness/compaction.js +1 -4
  37. package/dist/src/harness/input-requests.d.ts +1 -0
  38. package/dist/src/harness/input-requests.js +1 -1
  39. package/dist/src/harness/tool-loop.js +1 -1
  40. package/dist/src/internal/application/build-workspace.d.ts +1 -1
  41. package/dist/src/internal/application/build-workspace.js +1 -1
  42. package/dist/src/internal/application/compiled-artifacts.d.ts +13 -0
  43. package/dist/src/internal/application/compiled-artifacts.js +3 -2
  44. package/dist/src/internal/application/dev-environment.d.ts +4 -0
  45. package/dist/src/internal/application/dev-environment.js +1 -0
  46. package/dist/src/internal/application/optional-package-install.d.ts +2 -10
  47. package/dist/src/internal/application/optional-package-install.js +1 -1
  48. package/dist/src/internal/application/output-publication-lock.js +1 -1
  49. package/dist/src/internal/application/package.js +1 -1
  50. package/dist/src/internal/application/paths.d.ts +2 -0
  51. package/dist/src/internal/application/paths.js +1 -1
  52. package/dist/src/internal/application/tsconfig-dependencies.js +1 -1
  53. package/dist/src/internal/authored-module-loader.d.ts +3 -9
  54. package/dist/src/internal/authored-module-loader.js +2 -2
  55. package/dist/src/internal/authored-package-boundary.d.ts +0 -2
  56. package/dist/src/internal/authored-package-boundary.js +1 -1
  57. package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
  58. package/dist/src/internal/compiled-manifest-fingerprint.d.ts +5 -0
  59. package/dist/src/internal/compiled-manifest-fingerprint.js +1 -0
  60. package/dist/src/internal/materialized-authored-modules.d.ts +0 -3
  61. package/dist/src/internal/materialized-authored-modules.js +1 -1
  62. package/dist/src/internal/nitro/dev-client-address.d.ts +22 -0
  63. package/dist/src/internal/nitro/dev-client-address.js +1 -0
  64. package/dist/src/internal/nitro/dev-runtime-artifacts-retention.d.ts +12 -0
  65. package/dist/src/internal/nitro/dev-runtime-artifacts-retention.js +1 -0
  66. package/dist/src/internal/nitro/dev-runtime-artifacts.d.ts +19 -1
  67. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  68. package/dist/src/internal/nitro/development-generation.d.ts +5 -1
  69. package/dist/src/internal/nitro/development-generation.js +1 -1
  70. package/dist/src/internal/nitro/host/artifacts-config.d.ts +2 -0
  71. package/dist/src/internal/nitro/host/artifacts-config.js +1 -1
  72. package/dist/src/internal/nitro/host/build-application.js +1 -1
  73. package/dist/src/internal/nitro/host/channel-routes.d.ts +1 -13
  74. package/dist/src/internal/nitro/host/channel-routes.js +3 -3
  75. package/dist/src/internal/nitro/host/configure-nitro-routes.d.ts +1 -2
  76. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  77. package/dist/src/internal/nitro/host/copy-host-middleware.d.ts +12 -0
  78. package/dist/src/internal/nitro/host/copy-host-middleware.js +1 -0
  79. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +3 -5
  80. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  81. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.d.ts +32 -0
  82. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -0
  83. package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +4 -15
  84. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  85. package/dist/src/internal/nitro/host/dev-host-candidate.d.ts +16 -0
  86. package/dist/src/internal/nitro/host/dev-host-candidate.js +1 -0
  87. package/dist/src/internal/nitro/host/dev-host-fingerprint.d.ts +2 -0
  88. package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -0
  89. package/dist/src/internal/nitro/host/dev-host-workspace.d.ts +10 -0
  90. package/dist/src/internal/nitro/host/dev-host-workspace.js +1 -0
  91. package/dist/src/internal/nitro/host/dev-runner.d.ts +21 -0
  92. package/dist/src/internal/nitro/host/dev-runner.js +1 -0
  93. package/dist/src/internal/nitro/host/dev-server-http.d.ts +5 -0
  94. package/dist/src/internal/nitro/host/dev-server-http.js +1 -0
  95. package/dist/src/internal/nitro/host/dev-server-url.d.ts +6 -0
  96. package/dist/src/internal/nitro/host/dev-server-url.js +1 -0
  97. package/dist/src/internal/nitro/host/dev-workflow-world-setup.d.ts +9 -0
  98. package/dist/src/internal/nitro/host/dev-workflow-world-setup.js +1 -0
  99. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.js +1 -1
  100. package/dist/src/internal/nitro/host/drained-nitro-dev-server.d.ts +53 -0
  101. package/dist/src/internal/nitro/host/drained-nitro-dev-server.js +1 -0
  102. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +4 -5
  103. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  104. package/dist/src/internal/nitro/host/start-development-server.d.ts +2 -5
  105. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  106. package/dist/src/internal/nitro/host/types.d.ts +10 -0
  107. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  108. package/dist/src/internal/nitro/routes/runtime-artifacts.d.ts +7 -0
  109. package/dist/src/internal/nitro/routes/runtime-artifacts.js +1 -1
  110. package/dist/src/internal/nitro/routes/schedule-task.d.ts +9 -0
  111. package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
  112. package/dist/src/internal/workflow/development-generation-context.d.ts +8 -0
  113. package/dist/src/internal/workflow/development-generation-context.js +1 -0
  114. package/dist/src/internal/workflow/development-world-client.d.ts +29 -0
  115. package/dist/src/internal/workflow/development-world-client.js +1 -0
  116. package/dist/src/internal/workflow/development-world-codec.d.ts +11 -0
  117. package/dist/src/internal/workflow/development-world-codec.js +1 -0
  118. package/dist/src/internal/workflow/development-world-protocol.d.ts +31 -0
  119. package/dist/src/internal/workflow/development-world-protocol.js +1 -0
  120. package/dist/src/internal/workflow/development-world-server.d.ts +27 -0
  121. package/dist/src/internal/workflow/development-world-server.js +1 -0
  122. package/dist/src/public/next/vercel-output-config.js +1 -1
  123. package/dist/src/runtime/compiled-artifacts-source.d.ts +9 -0
  124. package/dist/src/runtime/compiled-artifacts-source.js +1 -1
  125. package/dist/src/runtime/durable-compiled-artifacts-source.d.ts +8 -0
  126. package/dist/src/runtime/durable-compiled-artifacts-source.js +1 -0
  127. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
  128. package/dist/src/setup/scaffold/create/project.js +1 -1
  129. package/dist/src/shared/atomic-write-file.d.ts +1 -1
  130. package/dist/src/shared/atomic-write-file.js +1 -1
  131. package/dist/src/shared/rename-with-retry.d.ts +5 -0
  132. package/dist/src/shared/rename-with-retry.js +1 -0
  133. package/docs/agent-config.md +3 -1
  134. package/docs/concepts/default-harness.md +1 -1
  135. package/docs/concepts/execution-model-and-durability.md +1 -1
  136. package/docs/reference/cli.md +1 -1
  137. package/package.json +2 -1
  138. package/dist/src/compiled/_chunks/node/retry-DkR2H1Y0.js +0 -1
  139. package/dist/src/compiled/_chunks/node/token-ORseRyWn.js +0 -1
  140. package/dist/src/internal/bundler/nitro-node-file-trace.d.ts +0 -10
  141. package/dist/src/internal/bundler/nitro-node-file-trace.js +0 -1
  142. package/dist/src/internal/materialize-authored-external-dependencies.d.ts +0 -10
  143. package/dist/src/internal/materialize-authored-external-dependencies.js +0 -2
  144. package/dist/src/internal/nitro/host/dev-live-virtual-modules.d.ts +0 -15
  145. package/dist/src/internal/nitro/host/dev-live-virtual-modules.js +0 -1
  146. package/dist/src/internal/nitro/host/server-external-packages.d.ts +0 -5
  147. package/dist/src/internal/nitro/host/server-external-packages.js +0 -1
@@ -0,0 +1,21 @@
1
+ export interface DevelopmentRunner {
2
+ readonly closed: boolean;
3
+ close(cause?: unknown): Promise<void>;
4
+ fetch(request: Request, init?: RequestInit): Promise<Response>;
5
+ onceClosed(listener: (cause?: unknown) => void): void;
6
+ upgrade(input: {
7
+ readonly node: {
8
+ readonly head: Buffer;
9
+ readonly req: import("node:http").IncomingMessage;
10
+ readonly socket: import("node:net").Socket;
11
+ };
12
+ }): Promise<void>;
13
+ waitForReady(timeout: number): Promise<void>;
14
+ }
15
+ export interface DevelopmentRunnerInput {
16
+ readonly entry: string;
17
+ readonly name: string;
18
+ readonly workerData: Readonly<Record<string, unknown>>;
19
+ }
20
+ export type DevelopmentRunnerFactory = (input: DevelopmentRunnerInput) => DevelopmentRunner;
21
+ export declare const createNodeDevelopmentRunner: DevelopmentRunnerFactory;
@@ -0,0 +1 @@
1
+ import{resolvePackageCompiledFilePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{Worker}from"node:worker_threads";import{BaseEnvRunner}from"#compiled/env-runner/index.js";var NodeDevelopmentRunner=class extends BaseEnvRunner{#e;#t=new Set;#n;constructor(t){let n=resolvePackageCompiledFilePath(`src/compiled/env-runner/node-worker.js`);super({data:{entry:t.entry,...t.workerData},hooks:{onClose:(e,t)=>{let n=[...this.#t];this.#t.clear();for(let e of n)e(t)}},name:t.name,workerEntry:n}),this._initWithVirtualData(()=>this.#r())}onceClosed(e){if(this.closed){e(this.#e);return}this.#t.add(e)}sendMessage(e){if(this.#n===void 0)throw Error(`Development worker is not initialized.`);this.#n.postMessage(e)}async waitForReady(e){try{await super.waitForReady(e)}catch(e){throw this.#e===void 0?e:Error(`Development worker failed before readiness: ${this.#e instanceof Error?this.#e.message:String(this.#e)}`,{cause:this.#e})}}_hasRuntime(){return this.#n!==void 0}_runtimeType(){return`worker`}async _closeRuntime(){let e=this.#n;e!==void 0&&(this.#n=void 0,e.removeAllListeners(),await e.terminate())}_handleMessage(e){isWorkerInitializationError(e)&&(this.#e=Error(e.error)),super._handleMessage(e)}#r(){if(!existsSync(this._workerEntry)){this.close(`Development worker entry not found at "${this._workerEntry}".`);return}let e=new Worker(this._workerEntry,{env:process.env,workerData:{name:this._name,...this._data}});this.#n=e,e.once(`error`,e=>{this.#e=e,this.close(e)}),e.once(`exit`,e=>{let t=Error(`Development worker exited with code ${String(e)}.`);this.#e??=t,this.close(t)}),e.on(`message`,e=>this._handleMessage(e))}};const createNodeDevelopmentRunner=e=>new NodeDevelopmentRunner(e);function isWorkerInitializationError(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.event===`init-error`&&typeof t.error==`string`}export{createNodeDevelopmentRunner};
@@ -0,0 +1,5 @@
1
+ import type { IncomingMessage, Server, ServerResponse } from "node:http";
2
+ export declare function createPublicRequest(request: IncomingMessage, signal: AbortSignal): Request;
3
+ export declare function writeResponse(response: ServerResponse, webResponse: Response, signal: AbortSignal): Promise<void>;
4
+ export declare function writeRequestError(response: ServerResponse, error: unknown): void;
5
+ export declare function closeServer(server: Server): Promise<void>;
@@ -0,0 +1 @@
1
+ import{toErrorMessage}from"#shared/errors.js";import{Readable}from"node:stream";function createPublicRequest(e,n){let r=e.headers.host??`localhost`,i=new URL(e.url??`/`,`http://${r}`),a=new Headers;for(let[t,n]of Object.entries(e.headers))if(Array.isArray(n))for(let e of n)a.append(t,e);else n!==void 0&&a.set(t,n);let o=e.method!==`GET`&&e.method!==`HEAD`;return new Request(i,{body:o?Readable.toWeb(e):void 0,duplex:o?`half`:void 0,headers:a,method:e.method,signal:n})}async function writeResponse(e,n,r){if(e.destroyed){await n.body?.cancel();return}e.statusCode=n.status,e.statusMessage=n.statusText;let i=n.headers.getSetCookie?.call(n.headers)??[];if(n.headers.forEach((t,n)=>{n.toLowerCase()!==`set-cookie`&&e.setHeader(n,t)}),i.length>0&&e.setHeader(`set-cookie`,[...i]),n.body===null){await endResponse(e);return}let a=Readable.fromWeb(n.body),cancelBody=()=>a.destroy(r.reason);r.addEventListener(`abort`,cancelBody,{once:!0});try{await new Promise((t,n)=>{a.once(`error`,n),e.once(`error`,n),e.once(`close`,()=>{e.writableEnded||n(Error(`Development client disconnected.`))}),e.once(`finish`,t),a.pipe(e)})}finally{r.removeEventListener(`abort`,cancelBody),!a.destroyed&&(r.aborted||e.destroyed)&&a.destroy()}}function writeRequestError(t,n){if(t.headersSent){t.destroy();return}t.statusCode=503,t.setHeader(`content-type`,`application/json; charset=utf-8`),!t.writableEnded&&!t.destroyed&&t.end(JSON.stringify({error:toErrorMessage(n)}))}function closeServer(e){if(!e.listening)return Promise.resolve();let t=new Promise((t,n)=>{e.close(e=>{e===void 0?t():n(e)})});return e.closeIdleConnections?.(),t}async function endResponse(e){await new Promise((t,n)=>{e.once(`error`,n),e.end(t)})}export{closeServer,createPublicRequest,writeRequestError,writeResponse};
@@ -0,0 +1,6 @@
1
+ export declare const DEFAULT_DEVELOPMENT_SERVER_HOST = "127.0.0.1";
2
+ /**
3
+ * Rewrites a server URL whose hostname is a wildcard listen address into a
4
+ * loopback URL on the same address family.
5
+ */
6
+ export declare function normalizeDevelopmentServerClientUrl(serverUrl: string): string;
@@ -0,0 +1 @@
1
+ const 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}export{DEFAULT_DEVELOPMENT_SERVER_HOST,normalizeDevelopmentServerClientUrl};
@@ -0,0 +1,9 @@
1
+ import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
2
+ import { type ParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-server.js";
3
+ export declare function createDevelopmentWorkflowWorld(input: {
4
+ readonly appRoot: string;
5
+ readonly preparedHost: PreparedDevelopmentApplicationHost;
6
+ readonly transportSecret: string;
7
+ }): ParentDevelopmentWorkflowWorld | undefined;
8
+ export declare function installWorkflowTransportEnvironment(appRoot: string, secret: string): () => void;
9
+ export declare function installWorkflowLocalQueueEnvironment(serverUrl: string): () => void;
@@ -0,0 +1 @@
1
+ import{basename}from"node:path";import{DEVELOPMENT_WORKER_APP_ROOT_ENV,DEVELOPMENT_WORKFLOW_SECRET_ENV,usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{readActiveDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";import{normalizeDevelopmentServerClientUrl}from"#internal/nitro/host/dev-server-url.js";import{createParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-server.js";const WORKFLOW_LOCAL_BASE_URL_ENV=`WORKFLOW_LOCAL_BASE_URL`,PORT_ENV=`PORT`;function createDevelopmentWorkflowWorld(t){if(usesParentDevelopmentWorkflowWorld(t.preparedHost.compileResult.manifest.config.experimental?.workflow?.world))return createParentDevelopmentWorkflowWorld({agentName:t.preparedHost.compileResult.manifest.config.name,appRoot:t.appRoot,resolveActiveGenerationId:()=>{let n=readActiveDevelopmentRuntimeArtifactsSnapshot(t.appRoot);if(n===void 0)throw Error(`Development runtime generation is unavailable.`);return basename(n.snapshotRoot)},transportSecret:t.transportSecret})}function installWorkflowTransportEnvironment(e,r){let i=process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV],a=process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV];return process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]=r,process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV]=e,()=>{i===void 0?delete process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]:process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]=i,a===void 0?delete process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV]:process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV]=a}}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}}export{createDevelopmentWorkflowWorld,installWorkflowLocalQueueEnvironment,installWorkflowTransportEnvironment};
@@ -1 +1 @@
1
- import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules}from"#runtime/schedules/resolve-schedule.js";var UnknownDevScheduleError=class extends Error{availableScheduleIds;scheduleId;constructor(e,t){let n=t.length===0?`No schedules are defined in this app.`:`Available schedules: ${t.map(e=>`"${e}"`).join(`, `)}.`;super(`Unknown schedule "${e}". ${n}`),this.name=`UnknownDevScheduleError`,this.scheduleId=e,this.availableScheduleIds=t}};async function dispatchScheduleInDev(r){let{appRoot:i,moduleMapLoaderPath:a}=r.artifactsConfig;if(!i||!a)throw Error(`Dev schedule dispatch requires "appRoot" and "moduleMapLoaderPath" in the artifacts config.`);let o=createScheduleRegistrations(await loadResolvedCompiledSchedules({compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(i,{moduleMapLoaderPath:a})})),s=o.find(e=>e.scheduleId===r.scheduleId);if(s===void 0)throw new UnknownDevScheduleError(r.scheduleId,o.map(e=>e.scheduleId));let{dispatchScheduleTask:c}=await import(`#internal/nitro/routes/schedule-task.js`),l=await c(s.taskName,r.artifactsConfig);return{scheduleId:l.scheduleId,sessionIds:[...l.sessionIds]}}export{UnknownDevScheduleError,dispatchScheduleInDev};
1
+ import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules}from"#runtime/schedules/resolve-schedule.js";var UnknownDevScheduleError=class extends Error{availableScheduleIds;scheduleId;constructor(e,t){let n=t.length===0?`No schedules are defined in this app.`:`Available schedules: ${t.map(e=>`"${e}"`).join(`, `)}.`;super(`Unknown schedule "${e}". ${n}`),this.name=`UnknownDevScheduleError`,this.scheduleId=e,this.availableScheduleIds=t}};async function dispatchScheduleInDev(r){let{appRoot:i,moduleMapLoaderPath:a}=r.artifactsConfig;if(!i||!a)throw Error(`Dev schedule dispatch requires "appRoot" and "moduleMapLoaderPath" in the artifacts config.`);let o=resolveNitroCompiledArtifactsSource(r.artifactsConfig),s=createScheduleRegistrations(await loadResolvedCompiledSchedules({compiledArtifactsSource:o})),c=s.find(e=>e.scheduleId===r.scheduleId);if(c===void 0)throw new UnknownDevScheduleError(r.scheduleId,s.map(e=>e.scheduleId));let{dispatchScheduleTaskFromArtifacts:l}=await import(`#internal/nitro/routes/schedule-task.js`),u=await l(c.taskName,o);return{scheduleId:u.scheduleId,sessionIds:[...u.sessionIds]}}export{UnknownDevScheduleError,dispatchScheduleInDev};
@@ -0,0 +1,53 @@
1
+ import { type Server } from "node:http";
2
+ import { type DevelopmentRunnerFactory } from "#internal/nitro/host/dev-runner.js";
3
+ export interface DrainedDevServerListener {
4
+ close(): Promise<void>;
5
+ readonly node: {
6
+ readonly server: Server;
7
+ };
8
+ ready(): Promise<void>;
9
+ readonly url: string | undefined;
10
+ }
11
+ export interface DevelopmentWorkerReplacement {
12
+ readonly dispose?: () => Promise<void>;
13
+ readonly entry: string;
14
+ readonly workerData: Readonly<Record<string, unknown>>;
15
+ }
16
+ interface DevServerLogger {
17
+ error(message: unknown, ...details: unknown[]): unknown;
18
+ }
19
+ /**
20
+ * Development server with drained worker replacement: `replaceWorker` swaps
21
+ * to a ready candidate while the retired worker keeps serving the responses
22
+ * and sockets it already admitted — without bound, a streaming turn can hold
23
+ * one for minutes — and is terminated once its last exchange settles. Stock
24
+ * Nitro's dev server terminates the previous worker as soon as the next one
25
+ * attaches, which resets admitted work; this class exists solely to close
26
+ * that gap and is intended to be deleted in favor of `createDevServer` once
27
+ * equivalent drain semantics are available upstream.
28
+ */
29
+ export declare class DrainedNitroDevServer {
30
+ #private;
31
+ constructor(logger?: DevServerLogger, createRunner?: DevelopmentRunnerFactory);
32
+ setControlHandler(handler: (request: Request) => Promise<Response | undefined>): void;
33
+ /**
34
+ * Enables signed client-address metadata on requests forwarded to
35
+ * workers. Without it the worker only ever observes the parent's loopback
36
+ * hop as the request's peer address.
37
+ */
38
+ setClientAddressSecret(secret: string): void;
39
+ /**
40
+ * Swaps to a ready worker built from `entry`. Throws without touching the
41
+ * active worker when the candidate fails readiness. `dispose` is invoked
42
+ * once the worker created here has fully retired (drained, crashed, or
43
+ * closed at shutdown), so a caller can tie workspace cleanup to it.
44
+ */
45
+ replaceWorker(replacement: DevelopmentWorkerReplacement): Promise<void>;
46
+ listen(input: {
47
+ readonly hostname: string;
48
+ readonly port: number;
49
+ }): DrainedDevServerListener;
50
+ waitForActiveRunner(timeoutMs?: number): Promise<void>;
51
+ close(): Promise<void>;
52
+ }
53
+ export {};
@@ -0,0 +1 @@
1
+ import{createServer}from"node:http";import{toErrorMessage}from"#shared/errors.js";import{closeServer,createPublicRequest,writeRequestError,writeResponse}from"#internal/nitro/host/dev-server-http.js";import{createNodeDevelopmentRunner}from"#internal/nitro/host/dev-runner.js";import{stampDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";const RUNNER_READY_TIMEOUT_MS=6e4;var DrainedNitroDevServer=class{#e;#t=new Set;#n=new Set;#r;#i;#a=[];#o;#s=!1;#c;#l;#u;#d=Promise.resolve();#f=0;constructor(e=console,t=createNodeDevelopmentRunner){this.#e=t,this.#r=e}setControlHandler(e){this.#l=e}setClientAddressSecret(e){this.#c=e}replaceWorker(e){let t=this.#d.catch(()=>void 0).then(async()=>await this.#p(e));return this.#d=t.catch(()=>void 0),t}async#p(e){if(this.#s)throw Error(`Development server is closed.`);let t={activeExchanges:0,dispose:e.dispose,disposed:!1,entry:e.entry,quietListeners:[],releasePromise:void 0,runner:this.#e({entry:e.entry,name:`eve-dev-${String(this.#f++)}`,workerData:e.workerData}),workerData:e.workerData};this.#u=t;try{await t.runner.waitForReady(RUNNER_READY_TIMEOUT_MS)}catch(e){throw await t.runner.close(e).catch(()=>void 0),await this.#_(t),e}finally{this.#u=void 0}if(this.#s)throw await this.#h(t),Error(`Development server closed before the worker was ready.`);let n=this.#i;this.#i=t,t.runner.onceClosed(()=>{this.#v(t)}),this.#C(),n!==void 0&&this.#y(n)}listen(t){if(this.#s)throw Error(`Development server is closed.`);let r=new Set,i=createServer((e,t)=>{this.#x(e,t)});i.on(`connection`,e=>{r.add(e),e.once(`close`,()=>r.delete(e))}),i.on(`upgrade`,(e,t,n)=>{this.#S(e,t,n)});let a,o=new Promise((e,n)=>{let onError=e=>{i.off(`listening`,onListening),n(e)},onListening=()=>{i.off(`error`,onError);let r=i.address();if(r===null||typeof r==`string`){n(Error(`Development server did not expose a TCP address.`));return}a=`http://${t.hostname.includes(`:`)?`[${t.hostname}]`:t.hostname}:${String(r.port)}/`,e()};i.once(`error`,onError),i.once(`listening`,onListening),i.listen({host:t.hostname,port:t.port})}),s,c={beginClose:()=>(s??=closeServer(i).finally(()=>{this.#n.delete(c)}),s),destroySockets:()=>{for(let e of r)e.destroy()}};return this.#n.add(c),{async close(){let e=c.beginClose();c.destroySockets(),await e},node:{server:i},ready:async()=>await o,get url(){return a}}}async waitForActiveRunner(e=RUNNER_READY_TIMEOUT_MS){let t=Date.now()+e;for(;this.#i===void 0&&!this.#s;){if(Date.now()>=t)throw Error(`Timed out waiting for the development worker to become ready.`);await new Promise(e=>{this.#a.push(e),setTimeout(e,100)})}if(this.#s)throw Error(`Development server is closed.`)}close(){return this.#o??=this.#m(),this.#o}async#m(){this.#s=!0,this.#C(),await this.#u?.runner.close(Error(`Development server is closing.`)).catch(()=>void 0),await this.#d.catch(()=>void 0);let e=[...this.#n],t=e.map(e=>e.beginClose()),n=[this.#i,...this.#t].filter(e=>e!==void 0);this.#i=void 0,this.#t.clear(),await Promise.all(n.map(async e=>await this.#h(e)));for(let t of e)t.destroySockets();await Promise.all(t)}#h(e){return e.releasePromise??=this.#g(e),e.releasePromise}async#g(e){await e.runner.close().catch(()=>void 0),await this.#_(e)}async#_(e){e.dispose===void 0||e.disposed||(e.disposed=!0,await e.dispose().catch(e=>{this.#r.error(`[eve:dev] failed to dispose a retired dev host: ${toErrorMessage(e)}`)}))}async#v(e){if(this.#s||this.#i!==e)return;this.#i=void 0,this.#r.error(`[eve:dev] dev worker exited; restarting.`);let n=this.#d.catch(()=>void 0).then(async()=>{if(this.#s||this.#i!==void 0){await this.#h(e);return}e.disposed=!0,e.releasePromise=Promise.resolve(),await this.#p({dispose:e.dispose,entry:e.entry,workerData:e.workerData})});this.#d=n.catch(()=>void 0);try{await n}catch(e){this.#r.error(`[eve:dev] dev worker restart failed: ${toErrorMessage(e)}`)}}#y(e){this.#t.add(e);let finishDrain=()=>{this.#h(e).finally(()=>this.#t.delete(e))};if(e.activeExchanges===0){finishDrain();return}e.quietListeners.push(finishDrain)}#b(e){e.activeExchanges+=1;let t=!1;return()=>{if(!t&&(t=!0,--e.activeExchanges,e.activeExchanges===0))for(let t of e.quietListeners.splice(0))t()}}async#x(e,t){let n=new AbortController,abortRequest=e=>{n.signal.aborted||n.abort(e)};e.once(`error`,abortRequest),t.once(`close`,()=>{t.writableEnded||abortRequest()});let o;try{let i=createPublicRequest(e,n.signal);stampDevelopmentClientAddress(i.headers,e.socket.remoteAddress??void 0,this.#c);let c=await this.#l?.(i);if(c!==void 0){await writeResponse(t,c,n.signal);return}await this.waitForActiveRunner();let l=this.#i;if(l===void 0)throw Error(`Development worker is unavailable.`);o=this.#b(l),await writeResponse(t,await l.runner.fetch(i,{signal:n.signal}),n.signal)}catch(e){n.signal.aborted||writeRequestError(t,e)}finally{o?.(),e.off(`error`,abortRequest)}}async#S(e,t,n){let r;try{stampDevelopmentClientAddress(e.headers,e.socket.remoteAddress??void 0,this.#c),await this.waitForActiveRunner();let i=this.#i;if(i===void 0)throw Error(`Development worker is unavailable.`);r=this.#b(i),t.once(`close`,r),t.once(`error`,r),await i.runner.upgrade({node:{head:n,req:e,socket:t}})}catch{r?.(),t.destroyed||t.destroy()}}#C(){for(let e of this.#a.splice(0))e()}};export{DrainedNitroDevServer};
@@ -1,11 +1,10 @@
1
1
  import type { ApplicationBuildWorkspace } from "#internal/application/build-workspace.js";
2
- import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";
2
+ import type { PreparedApplicationHost, PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
3
3
  /**
4
- * Compiles one authored app in place and stages the package-owned artifacts
5
- * the dev-server Nitro host needs, activating a fresh runtime-artifacts
6
- * snapshot for hot reload.
4
+ * Compiles one authored app and stages an isolated runtime generation and host
5
+ * candidate without changing the active development server.
7
6
  */
8
- export declare function prepareDevelopmentApplicationHost(startPath: string): Promise<PreparedApplicationHost>;
7
+ export declare function prepareDevelopmentApplicationHost(appRoot: string): Promise<PreparedDevelopmentApplicationHost>;
9
8
  /**
10
9
  * Compiles one authored app into an invocation-owned build workspace and
11
10
  * stages the package-owned artifacts the production Nitro build needs.
@@ -1 +1 @@
1
- import{join}from"node:path";import{resolveApplicationHostArtifactsDirectory,resolveWorkflowBuildDirectory}from"#internal/application/paths.js";import{createAuthoredSourceRuntimeCompiledArtifactsSource}from"#internal/application/runtime-compiled-artifacts-source.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules,resolveSchedules}from"#runtime/schedules/resolve-schedule.js";import{compileAgent,compileAgentInBuildWorkspace}from"#compiler/compile-agent.js";import{writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles}from"#internal/application/compiled-artifacts.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration,stageDevelopmentGeneration}from"#internal/nitro/development-generation.js";async function prepareDevelopmentApplicationHost(e){let i=await compileAgent({startPath:e}),a=await loadResolvedCompiledSchedules({compiledArtifactsSource:createAuthoredSourceRuntimeCompiledArtifactsSource(i.project.appRoot)}),o=await stageDevelopmentGeneration(i);try{let e=await writeDevelopmentCompiledArtifactsFiles({compileResult:i,outDir:resolveApplicationHostArtifactsDirectory(i.project.appRoot),runtimeAppRoot:o.runtimeAppRoot});return await activateDevelopmentGeneration({appRoot:i.project.appRoot,generation:o}),createPreparedApplicationHost({compileResult:i,compiledArtifacts:e,schedules:a,workflowBuildDir:resolveWorkflowBuildDirectory(i.project.appRoot)})}catch(e){throw await discardDevelopmentGeneration(o),e}}async function prepareProductionApplicationHost(t){let n=await compileAgentInBuildWorkspace({artifactLocations:{publishedRoot:join(t.publication.output.finalDir,`.eve`),writeRoot:t.compiler.artifactsDir},startPath:t.appRoot}),r=await resolveSchedules({manifest:n.manifest});return createPreparedApplicationHost({compileResult:n,compiledArtifacts:await writeCompiledArtifactsFiles({compileResult:n,defaultWorkflowWorld:resolveProductionWorkflowWorldTarget(),outDir:t.host.artifactsDir}),schedules:r,workflowBuildDir:t.workflow.buildDir})}function createPreparedApplicationHost(e){return{appRoot:e.compileResult.project.appRoot,compileResult:e.compileResult,compiledArtifacts:e.compiledArtifacts,scheduleRegistrations:createScheduleRegistrations(e.schedules),schedules:e.schedules,workflowBuildDir:e.workflowBuildDir}}function resolveProductionWorkflowWorldTarget(){return process.env.VERCEL?`vercel`:`local`}export{prepareDevelopmentApplicationHost,prepareProductionApplicationHost};
1
+ import{join}from"node:path";import{createDevelopmentHostWorkspace,removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import{discardDevelopmentGeneration,stageDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{resolveSchedules}from"#runtime/schedules/resolve-schedule.js";import{compileAgentInWorkspace}from"#compiler/compile-agent.js";import{writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles}from"#internal/application/compiled-artifacts.js";async function prepareDevelopmentApplicationHost(a){let o=await createDevelopmentHostWorkspace(a),s;try{let t=await compileAgentInWorkspace({artifactLocations:{publishedRoot:join(a,`.eve`),writeRoot:o.compilerArtifactsDir},startPath:a}),n=await resolveSchedules({manifest:t.manifest});return s=await stageDevelopmentGeneration(t),{...createPreparedApplicationHost({compileResult:t,compiledArtifacts:await writeDevelopmentCompiledArtifactsFiles({compileResult:t,outDir:o.artifactsDir,runtimeAppRoot:s.runtimeAppRoot}),schedules:n,workflowBuildDir:o.workflowBuildDir}),generation:s,workspace:o}}catch(e){let t=[removeDevelopmentHostWorkspace(o)];s!==void 0&&t.push(discardDevelopmentGeneration(s));let i=(await Promise.allSettled(t)).flatMap(e=>e.status===`rejected`?[e.reason]:[]);throw i.length>0?AggregateError([e,...i],`Failed to prepare and discard a development host candidate.`,{cause:e}):e}}async function prepareProductionApplicationHost(t){let n=await compileAgentInWorkspace({artifactLocations:{publishedRoot:join(t.publication.output.finalDir,`.eve`),writeRoot:t.compiler.artifactsDir},startPath:t.appRoot}),r=await resolveSchedules({manifest:n.manifest});return createPreparedApplicationHost({compileResult:n,compiledArtifacts:await writeCompiledArtifactsFiles({compileResult:n,defaultWorkflowWorld:resolveProductionWorkflowWorldTarget(),outDir:t.host.artifactsDir}),schedules:r,workflowBuildDir:t.workflow.buildDir})}function createPreparedApplicationHost(e){return{appRoot:e.compileResult.project.appRoot,compileResult:e.compileResult,compiledArtifacts:e.compiledArtifacts,scheduleRegistrations:createScheduleRegistrations(e.schedules),schedules:e.schedules,workflowBuildDir:e.workflowBuildDir}}function resolveProductionWorkflowWorldTarget(){return process.env.VERCEL?`vercel`:`local`}export{prepareDevelopmentApplicationHost,prepareProductionApplicationHost};
@@ -1,9 +1,6 @@
1
1
  import type { DevelopmentServer, DevelopmentServerOptions, StartedDevelopmentServer } from "#internal/nitro/host/types.js";
2
- /**
3
- * Rewrites a server URL whose hostname is a wildcard listen address into a
4
- * loopback URL on the same address family.
5
- */
6
- export declare function normalizeDevelopmentServerClientUrl(serverUrl: string): string;
2
+ import { normalizeDevelopmentServerClientUrl } from "#internal/nitro/host/dev-server-url.js";
3
+ export { normalizeDevelopmentServerClientUrl };
7
4
  /**
8
5
  * Returns whether a supplied URL identifies this app's healthy local development
9
6
  * server. Only that server receives the local TUI credential path.
@@ -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
  */
@@ -10,6 +12,10 @@ export type NitroBuildSurface = "all" | "app" | "flow";
10
12
  /** Options for one production application build. */
11
13
  export interface ApplicationBuildOptions {
12
14
  readonly skipVercelSandboxPrewarm: boolean;
15
+ readonly vercelServiceOutput?: {
16
+ readonly hostOutputDirectory: string;
17
+ readonly serviceOutputDirectory: string;
18
+ };
13
19
  }
14
20
  /** Outcome of starting a Nitro development server the current process owns. */
15
21
  export interface StartedDevelopmentServer {
@@ -61,3 +67,7 @@ export interface PreparedApplicationHost {
61
67
  schedules: readonly ResolvedScheduleDefinition[];
62
68
  workflowBuildDir: string;
63
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";var MissingDevelopmentGenerationError=class extends Error{constructor(e,t){super(`Workflow run references missing development generation "${e}". Remove ".workflow-data" 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{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:join(e.appRoot,`.workflow-data`),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 ".workflow-data" 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 ".workflow-data" 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 ".workflow-data" 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};
@@ -1 +1 @@
1
- import{dirname,join,relative}from"node:path";import{mkdir,readFile,writeFile}from"node:fs/promises";import{findClosestLinkedVercelDirectory,findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";const VERCEL_JSON_FILE_NAME=`vercel.json`,VERCEL_OUTPUT_CONFIG_FILE_NAME=`.vercel/output/config.json`;function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hasServices(e){return e!==void 0&&Object.keys(createServiceConfigRecord(e)).length>0}function isNamedServiceConfigArray(e){return Array.isArray(e)}function createServiceConfigRecord(e){if(e===void 0)return{};if(isNamedServiceConfigArray(e)){let t={};for(let n of e)if(typeof n.name==`string`&&n.name.trim().length>0){let{name:e,...r}=n;t[e]=r}return t}return e}function resolveRelativeEntrypoint(e,t){let r=relative(e,t);return r.length===0?`.`:r.replaceAll(`\\`,`/`)}async function resolveVercelOutputConfigLocation(n){let r=await findClosestLinkedVercelDirectory(n),i=r===void 0?n:dirname(r),a=await findClosestVercelOutputDirectory(n);return a===void 0?r===void 0?{canWriteGeneratedOutput:!!process.env.VERCEL,outputConfigPath:join(n,VERCEL_OUTPUT_CONFIG_FILE_NAME),projectRoot:i}:{canWriteGeneratedOutput:!0,outputConfigPath:join(r,`output`,`config.json`),projectRoot:i}:{canWriteGeneratedOutput:!0,outputConfigPath:join(a,`config.json`),projectRoot:i}}function normalizeVercelServicesConfig(e,t){if(!isRecord(e))throw Error(`${t} must contain a JSON object.`);let n=e.services;if(n!==void 0&&!isRecord(n)&&!(Array.isArray(n)&&n.every(e=>isRecord(e)&&typeof e.name==`string`&&e.name.trim().length>0)))throw Error(`${t} services must be a JSON object or named service array.`);let r=e.routes;if(r!==void 0&&!Array.isArray(r))throw Error(`${t} routes must be an array.`);return e}async function readVercelServicesConfig(e,t){try{return normalizeVercelServicesConfig(JSON.parse(await readFile(e,`utf8`)),t)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{};throw e}}function findServiceEntryByFramework(e,t){return Object.entries(e).map(([e,t])=>({name:e,service:t})).find(e=>e.service.framework===t)}function findServiceEntryByName(e,t){let n=e[t];return n===void 0?void 0:{name:t,service:n}}function resolveServicePrefix(e){if(e!==void 0){if(typeof e.routePrefix==`string`&&e.routePrefix.trim().length>0)return e.routePrefix.trim();if(typeof e.mount==`string`&&e.mount.trim().length>0)return e.mount.trim();if(isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0)return e.mount.path.trim()}}function resolveConfiguredServicePrefix(e){let t=findConfiguredEveServiceEntry(e.services,e.agent)?.service;return resolveServicePrefix(t)??e.agent.servicePrefix}function findConfiguredEveServiceEntry(e,t){if(t.name!==void 0){let n=findServiceEntryByName(e,createEveServiceName(t.name));if(n?.service.framework===`eve`)return n}return t.name===void 0?findServiceEntryByFramework(e,`eve`):void 0}function assertRootServicesIncludeEve(e){let t=[];for(let n of e.agents){let r=findConfiguredEveServiceEntry(e.services,n)?.service;if(r===void 0)throw Error(`${VERCEL_JSON_FILE_NAME} already defines services, so withEve cannot add generated eve services through ${VERCEL_OUTPUT_CONFIG_FILE_NAME}. Add the eve service for ${n.name??`the default agent`} to ${VERCEL_JSON_FILE_NAME}, or remove services from ${VERCEL_JSON_FILE_NAME}.`);t.push({name:n.name,servicePrefix:resolveServicePrefix(r)??n.servicePrefix})}return t}function createEveServiceRouteSrc(e){return e.length===0?`^/eve/v1/(.*)$`:`^${escapeRegExp(e.startsWith(`/`)?e:`/${e}`)}/eve/v1/(.*)$`}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function createEveServiceName(e){return e===void 0?`eve`:`eve-${e}`}function isEveServiceRoute(e,t,n){let r=e.destination;return e.src===n&&isRecord(r)&&r.type===`service`&&r.service===t}function createEveServiceRoute(e,t){return{destination:{service:e,type:`service`},src:t}}function isEveServiceRequestPathRoute(e,t){return e.src===t}function createEveServiceRequestPathRoute(e){return{src:e,transforms:[{args:`/eve/v1/$1`,op:`set`,type:`request.path`}]}}function insertEveServiceRequestPathRoute(e,t){let n=(e??[]).filter(e=>!isEveServiceRequestPathRoute(e,t));return[createEveServiceRequestPathRoute(t),...n]}function insertEveServiceRoutes(e,t){let n=e.filter(e=>!t.some(t=>isEveServiceRoute(e,t.serviceName,t.routeSrc))),r=n.findIndex(e=>e.handle===`filesystem`),i=t.map(e=>createEveServiceRoute(e.serviceName,e.routeSrc));return r===-1?[...i,...n]:[...n.slice(0,r),...i,...n.slice(r)]}async function ensureEveVercelOutputConfig(n){let{canWriteGeneratedOutput:i,outputConfigPath:o,projectRoot:s}=await resolveVercelOutputConfigLocation(n.nextRoot),c=(await readVercelServicesConfig(join(s,VERCEL_JSON_FILE_NAME),VERCEL_JSON_FILE_NAME)).services;if(hasServices(c))return{agents:assertRootServicesIncludeEve({agents:n.agents,services:createServiceConfigRecord(c)})};let l=await readVercelServicesConfig(o,VERCEL_OUTPUT_CONFIG_FILE_NAME),u=createServiceConfigRecord(l.services),d=n.agents.map(e=>({name:e.name,servicePrefix:resolveConfiguredServicePrefix({agent:e,services:u})}));if(!i)return{agents:d};let f={...u},p=[];for(let e of n.agents){let t=findConfiguredEveServiceEntry(u,e),r=t?.name??createEveServiceName(e.name),i=createEveServiceRouteSrc(e.publicRoutePrefix);if(t===void 0){let t={buildCommand:e.buildCommand,framework:`eve`,routes:insertEveServiceRequestPathRoute(void 0,i),root:resolveRelativeEntrypoint(n.nextRoot,e.appRoot)};e.publicRoutePrefix.length>0&&(t.routePrefix=e.publicRoutePrefix),f[r]=t}else f[r]={...t.service,routes:insertEveServiceRequestPathRoute(t.service.routes,i)};p.push({routeSrc:i,serviceName:r})}let{services:m,...h}=l,g={...h,routes:insertEveServiceRoutes(l.routes??[],p),services:f,version:3};return JSON.stringify(l)!==JSON.stringify(g)&&(await mkdir(dirname(o),{recursive:!0}),await writeFile(o,`${JSON.stringify(g,null,2)}\n`)),{agents:d}}export{ensureEveVercelOutputConfig};
1
+ import{dirname,join,relative}from"node:path";import{mkdir,readFile,writeFile}from"node:fs/promises";import{EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}from"#internal/application/paths.js";import{findClosestLinkedVercelDirectory,findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";const VERCEL_JSON_FILE_NAME=`vercel.json`,VERCEL_OUTPUT_CONFIG_FILE_NAME=`.vercel/output/config.json`;function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hasServices(e){return e!==void 0&&Object.keys(createServiceConfigRecord(e)).length>0}function isNamedServiceConfigArray(e){return Array.isArray(e)}function createServiceConfigRecord(e){if(e===void 0)return{};if(isNamedServiceConfigArray(e)){let t={};for(let n of e)if(typeof n.name==`string`&&n.name.trim().length>0){let{name:e,...r}=n;t[e]=r}return t}return e}function resolveRelativeEntrypoint(e,t){let r=relative(e,t);return r.length===0?`.`:r.replaceAll(`\\`,`/`)}function quoteShellArgument(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function createGeneratedServiceBuild(e){let n=join(e.nextRoot,`.eve/vercel-services`,e.serviceName),r=join(n,`.vercel`,`output`),i=resolveRelativeEntrypoint(n,e.agent.appRoot),a=resolveRelativeEntrypoint(e.agent.appRoot,r),c=resolveRelativeEntrypoint(e.agent.appRoot,e.hostOutputDirectory);return{buildCommand:`cd ${quoteShellArgument(i)} && export ${EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(a)} && export ${EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(c)} && ${e.agent.buildCommand}`,root:resolveRelativeEntrypoint(e.nextRoot,n),rootDirectory:n}}async function resolveVercelOutputConfigLocation(n){let r=await findClosestLinkedVercelDirectory(n),i=r===void 0?n:dirname(r),a=await findClosestVercelOutputDirectory(n);return a===void 0?r===void 0?{canWriteGeneratedOutput:!!process.env.VERCEL,outputConfigPath:join(n,VERCEL_OUTPUT_CONFIG_FILE_NAME),projectRoot:i}:{canWriteGeneratedOutput:!0,outputConfigPath:join(r,`output`,`config.json`),projectRoot:i}:{canWriteGeneratedOutput:!0,outputConfigPath:join(a,`config.json`),projectRoot:i}}function normalizeVercelServicesConfig(e,t){if(!isRecord(e))throw Error(`${t} must contain a JSON object.`);let n=e.services;if(n!==void 0&&!isRecord(n)&&!(Array.isArray(n)&&n.every(e=>isRecord(e)&&typeof e.name==`string`&&e.name.trim().length>0)))throw Error(`${t} services must be a JSON object or named service array.`);let r=e.routes;if(r!==void 0&&!Array.isArray(r))throw Error(`${t} routes must be an array.`);return e}async function readVercelServicesConfig(e,t){try{return normalizeVercelServicesConfig(JSON.parse(await readFile(e,`utf8`)),t)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{};throw e}}function findServiceEntryByFramework(e,t){return Object.entries(e).map(([e,t])=>({name:e,service:t})).find(e=>e.service.framework===t)}function findServiceEntryByName(e,t){let n=e[t];return n===void 0?void 0:{name:t,service:n}}function resolveServicePrefix(e){if(e!==void 0){if(typeof e.routePrefix==`string`&&e.routePrefix.trim().length>0)return e.routePrefix.trim();if(typeof e.mount==`string`&&e.mount.trim().length>0)return e.mount.trim();if(isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0)return e.mount.path.trim()}}function resolveConfiguredServicePrefix(e){let t=findConfiguredEveServiceEntry(e.services,e.agent)?.service;return resolveServicePrefix(t)??e.agent.servicePrefix}function findConfiguredEveServiceEntry(e,t){if(t.name!==void 0){let n=findServiceEntryByName(e,createEveServiceName(t.name));if(n?.service.framework===`eve`)return n}return t.name===void 0?findServiceEntryByFramework(e,`eve`):void 0}function assertRootServicesIncludeEve(e){let t=[];for(let n of e.agents){let r=findConfiguredEveServiceEntry(e.services,n)?.service;if(r===void 0)throw Error(`${VERCEL_JSON_FILE_NAME} already defines services, so withEve cannot add generated eve services through ${VERCEL_OUTPUT_CONFIG_FILE_NAME}. Add the eve service for ${n.name??`the default agent`} to ${VERCEL_JSON_FILE_NAME}, or remove services from ${VERCEL_JSON_FILE_NAME}.`);t.push({name:n.name,servicePrefix:resolveServicePrefix(r)??n.servicePrefix})}return t}function createEveServiceRouteSrc(e){return e.length===0?`^/eve/v1/(.*)$`:`^${escapeRegExp(e.startsWith(`/`)?e:`/${e}`)}/eve/v1/(.*)$`}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function createEveServiceName(e){return e===void 0?`eve`:`eve-${e}`}function isEveServiceRoute(e,t,n){let r=e.destination;return e.src===n&&isRecord(r)&&r.type===`service`&&r.service===t}function createEveServiceRoute(e,t){return{destination:{service:e,type:`service`},src:t}}function isEveServiceRequestPathRoute(e,t){return e.src===t}function createEveServiceRequestPathRoute(e){return{src:e,transforms:[{args:`/eve/v1/$1`,op:`set`,type:`request.path`}]}}function insertEveServiceRequestPathRoute(e,t){let n=(e??[]).filter(e=>!isEveServiceRequestPathRoute(e,t));return[createEveServiceRequestPathRoute(t),...n]}function insertEveServiceRoutes(e,t){let n=e.filter(e=>!t.some(t=>isEveServiceRoute(e,t.serviceName,t.routeSrc))),r=n.findIndex(e=>e.handle===`filesystem`),i=t.map(e=>createEveServiceRoute(e.serviceName,e.routeSrc));return r===-1?[...i,...n]:[...n.slice(0,r),...i,...n.slice(r)]}async function ensureEveVercelOutputConfig(n){let{canWriteGeneratedOutput:i,outputConfigPath:o,projectRoot:s}=await resolveVercelOutputConfigLocation(n.nextRoot),c=(await readVercelServicesConfig(join(s,VERCEL_JSON_FILE_NAME),VERCEL_JSON_FILE_NAME)).services;if(hasServices(c))return{agents:assertRootServicesIncludeEve({agents:n.agents,services:createServiceConfigRecord(c)})};let l=await readVercelServicesConfig(o,VERCEL_OUTPUT_CONFIG_FILE_NAME),u=createServiceConfigRecord(l.services),d=n.agents.map(e=>({name:e.name,servicePrefix:resolveConfiguredServicePrefix({agent:e,services:u})}));if(!i)return{agents:d};let f={...u},p=[];for(let t of n.agents){let i=findConfiguredEveServiceEntry(u,t),a=i?.name??createEveServiceName(t.name),s=createEveServiceRouteSrc(t.publicRoutePrefix);if(i===void 0){let i=createGeneratedServiceBuild({agent:t,hostOutputDirectory:dirname(o),nextRoot:n.nextRoot,serviceName:a});await mkdir(i.rootDirectory,{recursive:!0});let c={buildCommand:i.buildCommand,framework:`eve`,routes:insertEveServiceRequestPathRoute(void 0,s),root:i.root};t.publicRoutePrefix.length>0&&(c.routePrefix=t.publicRoutePrefix),f[a]=c}else f[a]={...i.service,routes:insertEveServiceRequestPathRoute(i.service.routes,s)};p.push({routeSrc:s,serviceName:a})}let{services:m,...h}=l,g={...h,routes:insertEveServiceRoutes(l.routes??[],p),services:f,version:3};return JSON.stringify(l)!==JSON.stringify(g)&&(await mkdir(dirname(o),{recursive:!0}),await writeFile(o,`${JSON.stringify(g,null,2)}\n`)),{agents:d}}export{ensureEveVercelOutputConfig};
@@ -29,6 +29,14 @@ export interface RuntimeDiskCompiledArtifactsSource {
29
29
  * while sandbox state should remain scoped to the authored application.
30
30
  */
31
31
  readonly sandboxAppRoot?: string;
32
+ /**
33
+ * How this source is recorded in durable Workflow payloads.
34
+ * `"development-generation"` stores a logical selector resolved from the
35
+ * delivery's generation context — valid only where deliveries install
36
+ * that context (the parent-owned dev World). Absent, the source is stored
37
+ * verbatim, pinning durable work to this exact path.
38
+ */
39
+ readonly durableReference?: "development-generation";
32
40
  }
33
41
  /**
34
42
  * Creates the bundled compiled-artifact source.
@@ -38,6 +46,7 @@ export declare function createBundledRuntimeCompiledArtifactsSource(): RuntimeBu
38
46
  * Creates the disk-backed compiled-artifact source for one authored app root.
39
47
  */
40
48
  export declare function createDiskRuntimeCompiledArtifactsSource(appRoot: string, options?: {
49
+ readonly durableReference?: "development-generation";
41
50
  readonly moduleMapLoaderPath?: string;
42
51
  readonly sandboxAppRoot?: string;
43
52
  }): RuntimeDiskCompiledArtifactsSource;