The Open Framework for Building Agents
Derive a stable build deployment id for self-hosted Worlds (#5054)
prhaee5e8e97de15
diff --git a/.changeset/stable-build-deployment-id.md b/.changeset/stable-build-deployment-id.mdnew file mode 100644index 000000000..f8809ca27--- /dev/null+++ b/.changeset/stable-build-deployment-id.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Self-hosted `eve build` output now carries a build identity derived from its contents. eve exposes it to Workflow Worlds as `WORKFLOW_DEPLOYMENT_ID` unless that variable is already set, and records it in `eve build --profile` reports.diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex a1d433bb2..bb71a0db3 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -224,7 +224,7 @@ Use a profile file to establish a repeatable baseline before changing the buildeve build --profile .eve/build-profiles/baseline.json```-The report is attempted only after a successful build. It records total elapsed time, completed phase timings, and final regular-file totals for file count, raw bytes, and the sum of each file compressed with gzip. For Vercel output it also includes a subtotal for every real `.func` directory, so app and flow bundles can be compared separately. The profile path resolves from the app root and should be outside the published output directory; profile collection does not add a file to the deployment. If collection or writing fails, eve emits a warning but keeps the completed build successful.+The report is attempted only after a successful build. It records total elapsed time, completed phase timings, and final regular-file totals for file count, raw bytes, and the sum of each file compressed with gzip. For Vercel output it also includes a subtotal for every real `.func` directory, so app and flow bundles can be compared separately. For self-hosted output it includes `deploymentId`, the content-derived build identity eve passes to the Workflow World as `WORKFLOW_DEPLOYMENT_ID` when that variable isn't already set. The profile path resolves from the app root and should be outside the published output directory; profile collection does not add a file to the deployment. If collection or writing fails, eve emits a warning but keeps the completed build successful.Production builds do not write through the stable compiler, host, Nitro, or Workflow files owned by `eve dev`, so builds can run while a local dev server is active. A failed build leaves the last successful `.output/` and agent summary untouched. Concurrent completed builds serialize only the final publication window.diff --git a/packages/eve/src/execution/install-workflow-deployment-id.test.ts b/packages/eve/src/execution/install-workflow-deployment-id.test.tsnew file mode 100644index 000000000..24b9c1997--- /dev/null+++ b/packages/eve/src/execution/install-workflow-deployment-id.test.ts@@ -0,0 +1,27 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { installWorkflowDeploymentId } from "./install-workflow-deployment-id.js";++const id = "eve_0123456789abcdef0123456789abcdef";++afterEach(() => vi.unstubAllEnvs());++describe("installWorkflowDeploymentId", () => {+ it("installs the artifact id before world creation", () => {+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", undefined);+ vi.stubEnv("WORKFLOW_DEPLOYMENT_ID", undefined);+ installWorkflowDeploymentId(id);+ expect(process.env.WORKFLOW_DEPLOYMENT_ID).toBe(id);+ });++ it.each([+ ["an operator value", { WORKFLOW_DEPLOYMENT_ID: "operator-supplied" }, id],+ ["Vercel", { VERCEL_DEPLOYMENT_ID: "dpl_platform" }, id],+ ["an unpatched plugin", {}, "eve_BUILD_DEPLOYMENT_ID_PLACEHOLDER_"],+ ])("defers to %s", (_label, env: Record<string, string>, deploymentId) => {+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", env.VERCEL_DEPLOYMENT_ID);+ vi.stubEnv("WORKFLOW_DEPLOYMENT_ID", env.WORKFLOW_DEPLOYMENT_ID);+ installWorkflowDeploymentId(deploymentId);+ expect(process.env.WORKFLOW_DEPLOYMENT_ID).toBe(env.WORKFLOW_DEPLOYMENT_ID);+ });+});diff --git a/packages/eve/src/execution/install-workflow-deployment-id.ts b/packages/eve/src/execution/install-workflow-deployment-id.tsnew file mode 100644index 000000000..3e55be80b--- /dev/null+++ b/packages/eve/src/execution/install-workflow-deployment-id.ts@@ -0,0 +1,11 @@+export const BUILD_DEPLOYMENT_ID_PATTERN = /^eve_[a-f0-9]{32}$/;++/** Installs the artifact identity before a production Workflow World is constructed. */+export function installWorkflowDeploymentId(deploymentId: string): void {+ // The bundle must contain the placeholder exactly once, so the unpatched+ // (development or non-node-server) value is recognized by shape, not by import.+ if (!BUILD_DEPLOYMENT_ID_PATTERN.test(deploymentId)) return;+ // Vercel supplies its own identity; an explicit operator value wins.+ if (process.env.VERCEL_DEPLOYMENT_ID || process.env.WORKFLOW_DEPLOYMENT_ID) return;+ process.env.WORKFLOW_DEPLOYMENT_ID = deploymentId;+}diff --git a/packages/eve/src/internal/application/build-profile.ts b/packages/eve/src/internal/application/build-profile.tsindex df665e5d1..5457badb9 100644--- a/packages/eve/src/internal/application/build-profile.ts+++ b/packages/eve/src/internal/application/build-profile.ts@@ -39,6 +39,8 @@ interface ApplicationBuildProfileTiming {/** Stable JSON document written by `eve build --profile <path>`. */export interface ApplicationBuildProfile {+ /** Build identity exposed to the Workflow World; self-hosted output only. */+ readonly deploymentId?: string | undefined;readonly durationMs: number;readonly kind: "eve-build-profile";readonly output: ApplicationBuildProfileOutput;@@ -143,11 +145,13 @@ export class ApplicationBuildProfiler {/** Creates the versioned report shape from completed timings and output measurements. */export function createApplicationBuildProfile(input: {+ readonly deploymentId?: string | undefined;readonly output: ApplicationBuildProfileOutput;readonly target: ApplicationBuildProfileTarget;readonly timing: ApplicationBuildProfileTiming;}): ApplicationBuildProfile {return {+ deploymentId: input.deploymentId,durationMs: input.timing.durationMs,kind: "eve-build-profile",output: input.output,diff --git a/packages/eve/src/internal/application/compiled-artifacts.test.ts b/packages/eve/src/internal/application/compiled-artifacts.test.tsindex d7027e774..b79991fa0 100644--- a/packages/eve/src/internal/application/compiled-artifacts.test.ts+++ b/packages/eve/src/internal/application/compiled-artifacts.test.ts@@ -23,6 +23,10 @@ describe("createWorkflowWorldPluginSource", () => {'await installWorkflowWorld({ packageName: "@acme/eve-world", world: workflowWorld });',);expect(source).not.toContain("resolveLocalWorkflowWorldDataDirectory");+ expect(source.indexOf('installWorkflowDeploymentId("')).toBeGreaterThan(-1);+ expect(source.indexOf('installWorkflowDeploymentId("')).toBeLessThan(+ source.indexOf("await createWorldFromModule("),+ );});it("configures the vendored local World with eve's app-local data resolver", () => {@@ -39,6 +43,10 @@ describe("createWorkflowWorldPluginSource", () => {source.indexOf("workflowWorldModule.createWorld"),);expect(source).not.toContain("createWorldFromModule(workflowWorldModule)");+ expect(source.indexOf('installWorkflowDeploymentId("')).toBeGreaterThan(-1);+ expect(source.indexOf('installWorkflowDeploymentId("')).toBeLessThan(+ source.indexOf("await workflowWorldModule.createWorld("),+ );});it("selects the vendored Vercel World with Workflow's selector", () => {@@ -51,6 +59,10 @@ describe("createWorkflowWorldPluginSource", () => {expect(source).toContain("/compiled/@workflow/world-vercel/index.js");expect(source).toMatch(/headers: \{ "User-Agent": "eve\/.+" \}/);expect(source).toContain("applyVercelWorkflowWorldDefaults(workflowWorld);");+ expect(source.indexOf('installWorkflowDeploymentId("')).toBeGreaterThan(-1);+ expect(source.indexOf('installWorkflowDeploymentId("')).toBeLessThan(+ source.indexOf("await workflowWorldModule.createWorld("),+ );expect(source.indexOf("applyVercelWorkflowWorldDefaults(workflowWorld);")).toBeLessThan(source.indexOf("await installWorkflowWorld("),);diff --git a/packages/eve/src/internal/application/compiled-artifacts.ts b/packages/eve/src/internal/application/compiled-artifacts.tsindex 56548789b..cf29d939e 100644--- a/packages/eve/src/internal/application/compiled-artifacts.ts+++ b/packages/eve/src/internal/application/compiled-artifacts.ts@@ -26,6 +26,7 @@ import {import { type InstrumentationLayout } from "#internal/instrumentation-layout.js";import { usesParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-protocol.js";import { resolveWorkflowWorldImport } from "#internal/workflow/world-target.js";+import { BUILD_DEPLOYMENT_ID_PLACEHOLDER } from "#internal/nitro/host/build-deployment-id.js";export type BuiltInWorkflowWorldTarget = "local" | "vercel";@@ -391,7 +392,9 @@ export function createWorkflowWorldPluginSource(input: {`import * as workflowWorldModule from ${stringifyEsmImportSpecifier(wiring.moduleImportSpecifier)};`,...wiring.extraImportLines,`import { installWorkflowWorld } from ${stringifyEsmImportSpecifier(resolveInstallWorldImportSpecifier())};`,+ `import { installWorkflowDeploymentId } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath("src/execution/install-workflow-deployment-id.ts"))};`,"",+ `installWorkflowDeploymentId(${JSON.stringify(BUILD_DEPLOYMENT_ID_PLACEHOLDER)});`,wiring.createWorldSource,`await installWorkflowWorld({ packageName: ${JSON.stringify(input.configuredWorld)}, world: workflowWorld });`,"",diff --git a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts b/packages/eve/src/internal/nitro/host/build-application.scenario.test.tsindex cbfa30bc7..f2b6050a2 100644--- a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts@@ -5,6 +5,7 @@ import type { Nitro } from "nitro/types";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { compileFromMemory } from "#internal/testing/compile-from-memory.js";+import { BUILD_DEPLOYMENT_ID_PLACEHOLDER } from "./build-deployment-id.js";import {APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,type ApplicationBuildProfile,@@ -49,6 +50,13 @@ const buildNitroMock = vi.fn(async (nitro: Nitro) => {)}\n`,);await writeFile(join(functionDirectory, "_runtime.mjs"), "export default {};\n");+ if (!process.env.VERCEL) {+ await mkdir(join(outputDir, "server"), { recursive: true });+ await writeFile(+ join(outputDir, "server", "index.mjs"),+ `const deploymentId = "${BUILD_DEPLOYMENT_ID_PLACEHOLDER}";\n`,+ );+ }await mkdir(join(outputDir, "functions", "eve", "v1"), { recursive: true });await symlink("./__server.func", join(outputDir, "functions", "index.func"), "dir");await symlink(@@ -175,6 +183,7 @@ function createNitroStub(outputDir: string): Nitro {return {close: vi.fn(async () => undefined),options: {+ preset: process.env.VERCEL ? "vercel" : "node-server",output: {dir: outputDir,},@@ -295,6 +304,7 @@ describe("buildApplication", () => {expect.arrayContaining([expect.objectContaining({ name: "host.prepare" }),expect.objectContaining({ name: "nitro.bundle" }),+ expect.objectContaining({ name: "id.compute" }),expect.objectContaining({ name: "output.publish" }),expect.objectContaining({ name: "workspace.remove" }),]),@@ -413,6 +423,28 @@ describe("buildApplication", () => {await expect(readFile(summaryPath, "utf8")).resolves.toBe("last-good-summary\n");});+ it("keeps the last-good output when the workflow-world placeholder is missing", async () => {+ vi.stubEnv("VERCEL", "");+ const appRoot = await createScratchDirectory("eve-build-application-missing-id-");+ const outputDir = join(appRoot, ".output");+ await mkdir(outputDir, { recursive: true });+ await writeFile(join(outputDir, "marker.txt"), "last-good-output\n");+ prepareProductionApplicationHostMock.mockImplementationOnce(prepareHostBuildWorkspace);+ createProductionApplicationNitroMock.mockImplementationOnce(+ async (_preparedHost: PreparedApplicationHost, options: { outputDir: string }) =>+ createNitroStub(options.outputDir),+ );+ buildNitroMock.mockImplementationOnce(async (nitro: Nitro) => {+ await mkdir(nitro.options.output.dir, { recursive: true });+ await writeFile(join(nitro.options.output.dir, "index.mjs"), "no world plugin\n");+ });+ const { buildApplication } = await import("./build-application.js");+ await expect(buildApplication(appRoot, DEPLOYABLE_BUILD_OPTIONS)).rejects.toThrow(+ "expected exactly one workflow-world placeholder",+ );+ expect(await readFile(join(outputDir, "marker.txt"), "utf8")).toBe("last-good-output\n");+ });+it("builds one Vercel Nitro output and normalizes eve functions", async () => {vi.stubEnv("VERCEL", "1");const appRoot = await createScratchDirectory("eve-build-application-vercel-");diff --git a/packages/eve/src/internal/nitro/host/build-application.ts b/packages/eve/src/internal/nitro/host/build-application.tsindex 14ea9b75c..898671b5c 100644--- a/packages/eve/src/internal/nitro/host/build-application.ts+++ b/packages/eve/src/internal/nitro/host/build-application.ts@@ -28,6 +28,7 @@ import {RecoverablePublicationError,} from "#internal/application/output-publication.js";import { stageProductionCompilerArtifacts } from "#internal/application/production-compiler-artifacts.js";+import { stageBuildDeploymentId } from "#internal/nitro/host/stage-build-deployment-id.js";import {materializeVercelWorkflowFunctionOutput,normalizeEveVercelFunctionOutput,@@ -88,6 +89,7 @@ function assertProfileOutputOutsideBuildOutput(}async function writeOptionalApplicationBuildProfile(input: {+ readonly deploymentId: string | undefined;readonly outputDirectory: string;readonly profileOutputPath: string;readonly profiler: ApplicationBuildProfiler;@@ -99,6 +101,7 @@ async function writeOptionalApplicationBuildProfile(input: {await writeApplicationBuildProfile(input.profileOutputPath,createApplicationBuildProfile({+ deploymentId: input.deploymentId,output,target: process.env.VERCEL ? "vercel" : "local",timing,@@ -262,9 +265,9 @@ export async function buildApplication(// staged artifacts inside this workspace; the next build's recovery// consumes and then removes it. Deleting it now would strand the journal.let preserveWorkspaceForRecovery = false;- let outputDirectory: string;+ let built: BuiltApplicationOutput;try {- outputDirectory = await buildApplicationInWorkspace(workspace, options, profiler);+ built = await buildApplicationInWorkspace(workspace, options, profiler);} catch (error) {preserveWorkspaceForRecovery = error instanceof RecoverablePublicationError;throw error;@@ -278,20 +281,26 @@ export async function buildApplication(if (profiler !== undefined && profileOutputPath !== undefined) {await writeOptionalApplicationBuildProfile({- outputDirectory,+ deploymentId: built.deploymentId,+ outputDirectory: built.outputDirectory,profileOutputPath,profiler,});}- return outputDirectory;+ return built.outputDirectory;+}++interface BuiltApplicationOutput {+ readonly deploymentId: string | undefined;+ readonly outputDirectory: string;}async function buildApplicationInWorkspace(workspace: ApplicationBuildWorkspace,options: ApplicationBuildOptions,profiler: ApplicationBuildProfiler | undefined,-): Promise<string> {+): Promise<BuiltApplicationOutput> {const preparedHost = await measureBuildPhase(profiler, "host.prepare", () =>prepareProductionApplicationHost(workspace),);@@ -414,10 +423,17 @@ async function buildApplicationInWorkspace(await measureBuildPhase(profiler, "nitro.close", () => nitro.close());}+ const deploymentId =+ nitro.options.preset === "node-server"+ ? await measureBuildPhase(profiler, "id.compute", () =>+ stageBuildDeploymentId(workspace.publication.output.stagedDir),+ )+ : undefined;+await measureBuildPhase(profiler, "output.publish", () =>publishCompletedApplicationBuild(workspace),);- return workspace.publication.output.finalDir;+ return { deploymentId, outputDirectory: workspace.publication.output.finalDir };}async function publishCompletedApplicationBuild(diff --git a/packages/eve/src/internal/nitro/host/build-deployment-id.scenario.test.ts b/packages/eve/src/internal/nitro/host/build-deployment-id.scenario.test.tsnew file mode 100644index 000000000..111b1b3b1--- /dev/null+++ b/packages/eve/src/internal/nitro/host/build-deployment-id.scenario.test.ts@@ -0,0 +1,76 @@+import { readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";++import { afterEach, describe, expect, it, vi } from "vitest";++import { useScenarioApp } from "#internal/testing/scenario-app.js";+import { buildApplication } from "./build-application.js";+import { startProductionServer } from "./start-production-server.js";++afterEach(() => vi.unstubAllEnvs());++describe("production deployment identity", () => {+ const scenarioApp = useScenarioApp();++ it("reproduces unchanged builds, changes with instructions, and reaches the World on direct Node startup", async () => {+ vi.stubEnv("VERCEL", "");+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", undefined);+ vi.stubEnv("WORKFLOW_DEPLOYMENT_ID", undefined);+ const app = await scenarioApp({+ name: "build-deployment-id",+ installDependencies: true,+ dependencies: { "@acme/test-world": "file:./world" },+ files: {+ "agent/agent.ts":+ 'export default { model: "openai/gpt-5.4", experimental: { workflow: { world: "@acme/test-world" } } };',+ "agent/instructions.md": "Help Alice organize her notes.\n",+ "agent/skills/notes.md": "---\ndescription: Organize notes.\n---\nGroup notes by topic.\n",+ "world/package.json": JSON.stringify({+ name: "@acme/test-world",+ version: "1.0.0",+ type: "module",+ exports: "./index.js",+ }),+ "world/index.js": [+ 'import { writeFileSync } from "node:fs";',+ "export function createWorld() {",+ " const constructed = process.env.WORKFLOW_DEPLOYMENT_ID;",+ " const world = {",+ " specVersion: 8, events: {},",+ ' createQueueHandler: () => async () => new Response("ok"),',+ " getDeploymentId: async () => process.env.WORKFLOW_DEPLOYMENT_ID,",+ " start: async () => writeFileSync(process.env.EVE_TEST_DEPLOYMENT_LOG, JSON.stringify({ constructed, started: await world.getDeploymentId() })),",+ " };",+ " return world;",+ "}",+ ].join("\n"),+ },+ });+ const profileOutputPath = join(app.appRoot, "build-profile.json");+ const build = async () => {+ await buildApplication(app.appRoot, { profileOutputPath, skipSandboxPrewarm: true });+ return (JSON.parse(await readFile(profileOutputPath, "utf8")) as { deploymentId?: string })+ .deploymentId;+ };+ const firstId = await build();+ expect(firstId).toMatch(/^eve_[a-f0-9]{32}$/);+ expect(await build()).toBe(firstId);+ await writeFile(join(app.appRoot, "agent/instructions.md"), "Help Bob organize his notes.\n");+ const changedId = await build();+ expect(changedId).not.toBe(firstId);+ const logPath = join(app.appRoot, "world-deployment.json");+ vi.stubEnv("EVE_TEST_DEPLOYMENT_LOG", logPath);+ // startProductionServer launches node .output/server/index.mjs, without a CLI bootstrap.+ for (let replica = 0; replica < 2; replica++) {+ const server = await startProductionServer(app.appRoot, { host: "127.0.0.1", port: 0 });+ try {+ expect(JSON.parse(await readFile(logPath, "utf8"))).toEqual({+ constructed: changedId,+ started: changedId,+ });+ } finally {+ await server.close();+ }+ }+ });+});diff --git a/packages/eve/src/internal/nitro/host/build-deployment-id.test.ts b/packages/eve/src/internal/nitro/host/build-deployment-id.test.tsnew file mode 100644index 000000000..f9b9202b0--- /dev/null+++ b/packages/eve/src/internal/nitro/host/build-deployment-id.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from "vitest";++import {+ BUILD_DEPLOYMENT_ID_PLACEHOLDER,+ computeBuildDeploymentId,+ replaceBuildDeploymentId,+} from "./build-deployment-id.js";++const file = (relativePath: string, content: string) => ({+ relativePath,+ bytes: Buffer.from(content),+});++function idOf(+ files: readonly { relativePath: string; bytes: Uint8Array }[],+ extras?: readonly string[],+): Promise<string> {+ const bytes = new Map(files.map((entry) => [entry.relativePath, entry.bytes]));+ return computeBuildDeploymentId(+ files.map((entry) => entry.relativePath),+ async (relativePath) => bytes.get(relativePath)!,+ extras,+ );+}++describe("build deployment identity", () => {+ it("hashes sorted paths, bytes, and environment inputs, excluding only root tooling metadata", async () => {+ const files = [file("server/index.mjs", "run();"), file(".eve/instructions.md", "Help Alice.")];+ const extras = ["[email protected]", "[email protected]"];+ const id = await idOf(files, extras);+ expect(id).toMatch(/^eve_[a-f0-9]{32}$/);+ expect(await idOf([...files].reverse(), [...extras].reverse())).toBe(id);+ expect(await idOf([...files, file("nitro.json", "volatile")], extras)).toBe(id);+ for (const changed of [+ [file("server/index.mjs", "run(1);"), files[1]!],+ [file("server/other.mjs", "run();"), files[1]!],+ [...files, file("server/nitro.json", "runtime input")],+ [files[0]!],+ ])+ expect(await idOf(changed, extras)).not.toBe(id);+ expect(await idOf(files, ["[email protected]", extras[1]!])).not.toBe(id);+ expect(await idOf([file("ab", "c")])).not.toBe(await idOf([file("a", "bc")]));+ });++ it("bounds reads in flight and surfaces the first read failure", async () => {+ const paths = Array.from(+ { length: 40 },+ (_, index) => `server/${String(index).padStart(2, "0")}`,+ );+ let inFlight = 0;+ let maxInFlight = 0;+ await computeBuildDeploymentId(paths, async () => {+ maxInFlight = Math.max(maxInFlight, ++inFlight);+ await new Promise((resolve) => setTimeout(resolve, 1));+ inFlight--;+ return new Uint8Array();+ });+ expect(maxInFlight).toBeLessThanOrEqual(16);+ await expect(+ computeBuildDeploymentId(paths, async (path) => {+ throw new Error(`unreadable ${path}`);+ }),+ ).rejects.toThrow("unreadable server/00");+ });++ it("patches exactly one placeholder without changing offsets or the original bytes", async () => {+ const original = file("server/chunk.mjs", `before:${BUILD_DEPLOYMENT_ID_PLACEHOLDER}:after`);+ const id = await idOf([original]);+ const patched = replaceBuildDeploymentId([original], id);+ expect(patched.relativePath).toBe(original.relativePath);+ expect(Buffer.from(patched.bytes).toString()).toBe(`before:${id}:after`);+ expect(patched.bytes.length).toBe(original.bytes.length);+ expect(original.bytes.toString()).toContain(BUILD_DEPLOYMENT_ID_PLACEHOLDER);+ for (const files of [+ [],+ [file("server/a.mjs", "missing")],+ [original, file("server/b.mjs", BUILD_DEPLOYMENT_ID_PLACEHOLDER)],+ [file("server/a.mjs", BUILD_DEPLOYMENT_ID_PLACEHOLDER.repeat(2))],+ ]) {+ expect(() => replaceBuildDeploymentId(files, id)).toThrow(+ "expected exactly one workflow-world placeholder",+ );+ }+ expect(() => replaceBuildDeploymentId([original], "latest")).toThrow(+ "Invalid build deployment id",+ );+ });+});diff --git a/packages/eve/src/internal/nitro/host/build-deployment-id.ts b/packages/eve/src/internal/nitro/host/build-deployment-id.tsnew file mode 100644index 000000000..41999c7a0--- /dev/null+++ b/packages/eve/src/internal/nitro/host/build-deployment-id.ts@@ -0,0 +1,88 @@+import { createHash } from "node:crypto";++import { BUILD_DEPLOYMENT_ID_PATTERN } from "#execution/install-workflow-deployment-id.js";++export const BUILD_DEPLOYMENT_ID_PLACEHOLDER = "eve_BUILD_DEPLOYMENT_ID_PLACEHOLDER_";+const READ_AHEAD = 16;++export interface BuildDeploymentFile {+ readonly relativePath: string;+ readonly bytes: Uint8Array;+}++/** Hashes files in path order while holding at most `READ_AHEAD` files in memory. */+export async function computeBuildDeploymentId(+ relativePaths: readonly string[],+ readBytes: (relativePath: string) => Promise<Uint8Array>,+ extraInputs: readonly string[] = [],+): Promise<string> {+ const hash = createHash("sha256");+ const append = (bytes: Uint8Array) => {+ hash.update(`${bytes.byteLength}:`);+ hash.update(bytes);+ };+ hash.update("eve-build-v1\0");+ // Nitro writes a build timestamp to the root nitro.json; nothing reads it at runtime.+ const paths = relativePaths+ .filter((path) => path !== "nitro.json")+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));+ const reads: Promise<Uint8Array>[] = [];+ const startRead = (index: number) => {+ if (index >= paths.length) return;+ const read = readBytes(paths[index]!);+ // Reads ahead may reject after an earlier read already failed the hash.+ read.catch(() => undefined);+ reads[index] = read;+ };+ for (let index = 0; index < READ_AHEAD; index++) startRead(index);+ for (let index = 0; index < paths.length; index++) {+ const bytes = await reads[index]!;+ delete reads[index];+ startRead(index + READ_AHEAD);+ hash.update("file\0");+ append(Buffer.from(paths[index]!));+ append(bytes);+ }+ for (const input of [...extraInputs].sort()) {+ hash.update("input\0");+ append(Buffer.from(input));+ }+ return `eve_${hash.digest("hex").slice(0, 32)}`;+}++export function replaceBuildDeploymentId(+ files: readonly BuildDeploymentFile[],+ deploymentId: string,+): BuildDeploymentFile {+ const placeholder = Buffer.from(BUILD_DEPLOYMENT_ID_PLACEHOLDER);+ const replacement = Buffer.from(deploymentId);+ if (+ !BUILD_DEPLOYMENT_ID_PATTERN.test(deploymentId) ||+ replacement.length !== placeholder.length+ ) {+ throw new Error(+ "Invalid build deployment id: expected eve_ followed by 32 lowercase hex characters.",+ );+ }+ let match: { file: BuildDeploymentFile; offset: number } | undefined;+ let count = 0;+ for (const file of files) {+ const bytes = Buffer.from(file.bytes);+ for (+ let offset = bytes.indexOf(placeholder);+ offset !== -1;+ offset = bytes.indexOf(placeholder, offset + placeholder.length)+ ) {+ count++;+ match = { file, offset };+ }+ }+ if (count !== 1 || match === undefined) {+ throw new Error(+ `Cannot install build deployment id: expected exactly one workflow-world placeholder in server/**/*.mjs outside node_modules, found ${count}. This is an eve bug; please report it.`,+ );+ }+ const bytes = Buffer.from(match.file.bytes);+ replacement.copy(bytes, match.offset);+ return { relativePath: match.file.relativePath, bytes };+}diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.tsindex bfe6a93b5..004340209 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts@@ -862,7 +862,11 @@ export async function createProductionApplicationNitro(plugins: nitroPlugins,publicAssets: [],scanDirs: [resolvePackageSourceDirectoryPath("src/execution")],- rolldownConfig: bundler.nitroRolldownConfig,+ rolldownConfig: {+ ...bundler.nitroRolldownConfig,+ // Region comments contain invocation-random scratch paths, not runtime inputs.+ experimental: { attachDebugInfo: "none" },+ },rollupConfig: bundler.nitroRollupConfig,rootDir: preparedHost.appRoot,serverAssets: skillServerAssets,diff --git a/packages/eve/src/internal/nitro/host/skill-server-assets.ts b/packages/eve/src/internal/nitro/host/skill-server-assets.tsindex d6618aa6b..f99ead3bf 100644--- a/packages/eve/src/internal/nitro/host/skill-server-assets.ts+++ b/packages/eve/src/internal/nitro/host/skill-server-assets.ts@@ -1,5 +1,5 @@import { createHash } from "node:crypto";-import { mkdir, rm, writeFile } from "node:fs/promises";+import { mkdir, rm, utimes, writeFile } from "node:fs/promises";import { join, resolve } from "node:path";import {@@ -62,14 +62,19 @@ export async function prepareSkillServerAssets(input: {// Hash and stage the bytes that were read, not a second read of the path.const bytes = await source.readFile(skill, path);const sha256 = createHash("sha256").update(bytes).digest("hex");- await writeFile(join(filesDirectory, skillFileStorageKey(sha256)), bytes);+ const assetPath = join(filesDirectory, skillFileStorageKey(sha256));+ await writeFile(assetPath, bytes);+ // Nitro embeds mtimes; generated assets are identified by their contents instead.+ await utimes(assetPath, 0, 0);files.push([path, bytes.byteLength, sha256]);}index.push([skill, files, await source.listDirectories(skill)]);}const skillFilesIndex: SkillFilesIndex = { version: 1, skills: index };- await writeFile(join(indexDirectory, SKILL_FILES_INDEX_KEY), JSON.stringify(skillFilesIndex));+ const indexPath = join(indexDirectory, SKILL_FILES_INDEX_KEY);+ await writeFile(indexPath, JSON.stringify(skillFilesIndex));+ await utimes(indexPath, 0, 0);return [{ baseName: SKILL_FILES_INDEX_SERVER_ASSET_BASE, dir: indexDirectory },{ baseName: SKILL_FILES_SERVER_ASSET_BASE, dir: filesDirectory },diff --git a/packages/eve/src/internal/nitro/host/stage-build-deployment-id.ts b/packages/eve/src/internal/nitro/host/stage-build-deployment-id.tsnew file mode 100644index 000000000..ebd2c17d2--- /dev/null+++ b/packages/eve/src/internal/nitro/host/stage-build-deployment-id.ts@@ -0,0 +1,98 @@+import { readFile, readdir, realpath, stat, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { createRequire } from "node:module";++import { resolveInstalledPackageInfo } from "#internal/application/package.js";+import {+ BUILD_DEPLOYMENT_ID_PLACEHOLDER,+ computeBuildDeploymentId,+ replaceBuildDeploymentId,+ type BuildDeploymentFile,+} from "#internal/nitro/host/build-deployment-id.js";++async function optionalPeerIdentity(outputDirectory: string): Promise<string> {+ // otel-registration probes this peer with createRequire at runtime, outside Nitro tracing.+ const require = createRequire(join(outputDirectory, "server", "index.mjs"));+ let entryPath: string;+ try {+ entryPath = require.resolve("@opentelemetry/api");+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "MODULE_NOT_FOUND") {+ return "@opentelemetry/api@absent";+ }+ throw error;+ }+ for (let directory = dirname(entryPath); ; directory = dirname(directory)) {+ try {+ const manifest: unknown = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));+ if (+ manifest !== null &&+ typeof manifest === "object" &&+ "name" in manifest &&+ manifest.name === "@opentelemetry/api" &&+ "version" in manifest &&+ typeof manifest.version === "string"+ ) {+ return `@opentelemetry/api@${manifest.version}`;+ }+ } catch (error) {+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;+ }+ if (dirname(directory) === directory) {+ throw new Error(+ "Cannot compute build deployment id: @opentelemetry/api has no package version.",+ );+ }+ }+}++/** The World plugin is always bundled into an eve server chunk, never a traced dependency. */+function mayContainPlaceholder(relativePath: string): boolean {+ return (+ relativePath.startsWith("server/") &&+ relativePath.endsWith(".mjs") &&+ !relativePath.split("/").includes("node_modules")+ );+}++/** Hashes the staged output, installs the id in the World plugin, and returns the id. */+export async function stageBuildDeploymentId(outputDirectory: string): Promise<string> {+ const relativePaths: string[] = [];+ async function walk(relativeDirectory: string, ancestors: ReadonlySet<string>): Promise<void> {+ const directory = join(outputDirectory, relativeDirectory);+ const canonicalDirectory = await realpath(directory);+ if (ancestors.has(canonicalDirectory)) {+ throw new Error(`Cannot hash build output: cyclic directory link at ${relativeDirectory}.`);+ }+ const nextAncestors = new Set([...ancestors, canonicalDirectory]);+ for (const entry of await readdir(directory, { withFileTypes: true })) {+ const relativePath = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;+ const info = entry.isSymbolicLink() ? await stat(join(outputDirectory, relativePath)) : entry;+ if (info.isDirectory()) await walk(relativePath, nextAncestors);+ else if (info.isFile()) relativePaths.push(relativePath);+ else throw new Error(`Cannot hash build output: unsupported file type at ${relativePath}.`);+ }+ }+ await walk("", new Set());++ const placeholder = Buffer.from(BUILD_DEPLOYMENT_ID_PLACEHOLDER);+ const candidates: BuildDeploymentFile[] = [];+ const deploymentId = await computeBuildDeploymentId(+ relativePaths,+ async (relativePath) => {+ const bytes = await readFile(join(outputDirectory, relativePath));+ if (mayContainPlaceholder(relativePath) && bytes.includes(placeholder)) {+ candidates.push({ relativePath, bytes });+ }+ return bytes;+ },+ [+ `eve@${resolveInstalledPackageInfo().version}`,+ `node@${process.version}`,+ await optionalPeerIdentity(outputDirectory),+ ],+ );+ const replacement = replaceBuildDeploymentId(candidates, deploymentId);+ await writeFile(join(outputDirectory, replacement.relativePath), replacement.bytes);+ return deploymentId;+}