The Open Framework for Building Agents
feat(dev): own the local Workflow World in the CLI parent process (#790)
Casey Gowrie5473f76e5806
diff --git a/.changeset/steady-worlds-wait.md b/.changeset/steady-worlds-wait.mdnew file mode 100644index 000000000..ed0560fce--- /dev/null+++ b/.changeset/steady-worlds-wait.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep active local Workflow turns on the development generation they selected across reloads, retries, and server restarts. New turns use the latest successful generation, and `eve dev` stores local Workflow state under `.workflow-data`.diff --git a/docs/concepts/execution-model-and-durability.md b/docs/concepts/execution-model-and-durability.mdindex 64014d3ff..28a94daed 100644--- a/docs/concepts/execution-model-and-durability.md+++ b/docs/concepts/execution-model-and-durability.md@@ -15,7 +15,7 @@ Work nests in three levels:Every turn runs as a durable workflow, built on the open-source [Workflow SDK](https://workflow-sdk.dev/) (Vercel Workflow when you deploy on Vercel). eve checkpoints progress and serializes durable state at each step boundary. Your code runs inside a managed step, so tools, the sandbox, and subagents feel synchronous even though the session underneath them is durable.-The Workflow SDK is not inherently tied to Vercel. In local development and in a self-deployed `eve start` process, eve uses the SDK's local world by default; that world persists workflow runs on disk, normally under `.workflow-data`, and dispatches through the same Nitro-hosted workflow routes. On Vercel, the same workflow code runs against Vercel Workflow instead, which adds platform features such as latest production deployment routing and dashboard run metadata.+The Workflow SDK is not inherently tied to Vercel. In local development and in a self-deployed `eve start` process, eve uses the SDK's local world by default; that world persists workflow runs on disk under `.workflow-data` and dispatches through the same Nitro-hosted workflow routes. On Vercel, the same workflow code runs against Vercel Workflow instead, which adds platform features such as latest production deployment routing and dashboard run metadata.When a Vercel production deployment changes, the next model turn in an existing session uses that deployment's current instructions, model, and tools. The durable session keeps its conversation history and authored state, so identity-based channels such as Telegram private chats and Twilio phone-number conversations adopt agent updates without requiring a new session.diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 369f83ade..a744fd64f 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -158,7 +158,7 @@ For bearer tokens or custom schemes, pass explicit headers with `-H`.Local dev records the last ready URL per resolved app root in `.eve/dev-server-state.v1.json`. A second interactive `eve dev` reconnects only when that URL is loopback and healthy; each terminal UI creates a fresh client session while sharing the server process. A stale or malformed record is replaced when eve starts a new server. Passing `--host`, `--port`, or a `PORT` environment value skips reconnection and reports a healthy recorded server instead.-Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight sessions hold a consistent code revision while new prompts pick up rebuilds. On startup, `eve dev` prunes stale runtime snapshots and old local sandbox templates in the background. For manual cleanup, stop `eve dev` and delete `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`.+Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight sessions hold a consistent code revision while new prompts pick up rebuilds. `eve dev` retains activated runtime snapshots so durable local Workflow turns can resume on their selected revision, and it prunes old local sandbox templates in the background. For manual cleanup, stop `eve dev` before deleting `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`. Deleting runtime snapshots while retaining `.workflow-data` can prevent an unfinished turn from resuming; remove both only when you intend to discard local Workflow state.## `eve link`diff --git a/packages/eve/scripts/vendor-compiled/@workflow/world-local.mjs b/packages/eve/scripts/vendor-compiled/@workflow/world-local.mjsindex dbd48b6b3..6f4ffb4fd 100644--- a/packages/eve/scripts/vendor-compiled/@workflow/world-local.mjs+++ b/packages/eve/scripts/vendor-compiled/@workflow/world-local.mjs@@ -2,6 +2,8 @@ import { readFileSync } from "node:fs";import { createRequire } from "node:module";import { dirname, join } from "node:path";+import { loadDeclaration } from "../_shared.mjs";+const require = createRequire(import.meta.url);function resolveWorkflowWorldLocalVersion() {@@ -35,13 +37,18 @@ const workflowWorldLocalVersion = resolveWorkflowWorldLocalVersion();const workflowWorldLocalVersionPlugin = {name: "eve-workflow-world-local-version",transform(source, id) {- if (!id.endsWith("/@workflow/world-local/dist/init.js")) {+ if (!id.replaceAll("\\", "/").endsWith("/@workflow/world-local/dist/init.js")) {return undefined;}+ const bundledVersionSource = "version: 'bundled',";+ if (!source.includes(bundledVersionSource)) {+ throw new Error("Failed to find the bundled @workflow/world-local version fallback.");+ }+return {code: source.replace(- "version: 'bundled',",+ bundledVersionSource,`version: ${JSON.stringify(workflowWorldLocalVersion)},`,),map: null,@@ -53,5 +60,6 @@ export default {packageName: "@workflow/world-local",compiledPath: "@workflow/world-local",chunkGroup: "workflow",+ declaration: await loadDeclaration("workflow-world-local.d.ts"),plugins: [workflowWorldLocalVersionPlugin],};diff --git a/packages/eve/scripts/vendor-compiled/declarations/workflow-world-local.d.ts b/packages/eve/scripts/vendor-compiled/declarations/workflow-world-local.d.tsnew file mode 100644index 000000000..6eba378ce--- /dev/null+++ b/packages/eve/scripts/vendor-compiled/declarations/workflow-world-local.d.ts@@ -0,0 +1,14 @@+import type { QueuePrefix, World } from "#compiled/@workflow/world/index.js";++export type LocalWorld = World & {+ clear(): Promise<void>;+ registerHandler(prefix: QueuePrefix, handler: (request: Request) => Promise<Response>): void;+};++export function createWorld(options?: {+ readonly baseUrl?: string;+ readonly dataDir?: string;+ readonly recoverActiveRuns?: boolean;+ readonly streamFlushIntervalMs?: number;+ readonly tag?: string;+}): LocalWorld;diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex df10de45d..d39e5525c 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -1,5 +1,8 @@-import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";+import {+ type DurableCompiledArtifactsSource,+ resolveDurableCompiledArtifactsSource,+} from "#runtime/durable-compiled-artifacts-source.js";import {createDurableSessionState,type DurableSessionState,@@ -26,7 +29,7 @@ export interface CreateSessionStepResult {* the root agent.*/export async function createSessionStep(input: {- readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;+ readonly compiledArtifactsSource: DurableCompiledArtifactsSource;readonly continuationToken: string;readonly inheritedLimits?: RunSessionLimits;readonly outputSchema?: JsonObject;@@ -38,7 +41,7 @@ export async function createSessionStep(input: {"use step";const bundle = await getCompiledRuntimeAgentBundle({- compiledArtifactsSource: input.compiledArtifactsSource,+ compiledArtifactsSource: resolveDurableCompiledArtifactsSource(input.compiledArtifactsSource),nodeId: input.nodeId,});diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex 7b10b55e6..29e60be99 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -10,7 +10,7 @@ import type {import { coalesceDeliveries } from "#harness/messages.js";import { readChannelRequestId, readRootSessionId } from "#execution/eve-workflow-attributes.js";import type { RunMode } from "#shared/run-mode.js";-import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import type { DurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";import { notifyDelegatedParentStep } from "#execution/delegated-parent-notification.js";import {createDelegatedSubagentErrorResult,@@ -74,7 +74,7 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow| SessionCapabilities| undefined;const serializedBundle = input.serializedContext["eve.bundle"] as {- source: RuntimeCompiledArtifactsSource;+ source: DurableCompiledArtifactsSource;nodeId?: string;};diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex f32f6ddbe..5872efed3 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -15,6 +15,7 @@ import {readParentLineage,} from "#execution/eve-workflow-attributes.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";+import { isEveDevEnvironment } from "#internal/application/dev-environment.js";import { createLogger, logError } from "#internal/logging.js";import {getRun,@@ -220,15 +221,12 @@ export async function startWorkflowPreferLatest<TArgs extends unknown[], TResult}/**- * Latest-deployment routing only applies on Vercel production: the platform- * resolves "latest" through the deployment's git branch reference, which- * only production deployments carry. Preview and CLI deployments have no- * branch and fail with HTTP 400 ("Source deployment has no git branch"), so- * they pin workflow runs to their own immutable deployment — which is also- * the correct isolation semantic for previews.+ * Local development resolves "latest" to the active promoted generation.+ * Vercel resolves it only for production deployments; previews and CLI+ * deployments have no branch reference and remain pinned to themselves.*/function shouldRouteToLatestDeployment(): boolean {- return process.env.VERCEL_ENV === "production";+ return process.env.VERCEL_ENV === "production" || isEveDevEnvironment();}function isLatestDeploymentUnsupportedError(error: unknown): boolean {diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 1cf6997f3..379aa9b12 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -226,6 +226,20 @@ describe("dispatchTurnStep", () => {);});+ it("starts turn workflows on the latest promoted generation in local development", async () => {+ vi.stubEnv("EVE_DEV", "1");+ const input = createTurnInput();+ startMock.mockResolvedValue({ runId: "turn-run" });++ await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });++ expect(startMock).toHaveBeenCalledWith(+ turnWorkflowReference,+ [createTurnWorkflowInput(input)],+ expect.objectContaining({ deploymentId: "latest" }),+ );+ });+it("pins turn workflows to the current deployment off production", async () => {vi.stubEnv("VERCEL_ENV", "preview");const input = createTurnInput();diff --git a/packages/eve/src/internal/application/compiled-artifacts.test.ts b/packages/eve/src/internal/application/compiled-artifacts.test.tsindex 10628bfe2..0c8b9bc24 100644--- a/packages/eve/src/internal/application/compiled-artifacts.test.ts+++ b/packages/eve/src/internal/application/compiled-artifacts.test.ts@@ -1,6 +1,9 @@import { describe, expect, it } from "vitest";-import { createWorkflowWorldPluginSource } from "#internal/application/compiled-artifacts.js";+import {+ createDevelopmentWorkflowWorldPluginSource,+ createWorkflowWorldPluginSource,+} from "#internal/application/compiled-artifacts.js";describe("createWorkflowWorldPluginSource", () => {it("imports a configured world package and delegates its construction to Workflow", () => {@@ -41,3 +44,27 @@ describe("createWorkflowWorldPluginSource", () => {).toContain("/compiled/@workflow/world-vercel/index.js");});});++describe("createDevelopmentWorkflowWorldPluginSource", () => {+ it("installs the parent-backed World without starting a local World in the worker", () => {+ const source = createDevelopmentWorkflowWorldPluginSource({+ compiledArtifactsBootstrapPath: "/app/.eve/host/bootstrap.mjs",+ configuredWorld: undefined,+ });++ expect(source).toContain("createDevelopmentWorkflowWorld");+ expect(source).toContain("setWorld(createDevelopmentWorkflowWorld());");+ expect(source).not.toContain("@workflow/world-local");+ expect(source).not.toContain("workflowWorld.start");+ });++ it("keeps explicitly configured remote Worlds inside the worker", () => {+ const source = createDevelopmentWorkflowWorldPluginSource({+ compiledArtifactsBootstrapPath: "/app/.eve/host/bootstrap.mjs",+ configuredWorld: "@acme/eve-world",+ });++ expect(source).toContain('import * as workflowWorldModule from "@acme/eve-world";');+ expect(source).toContain("await workflowWorld.start?.();");+ });+});diff --git a/packages/eve/src/internal/application/compiled-artifacts.ts b/packages/eve/src/internal/application/compiled-artifacts.tsindex 9554ea909..ebfea2c36 100644--- a/packages/eve/src/internal/application/compiled-artifacts.ts+++ b/packages/eve/src/internal/application/compiled-artifacts.ts@@ -13,6 +13,7 @@ import {} from "#internal/application/package.js";import type { AgentWorkflowWorldDefinition } from "#shared/agent-definition.js";import { readMaterializedAuthoredModuleIndex } from "#internal/materialized-authored-modules.js";+import { usesParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-protocol.js";export type BuiltInWorkflowWorldTarget = "local" | "vercel";@@ -129,10 +130,9 @@ export async function writeDevelopmentCompiledArtifactsFiles(input: {);await writeFile(workflowWorldPluginPath,- createWorkflowWorldPluginSource({+ createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath: bootstrapPath,configuredWorld: input.compileResult.manifest.config.experimental?.workflow?.world,- defaultWorld: "local",}),);@@ -279,6 +279,45 @@ export function createWorkflowWorldPluginSource(input: {].join("\n");}+/**+ * Generates the dev worker's Workflow World wiring. Configs that resolve to+ * the vendored local World get the parent RPC client so run state survives+ * worker replacement; any other World is instantiated inside the worker+ * unchanged, because eve does not own its lifetime. The selection predicate+ * is shared with the parent's world creation — a worker wired for the RPC+ * client fails every World call unless the parent created a World to serve+ * it.+ */+export function createDevelopmentWorkflowWorldPluginSource(input: {+ compiledArtifactsBootstrapPath: string;+ configuredWorld: AgentWorkflowWorldDefinition | undefined;+}): string {+ if (!usesParentDevelopmentWorkflowWorld(input.configuredWorld)) {+ return createWorkflowWorldPluginSource({+ ...input,+ defaultWorld: "local",+ });+ }+ const workflowRuntimeImportSpecifier = resolvePackageCompiledFilePath(+ "src/compiled/@workflow/core/runtime.js",+ );+ const developmentWorldImportSpecifier = resolvePackageSourceFilePath(+ "src/internal/workflow/development-world-client.ts",+ );+ return [+ "// Generated by eve. Do not edit by hand.",+ `import ${stringifyEsmImportSpecifier(input.compiledArtifactsBootstrapPath)};`,+ `import { getWorld, setWorld } from ${stringifyEsmImportSpecifier(workflowRuntimeImportSpecifier)};`,+ `import { createDevelopmentWorkflowWorld } from ${stringifyEsmImportSpecifier(developmentWorldImportSpecifier)};`,+ "",+ "setWorld(createDevelopmentWorkflowWorld());",+ "await getWorld();",+ "",+ "export default function installDevelopmentWorkflowWorldPlugin() {}",+ "",+ ].join("\n");+}+function createInstrumentationPluginSource(input: {agentName: string;instrumentationPath: string;diff --git a/packages/eve/src/internal/application/dev-environment.ts b/packages/eve/src/internal/application/dev-environment.tsnew file mode 100644index 000000000..acbd09cfc--- /dev/null+++ b/packages/eve/src/internal/application/dev-environment.ts@@ -0,0 +1,7 @@+/** Environment flag set for processes that belong to an `eve dev` session. */+export const EVE_DEV_ENV_FLAG = "EVE_DEV";++/** Reports whether this process belongs to an `eve dev` session. */+export function isEveDevEnvironment(): boolean {+ return process.env[EVE_DEV_ENV_FLAG] === "1";+}diff --git a/packages/eve/src/internal/application/optional-package-install.ts b/packages/eve/src/internal/application/optional-package-install.tsindex b16467a66..1b347f5dc 100644--- a/packages/eve/src/internal/application/optional-package-install.ts+++ b/packages/eve/src/internal/application/optional-package-install.ts@@ -5,19 +5,9 @@ import { dirname, join } from "node:path";import { pathToFileURL } from "node:url";import { Worker } from "node:worker_threads";-/**- * Environment flag set by `eve dev` so runtime code can distinguish the- * interactive development server from production processes. Optional- * engine packages are auto-installed only when this is set.- */-export const EVE_DEV_ENV_FLAG = "EVE_DEV";+import { EVE_DEV_ENV_FLAG, isEveDevEnvironment } from "#internal/application/dev-environment.js";-/**- * Reports whether this process belongs to an `eve dev` session.- */-export function isEveDevEnvironment(): boolean {- return process.env[EVE_DEV_ENV_FLAG] === "1";-}+export { EVE_DEV_ENV_FLAG, isEveDevEnvironment };export type ProjectPackageManager = "bun" | "npm" | "pnpm" | "yarn";diff --git a/packages/eve/src/internal/nitro/dev-client-address.test.ts b/packages/eve/src/internal/nitro/dev-client-address.test.tsnew file mode 100644index 000000000..b42a8dbe8--- /dev/null+++ b/packages/eve/src/internal/nitro/dev-client-address.test.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "vitest";++import {+ DEVELOPMENT_CLIENT_ADDRESS_HEADER,+ DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER,+ readTrustedDevelopmentClientAddress,+ stampDevelopmentClientAddress,+ timingSafeEqualStrings,+} from "#internal/nitro/dev-client-address.js";++const SECRET = "test-transport-secret";++describe("development client address metadata", () => {+ it("round-trips a stamped address through signature verification", () => {+ const headers = new Headers();+ stampDevelopmentClientAddress(headers, "192.168.1.5", SECRET);+ expect(readTrustedDevelopmentClientAddress(headers, SECRET)).toBe("192.168.1.5");+ });++ it("strips forged public copies before stamping", () => {+ const headers = new Headers({+ [DEVELOPMENT_CLIENT_ADDRESS_HEADER]: "203.0.113.7",+ [DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER]: "forged",+ });+ stampDevelopmentClientAddress(headers, "10.0.0.9", SECRET);+ expect(headers.get(DEVELOPMENT_CLIENT_ADDRESS_HEADER)).toBe("10.0.0.9");+ expect(readTrustedDevelopmentClientAddress(headers, SECRET)).toBe("10.0.0.9");+ });++ it("drops the metadata entirely when no secret or address is available", () => {+ const headers = new Headers({+ [DEVELOPMENT_CLIENT_ADDRESS_HEADER]: "203.0.113.7",+ [DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER]: "forged",+ });+ stampDevelopmentClientAddress(headers, undefined, SECRET);+ expect(headers.get(DEVELOPMENT_CLIENT_ADDRESS_HEADER)).toBeNull();+ expect(headers.get(DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER)).toBeNull();+ });++ it("rejects a tampered address or signature", () => {+ const headers = new Headers();+ stampDevelopmentClientAddress(headers, "192.168.1.5", SECRET);+ headers.set(DEVELOPMENT_CLIENT_ADDRESS_HEADER, "203.0.113.7");+ expect(readTrustedDevelopmentClientAddress(headers, SECRET)).toBeUndefined();++ const forged = new Headers({+ [DEVELOPMENT_CLIENT_ADDRESS_HEADER]: "203.0.113.7",+ [DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER]: "not-a-signature",+ });+ expect(readTrustedDevelopmentClientAddress(forged, SECRET)).toBeUndefined();+ });++ it("rejects verification without a secret", () => {+ const headers = new Headers();+ stampDevelopmentClientAddress(headers, "192.168.1.5", SECRET);+ expect(readTrustedDevelopmentClientAddress(headers, undefined)).toBeUndefined();+ expect(readTrustedDevelopmentClientAddress(headers, "")).toBeUndefined();+ });++ it("compares strings without length leakage", () => {+ expect(timingSafeEqualStrings("abc", "abc")).toBe(true);+ expect(timingSafeEqualStrings("abc", "abcd")).toBe(false);+ expect(timingSafeEqualStrings("", "x")).toBe(false);+ });+});diff --git a/packages/eve/src/internal/nitro/dev-client-address.ts b/packages/eve/src/internal/nitro/dev-client-address.tsnew file mode 100644index 000000000..1e79baa9b--- /dev/null+++ b/packages/eve/src/internal/nitro/dev-client-address.ts@@ -0,0 +1,67 @@+import { createHash, createHmac, timingSafeEqual } from "node:crypto";++export const DEVELOPMENT_CLIENT_ADDRESS_HEADER = "x-eve-dev-client-address";+export const DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER = "x-eve-dev-client-address-signature";++/**+ * Stamps the accepted socket's peer address onto a request bound for the+ * dev worker. Public copies of the metadata headers are dropped first, and+ * the value is signed with the per-process dev transport secret: the+ * worker's own HTTP port is reachable by other local processes, so an+ * unsigned header could be forged by anything that discovers it.+ */+export function stampDevelopmentClientAddress(+ headers: Headers,+ address: string | undefined,+ secret: string | undefined,+): void {+ headers.delete(DEVELOPMENT_CLIENT_ADDRESS_HEADER);+ headers.delete(DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER);+ if (+ address === undefined ||+ address.length === 0 ||+ secret === undefined ||+ secret.length === 0+ ) {+ return;+ }+ headers.set(DEVELOPMENT_CLIENT_ADDRESS_HEADER, address);+ headers.set(DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER, signClientAddress(address, secret));+}++/**+ * Returns the parent-stamped client address when its signature verifies,+ * `undefined` otherwise. Callers fall back to the socket peer, which in the+ * proxied dev topology is the parent's loopback hop.+ */+export function readTrustedDevelopmentClientAddress(+ headers: Headers,+ secret: string | undefined,+): string | undefined {+ const address = headers.get(DEVELOPMENT_CLIENT_ADDRESS_HEADER);+ const signature = headers.get(DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER);+ if (+ address === null ||+ signature === null ||+ secret === undefined ||+ secret.length === 0 ||+ !timingSafeEqualStrings(signature, signClientAddress(address, secret))+ ) {+ return undefined;+ }+ return address;+}++/**+ * Constant-time string comparison over fixed-length digests, so neither the+ * length nor the content of a secret comparison leaks through timing.+ */+export function timingSafeEqualStrings(a: string, b: string): boolean {+ const digestA = createHash("sha256").update(a).digest();+ const digestB = createHash("sha256").update(b).digest();+ return timingSafeEqual(digestA, digestB);+}++function signClientAddress(address: string, secret: string): string {+ return createHmac("sha256", secret).update(address).digest("base64url");+}diff --git a/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts b/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.tsindex 89d3b2e98..2ffbd5696 100644--- a/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts+++ b/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts@@ -148,6 +148,9 @@ describe("development runtime artifact snapshots", () => {expect(readDevelopmentRuntimeArtifactsRevision(appRoot)).toEqual({revision: appRoot,});+ expect(+ JSON.parse(await readFile(join(snapshot.snapshotRoot, "generation.json"), "utf8")),+ ).toEqual({ runtimeAppRoot: snapshot.runtimeAppRoot });await activateDevelopmentRuntimeArtifactsSnapshot({ appRoot, snapshot });diff --git a/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts b/packages/eve/src/internal/nitro/dev-runtime-artifacts.tsindex 4c3348c69..65b386bc2 100644--- a/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts+++ b/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts@@ -10,6 +10,7 @@ import { renameWithTransientBusyRetry } from "#shared/rename-with-retry.js";const DEV_RUNTIME_ARTIFACTS_DIRECTORY = "dev-runtime";const DEV_RUNTIME_ARTIFACTS_ACTIVATED_MARKER = "activated";+const DEV_RUNTIME_ARTIFACTS_GENERATION_METADATA = "generation.json";const DEV_RUNTIME_ARTIFACTS_POINTER_VERSION = 2;const DEV_RUNTIME_SNAPSHOT_RECENT_WINDOW_MS = 15 * 60 * 1000;const DEV_RUNTIME_SNAPSHOT_RETAIN_COUNT = 5;@@ -106,6 +107,10 @@ export async function stageDevelopmentRuntimeArtifactsSnapshot(),runtimeAppRoot: sourceSnapshotPlan.runtimeAppRoot,});+ await writeFile(+ join(snapshotRoot, DEV_RUNTIME_ARTIFACTS_GENERATION_METADATA),+ `${JSON.stringify({ runtimeAppRoot: sourceSnapshotPlan.runtimeAppRoot })}\n`,+ );} catch (error) {await rm(snapshotRoot, { force: true, recursive: true }).catch(() => {});throw error;diff --git a/packages/eve/src/internal/nitro/host/artifacts-config.test.ts b/packages/eve/src/internal/nitro/host/artifacts-config.test.tsnew file mode 100644index 000000000..3e4d7fb17--- /dev/null+++ b/packages/eve/src/internal/nitro/host/artifacts-config.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";++import { createDevelopmentNitroArtifactsConfig } from "#internal/nitro/host/artifacts-config.js";+import { resolveNitroCompiledArtifactsSource } from "#internal/nitro/routes/runtime-artifacts.js";+import { serializeDurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";++describe("development artifacts durable strategy", () => {+ it("stores logical generation selectors when the parent owns the World", () => {+ const config = createDevelopmentNitroArtifactsConfig({+ appRoot: "/tmp/eve-test-app",+ });++ const source = resolveNitroCompiledArtifactsSource(config);+ expect(serializeDurableCompiledArtifactsSource(source)).toEqual({ kind: "development" });+ });++ it("treats an explicitly local World as parent-owned", () => {+ const config = createDevelopmentNitroArtifactsConfig({+ appRoot: "/tmp/eve-test-app",+ configuredWorld: "local",+ });++ const source = resolveNitroCompiledArtifactsSource(config);+ expect(serializeDurableCompiledArtifactsSource(source)).toEqual({ kind: "development" });+ });++ it("pins custom-World payloads to their exact snapshot", () => {+ const config = createDevelopmentNitroArtifactsConfig({+ appRoot: "/tmp/eve-test-app",+ configuredWorld: "@workflow/world-postgres",+ });++ // A custom World's deliveries never install eve's generation context,+ // so the durable payload must be resolvable without it.+ const source = resolveNitroCompiledArtifactsSource(config);+ const durable = serializeDurableCompiledArtifactsSource(source);+ expect(durable).toBe(source);+ });+});diff --git a/packages/eve/src/internal/nitro/host/artifacts-config.ts b/packages/eve/src/internal/nitro/host/artifacts-config.tsindex 9cc0b1f21..7b6b405c3 100644--- a/packages/eve/src/internal/nitro/host/artifacts-config.ts+++ b/packages/eve/src/internal/nitro/host/artifacts-config.ts@@ -4,6 +4,8 @@ import type {DevelopmentNitroArtifactsConfig,ProductionNitroArtifactsConfig,} from "#internal/nitro/routes/runtime-artifacts.js";+import { usesParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-protocol.js";+import type { AgentWorkflowWorldDefinition } from "#shared/agent-definition.js";/*** Runtime-artifacts wiring for the dev server: routes read compiled@@ -12,10 +14,17 @@ import type {*/export function createDevelopmentNitroArtifactsConfig(input: {readonly appRoot: string;+ readonly configuredWorld?: AgentWorkflowWorldDefinition;}): DevelopmentNitroArtifactsConfig {return {appRoot: input.appRoot,devRuntimeArtifactsPointerPath: resolveDevelopmentRuntimeArtifactsPointerPath(input.appRoot),+ // Only parent-World deliveries install the generation context that a+ // logical durable selector needs; a custom World's payloads must pin+ // their exact snapshot instead.+ durableArtifactsReference: usesParentDevelopmentWorkflowWorld(input.configuredWorld)+ ? "development-generation"+ : undefined,kind: "development",moduleMapLoaderPath: resolvePackageSourceFilePath("src/internal/authored-module-map-loader.ts"),};diff --git a/packages/eve/src/internal/nitro/host/channel-routes.test.ts b/packages/eve/src/internal/nitro/host/channel-routes.test.tsindex d65c5358a..92e747326 100644--- a/packages/eve/src/internal/nitro/host/channel-routes.test.ts+++ b/packages/eve/src/internal/nitro/host/channel-routes.test.ts@@ -13,7 +13,9 @@ describe("registerChannelVirtualHandlers", () => {};registerChannelVirtualHandlers(nitro, {- artifactsConfig: createDevelopmentNitroArtifactsConfig({ appRoot: "/app" }),+ artifactsConfig: createDevelopmentNitroArtifactsConfig({+ appRoot: "/app",+ }),registrations: [{ cors: {}, method: "POST", route: "/eve/v1/session" }],});@@ -49,7 +51,9 @@ describe("registerChannelVirtualHandlers", () => {};registerChannelVirtualHandlers(nitro, {- artifactsConfig: createDevelopmentNitroArtifactsConfig({ appRoot: "/app" }),+ artifactsConfig: createDevelopmentNitroArtifactsConfig({+ appRoot: "/app",+ }),registrations: [{ cors: {}, method: "GET", route: "/eve/v1/session/:sessionId/events" },{ cors: {}, method: "POST", route: "/eve/v1/session/:sessionId/events" },@@ -73,7 +77,9 @@ describe("registerChannelVirtualHandlers", () => {};registerChannelVirtualHandlers(nitro, {- artifactsConfig: createDevelopmentNitroArtifactsConfig({ appRoot: "/app" }),+ artifactsConfig: createDevelopmentNitroArtifactsConfig({+ appRoot: "/app",+ }),registrations: [{ method: "WEBSOCKET", route: "/voice" }],});diff --git a/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts b/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.tsindex 273551527..0f0526259 100644--- a/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts+++ b/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts@@ -271,7 +271,7 @@ describe("Nitro route configuration", () => {expect(workflowBuilderMocks.build).toHaveBeenCalledOnce();});- it("registers direct workflow queue handlers in dev mode so the worker bypasses HTTP dispatch", async () => {+ it("leaves development queue dispatch to the stable parent", async () => {const root = "/tmp/eve-nitro-direct-handlers";const buildDir = `${root}/nitro`;const nitro = createNitroStub({ buildDir, dev: true, rootDir: root });@@ -281,19 +281,25 @@ describe("Nitro route configuration", () => {const workflowHandlerSource = readWriteFileSourceMatching("/workflow/workflows-handler.mjs");expect(workflowHandlerSource).toContain('import { POST } from "./workflows.mjs";');- expect(workflowHandlerSource).toContain(- 'import "../../.eve/compiled-artifacts-workflow-world.mjs";',- );- expect(workflowHandlerSource).toContain(- 'import { getWorld as __eveGetWorkflowWorld } from "file:///G:/projects/test-eve/node_modules/.pnpm/[email protected]/node_modules/eve/dist/src/compiled/@workflow/core/runtime.js";',+ expect(workflowHandlerSource).not.toContain("registerHandler");+ expect(workflowHandlerSource).not.toContain("__eveGetWorkflowWorld");+ expect(readWriteFileSourceMatching("/workflow/steps-handler.mjs")).toBeUndefined();+ });++ it("keeps configured development World queue dispatch inside the worker", async () => {+ const root = "/tmp/eve-nitro-configured-world-handlers";+ const nitro = createNitroStub({ buildDir: `${root}/nitro`, dev: true, rootDir: root });++ await configureDevelopmentNitroRoutes(+ nitro,+ createPreparedHost({ appRoot: root, workflowWorld: "@workflow/world-postgres" }),);++ const workflowHandlerSource = readWriteFileSourceMatching("/workflow/workflows-handler.mjs");expect(workflowHandlerSource).toContain("const __eveWorkflowWorld = await __eveGetWorkflowWorld();",);- expect(workflowHandlerSource).toContain(- '__eveWorkflowWorld.registerHandler("__eve746573742d6167656e74_wkf_workflow_", POST);',- );- expect(readWriteFileSourceMatching("/workflow/steps-handler.mjs")).toBeUndefined();+ expect(workflowHandlerSource).toContain("__eveWorkflowWorld.registerHandler");});it("bakes the module map loader into the dev schedule handler", async () => {diff --git a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts b/packages/eve/src/internal/nitro/host/configure-nitro-routes.tsindex fdee73ecf..d4f5123df 100644--- a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts+++ b/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts@@ -27,6 +27,7 @@ import type {NitroArtifactsConfig,} from "#internal/nitro/routes/runtime-artifacts.js";import { deriveEveWorkflowQueuePrefix } from "#internal/workflow/queue-namespace.js";+import { usesParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-protocol.js";import {computeChannelRouteRegistrations,registerChannelVirtualHandlers,@@ -395,14 +396,21 @@ export async function configureDevelopmentNitroRoutes(const artifactsConfig = createDevelopmentNitroArtifactsConfig({appRoot: preparedHost.appRoot,+ configuredWorld: preparedHost.compileResult.manifest.config.experimental?.workflow?.world,});registerApplicationRoutes(nitro, preparedHost, artifactsConfig);registerDevelopmentControlRoutes(nitro, artifactsConfig);const workflowBundlePath = join(workflowBuildDirectory, "workflows.mjs");- await registerWorkflowRoute(nitro, preparedHost, workflowBundlePath, [- createWorkflowDirectHandlerEntry(preparedHost, workflowBundlePath),- ]);+ const directHandlers: WorkflowDirectHandlerEntry[] = [];+ if (+ !usesParentDevelopmentWorkflowWorld(+ preparedHost.compileResult.manifest.config.experimental?.workflow?.world,+ )+ ) {+ directHandlers.push(createWorkflowDirectHandlerEntry(preparedHost, workflowBundlePath));+ }+ await registerWorkflowRoute(nitro, preparedHost, workflowBundlePath, directHandlers);nitro.routing.sync();}diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.tsindex c1897376c..8eae554bd 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts@@ -160,7 +160,6 @@ describe("transactional authored rebuild coordinator", () => {appRoot: retryHost.appRoot,generation: retryHost.generation,});-await devServer.close();});@@ -194,7 +193,6 @@ describe("transactional authored rebuild coordinator", () => {expect(mocks.activateDevelopmentGeneration).not.toHaveBeenCalled();expect(mocks.environmentRollback).toHaveBeenCalledOnce();expect(mocks.environmentCommit).not.toHaveBeenCalled();-await devServer.close();});});diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.tsindex ee7888b35..90ec2d955 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts@@ -54,6 +54,16 @@ export async function createDevelopmentAuthoredRebuildCoordinator(input: {});}+/**+ * Serializes authored rebuilds into a transaction whose commit order makes+ * rollback unnecessary: a candidate generation and worker are prepared while+ * the previous worker keeps serving, the ready worker is swapped in first,+ * and the generation pointer is activated second. Workers are+ * generation-neutral (they load authored modules through the pointer), so+ * every intermediate state serves consistent code, and any failure before+ * the swap simply discards the candidate. Failures after the swap must+ * never travel the discard path — see {@link PostCommitDevelopmentRebuildError}.+ */class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentAuthoredRebuildCoordinator {#currentHost: PreparedDevelopmentApplicationHost;#currentHostFingerprint: string;@@ -225,7 +235,10 @@ function startSandboxPrewarmAfterCommit(if (!hasSandboxRelatedChange(host.compileResult.project.agentRoot, changedPaths)) {return;}- const artifactsConfig = createDevelopmentNitroArtifactsConfig({ appRoot: host.appRoot });+ const artifactsConfig = createDevelopmentNitroArtifactsConfig({+ appRoot: host.appRoot,+ configuredWorld: host.compileResult.manifest.config.experimental?.workflow?.world,+ });startDevelopmentSandboxPrewarmInBackground({appRoot: host.appRoot,compiledArtifactsSource: resolveNitroCompiledArtifactsSource(artifactsConfig),diff --git a/packages/eve/src/internal/nitro/host/dev-server-url.ts b/packages/eve/src/internal/nitro/host/dev-server-url.tsnew file mode 100644index 000000000..bcc141153--- /dev/null+++ b/packages/eve/src/internal/nitro/host/dev-server-url.ts@@ -0,0 +1,29 @@+export const DEFAULT_DEVELOPMENT_SERVER_HOST = "127.0.0.1";++const IPV6_LOOPBACK_HOSTNAME = "[::1]";++/**+ * Hostnames Nitro/srvx surface when listening on an IPv6 wildcard interface.+ * They are valid bind targets but invalid as connect targets.+ */+const IPV6_WILDCARD_LISTEN_HOSTNAMES: ReadonlySet<string> = new Set(["[::]", "::"]);++/**+ * Rewrites a server URL whose hostname is a wildcard listen address into a+ * loopback URL on the same address family.+ */+export function normalizeDevelopmentServerClientUrl(serverUrl: string): string {+ const url = new URL(serverUrl);++ if (IPV6_WILDCARD_LISTEN_HOSTNAMES.has(url.hostname)) {+ url.hostname = IPV6_LOOPBACK_HOSTNAME;+ return url.toString();+ }++ if (url.hostname === "0.0.0.0") {+ url.hostname = DEFAULT_DEVELOPMENT_SERVER_HOST;+ return url.toString();+ }++ return serverUrl;+}diff --git a/packages/eve/src/internal/nitro/host/dev-workflow-world-setup.ts b/packages/eve/src/internal/nitro/host/dev-workflow-world-setup.tsnew file mode 100644index 000000000..2d6bd8558--- /dev/null+++ b/packages/eve/src/internal/nitro/host/dev-workflow-world-setup.ts@@ -0,0 +1,91 @@+import { basename } from "node:path";++import { readActiveDevelopmentRuntimeArtifactsSnapshot } from "#internal/nitro/dev-runtime-artifacts.js";+import { normalizeDevelopmentServerClientUrl } from "#internal/nitro/host/dev-server-url.js";+import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";+import {+ createParentDevelopmentWorkflowWorld,+ type ParentDevelopmentWorkflowWorld,+} from "#internal/workflow/development-world-server.js";+import {+ DEVELOPMENT_WORKER_APP_ROOT_ENV,+ DEVELOPMENT_WORKFLOW_SECRET_ENV,+ usesParentDevelopmentWorkflowWorld,+} from "#internal/workflow/development-world-protocol.js";++const WORKFLOW_LOCAL_BASE_URL_ENV = "WORKFLOW_LOCAL_BASE_URL";+const PORT_ENV = "PORT";++export function createDevelopmentWorkflowWorld(input: {+ readonly appRoot: string;+ readonly preparedHost: PreparedDevelopmentApplicationHost;+ readonly transportSecret: string;+}): ParentDevelopmentWorkflowWorld | undefined {+ // A World that does not resolve to the vendored local package stays inside+ // the worker; the parent only owns the local World, which must survive+ // worker replacement. The predicate is shared with the generated worker+ // plugin so the two sides cannot disagree.+ if (+ !usesParentDevelopmentWorkflowWorld(+ input.preparedHost.compileResult.manifest.config.experimental?.workflow?.world,+ )+ ) {+ return undefined;+ }+ return createParentDevelopmentWorkflowWorld({+ agentName: input.preparedHost.compileResult.manifest.config.name,+ appRoot: input.appRoot,+ resolveActiveGenerationId: () => {+ const snapshot = readActiveDevelopmentRuntimeArtifactsSnapshot(input.appRoot);+ if (snapshot === undefined) {+ throw new Error("Development runtime generation is unavailable.");+ }+ return basename(snapshot.snapshotRoot);+ },+ transportSecret: input.transportSecret,+ });+}++export function installWorkflowTransportEnvironment(appRoot: string, secret: string): () => void {+ const previousSecret = process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV];+ const previousAppRoot = process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV];+ process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV] = secret;+ process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV] = appRoot;+ return () => {+ if (previousSecret === undefined) {+ delete process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV];+ } else {+ process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV] = previousSecret;+ }+ if (previousAppRoot === undefined) {+ delete process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV];+ } else {+ process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV] = previousAppRoot;+ }+ };+}++export function installWorkflowLocalQueueEnvironment(serverUrl: string): () => void {+ const previousWorkflowLocalBaseUrl = process.env[WORKFLOW_LOCAL_BASE_URL_ENV];+ const previousPort = process.env[PORT_ENV];+ const url = new URL(normalizeDevelopmentServerClientUrl(serverUrl));++ process.env[WORKFLOW_LOCAL_BASE_URL_ENV] = url.origin;+ if (url.port) {+ process.env[PORT_ENV] = url.port;+ }++ return () => {+ if (previousWorkflowLocalBaseUrl === undefined) {+ delete process.env[WORKFLOW_LOCAL_BASE_URL_ENV];+ } else {+ process.env[WORKFLOW_LOCAL_BASE_URL_ENV] = previousWorkflowLocalBaseUrl;+ }++ if (previousPort === undefined) {+ delete process.env[PORT_ENV];+ } else {+ process.env[PORT_ENV] = previousPort;+ }+ };+}diff --git a/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.scenario.test.ts b/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.scenario.test.tsindex 817ad69ea..c1e1c0db7 100644--- a/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.scenario.test.ts@@ -6,6 +6,11 @@ import {DrainedNitroDevServer,type DrainedDevServerListener,} from "#internal/nitro/host/drained-nitro-dev-server.js";+import {+ DEVELOPMENT_CLIENT_ADDRESS_HEADER,+ DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER,+ readTrustedDevelopmentClientAddress,+} from "#internal/nitro/dev-client-address.js";import type {DevelopmentRunner,DevelopmentRunnerFactory,@@ -357,6 +362,43 @@ describe("drained Nitro dev server", () => {await server.close();});+ it("stamps a signed client address and strips forged copies", async () => {+ const SECRET = "scenario-transport-secret";+ const { createRunner } = createRunnerFactory(async (request) =>+ Response.json({+ address: request.headers.get(DEVELOPMENT_CLIENT_ADDRESS_HEADER),+ signature: request.headers.get(DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER),+ }),+ );+ const server = new DrainedNitroDevServer(LOGGER, createRunner);+ server.setClientAddressSecret(SECRET);+ const listener = await listen(server);+ await server.replaceWorker(replacement("/tmp/first.mjs"));++ const response = await fetch(new URL("/", listener.url), {+ headers: {+ [DEVELOPMENT_CLIENT_ADDRESS_HEADER]: "203.0.113.7",+ [DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER]: "forged",+ },+ });+ const body = (await response.json()) as { address: string | null; signature: string | null };++ // The forged public copy is replaced by the socket peer, and the stamped+ // value carries a signature the worker can verify.+ expect(body.address).toBe("127.0.0.1");+ expect(body.signature).not.toBe("forged");+ const verified = readTrustedDevelopmentClientAddress(+ new Headers({+ [DEVELOPMENT_CLIENT_ADDRESS_HEADER]: body.address ?? "",+ [DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER]: body.signature ?? "",+ }),+ SECRET,+ );+ expect(verified).toBe("127.0.0.1");++ await server.close();+ });+it("answers control requests without admitting them to the worker", async () => {const fetchMock = vi.fn(async () => new Response("worker"));const { createRunner } = createRunnerFactory(fetchMock);diff --git a/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.ts b/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.tsindex 49ad20dbc..6d5f222b3 100644--- a/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.ts+++ b/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.ts@@ -12,6 +12,7 @@ import {type DevelopmentRunner,type DevelopmentRunnerFactory,} from "#internal/nitro/host/dev-runner.js";+import { stampDevelopmentClientAddress } from "#internal/nitro/dev-client-address.js";import { toErrorMessage } from "#shared/errors.js";const RUNNER_READY_TIMEOUT_MS = 60_000;@@ -63,6 +64,7 @@ export class DrainedNitroDevServer {#activeWaiters: Array<() => void> = [];#closePromise: Promise<void> | undefined;#closed = false;+ #clientAddressSecret: string | undefined;#controlHandler: ((request: Request) => Promise<Response | undefined>) | undefined;#pendingSlot: RunnerSlot | undefined;#replaceChain: Promise<void> = Promise.resolve();@@ -80,6 +82,15 @@ export class DrainedNitroDevServer {this.#controlHandler = handler;}+ /**+ * Enables signed client-address metadata on requests forwarded to+ * workers. Without it the worker only ever observes the parent's loopback+ * hop as the request's peer address.+ */+ setClientAddressSecret(secret: string): void {+ this.#clientAddressSecret = secret;+ }+/*** Swaps to a ready worker built from `entry`. Throws without touching the* active worker when the candidate fails readiness. `dispose` is invoked@@ -363,6 +374,11 @@ export class DrainedNitroDevServer {let settle: (() => void) | undefined;try {const publicRequest = createPublicRequest(request, requestAbort.signal);+ stampDevelopmentClientAddress(+ publicRequest.headers,+ request.socket.remoteAddress ?? undefined,+ this.#clientAddressSecret,+ );const controlResponse = await this.#controlHandler?.(publicRequest);if (controlResponse !== undefined) {await writeResponse(response, controlResponse, requestAbort.signal);diff --git a/packages/eve/src/internal/nitro/host/start-development-server.test.ts b/packages/eve/src/internal/nitro/host/start-development-server.test.tsindex 4bf56df7f..a0dee6e2c 100644--- a/packages/eve/src/internal/nitro/host/start-development-server.test.ts+++ b/packages/eve/src/internal/nitro/host/start-development-server.test.ts@@ -18,6 +18,11 @@ const mocks = vi.hoisted(() => {flush: vi.fn(async () => undefined),rebuild: vi.fn(async () => undefined),};+ const mocksWorldInstance = {+ close: vi.fn(async () => undefined),+ handleRequest: vi.fn(async () => undefined),+ start: vi.fn(async () => undefined),+ };const listenerServer = {close: vi.fn(async () => undefined),ready: vi.fn(async () => undefined),@@ -28,6 +33,7 @@ const mocks = vi.hoisted(() => {discardCandidate: vi.fn(async () => undefined),listen: vi.fn(() => listenerServer),replaceWorker: vi.fn(async () => undefined),+ setClientAddressSecret: vi.fn(),setControlHandler: vi.fn(),upgrade: vi.fn(async (_req: unknown, _socket: unknown, _head: unknown) => undefined),waitForActiveRunner: vi.fn(async () => undefined),@@ -73,6 +79,9 @@ const mocks = vi.hoisted(() => {nitro,prepareDevelopmentApplicationHost: vi.fn(async () => ({appRoot: "/tmp/eve-test",+ compileResult: {+ manifest: { config: { name: "test-agent" } },+ },generation: {fingerprint: "test",runtimeAppRoot: "/tmp/eve-test/.eve/dev-runtime/snapshots/test/source/app",@@ -90,6 +99,8 @@ const mocks = vi.hoisted(() => {},})),activateDevelopmentGeneration: vi.fn(async () => undefined),+ createParentDevelopmentWorkflowWorld: vi.fn(() => mocksWorldInstance),+ worldInstance: mocksWorldInstance,discardDevelopmentGeneration: vi.fn(async () => undefined),removeDevelopmentHostWorkspace: vi.fn(async () => undefined),readFile: vi.fn(async (path: string) => {@@ -160,6 +171,10 @@ vi.mock("./dev-host-workspace.js", () => ({removeDevelopmentHostWorkspace: mocks.removeDevelopmentHostWorkspace,}));+vi.mock("#internal/workflow/development-world-server.js", () => ({+ createParentDevelopmentWorkflowWorld: mocks.createParentDevelopmentWorkflowWorld,+}));+vi.mock("#internal/nitro/development-generation.js", () => ({activateDevelopmentGeneration: mocks.activateDevelopmentGeneration,discardDevelopmentGeneration: mocks.discardDevelopmentGeneration,@@ -379,6 +394,12 @@ describe("createDevelopmentServer", () => {},});expect(mocks.pruneLocalSandboxTemplatesInBackground).toHaveBeenCalledWith("/tmp/eve-test");+ expect(mocks.createParentDevelopmentWorkflowWorld).toHaveBeenCalledWith(+ expect.objectContaining({ agentName: "test-agent", appRoot: "/tmp/eve-test" }),+ );+ expect(mocks.worldInstance.start).toHaveBeenCalledOnce();+ expect(process.env.EVE_DEV_WORKFLOW_TRANSPORT_SECRET).toEqual(expect.any(String));+ expect(process.env.EVE_DEV_WORKER_APP_ROOT).toBe("/tmp/eve-test");expect(process.env.WORKFLOW_LOCAL_BASE_URL).toBe("http://127.0.0.1:42123");expect(process.env.PORT).toBe("42123");@@ -391,7 +412,57 @@ describe("createDevelopmentServer", () => {});expect(process.env.WORKFLOW_LOCAL_BASE_URL).toBeUndefined();expect(process.env.PORT).toBeUndefined();+ expect(process.env.EVE_DEV_WORKFLOW_TRANSPORT_SECRET).toBeUndefined();+ expect(process.env.EVE_DEV_WORKER_APP_ROOT).toBeUndefined();expect(process.env.EVE_DEVELOPMENT_SANDBOX_RUN_ID).toBeUndefined();+ expect(mocks.worldInstance.close).toHaveBeenCalledOnce();+ });++ it("serves the parent World for an explicitly local Workflow World", async () => {+ const preparedHost = await mocks.prepareDevelopmentApplicationHost();+ mocks.prepareDevelopmentApplicationHost.mockClear();+ mocks.prepareDevelopmentApplicationHost.mockResolvedValueOnce({+ ...preparedHost,+ compileResult: {+ manifest: {+ config: {+ experimental: { workflow: { world: "local" } },+ name: "test-agent",+ },+ },+ },+ } as never);+ const startDevelopmentServer = await loadStartDevelopmentServer();++ const server = await startDevelopmentServer("/tmp/eve-test");++ // Explicit "local" resolves to the same vendored world as an absent+ // config; the worker plugin wires the parent RPC client for it, so the+ // parent must create the World that serves those calls.+ expect(mocks.createParentDevelopmentWorkflowWorld).toHaveBeenCalledOnce();+ await server.close();+ });++ it("keeps an explicitly configured Workflow World inside the worker", async () => {+ const preparedHost = await mocks.prepareDevelopmentApplicationHost();+ mocks.prepareDevelopmentApplicationHost.mockClear();+ mocks.prepareDevelopmentApplicationHost.mockResolvedValueOnce({+ ...preparedHost,+ compileResult: {+ manifest: {+ config: {+ experimental: { workflow: { world: "@workflow/world-postgres" } },+ name: "test-agent",+ },+ },+ },+ } as never);+ const startDevelopmentServer = await loadStartDevelopmentServer();++ const server = await startDevelopmentServer("/tmp/eve-test");++ expect(mocks.createParentDevelopmentWorkflowWorld).not.toHaveBeenCalled();+ await server.close();});it("uses Eve's default port when no port is requested", async () => {@@ -488,6 +559,19 @@ describe("createDevelopmentServer", () => {await server.close();});+ it("registers the control handler before the workflow World starts delivering", async () => {+ const startDevelopmentServer = await loadStartDevelopmentServer();+ const server = await startDevelopmentServer("/tmp/eve-test");++ const handlerOrder = mocks.devServer.setControlHandler.mock.invocationCallOrder[0];+ const startOrder = mocks.worldInstance.start.mock.invocationCallOrder[0];+ expect(handlerOrder).toBeDefined();+ expect(startOrder).toBeDefined();+ expect(handlerOrder ?? Infinity).toBeLessThan(startOrder ?? 0);++ await server.close();+ });+it("registers a host-owned runtime rebuild handler that forces the live watcher", async () => {const startDevelopmentServer = await loadStartDevelopmentServer();const server = await startDevelopmentServer("/tmp/eve-test");diff --git a/packages/eve/src/internal/nitro/host/start-development-server.ts b/packages/eve/src/internal/nitro/host/start-development-server.tsindex d2ad4a0b2..f3065863b 100644--- a/packages/eve/src/internal/nitro/host/start-development-server.ts+++ b/packages/eve/src/internal/nitro/host/start-development-server.ts@@ -51,38 +51,22 @@ import {activateDevelopmentGeneration,discardDevelopmentGeneration,} from "#internal/nitro/development-generation.js";+import { randomBytes } from "node:crypto";+import {+ createDevelopmentWorkflowWorld,+ installWorkflowLocalQueueEnvironment,+ installWorkflowTransportEnvironment,+} from "#internal/nitro/host/dev-workflow-world-setup.js";+import type { ParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-server.js";+import {+ DEFAULT_DEVELOPMENT_SERVER_HOST,+ normalizeDevelopmentServerClientUrl,+} from "#internal/nitro/host/dev-server-url.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT = 65_535;-const WORKFLOW_LOCAL_BASE_URL_ENV = "WORKFLOW_LOCAL_BASE_URL";const PORT_ENV = "PORT";-const DEFAULT_DEVELOPMENT_SERVER_HOST = "127.0.0.1";-const IPV6_LOOPBACK_HOSTNAME = "[::1]";--/**- * Hostnames Nitro/srvx surface when listening on an IPv6 wildcard interface.- * They are valid bind targets but invalid as connect targets.- */-const IPV6_WILDCARD_LISTEN_HOSTNAMES: ReadonlySet<string> = new Set(["[::]", "::"]);--/**- * Rewrites a server URL whose hostname is a wildcard listen address into a- * loopback URL on the same address family.- */-export function normalizeDevelopmentServerClientUrl(serverUrl: string): string {- const url = new URL(serverUrl);-- if (IPV6_WILDCARD_LISTEN_HOSTNAMES.has(url.hostname)) {- url.hostname = IPV6_LOOPBACK_HOSTNAME;- return url.toString();- }- if (url.hostname === "0.0.0.0") {- url.hostname = DEFAULT_DEVELOPMENT_SERVER_HOST;- return url.toString();- }-- return serverUrl;-}+export { normalizeDevelopmentServerClientUrl };/*** Returns whether a supplied URL identifies this app's healthy local development@@ -209,37 +193,17 @@ function resolveDevelopmentServerPorts(input: {return ports as [number, ...number[]];}-function installWorkflowLocalQueueEnvironment(serverUrl: string): () => void {- const previousWorkflowLocalBaseUrl = process.env[WORKFLOW_LOCAL_BASE_URL_ENV];- const previousPort = process.env[PORT_ENV];- const url = new URL(normalizeDevelopmentServerClientUrl(serverUrl));-- process.env[WORKFLOW_LOCAL_BASE_URL_ENV] = url.origin;- if (url.port) {- process.env[PORT_ENV] = url.port;- }-- return () => {- if (previousWorkflowLocalBaseUrl === undefined) {- delete process.env[WORKFLOW_LOCAL_BASE_URL_ENV];- } else {- process.env[WORKFLOW_LOCAL_BASE_URL_ENV] = previousWorkflowLocalBaseUrl;- }-- if (previousPort === undefined) {- delete process.env[PORT_ENV];- } else {- process.env[PORT_ENV] = previousPort;- }- };-}--function addDevelopmentRuntimeArtifactsRebuildHandler(input: {+function addDevelopmentControlHandler(input: {readonly appRoot: string;readonly devServer: DrainedNitroDevServer;- readonly watcher: AuthoredSourceWatcherHandle;+ readonly getWatcher: () => AuthoredSourceWatcherHandle | undefined;+ readonly workflowWorld: ParentDevelopmentWorkflowWorld | undefined;}): void {input.devServer.setControlHandler(async (request) => {+ const worldResponse = await input.workflowWorld?.handleRequest(request);+ if (worldResponse !== undefined) {+ return worldResponse;+ }const url = new URL(request.url);if (url.pathname === EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH && request.method === "GET") {return handleDevRuntimeArtifactsRequest({ appRoot: input.appRoot });@@ -247,10 +211,14 @@ function addDevelopmentRuntimeArtifactsRebuildHandler(input: {if (url.pathname !== EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH || request.method !== "GET") {return undefined;}+ const watcher = input.getWatcher();+ if (watcher === undefined) {+ return Response.json({ error: "The development server is still starting." }, { status: 503 });+ }if (url.searchParams.get("force") === "1") {- await input.watcher.rebuild();+ await watcher.rebuild();} else {- await input.watcher.flush();+ await watcher.flush();}return handleDevRuntimeArtifactsRequest({ appRoot: input.appRoot });});@@ -261,6 +229,7 @@ async function closeDevelopmentServerResources(input: {readonly devServer: NitroDevelopmentServer | undefined;readonly developmentSandboxRunId: string;readonly nitro: Nitro | undefined;+ readonly workflowWorld: ParentDevelopmentWorkflowWorld | undefined;}): Promise<{ readonly errors: readonly unknown[]; readonly listenerClosed: boolean }> {const errors: unknown[] = [];const attempt = async (operation: () => Promise<void>): Promise<boolean> => {@@ -279,6 +248,10 @@ async function closeDevelopmentServerResources(input: {}const devServer = input.devServer;const listenerClosed = devServer === undefined ? true : await attempt(() => devServer.close());+ const workflowWorld = input.workflowWorld;+ if (workflowWorld !== undefined) {+ await attempt(() => workflowWorld.close());+ }const nitro = input.nitro;if (nitro !== undefined) {await attempt(() => nitro.close());@@ -410,6 +383,8 @@ async function startNitroDevelopmentServer(let nitro: Nitro | undefined;let devServer: NitroDevelopmentServer | undefined;let restoreWorkflowLocalQueueEnvironment: (() => void) | undefined;+ let restoreWorkflowTransportEnvironment: (() => void) | undefined;+ let workflowWorld: ParentDevelopmentWorkflowWorld | undefined;let authoredSourceWatcher: AuthoredSourceWatcherHandle | undefined;let preparedDevelopmentHost: PreparedDevelopmentApplicationHost | undefined;let initialGenerationPublished = false;@@ -425,6 +400,7 @@ async function startNitroDevelopmentServer(const compiledArtifactsSource = resolveNitroCompiledArtifactsSource(createDevelopmentNitroArtifactsConfig({appRoot: preparedHost.appRoot,+ configuredWorld: preparedHost.compileResult.manifest.config.experimental?.workflow?.world,}),);pruneLocalSandboxTemplatesInBackground(preparedHost.appRoot);@@ -436,6 +412,26 @@ async function startNitroDevelopmentServer(nitro = activeNitro;devServer = new DrainedNitroDevServer(activeNitro.logger);const activeDevServer = devServer;+ const workflowTransportSecret = randomBytes(32).toString("base64url");+ activeDevServer.setClientAddressSecret(workflowTransportSecret);+ restoreWorkflowTransportEnvironment = installWorkflowTransportEnvironment(+ project.appRoot,+ workflowTransportSecret,+ );+ workflowWorld = createDevelopmentWorkflowWorld({+ appRoot: project.appRoot,+ preparedHost,+ transportSecret: workflowTransportSecret,+ });+ // Parent-owned control routes must answer before the World starts: queue+ // redelivery begins at start(), and a delivery's World calls would+ // otherwise fall through to the worker and 404.+ addDevelopmentControlHandler({+ appRoot: project.appRoot,+ devServer: activeDevServer,+ getWatcher: () => authoredSourceWatcher,+ workflowWorld,+ });const hostname =options.host ?? activeNitro.options.devServer.hostname ?? DEFAULT_DEVELOPMENT_SERVER_HOST;const retryOnAddressInUse = requestedPort === undefined;@@ -480,6 +476,7 @@ async function startNitroDevelopmentServer(},options.onBootProgress,);+ await workflowWorld?.start();startDevelopmentSandboxPrewarmInBackground({appRoot: preparedHost.appRoot,compiledArtifactsSource,@@ -502,11 +499,6 @@ async function startNitroDevelopmentServer(},options.onBootProgress,);- addDevelopmentRuntimeArtifactsRebuildHandler({- appRoot: project.appRoot,- devServer: activeDevServer,- watcher: authoredSourceWatcher,- });await state.write(serverUrl);const restoreWorkflowLocalQueueEnvironmentOnClose = restoreWorkflowLocalQueueEnvironment;if (restoreWorkflowLocalQueueEnvironmentOnClose === undefined) {@@ -515,6 +507,8 @@ async function startNitroDevelopmentServer(const authoredSourceWatcherOnClose = authoredSourceWatcher;const devServerOnClose = devServer;+ const workflowWorldOnClose = workflowWorld;+ const restoreWorkflowTransportEnvironmentOnClose = restoreWorkflowTransportEnvironment;let closePromise: Promise<void> | undefined;const close = (): Promise<void> => {closePromise ??= (async () => {@@ -523,6 +517,7 @@ async function startNitroDevelopmentServer(devServer: devServerOnClose,developmentSandboxRunId,nitro: undefined,+ workflowWorld: workflowWorldOnClose,});if (cleanup.listenerClosed) {await state.remove().catch(() => {});@@ -536,6 +531,7 @@ async function startNitroDevelopmentServer(} finally {clearInitializedDevelopmentSandboxBackendNames(developmentSandboxRunId);restoreWorkflowLocalQueueEnvironmentOnClose();+ restoreWorkflowTransportEnvironmentOnClose?.();restoreDevelopmentSandboxRunId(previousDevelopmentSandboxRunId);}})();@@ -551,6 +547,7 @@ async function startNitroDevelopmentServer(devServer,developmentSandboxRunId,nitro,+ workflowWorld,});const cleanupErrors = [...cleanup.errors];if (preparedDevelopmentHost !== undefined && !initialGenerationPublished) {@@ -568,6 +565,7 @@ async function startNitroDevelopmentServer();}restoreWorkflowLocalQueueEnvironment?.();+ restoreWorkflowTransportEnvironment?.();clearInitializedDevelopmentSandboxBackendNames(developmentSandboxRunId);if (cleanup.listenerClosed) {await state.remove().catch(() => {});diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex a01e2b290..10c9b9e63 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -9,6 +9,8 @@ import type { RouteHandlerArgs, WebSocketRouteHooks } from "#channel/routes.js";import { createSendFn } from "#channel/send.js";import { createGetSessionFn } from "#channel/session.js";import { createLogger, logError } from "#internal/logging.js";+import { readTrustedDevelopmentClientAddress } from "#internal/nitro/dev-client-address.js";+import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";import { attachAgentInfoRouteResponse } from "#internal/nitro/routes/channel-route-context.js";import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";import { resolveNitroChannelRuntimeBundle } from "#internal/nitro/routes/runtime-stack.js";@@ -167,7 +169,7 @@ function buildRouteArgs(config: NitroArtifactsConfig,): BuiltRouteArgs {const requestId = readVercelRequestId(event.req.headers);- const requestIp = extractSocketIp(event);+ const requestIp = extractRequestIp(event, config);const backgroundTasks: Promise<unknown>[] = [];const rawParams = (event.context.params as Record<string, string>) ?? {};const params: Record<string, string> = {};@@ -270,6 +272,21 @@ function flushBackgroundTasks();}+function extractRequestIp(event: H3Event, config: NitroArtifactsConfig): string | null {+ if (config.kind === "development") {+ // In the proxied dev topology the socket peer is the parent's loopback+ // hop; the original client address arrives as parent-signed metadata.+ const trusted = readTrustedDevelopmentClientAddress(+ event.req.headers,+ process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV],+ );+ if (trusted !== undefined) {+ return trusted;+ }+ }+ return extractSocketIp(event);+}+function extractSocketIp(event: H3Event): string | null {const ip = event.req.ip;return typeof ip === "string" && ip.length > 0 ? ip : null;diff --git a/packages/eve/src/internal/nitro/routes/runtime-artifacts.ts b/packages/eve/src/internal/nitro/routes/runtime-artifacts.tsindex a4e65679f..42161bec5 100644--- a/packages/eve/src/internal/nitro/routes/runtime-artifacts.ts+++ b/packages/eve/src/internal/nitro/routes/runtime-artifacts.ts@@ -14,6 +14,13 @@ import { readDevelopmentRuntimeArtifactsSnapshotRoot } from "#internal/nitro/devexport interface DevelopmentNitroArtifactsConfig {readonly appRoot: string;readonly devRuntimeArtifactsPointerPath: string;+ /**+ * Set when durable Workflow payloads may store a logical generation+ * selector instead of this source's exact snapshot path. Only true when+ * the parent-owned dev World delivers the queue, because only those+ * deliveries install the context that resolves the selector.+ */+ readonly durableArtifactsReference?: "development-generation";readonly kind: "development";readonly moduleMapLoaderPath: string;}@@ -37,6 +44,7 @@ export function resolveNitroCompiledArtifactsSource(config.appRoot;return createDiskRuntimeCompiledArtifactsSource(runtimeAppRoot, {+ durableReference: config.durableArtifactsReference,moduleMapLoaderPath: config.moduleMapLoaderPath,sandboxAppRoot: config.appRoot,});diff --git a/packages/eve/src/internal/workflow/development-generation-context.ts b/packages/eve/src/internal/workflow/development-generation-context.tsnew file mode 100644index 000000000..d7da36b3a--- /dev/null+++ b/packages/eve/src/internal/workflow/development-generation-context.ts@@ -0,0 +1,25 @@+import { ContextContainer, contextStorage } from "#context/container.js";+import { ContextKey } from "#context/key.js";+import type { RuntimeDiskCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";++interface DevelopmentGenerationContext {+ readonly generationId: string;+ readonly source: RuntimeDiskCompiledArtifactsSource;+}++const DevelopmentGenerationKey = new ContextKey<DevelopmentGenerationContext>(+ "eve.internal.developmentGeneration",+);++export function getDevelopmentWorkflowGeneration(): DevelopmentGenerationContext | undefined {+ return contextStorage.getStore()?.get(DevelopmentGenerationKey);+}++export async function withDevelopmentWorkflowGeneration<T>(+ context: DevelopmentGenerationContext,+ operation: () => Promise<T>,+): Promise<T> {+ const ctx = new ContextContainer();+ ctx.setVirtualContext(DevelopmentGenerationKey, context);+ return await contextStorage.run(ctx, operation);+}diff --git a/packages/eve/src/internal/workflow/development-world-client.ts b/packages/eve/src/internal/workflow/development-world-client.tsnew file mode 100644index 000000000..c3a402f4e--- /dev/null+++ b/packages/eve/src/internal/workflow/development-world-client.ts@@ -0,0 +1,342 @@+import type {+ MessageId,+ QueuePrefix,+ SpecVersion,+ ValidQueueName,+ World,+} from "#compiled/@workflow/world/index.js";+import { resolvePackageSourceFilePath } from "#internal/application/package.js";+import { readFile } from "node:fs/promises";+import { basename, join } from "node:path";++import { turnWorkflowReference } from "#execution/workflow-runtime.js";+import {+ decodeDevelopmentWorldJson,+ decodeDevelopmentWorldValue,+ deserializeDevelopmentWorldError,+ encodeDevelopmentWorldValue,+} from "#internal/workflow/development-world-codec.js";+import {+ getDevelopmentWorkflowGeneration,+ withDevelopmentWorkflowGeneration,+} from "#internal/workflow/development-generation-context.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,+ type DevelopmentWorldCall,+ type DevelopmentWorldOperation,+} from "#internal/workflow/development-world-protocol.js";+import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { timingSafeEqualStrings } from "#internal/nitro/dev-client-address.js";++const WORKFLOW_LOCAL_BASE_URL_ENV = "WORKFLOW_LOCAL_BASE_URL";++/**+ * Raised when a delivery's recorded generation no longer exists on disk.+ * This never heals on retry, so the queue handler acknowledges and drops+ * the delivery instead of letting the queue redeliver it for its full+ * retry budget.+ */+export class MissingDevelopmentGenerationError extends Error {+ constructor(generationId: string, cause?: unknown) {+ super(+ `Workflow run references missing development generation "${generationId}". ` ++ `Remove ".workflow-data" to discard the app's active local Workflow runs.`,+ cause === undefined ? undefined : { cause },+ );+ this.name = "MissingDevelopmentGenerationError";+ }+}++async function call<T>(+ operation: DevelopmentWorldOperation,+ args: readonly unknown[] = [],+): Promise<T> {+ const response = await fetchDevelopmentWorld(DEVELOPMENT_WORKFLOW_WORLD_ROUTE, {+ body: encodeDevelopmentWorldValue({+ arguments: args,+ operation,+ } satisfies DevelopmentWorldCall),+ method: "POST",+ });+ return decodeDevelopmentWorldValue(await response.text()) as T;+}++/**+ * Worker-side Workflow World: an interface-faithful shim whose every method+ * forwards to the real local World in the CLI parent process.+ *+ * Why: a dev worker is disposed on every structural reload, so nothing with+ * run lifetime may live inside it. The `World` interface is already fully+ * async because production Worlds are remote services — inserting HTTP+ * between the runtime and the World changes topology, not semantics, and+ * makes development match production's compute/state split. The runtime+ * cannot observe the difference, so `@workflow/core` needs no changes and+ * this file is deletable the day a multi-process local World ships upstream.+ *+ * Two members are not simple forwards. `streams.get` must return a live+ * `ReadableStream`, so it uses a dedicated route and hands back the response+ * body. `createQueueHandler` points the other way entirely: it returns the+ * HTTP handler that the parent's queue posts deliveries into, and is where a+ * delivery gets pinned to the generation its run started on.+ */+export function createDevelopmentWorkflowWorld(): World {+ const forwarded = buildForwardedOperations();+ const world = {+ specVersion: 5 as SpecVersion,+ processExitTriggersQueueRedelivery: false,+ async getDeploymentId() {+ // Inside a pinned delivery, steps and child runs must record the+ // delivery's generation — not whatever is active — so replay after a+ // reload returns to the same authored modules.+ return (+ getDevelopmentWorkflowGeneration()?.generationId ?? (await call<string>("getDeploymentId"))+ );+ },+ resolveLatestDeploymentId: forwarded.topLevel+ .resolveLatestDeploymentId as World["resolveLatestDeploymentId"],+ queue: forwarded.topLevel.queue as World["queue"],+ createQueueHandler,+ runs: forwarded.groups.runs as World["runs"],+ steps: forwarded.groups.steps as World["steps"],+ events: forwarded.groups.events as World["events"],+ hooks: forwarded.groups.hooks as World["hooks"],+ streams: {+ ...forwarded.groups.streams,+ // A live stream cannot ride the value codec; it flows through a+ // dedicated route as a raw response body.+ get: async (runId: string, name: string, startIndex?: number) => {+ const url = new URL(resolveDevelopmentWorldBaseUrl());+ url.pathname = DEVELOPMENT_WORKFLOW_STREAM_ROUTE;+ url.searchParams.set("runId", runId);+ url.searchParams.set("name", name);+ if (startIndex !== undefined) {+ url.searchParams.set("startIndex", String(startIndex));+ }+ const response = await fetchDevelopmentWorld(url, { method: "GET" });+ if (response.body === null) {+ throw new Error("Development Workflow stream response had no body.");+ }+ return response.body;+ },+ } as World["streams"],+ async start() {},+ async close() {},+ } satisfies World;++ return world;+}++type ForwardedOperation = (...args: unknown[]) => Promise<unknown>;++/**+ * Generates one forwarding method per entry in the shared operation table,+ * so the client's surface tracks the table instead of hand-written stubs.+ */+function buildForwardedOperations(): {+ readonly groups: Readonly<Record<string, Readonly<Record<string, ForwardedOperation>>>>;+ readonly topLevel: Readonly<Record<string, ForwardedOperation>>;+} {+ const groups: Record<string, Record<string, ForwardedOperation>> = {};+ const topLevel: Record<string, ForwardedOperation> = {};+ for (const operation of DEVELOPMENT_WORLD_OPERATIONS) {+ const forward: ForwardedOperation = async (...args) => await call(operation, args);+ const separator = operation.indexOf(".");+ if (separator === -1) {+ topLevel[operation] = forward;+ } else {+ (groups[operation.slice(0, separator)] ??= {})[operation.slice(separator + 1)] = forward;+ }+ }+ return { groups, topLevel };+}++function createQueueHandler(+ prefix: QueuePrefix,+ handler: (+ message: unknown,+ metadata: {+ attempt: number;+ queueName: ValidQueueName;+ messageId: MessageId;+ requestId?: string;+ },+ ) => Promise<void | { timeoutSeconds: number }>,+): (request: Request) => Promise<Response> {+ return async (request) => {+ const secret = readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV);+ const deliveryHeader = request.headers.get(DEVELOPMENT_WORKFLOW_DELIVERY_HEADER);+ if (deliveryHeader === null || !timingSafeEqualStrings(deliveryHeader, secret)) {+ return Response.json({ error: "Workflow delivery is not trusted." }, { status: 401 });+ }+ const queueName = request.headers.get("x-vqs-queue-name");+ const messageId = request.headers.get("x-vqs-message-id");+ const attempt = Number(request.headers.get("x-vqs-message-attempt"));+ if (+ queueName === null ||+ !queueName.startsWith(prefix) ||+ messageId === null ||+ !Number.isInteger(attempt) ||+ attempt < 1 ||+ request.body === null+ ) {+ return Response.json({ error: "Workflow delivery is malformed." }, { status: 400 });+ }+ const message = decodeDevelopmentWorldJson(await request.text());+ try {+ const appRoot = readRequiredEnvironment(DEVELOPMENT_WORKER_APP_ROOT_ENV);+ const generationId = await resolveDeliveryGenerationId(message);+ const runtimeAppRoot = await readGenerationRuntimeAppRoot(appRoot, generationId);+ const result = await withDevelopmentWorkflowGeneration(+ {+ generationId,+ source: createDiskRuntimeCompiledArtifactsSource(runtimeAppRoot, {+ durableReference: "development-generation",+ moduleMapLoaderPath: resolvePackageSourceFilePath(+ "src/internal/authored-module-map-loader.ts",+ ),+ sandboxAppRoot: appRoot,+ }),+ },+ async () =>+ await handler(message, {+ attempt,+ messageId: messageId as MessageId,+ queueName: queueName as ValidQueueName,+ }),+ );+ return Response.json(+ result === undefined ? { ok: true } : { timeoutSeconds: result.timeoutSeconds },+ );+ } catch (error) {+ if (error instanceof MissingDevelopmentGenerationError) {+ // Retrying cannot bring the generation back; acknowledge the+ // delivery so the queue stops redelivering, and leave the loud+ // error for the user to act on.+ console.error(`[eve:dev] ${error.message}`);+ return Response.json({ ok: true });+ }+ return Response.json(String(error), { status: 500 });+ }+ };+}++/**+ * Resolves the generation a delivery executes against. Selection trusts two+ * sources: run records owned by the parent World, and — for the first+ * delivery of a resilient start, which can arrive before its run record is+ * persisted — the `runInput.deploymentId` carried in the delivery body+ * itself. The body is trustworthy because deliveries are produced only by+ * the parent's queue and authenticated with the transport secret; nothing+ * an untrusted caller controls participates.+ */+async function resolveDeliveryGenerationId(message: unknown): Promise<string> {+ if (!isRecord(message)) {+ return await call<string>("resolveLatestDeploymentId");+ }+ const runInput = isRecord(message.runInput) ? message.runInput : undefined;+ if (runInput !== undefined) {+ return runInput.workflowName === turnWorkflowReference.workflowId &&+ typeof runInput.deploymentId === "string"+ ? runInput.deploymentId+ : await call<string>("resolveLatestDeploymentId");+ }+ const runId =+ typeof message.runId === "string"+ ? message.runId+ : typeof message.workflowRunId === "string"+ ? message.workflowRunId+ : undefined;+ if (runId === undefined) {+ return await call<string>("resolveLatestDeploymentId");+ }+ const run = await call<{ readonly deploymentId: string; readonly workflowName: string }>(+ "runs.get",+ [runId, { resolveData: "none" }],+ );+ return run.workflowName === turnWorkflowReference.workflowId+ ? run.deploymentId+ : await call<string>("resolveLatestDeploymentId");+}++async function readGenerationRuntimeAppRoot(+ appRoot: string,+ generationId: string,+): Promise<string> {+ if (+ generationId.length === 0 ||+ generationId === "." ||+ generationId === ".." ||+ basename(generationId) !== generationId+ ) {+ throw new Error(`Workflow run references invalid development generation "${generationId}".`);+ }+ const metadataPath = join(+ appRoot,+ ".eve",+ "dev-runtime",+ "snapshots",+ generationId,+ "generation.json",+ );+ let metadata: unknown;+ try {+ metadata = JSON.parse(await readFile(metadataPath, "utf8"));+ } catch (error) {+ throw new MissingDevelopmentGenerationError(generationId, error);+ }+ if (!isRecord(metadata) || typeof metadata.runtimeAppRoot !== "string") {+ throw new Error(`Development generation "${generationId}" has invalid metadata.`);+ }+ return metadata.runtimeAppRoot;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++async function fetchDevelopmentWorld(route: string | URL, init: RequestInit): Promise<Response> {+ const url = route instanceof URL ? route : new URL(route, resolveDevelopmentWorldBaseUrl());+ const headers = new Headers(init.headers);+ headers.set(+ DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,+ readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV),+ );+ const response = await fetch(url, { ...init, headers });+ if (!response.ok) {+ const source = await response.text();+ const error = readDevelopmentWorldError(source);+ if (error !== undefined) {+ throw error;+ }+ throw new Error(+ `Development Workflow World request failed (${String(response.status)}): ${source}`,+ );+ }+ return response;+}++function readDevelopmentWorldError(source: string): Error | undefined {+ try {+ return deserializeDevelopmentWorldError(decodeDevelopmentWorldValue(source));+ } catch {+ return undefined;+ }+}++function resolveDevelopmentWorldBaseUrl(): string {+ return readRequiredEnvironment(WORKFLOW_LOCAL_BASE_URL_ENV);+}++function readRequiredEnvironment(name: string): string {+ const value = process.env[name];+ if (value === undefined || value.length === 0) {+ throw new Error(`Development Workflow transport is missing ${name}.`);+ }+ return value;+}diff --git a/packages/eve/src/internal/workflow/development-world-codec.test.ts b/packages/eve/src/internal/workflow/development-world-codec.test.tsnew file mode 100644index 000000000..89282cb85--- /dev/null+++ b/packages/eve/src/internal/workflow/development-world-codec.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";++import {+ decodeDevelopmentWorldValue,+ deserializeDevelopmentWorldError,+ encodeDevelopmentWorldValue,+ serializeDevelopmentWorldError,+} from "#internal/workflow/development-world-codec.js";++describe("development Workflow World codec", () => {+ it("preserves dates, bytes, and undefined values across the private transport", () => {+ const createdAt = new Date("2026-07-13T12:00:00.000Z");++ expect(+ decodeDevelopmentWorldValue(+ encodeDevelopmentWorldValue({+ createdAt,+ input: new Uint8Array([1, 2, 3]),+ output: undefined,+ }),+ ),+ ).toEqual({ createdAt, input: new Uint8Array([1, 2, 3]), output: undefined });+ });++ it("preserves World error identity and retry metadata", () => {+ const source = Object.assign(new Error("try later"), {+ name: "WorkflowWorldError",+ retryAfter: 3,+ });++ const error = deserializeDevelopmentWorldError(serializeDevelopmentWorldError(source));++ expect(error).toMatchObject({+ message: "try later",+ name: "WorkflowWorldError",+ retryAfter: 3,+ });+ });+});diff --git a/packages/eve/src/internal/workflow/development-world-codec.ts b/packages/eve/src/internal/workflow/development-world-codec.tsnew file mode 100644index 000000000..73fff38a0--- /dev/null+++ b/packages/eve/src/internal/workflow/development-world-codec.ts@@ -0,0 +1,113 @@+// World values are not plain JSON: run records carry Dates, stream chunks+// carry Uint8Arrays, and rejections must rehydrate into real Errors on the+// caller's side so the workflow runtime observes the same values it would+// from an in-process World. This codec exists only to preserve those shapes+// across the parent/worker HTTP boundary.+const VALUE_TYPE_KEY = "__eveDevelopmentWorldType";+const DATE_MARKER = "date";+const UINT8_ARRAY_MARKER = "uint8-array";+const UNDEFINED_MARKER = "undefined";++interface EncodedValue {+ readonly [VALUE_TYPE_KEY]: string;+ readonly data?: string;+}++export interface SerializedDevelopmentWorldError {+ readonly details: Readonly<Record<string, unknown>>;+ readonly message: string;+ readonly name: string;+ readonly stack?: string;+}++export function encodeDevelopmentWorldValue(value: unknown): string {+ return JSON.stringify({ value: encodeValue(value) });+}++export function decodeDevelopmentWorldValue(source: string): unknown {+ const decoded = decodeDevelopmentWorldJson(source) as { readonly value?: unknown };+ return decoded.value;+}++export function decodeDevelopmentWorldJson(source: string): unknown {+ return decodeValue(JSON.parse(source) as unknown);+}++export function serializeDevelopmentWorldError(error: unknown): SerializedDevelopmentWorldError {+ if (!(error instanceof Error)) {+ return { details: {}, message: String(error), name: "Error" };+ }+ return {+ details: Object.fromEntries(Object.entries(error)),+ message: error.message,+ name: error.name,+ stack: error.stack,+ };+}++export function deserializeDevelopmentWorldError(value: unknown): Error | undefined {+ if (!isRecord(value) || !isRecord(value.details)) {+ return undefined;+ }+ if (typeof value.message !== "string" || typeof value.name !== "string") {+ return undefined;+ }+ const error = new Error(value.message);+ error.name = value.name;+ if (typeof value.stack === "string") {+ error.stack = value.stack;+ }+ Object.assign(error, value.details);+ return error;+}++function encodeValue(value: unknown): unknown {+ if (value === undefined) {+ return { [VALUE_TYPE_KEY]: UNDEFINED_MARKER } satisfies EncodedValue;+ }+ if (value instanceof Date) {+ return {+ [VALUE_TYPE_KEY]: DATE_MARKER,+ data: value.toISOString(),+ } satisfies EncodedValue;+ }+ if (value instanceof Uint8Array) {+ return {+ [VALUE_TYPE_KEY]: UINT8_ARRAY_MARKER,+ data: Buffer.from(value).toString("base64"),+ } satisfies EncodedValue;+ }+ if (Array.isArray(value)) {+ return value.map((item) => encodeValue(item));+ }+ if (isRecord(value)) {+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encodeValue(item)]));+ }+ return value;+}++function decodeValue(value: unknown): unknown {+ if (Array.isArray(value)) {+ return value.map((item) => decodeValue(item));+ }+ if (!isRecord(value)) {+ return value;+ }+ if (value[VALUE_TYPE_KEY] === UNDEFINED_MARKER) {+ return undefined;+ }+ if (value[VALUE_TYPE_KEY] === DATE_MARKER && typeof value.data === "string") {+ return new Date(value.data);+ }+ if (+ (value[VALUE_TYPE_KEY] === UINT8_ARRAY_MARKER || value.__type === "Uint8Array") &&+ typeof value.data === "string"+ ) {+ return Uint8Array.from(Buffer.from(value.data, "base64"));+ }+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, decodeValue(item)]));+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/packages/eve/src/internal/workflow/development-world-protocol.ts b/packages/eve/src/internal/workflow/development-world-protocol.tsnew file mode 100644index 000000000..4756b84a6--- /dev/null+++ b/packages/eve/src/internal/workflow/development-world-protocol.ts@@ -0,0 +1,67 @@+import { getWorldImport } from "@workflow/utils";++import type { AgentWorkflowWorldDefinition } from "#shared/agent-definition.js";++export const DEVELOPMENT_WORKFLOW_WORLD_ROUTE = "/eve/v1/dev/internal/workflow-world";++/**+ * Whether development serves this app's Workflow World from the CLI parent.+ * The parent's world creation and the generated worker plugin must agree on+ * this predicate: a worker wired for the parent RPC client fails every World+ * call when the parent never created a World to serve it. An explicit+ * `world: "local"` resolves to the same vendored world as an absent config,+ * so both take the parent-owned path.+ */+export function usesParentDevelopmentWorkflowWorld(+ configuredWorld: AgentWorkflowWorldDefinition | undefined,+): boolean {+ return (+ getWorldImport({ WORKFLOW_TARGET_WORLD: configuredWorld ?? "local" }) ===+ "@workflow/world-local"+ );+}+export const DEVELOPMENT_WORKFLOW_SECRET_ENV = "EVE_DEV_WORKFLOW_TRANSPORT_SECRET";+export const DEVELOPMENT_WORKER_APP_ROOT_ENV = "EVE_DEV_WORKER_APP_ROOT";+export const DEVELOPMENT_WORKFLOW_STREAM_ROUTE = `${DEVELOPMENT_WORKFLOW_WORLD_ROUTE}/stream`;+export const DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER = "x-eve-dev-workflow-transport";+export const DEVELOPMENT_WORKFLOW_DELIVERY_HEADER = "x-eve-dev-workflow-delivery";++/**+ * The single source of truth for World operations forwarded over the dev+ * RPC: the worker client generates its method forwards from this list and+ * the parent dispatches by walking the same dot-path on the real world, so+ * adapting to a vendored-world interface change is one entry here. The+ * members NOT listed are the deliberate exceptions — `streams.get` returns+ * a live stream over its own route, `createQueueHandler` runs entirely in+ * the worker, and `start`/`close` belong to the parent's lifecycle.+ */+export const 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",+] as const;++export type DevelopmentWorldOperation = (typeof DEVELOPMENT_WORLD_OPERATIONS)[number];++export interface DevelopmentWorldCall {+ readonly arguments: readonly unknown[];+ readonly operation: DevelopmentWorldOperation;+}diff --git a/packages/eve/src/internal/workflow/development-world-server.integration.test.ts b/packages/eve/src/internal/workflow/development-world-server.integration.test.tsnew file mode 100644index 000000000..9468bfea6--- /dev/null+++ b/packages/eve/src/internal/workflow/development-world-server.integration.test.ts@@ -0,0 +1,362 @@+import { access, mkdir, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";++import { afterEach, describe, expect, it, vi } from "vitest";++import { turnWorkflowReference, workflowEntryReference } from "#execution/workflow-runtime.js";+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";+import { getDevelopmentWorkflowGeneration } from "#internal/workflow/development-generation-context.js";+import { deriveEveWorkflowQueuePrefix } from "#internal/workflow/queue-namespace.js";+import {+ decodeDevelopmentWorldValue,+ encodeDevelopmentWorldValue,+} from "#internal/workflow/development-world-codec.js";+import { createDevelopmentWorkflowWorld } from "#internal/workflow/development-world-client.js";+import {+ createParentDevelopmentWorkflowWorld,+ type ParentDevelopmentWorkflowWorld,+} from "#internal/workflow/development-world-server.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,+} from "#internal/workflow/development-world-protocol.js";++const createScratchDirectory = useTemporaryDirectories();+const SECRET = "workflow-transport-secret";+const RUN_ID = "wrun_01J00000000000000000000000";+const AGENT_NAME = "workflow-world-test";+const QUEUE_PREFIX = deriveEveWorkflowQueuePrefix(AGENT_NAME);++const originalFetch = globalThis.fetch;++afterEach(() => {+ globalThis.fetch = originalFetch;+ delete process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV];+ delete process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV];+ delete process.env.WORKFLOW_LOCAL_BASE_URL;+});++describe("parent development Workflow World", () => {+ it("stores local Workflow state under the app's top-level .workflow-data directory", async () => {+ const appRoot = await createScratchDirectory("eve-parent-workflow-data-dir-");+ const world = createWorld({ activeGenerationId: () => "generation-a", appRoot });++ try {+ await world.start();+ await expect(access(join(appRoot, ".workflow-data", "version.txt"))).resolves.toBeUndefined();+ await expect(access(join(appRoot, ".eve", "workflow-data"))).rejects.toMatchObject({+ code: "ENOENT",+ });+ } finally {+ await world.close();+ }+ });++ it("pins a turn delivery to its recorded generation", async () => {+ const appRoot = await createScratchDirectory("eve-parent-workflow-world-");+ await seedGeneration(appRoot, "generation-a");+ await seedGeneration(appRoot, "generation-b");+ let activeGenerationId = "generation-a";+ const world = createWorld({ activeGenerationId: () => activeGenerationId, appRoot });+ connectWorkerToWorld(world, appRoot);++ try {+ await world.start();+ const created = await callWorld(world, "events.create", [+ null,+ {+ eventData: {+ deploymentId: "generation-a",+ executionContext: {},+ input: new Uint8Array(),+ workflowName: turnWorkflowReference.workflowId,+ },+ eventType: "run_created",+ specVersion: 5,+ },+ ]);+ const runId = readCreatedRunId(created);++ activeGenerationId = "generation-b";+ await expect(deliverToWorker({ runId })).resolves.toBe("generation-a");+ } finally {+ await world.close();+ }+ });++ it("routes the generation-neutral driver to active and rejects untrusted deliveries", async () => {+ const appRoot = await createScratchDirectory("eve-parent-workflow-routing-");+ await seedGeneration(appRoot, "generation-b");+ const world = createWorld({ activeGenerationId: () => "generation-b", appRoot });+ connectWorkerToWorld(world, appRoot);++ try {+ await world.start();+ await expect(+ deliverToWorker({+ runId: RUN_ID,+ runInput: {+ deploymentId: "generation-a",+ input: new Uint8Array(),+ specVersion: 5,+ workflowName: workflowEntryReference.workflowId,+ },+ }),+ ).resolves.toBe("generation-b");++ const untrusted = await createWorkerQueueHandler()(+ new Request("http://localhost/.well-known/workflow/v1/flow", {+ body: JSON.stringify({ runId: RUN_ID }),+ headers: deliveryHeaders({ secret: "forged" }),+ method: "POST",+ }),+ );+ expect(untrusted.status).toBe(401);+ } finally {+ await world.close();+ }+ });++ it("quarantines runs referencing missing generations without refusing to boot", async () => {+ const appRoot = await createScratchDirectory("eve-parent-workflow-missing-generation-");+ await seedGeneration(appRoot, "generation-a");+ const first = createWorld({ activeGenerationId: () => "generation-a", appRoot });+ await first.start();+ await callWorld(first, "events.create", [+ null,+ {+ eventData: {+ deploymentId: "generation-a",+ executionContext: {},+ input: new Uint8Array(),+ workflowName: turnWorkflowReference.workflowId,+ },+ eventType: "run_created",+ specVersion: 5,+ },+ ]);+ await first.close();+ await rm(join(appRoot, ".eve", "dev-runtime", "snapshots", "generation-a"), {+ force: true,+ recursive: true,+ });++ const restarted = createWorld({ activeGenerationId: () => "generation-b", appRoot });+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);+ try {+ // One poisoned run must not take the app's other active runs down:+ // boot proceeds, the poisoned run's deliveries are quarantined, and+ // the failure is reported explicitly.+ await expect(restarted.start()).resolves.toBeUndefined();+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("generation-a"));+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining(".workflow-data"));+ } finally {+ errorSpy.mockRestore();+ await restarted.close();+ }+ });++ it("acknowledges and drops a delivery whose generation is permanently missing", async () => {+ const appRoot = await createScratchDirectory("eve-parent-workflow-dropped-delivery-");+ await seedGeneration(appRoot, "generation-a");+ const world = createWorld({ activeGenerationId: () => "generation-a", appRoot });+ connectWorkerToWorld(world, appRoot);+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);++ try {+ await world.start();+ const created = await callWorld(world, "events.create", [+ null,+ {+ eventData: {+ deploymentId: "generation-a",+ executionContext: {},+ input: new Uint8Array(),+ workflowName: turnWorkflowReference.workflowId,+ },+ eventType: "run_created",+ specVersion: 5,+ },+ ]);+ const runId = readCreatedRunId(created);+ await rm(join(appRoot, ".eve", "dev-runtime", "snapshots", "generation-a"), {+ force: true,+ recursive: true,+ });++ const handled = vi.fn(async () => undefined);+ const handler = createDevelopmentWorkflowWorld().createQueueHandler(QUEUE_PREFIX, handled);+ const response = await handler(+ new Request("http://localhost/.well-known/workflow/v1/flow", {+ body: JSON.stringify({ runId }),+ headers: deliveryHeaders({}),+ method: "POST",+ }),+ );++ // A missing generation never heals on retry: the delivery is+ // acknowledged so the queue stops redelivering, and the handler+ // never runs.+ expect(response.status).toBe(200);+ expect(handled).not.toHaveBeenCalled();+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("generation-a"));+ } finally {+ errorSpy.mockRestore();+ await world.close();+ }+ });++ it("rejects untrusted World requests on the call and stream routes", async () => {+ const appRoot = await createScratchDirectory("eve-parent-workflow-untrusted-");+ const world = createWorld({ activeGenerationId: () => "generation-a", appRoot });++ try {+ const missingHeader = await world.handleRequest(+ new Request(`http://localhost${DEVELOPMENT_WORKFLOW_WORLD_ROUTE}`, {+ body: encodeDevelopmentWorldValue({ arguments: [], operation: "runs.list" }),+ method: "POST",+ }),+ );+ expect(missingHeader?.status).toBe(401);++ const forgedHeader = await world.handleRequest(+ new Request(`http://localhost${DEVELOPMENT_WORKFLOW_WORLD_ROUTE}`, {+ body: encodeDevelopmentWorldValue({ arguments: [], operation: "runs.list" }),+ headers: { [DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER]: "forged" },+ method: "POST",+ }),+ );+ expect(forgedHeader?.status).toBe(401);++ const stream = await world.handleRequest(+ new Request(`http://localhost${DEVELOPMENT_WORKFLOW_STREAM_ROUTE}?runId=r&name=n`),+ );+ expect(stream?.status).toBe(401);+ } finally {+ await world.close();+ }+ });++ it("refuses a transport secret too short to be trusted", () => {+ expect(() =>+ createParentDevelopmentWorkflowWorld({+ agentName: AGENT_NAME,+ appRoot: "/tmp/eve-test",+ resolveActiveGenerationId: () => "generation-a",+ transportSecret: "",+ }),+ ).toThrow("too short");+ });+});++/**+ * Wires the worker-side world client to the parent world in memory: the+ * client's fetches route straight into `world.handleRequest`, standing in for+ * the parent listener without binding a port.+ */+function connectWorkerToWorld(world: ParentDevelopmentWorkflowWorld, appRoot: string): void {+ process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV] = SECRET;+ process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV] = appRoot;+ process.env.WORKFLOW_LOCAL_BASE_URL = "http://eve-dev.local";+ globalThis.fetch = (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {+ const request = new Request(input, init);+ const response = await world.handleRequest(request);+ if (response === undefined) {+ throw new Error(`Unexpected fetch during test: ${request.url}`);+ }+ return response;+ }) as typeof fetch;+}++function createWorkerQueueHandler(): (request: Request) => Promise<Response> {+ const worker = createDevelopmentWorkflowWorld();+ const handler = worker.createQueueHandler(QUEUE_PREFIX, async () => undefined);+ return handler;+}++/**+ * Runs one queue delivery through the worker-side handler and reports the+ * generation the handler executed under.+ */+async function deliverToWorker(payload: unknown): Promise<string | undefined> {+ const worker = createDevelopmentWorkflowWorld();+ let observedGenerationId: string | undefined;+ const handler = worker.createQueueHandler(QUEUE_PREFIX, async () => {+ observedGenerationId = getDevelopmentWorkflowGeneration()?.generationId;+ });+ const response = await handler(+ new Request("http://localhost/.well-known/workflow/v1/flow", {+ body: JSON.stringify(payload),+ headers: deliveryHeaders({}),+ method: "POST",+ }),+ );+ const body = await response.text();+ expect(response.status, body).toBe(200);+ return observedGenerationId;+}++function deliveryHeaders(input: { readonly secret?: string }): Record<string, string> {+ return {+ [DEVELOPMENT_WORKFLOW_DELIVERY_HEADER]: input.secret ?? SECRET,+ "x-vqs-message-attempt": "1",+ "x-vqs-message-id": "msg_test",+ "x-vqs-queue-name": `${QUEUE_PREFIX}${turnWorkflowReference.workflowId}`,+ };+}++async function seedGeneration(appRoot: string, generationId: string): Promise<void> {+ const snapshotRoot = join(appRoot, ".eve", "dev-runtime", "snapshots", generationId);+ const runtimeAppRoot = join(snapshotRoot, "source", "app");+ await mkdir(runtimeAppRoot, { recursive: true });+ await writeFile(join(snapshotRoot, "generation.json"), `${JSON.stringify({ runtimeAppRoot })}\n`);+}++function readCreatedRunId(value: unknown): string {+ if (+ typeof value === "object" &&+ value !== null &&+ "run" in value &&+ typeof value.run === "object" &&+ value.run !== null &&+ "runId" in value.run &&+ typeof value.run.runId === "string"+ ) {+ return value.run.runId;+ }+ throw new Error("Workflow World did not return the created run ID.");+}++function createWorld(input: {+ readonly activeGenerationId: () => string;+ readonly appRoot: string;+}): ParentDevelopmentWorkflowWorld {+ return createParentDevelopmentWorkflowWorld({+ agentName: AGENT_NAME,+ appRoot: input.appRoot,+ resolveActiveGenerationId: input.activeGenerationId,+ transportSecret: SECRET,+ });+}++async function callWorld(+ world: ParentDevelopmentWorkflowWorld,+ operation: string,+ args: readonly unknown[],+): Promise<unknown> {+ const response = await world.handleRequest(+ new Request(`http://localhost${DEVELOPMENT_WORKFLOW_WORLD_ROUTE}`, {+ body: encodeDevelopmentWorldValue({ arguments: args, operation }),+ headers: { [DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER]: SECRET },+ method: "POST",+ }),+ );+ expect(response).toBeDefined();+ const body = await response!.text();+ expect(response!.status, body).toBe(200);+ return decodeDevelopmentWorldValue(body);+}diff --git a/packages/eve/src/internal/workflow/development-world-server.ts b/packages/eve/src/internal/workflow/development-world-server.tsnew file mode 100644index 000000000..8a5638cfb--- /dev/null+++ b/packages/eve/src/internal/workflow/development-world-server.ts@@ -0,0 +1,319 @@+import { existsSync } from "node:fs";+import { basename, join } from "node:path";++import type { ValidQueueName, World } from "#compiled/@workflow/world/index.js";+import { createWorld } from "#compiled/@workflow/world-local/index.js";+import { turnWorkflowReference } from "#execution/workflow-runtime.js";+import { deriveEveWorkflowQueuePrefix } from "#internal/workflow/queue-namespace.js";+import {+ decodeDevelopmentWorldValue,+ encodeDevelopmentWorldValue,+ serializeDevelopmentWorldError,+} from "#internal/workflow/development-world-codec.js";+import { timingSafeEqualStrings } from "#internal/nitro/dev-client-address.js";+import {+ DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,+ DEVELOPMENT_WORKFLOW_STREAM_ROUTE,+ DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,+ DEVELOPMENT_WORKFLOW_WORLD_ROUTE,+ DEVELOPMENT_WORLD_OPERATIONS,+ type DevelopmentWorldCall,+} from "#internal/workflow/development-world-protocol.js";++/**+ * The application's one local Workflow World, owned by the CLI parent.+ *+ * Why the parent: run records, the queue, and stream state must outlive the+ * Nitro dev worker, which is disposed on every structural reload. The parent+ * is the only process whose lifetime matches the run data, so it holds the+ * real (stock, vendored) world-local instance and serves it to workers over+ * an RPC route on the public listener; workers hold only an+ * interface-faithful client. Deliveries are not served here — the queue+ * posts them through the public listener to the active worker like any+ * other request, so drained replacement covers them automatically.+ *+ * `handleRequest` must be reachable before `start()` runs: starting the+ * world begins queue redelivery immediately, and a delivery's first World+ * call arrives back on the listener within milliseconds.+ */+export interface ParentDevelopmentWorkflowWorld {+ close(): Promise<void>;+ handleRequest(request: Request): Promise<Response | undefined>;+ start(): Promise<void>;+}++export function createParentDevelopmentWorkflowWorld(input: {+ readonly agentName: string;+ readonly appRoot: string;+ readonly resolveActiveGenerationId: () => string;+ readonly transportSecret: string;+}): ParentDevelopmentWorkflowWorld {+ return new LocalParentDevelopmentWorkflowWorld(input);+}++class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWorld {+ readonly #agentName: string;+ readonly #appRoot: string;+ readonly #resolveActiveGenerationId: () => string;+ readonly #transportSecret: string;+ readonly #world: World;+ #closed = false;+ #started = false;++ constructor(input: {+ readonly agentName: string;+ readonly appRoot: string;+ readonly resolveActiveGenerationId: () => string;+ readonly transportSecret: string;+ }) {+ if (input.transportSecret.length < 16) {+ throw new Error("Development Workflow transport secret is too short to be trusted.");+ }+ this.#agentName = input.agentName;+ this.#appRoot = input.appRoot;+ this.#resolveActiveGenerationId = input.resolveActiveGenerationId;+ this.#transportSecret = input.transportSecret;+ this.#world = createWorld({+ dataDir: join(input.appRoot, ".workflow-data"),+ recoverActiveRuns: false,+ });+ }++ async start(): Promise<void> {+ if (this.#started) {+ return;+ }+ const referencedGenerationIds = await this.#collectActiveTurnGenerationIds();+ const missingGenerationIds = new Set<string>();+ for (const generationId of referencedGenerationIds) {+ if (!this.#generationExists(generationId)) {+ missingGenerationIds.add(generationId);+ }+ }+ if (missingGenerationIds.size > 0) {+ // One poisoned run must not take the rest of the app's active runs+ // down with it: quarantine its deliveries and keep booting.+ console.error(+ `[eve:dev] ${String(missingGenerationIds.size)} active local Workflow run(s) reference development generations that no longer exist ` ++ `(${[...missingGenerationIds].join(", ")}). Their deliveries are quarantined; ` ++ `remove ".workflow-data" to discard the app's active local Workflow runs.`,+ );+ }+ await this.#world.start?.();+ this.#started = true;+ await reenqueueActiveDevelopmentRuns({+ enqueue: this.#queue.bind(this),+ prefix: deriveEveWorkflowQueuePrefix(this.#agentName),+ quarantinedGenerationIds: missingGenerationIds,+ world: this.#world,+ });+ }++ async close(): Promise<void> {+ if (this.#closed) {+ return;+ }+ this.#closed = true;+ this.#started = false;+ await this.#world.close?.();+ }++ async handleRequest(request: Request): Promise<Response | undefined> {+ const url = new URL(request.url);+ if (url.pathname === DEVELOPMENT_WORKFLOW_WORLD_ROUTE) {+ return await this.#handleCall(request);+ }+ if (url.pathname === DEVELOPMENT_WORKFLOW_STREAM_ROUTE) {+ return await this.#handleStream(request, url);+ }+ return undefined;+ }++ async #collectActiveTurnGenerationIds(): Promise<ReadonlySet<string>> {+ const generationIds = new Set<string>();+ for (const status of ["pending", "running"] as const) {+ let cursor: string | undefined;+ do {+ let page: Awaited<ReturnType<World["runs"]["list"]>>;+ try {+ page = await this.#world.runs.list({+ pagination: { cursor, limit: 1_000 },+ resolveData: "none",+ status,+ });+ } catch (error) {+ throw new Error(+ `Failed to read the app's active local Workflow runs. ` ++ `Remove ".workflow-data" to discard them.`,+ { cause: error },+ );+ }+ for (const run of page.data) {+ if (run.workflowName === turnWorkflowReference.workflowId) {+ generationIds.add(run.deploymentId);+ }+ }+ cursor = page.hasMore ? (page.cursor ?? undefined) : undefined;+ } while (cursor !== undefined);+ }+ return generationIds;+ }++ async #handleCall(request: Request): Promise<Response> {+ if (!this.#isTrusted(request) || request.method !== "POST") {+ return Response.json({ error: "Workflow World request is not trusted." }, { status: 401 });+ }+ try {+ const call = decodeDevelopmentWorldValue(await request.text()) as DevelopmentWorldCall;+ const result = await this.#call(call);+ return new Response(encodeDevelopmentWorldValue(result));+ } catch (error) {+ return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(error)), {+ status: 500,+ });+ }+ }++ async #handleStream(request: Request, url: URL): Promise<Response> {+ if (!this.#isTrusted(request) || request.method !== "GET") {+ return Response.json({ error: "Workflow World request is not trusted." }, { status: 401 });+ }+ const runId = url.searchParams.get("runId");+ const name = url.searchParams.get("name");+ const rawStartIndex = url.searchParams.get("startIndex");+ if (runId === null || name === null) {+ return Response.json({ error: "Workflow stream request is malformed." }, { status: 400 });+ }+ const startIndex =+ rawStartIndex === null || rawStartIndex === "" ? undefined : Number(rawStartIndex);+ if (rawStartIndex === "" || (startIndex !== undefined && !Number.isInteger(startIndex))) {+ return Response.json({ error: "Workflow stream start index is invalid." }, { status: 400 });+ }+ try {+ return new Response(await this.#world.streams.get(runId, name, startIndex));+ } catch (error) {+ return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(error)), {+ status: 500,+ });+ }+ }++ async #queue(...args: Parameters<World["queue"]>): ReturnType<World["queue"]> {+ const [queueName, message, options] = args;+ return await this.#world.queue(queueName, message, {+ ...options,+ headers: {+ ...options?.headers,+ [DEVELOPMENT_WORKFLOW_DELIVERY_HEADER]: this.#transportSecret,+ },+ });+ }++ async #call(call: DevelopmentWorldCall): Promise<unknown> {+ if (!isDevelopmentWorldCall(call)) {+ throw new Error("Development Workflow World call is malformed.");+ }+ const args = [...call.arguments];+ // Deployment identity and enqueueing carry eve semantics (generation+ // resolution, the delivery header); everything else forwards to the+ // vendored world by the dot-path the shared operation table names.+ if (call.operation === "getDeploymentId" || call.operation === "resolveLatestDeploymentId") {+ return this.#resolveActiveGenerationId();+ }+ if (call.operation === "queue") {+ return await this.#queue(...(args as Parameters<World["queue"]>));+ }+ if (call.operation === "streams.writeMulti" && this.#world.streams.writeMulti === undefined) {+ for (const chunk of args[2] as readonly (string | Uint8Array)[]) {+ await this.#world.streams.write(args[0] as string, args[1] as string, chunk);+ }+ return undefined;+ }+ const separator = call.operation.indexOf(".");+ const receiver: unknown = this.#world[call.operation.slice(0, separator) as keyof World];+ const operation =+ typeof receiver === "object" && receiver !== null+ ? (receiver as Record<string, unknown>)[call.operation.slice(separator + 1)]+ : undefined;+ if (typeof operation !== "function") {+ // Optional interface members (e.g. runs.experimentalSetAttributes)+ // no-op rather than fail a caller probing for support.+ return undefined;+ }+ return await Reflect.apply(operation, receiver, args);+ }++ #isTrusted(request: Request): boolean {+ const header = request.headers.get(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER);+ return header !== null && timingSafeEqualStrings(header, this.#transportSecret);+ }++ #generationExists(generationId: string): boolean {+ if (!isValidGenerationId(generationId)) {+ return false;+ }+ return existsSync(+ join(this.#appRoot, ".eve", "dev-runtime", "snapshots", generationId, "generation.json"),+ );+ }+}++function isValidGenerationId(generationId: string): boolean {+ return (+ generationId.length > 0 &&+ generationId !== "." &&+ generationId !== ".." &&+ basename(generationId) === generationId+ );+}++const DEVELOPMENT_WORLD_OPERATION_SET: ReadonlySet<string> = new Set(DEVELOPMENT_WORLD_OPERATIONS);++function isDevelopmentWorldCall(value: unknown): value is DevelopmentWorldCall {+ return (+ isObject(value) &&+ typeof value.operation === "string" &&+ DEVELOPMENT_WORLD_OPERATION_SET.has(value.operation) &&+ Array.isArray(value.arguments)+ );+}++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++async function reenqueueActiveDevelopmentRuns(input: {+ readonly enqueue: World["queue"];+ readonly prefix: string;+ readonly quarantinedGenerationIds: ReadonlySet<string>;+ readonly world: World;+}): Promise<void> {+ for (const status of ["pending", "running"] as const) {+ let cursor: string | undefined;+ do {+ let page: Awaited<ReturnType<World["runs"]["list"]>>;+ try {+ page = await input.world.runs.list({+ pagination: { cursor },+ resolveData: "none",+ status,+ });+ } catch (error) {+ throw new Error(+ `Failed to read the app's active local Workflow runs. ` ++ `Remove ".workflow-data" to discard them.`,+ { cause: error },+ );+ }+ for (const run of page.data) {+ if (input.quarantinedGenerationIds.has(run.deploymentId)) {+ continue;+ }+ await input.enqueue(`${input.prefix}${run.workflowName}` as ValidQueueName, {+ runId: run.runId,+ });+ }+ cursor = page.hasMore ? (page.cursor ?? undefined) : undefined;+ } while (cursor !== undefined);+ }+}diff --git a/packages/eve/src/runtime/compiled-artifacts-source.ts b/packages/eve/src/runtime/compiled-artifacts-source.tsindex 419fcc06a..9baf711a3 100644--- a/packages/eve/src/runtime/compiled-artifacts-source.ts+++ b/packages/eve/src/runtime/compiled-artifacts-source.ts@@ -33,6 +33,14 @@ export interface RuntimeDiskCompiledArtifactsSource {* while sandbox state should remain scoped to the authored application.*/readonly sandboxAppRoot?: string;+ /**+ * How this source is recorded in durable Workflow payloads.+ * `"development-generation"` stores a logical selector resolved from the+ * delivery's generation context — valid only where deliveries install+ * that context (the parent-owned dev World). Absent, the source is stored+ * verbatim, pinning durable work to this exact path.+ */+ readonly durableReference?: "development-generation";}/**@@ -50,13 +58,19 @@ export function createBundledRuntimeCompiledArtifactsSource(): RuntimeBundledComexport function createDiskRuntimeCompiledArtifactsSource(appRoot: string,options: {+ readonly durableReference?: "development-generation";readonly moduleMapLoaderPath?: string;readonly sandboxAppRoot?: string;} = {},): RuntimeDiskCompiledArtifactsSource {- if (options.moduleMapLoaderPath !== undefined || options.sandboxAppRoot !== undefined) {+ if (+ options.moduleMapLoaderPath !== undefined ||+ options.sandboxAppRoot !== undefined ||+ options.durableReference !== undefined+ ) {return {appRoot,+ durableReference: options.durableReference,kind: "disk",moduleMapLoaderPath: options.moduleMapLoaderPath,sandboxAppRoot: options.sandboxAppRoot,diff --git a/packages/eve/src/runtime/durable-compiled-artifacts-source.test.ts b/packages/eve/src/runtime/durable-compiled-artifacts-source.test.tsnew file mode 100644index 000000000..45a9dcc13--- /dev/null+++ b/packages/eve/src/runtime/durable-compiled-artifacts-source.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from "vitest";++import { withDevelopmentWorkflowGeneration } from "#internal/workflow/development-generation-context.js";+import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import {+ resolveDurableCompiledArtifactsSource,+ serializeDurableCompiledArtifactsSource,+} from "#runtime/durable-compiled-artifacts-source.js";++describe("durable compiled artifact sources", () => {+ it("preserves deployed artifact sources", () => {+ const source = createDiskRuntimeCompiledArtifactsSource("/var/task/.eve/compile");++ expect(serializeDurableCompiledArtifactsSource(source)).toBe(source);+ });++ it("persists a logical selector and resolves it from the admitted child generation", async () => {+ const original = createDiskRuntimeCompiledArtifactsSource(+ "/app/.eve/dev-runtime/snapshots/generation-a/source/app",+ { durableReference: "development-generation" },+ );+ const admitted = createDiskRuntimeCompiledArtifactsSource(+ "/app/.eve/dev-runtime/snapshots/generation-b/source/app",+ );+ const durable = serializeDurableCompiledArtifactsSource(original);++ expect(durable).toEqual({ kind: "development" });+ expect(JSON.stringify(durable)).not.toContain("generation-a");+ await withDevelopmentWorkflowGeneration(+ { generationId: "generation-b", source: admitted },+ async () => {+ expect(resolveDurableCompiledArtifactsSource(durable)).toBe(admitted);+ },+ );+ });++ it("stores untagged development sources verbatim and resolves them without delivery context", () => {+ // A custom World's deliveries never install a generation context, so+ // its payloads must pin their exact snapshot instead of a selector.+ const source = createDiskRuntimeCompiledArtifactsSource(+ "/app/.eve/dev-runtime/snapshots/generation-a/source/app",+ { moduleMapLoaderPath: "/pkg/loader.ts", sandboxAppRoot: "/app" },+ );++ const durable = serializeDurableCompiledArtifactsSource(source);+ expect(durable).toBe(source);+ expect(resolveDurableCompiledArtifactsSource(durable)).toBe(source);+ });++ it("rejects resolving a logical selector outside a generation-bound delivery", () => {+ const durable = serializeDurableCompiledArtifactsSource(+ createDiskRuntimeCompiledArtifactsSource("/app/.eve/dev-runtime/snapshots/g/source/app", {+ durableReference: "development-generation",+ }),+ );+ expect(() => resolveDurableCompiledArtifactsSource(durable)).toThrow(+ "outside a generation-bound delivery",+ );+ });+});diff --git a/packages/eve/src/runtime/durable-compiled-artifacts-source.ts b/packages/eve/src/runtime/durable-compiled-artifacts-source.tsnew file mode 100644index 000000000..ab73e0e39--- /dev/null+++ b/packages/eve/src/runtime/durable-compiled-artifacts-source.ts@@ -0,0 +1,38 @@+import { getDevelopmentWorkflowGeneration } from "#internal/workflow/development-generation-context.js";+import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";++interface DevelopmentCompiledArtifactsSelector {+ readonly kind: "development";+}++export type DurableCompiledArtifactsSource =+ | RuntimeCompiledArtifactsSource+ | DevelopmentCompiledArtifactsSelector;++export function serializeDurableCompiledArtifactsSource(+ source: RuntimeCompiledArtifactsSource,+): DurableCompiledArtifactsSource {+ // Only sources whose deliveries install a generation context may store+ // the logical selector; everything else (custom Worlds in dev, production+ // disk sources) stores its exact location so replay needs no eve-specific+ // delivery context.+ if (source.kind === "disk" && source.durableReference === "development-generation") {+ return { kind: "development" };+ }+ return source;+}++export function resolveDurableCompiledArtifactsSource(+ source: DurableCompiledArtifactsSource,+): RuntimeCompiledArtifactsSource {+ if (source.kind !== "development") {+ return source;+ }+ const generation = getDevelopmentWorkflowGeneration();+ if (generation === undefined) {+ throw new Error(+ "A development Workflow generation selector was resumed outside a generation-bound delivery.",+ );+ }+ return generation.source;+}diff --git a/packages/eve/src/runtime/sessions/runtime-context-keys.ts b/packages/eve/src/runtime/sessions/runtime-context-keys.tsindex 9c6aa7a49..92ac6dc89 100644--- a/packages/eve/src/runtime/sessions/runtime-context-keys.ts+++ b/packages/eve/src/runtime/sessions/runtime-context-keys.ts@@ -7,7 +7,11 @@ import type { ChannelAdapter } from "#channel/adapter.js";import { getAdapterKind } from "#channel/adapter.js";import { ContextKey } from "#context/key.js";import { deserializeRuntimeAdapter } from "#runtime/channels/registry.js";-import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import {+ type DurableCompiledArtifactsSource,+ resolveDurableCompiledArtifactsSource,+ serializeDurableCompiledArtifactsSource,+} from "#runtime/durable-compiled-artifacts-source.js";import {type CompiledRuntimeAgentBundle,getCompiledRuntimeAgentBundle,@@ -24,7 +28,7 @@ export type CompiledBundle = CompiledRuntimeAgentBundle;interface SerializedBundle {readonly nodeId?: string;- readonly source: RuntimeCompiledArtifactsSource;+ readonly source: DurableCompiledArtifactsSource;}export const ChannelKey = new ContextKey<ChannelAdapter>("eve.channel", {@@ -53,12 +57,12 @@ export const BundleKey = new ContextKey<CompiledBundle>("eve.bundle", {codec: {serialize: (bundle): SerializedBundle => ({nodeId: bundle.nodeId,- source: bundle.compiledArtifactsSource,+ source: serializeDurableCompiledArtifactsSource(bundle.compiledArtifactsSource),}),deserialize: (data) => {const { source, nodeId } = data as SerializedBundle;return getCompiledRuntimeAgentBundle({- compiledArtifactsSource: source,+ compiledArtifactsSource: resolveDurableCompiledArtifactsSource(source),nodeId,});},diff --git a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts b/packages/eve/test/scenarios/agent-info-route.scenario.test.tsindex 1e092861f..c06a4f2bc 100644--- a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts+++ b/packages/eve/test/scenarios/agent-info-route.scenario.test.ts@@ -73,7 +73,7 @@ async function requestAgentInfo(appRoot: string, request: Request): Promise<Respreturn await dispatchChannelRequest(createInfoEvent(request),INFO_ROUTE_KEY,- createDevelopmentNitroArtifactsConfig({ appRoot }),+ createDevelopmentNitroArtifactsConfig({ configuredWorld: undefined, appRoot }),);}diff --git a/packages/eve/test/scenarios/dev-server.scenario.test.ts b/packages/eve/test/scenarios/dev-server.scenario.test.tsindex 028ae00fc..06122f73e 100644--- a/packages/eve/test/scenarios/dev-server.scenario.test.ts+++ b/packages/eve/test/scenarios/dev-server.scenario.test.ts@@ -1,6 +1,6 @@import { spawn, type ChildProcessByStdio } from "node:child_process";import { existsSync, watch as watchFileSystem } from "node:fs";-import { rm, writeFile } from "node:fs/promises";+import { readFile, rm, writeFile } from "node:fs/promises";import { dirname, join } from "node:path";import type { Readable } from "node:stream";@@ -121,6 +121,76 @@ const STREAM_PROMOTION_DESCRIPTOR: ScenarioAppDescriptor = {].join("\n"),},};+const WORKFLOW_GENERATION_DESCRIPTOR: ScenarioAppDescriptor = {+ ...TRANSACTIONAL_REBUILD_DESCRIPTOR,+ files: {+ ...Object.fromEntries(+ Object.entries(TRANSACTIONAL_REBUILD_DESCRIPTOR.files).filter(+ ([path]) => path !== "agent/tools/get_weather.ts" && !path.startsWith("agent/skills/"),+ ),+ ),+ "agent/tools/get_marker.ts": createGenerationMarkerToolSource("generation-one", true),+ },+};++function createGenerationMarkerToolSource(marker: string, crashOnce: boolean): string {+ const lifecycle = crashOnce+ ? [+ 'import { existsSync, watch, writeFileSync } from "node:fs";',+ 'import { basename, join } from "node:path";',+ "",+ "async function waitForPath(path: string) {",+ " if (existsSync(path)) return;",+ " await new Promise<void>((resolve) => {",+ " const watcher = watch(process.cwd(), (_event, filename) => {",+ " if (filename !== basename(path)) return;",+ " watcher.close();",+ " resolve();",+ " });",+ " if (existsSync(path)) {",+ " watcher.close();",+ " resolve();",+ " }",+ " });",+ "}",+ "",+ ]+ : [];+ const execute = crashOnce+ ? [+ ' const startedPath = join(process.cwd(), ".turn-started");',+ ' const crashPath = join(process.cwd(), ".crash-turn-worker");',+ ' const crashedPath = join(process.cwd(), ".turn-worker-crashed");',+ ' const restartPath = join(process.cwd(), ".restart-generation-test");',+ ' writeFileSync(startedPath, "ready");',+ " if (existsSync(restartPath)) {",+ ` writeFileSync(join(process.cwd(), ".recovered-turn-started"), JSON.stringify({ instrumentation: String(globalThis.__EVE_INSTRUMENTATION_MARKER__ ?? "missing"), marker: ${JSON.stringify(marker)} }));`,+ " } else {",+ " await waitForPath(crashPath);",+ " if (!existsSync(crashedPath)) {",+ ' writeFileSync(crashedPath, "crashed");',+ " process.exit(1);",+ " }",+ " }",+ ]+ : [];++ return [+ ...lifecycle,+ 'import { defineTool } from "eve/tools";',+ 'import { z } from "zod";',+ "",+ "export default defineTool({",+ ' description: "Return the selected development generation marker.",',+ " inputSchema: z.object({ city: z.string().optional() }),",+ " async execute() {",+ ...execute,+ ` return { instrumentation: "instrumentation-" + String(globalThis.__EVE_INSTRUMENTATION_MARKER__ ?? "missing"), marker: ${JSON.stringify(marker)} };`,+ " },",+ "});",+ "",+ ].join("\n");+}function createInstrumentationSource(marker: string): string {return [@@ -200,6 +270,7 @@ function createBlockedInstrumentationSource(): string {}interface RunningEveDev {+ crash(): Promise<void>;readonly stderr: () => string;readonly stdout: () => string;readonly url: string;@@ -401,6 +472,19 @@ async function waitForWebSocketEvent<T>(}async function startEveDev(appRoot: string): Promise<RunningEveDev> {+ return await startEveDevProcess(appRoot, {});+}++async function startEveDevWithBoundedWorkflowRecovery(appRoot: string): Promise<RunningEveDev> {+ return await startEveDevProcess(appRoot, {+ WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS: "1",+ });+}++async function startEveDevProcess(+ appRoot: string,+ environment: Readonly<Record<string, string | undefined>>,+): Promise<RunningEveDev> {const eveBinPath = join(appRoot, "node_modules", "eve", "bin", "eve.js");const child = spawn(process.execPath,@@ -409,6 +493,7 @@ async function startEveDev(appRoot: string): Promise<RunningEveDev> {cwd: appRoot,env: {...process.env,+ ...environment,// Activate the deterministic mock-model adapter in the spawned dev// server so the streamed turn completes without model credentials.NODE_ENV: "test",@@ -438,6 +523,18 @@ async function startEveDev(appRoot: string): Promise<RunningEveDev> {await waitForPath(join(appRoot, ".eve", "dev-server-state.v1.json"));return {+ async crash() {+ if (child.exitCode !== null || child.signalCode !== null) {+ return;+ }+ await withinDeadline(+ new Promise<void>((resolve) => {+ child.once("exit", () => resolve());+ child.kill("SIGKILL");+ }),+ "Timed out waiting for the dev server process to crash.",+ );+ },stderr: () => stderr,stdout: () => stdout,async stop() {@@ -769,8 +866,132 @@ describe("eve dev server", () => {},DEV_SERVER_SCENARIO_TIMEOUT_MS,);++ it(+ "retries an active child Workflow on its selected generation after promotion",+ async () => {+ const app = await scenarioApp(WORKFLOW_GENERATION_DESCRIPTOR);+ const server = await startEveDev(app.appRoot);+ const turnStartedPath = join(app.appRoot, ".turn-started");+ const crashWorkerPath = join(app.appRoot, ".crash-turn-worker");++ try {+ const firstTurn = sendDevelopmentMessage({+ message: "Use get_marker.",+ session: createDevelopmentSessionState(),+ serverUrl: server.url,+ });+ await waitForPath(turnStartedPath);++ await writeFile(+ join(app.appRoot, "agent", "tools", "get_marker.ts"),+ createGenerationMarkerToolSource("generation-two", false),+ );+ await writeFile(+ join(app.appRoot, "agent", "instrumentation.ts"),+ createInstrumentationSource("two"),+ );+ await forceDevelopmentRebuild(server.url);+ await expect(fetchText(server.url, "/instrumentation-marker")).resolves.toBe("two");++ await writeFile(crashWorkerPath, "crash");+ const firstResult = await withinDeadline(+ firstTurn,+ `Timed out waiting for the selected-generation retry.\n\nstdout:\n${server.stdout()}\n\nstderr:\n${server.stderr()}`,+ );+ expect(readCompletedMessages(firstResult.events)).toContain("generation-one");+ // Deliberate contract change from the worker-pinned architecture: the+ // retried turn keeps its generation's authored modules but resumes in+ // the replaced worker, so it observes the current instrumentation.+ expect(readCompletedMessages(firstResult.events)).toContain("instrumentation-two");++ const secondResult = await sendDevelopmentMessage({+ message: "Use get_marker.",+ session: firstResult.session,+ serverUrl: server.url,+ });+ expect(readCompletedMessages(secondResult.events)).toContain("generation-two");+ expect(readCompletedMessages(secondResult.events)).toContain("instrumentation-two");+ } finally {+ await server.stop();+ }+ },+ DEV_SERVER_SCENARIO_TIMEOUT_MS,+ );++ it(+ "recovers a nonterminal child Workflow on its selected generation after restart",+ async () => {+ const app = await scenarioApp(WORKFLOW_GENERATION_DESCRIPTOR);+ let server = await startEveDevWithBoundedWorkflowRecovery(app.appRoot);+ const turnStartedPath = join(app.appRoot, ".turn-started");+ const restartPath = join(app.appRoot, ".restart-generation-test");+ const recoveredPath = join(app.appRoot, ".recovered-turn-started");++ try {+ await writeFile(+ join(app.appRoot, "agent", "tools", "get_marker.ts"),+ createGenerationMarkerToolSource("generation-one-runtime", true),+ );+ await forceDevelopmentRebuild(server.url);+ await expect(fetchText(server.url, "/instrumentation-marker")).resolves.toBe("one");++ const interruptedTurn = sendDevelopmentMessage({+ message: "Use get_marker.",+ session: createDevelopmentSessionState(),+ serverUrl: server.url,+ }).catch(() => undefined);+ await waitForPath(turnStartedPath);++ await writeFile(+ join(app.appRoot, "agent", "tools", "get_marker.ts"),+ createGenerationMarkerToolSource("generation-two", false),+ );+ await writeFile(+ join(app.appRoot, "agent", "instrumentation.ts"),+ createInstrumentationSource("two"),+ );+ await forceDevelopmentRebuild(server.url);+ await expect(fetchText(server.url, "/instrumentation-marker")).resolves.toBe("two");++ await server.crash();+ await withinDeadline(interruptedTurn, "Interrupted client stream did not settle.");+ await writeFile(restartPath, "restart");+ server = await startEveDevWithBoundedWorkflowRecovery(app.appRoot);+ await waitForPath(recoveredPath);+ await expect(+ readFile(recoveredPath, "utf8").then((source) => JSON.parse(source) as unknown),+ ).resolves.toEqual({+ // The recovered delivery executes in the restarted worker (current+ // instrumentation) with its recorded generation's modules.+ instrumentation: "two",+ marker: "generation-one-runtime",+ });+ } finally {+ await server.stop();+ }+ },+ DEV_SERVER_SCENARIO_TIMEOUT_MS,+ );});+function readCompletedMessages(+ events: readonly { readonly data?: unknown; readonly type: string }[],+): string {+ return events+ .flatMap((event) => {+ if (event.type !== "message.completed" || !isRecord(event.data)) {+ return [];+ }+ return typeof event.data.message === "string" ? [event.data.message] : [];+ })+ .join("\n");+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+async function fetchText(serverUrl: string, path: string): Promise<string> {const response = await fetch(new URL(path, serverUrl));if (!response.ok) {@@ -808,7 +1029,7 @@ async function readDevelopmentRevision(serverUrl: string): Promise<string> {return body.revision;}-async function waitForPath(path: string): Promise<void> {+async function waitForPath(path: string, timeoutMs: number = 60_000): Promise<void> {if (existsSync(path)) {return;}@@ -821,7 +1042,7 @@ async function waitForPath(path: string): Promise<void> {});const timeout = setTimeout(() => {settle(() => reject(new Error(`Timed out waiting for ${path}.`)));- }, 60_000);+ }, timeoutMs);function settle(complete: () => void) {if (settled) {return;