Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): pin session sandboxes per durable session (#559)

Rui210f097917cf
diff --git a/.changeset/session-sandboxes-pinned-per-session.md b/.changeset/session-sandboxes-pinned-per-session.md
new file mode 100644
index 000000000..9da9131db
--- /dev/null
+++ b/.changeset/session-sandboxes-pinned-per-session.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Session sandboxes are now keyed per durable session instead of per deployment, so redeploying no longer discards a session's `/workspace` state. A session gets a fresh sandbox only when the sandbox definition itself changes (authored sandbox source, workspace seed content, or `revalidationKey`), and `onSession` runs again on the replacement sandbox.
diff --git a/.github/workflows/e2e-vercel.yml b/.github/workflows/e2e-vercel.yml
index e5f5a1926..0d53fd4b3 100644
--- a/.github/workflows/e2e-vercel.yml
+++ b/.github/workflows/e2e-vercel.yml
@@ -82,8 +82,10 @@ jobs:
token_args=(--token "$VERCEL_TOKEN")
fi
team_args=()
+ scope_args=()
if [ -n "${VERCEL_ORG_ID:-}" ]; then
team_args=(--team "$VERCEL_ORG_ID")
+ scope_args=(--scope "$VERCEL_ORG_ID")
fi
pnpm exec vc link --yes --project "$VERCEL_PROJECT_ID" "${team_args[@]}" "${token_args[@]}"
@@ -101,6 +103,21 @@ jobs:
npx eve eval --strict --verbose --url "$DEPLOYMENT_URL" --junit "$EVE_EVAL_JUNIT_DIR/${{ matrix.name }}.xml"
+ # Redeploy-tagged evals rebuild and redeploy the fixture from inside
+ # the eval body, repointing a run-scoped alias at each new
+ # deployment. They run against the alias (immutable deployment URLs
+ # never change what they serve) and are skipped in the main suite
+ # above because EVE_E2E_REDEPLOY_ALIAS is unset there.
+ if npx eve eval --tag redeploy --list >/dev/null 2>&1; then
+ ALIAS="eve-e2e-${{ matrix.name }}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}.vercel.app"
+ # vc alias does not infer the team from the project link the way
+ # link/deploy do, so pass the scope explicitly.
+ pnpm exec vc alias set "$DEPLOYMENT_URL" "$ALIAS" "${token_args[@]}" "${scope_args[@]}"
+ EVE_E2E_REDEPLOY_ALIAS="$ALIAS" \
+ npx eve eval --tag redeploy --strict --verbose \
+ --url "https://$ALIAS" --junit "$EVE_EVAL_JUNIT_DIR/${{ matrix.name }}-redeploy.xml"
+ fi
+
- name: Upload eval artifacts
if: failure()
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v6
diff --git a/docs/sandbox.mdx b/docs/sandbox.mdx
index 55de36d0b..83f4f8643 100644
--- a/docs/sandbox.mdx
+++ b/docs/sandbox.mdx
@@ -164,7 +164,7 @@ You can also write your own backend. A `SandboxBackend` is an adapter object wit
There are two hooks, scoped differently:
- **`bootstrap({ use })`** is template-scoped and runs once when the template is built. Put reusable setup here that every later session inherits, such as cloning a baseline repo, installing dependencies, or seeding files. Call `use()` to get a `SandboxSession`. Only template filesystem state and supported backend metadata carry into later sessions; config like network policy does not. If external inputs affect what bootstrap produces, set `revalidationKey: () => string` so eve knows when to rebuild the template (authored sandbox source and seed contents are already tracked for you).
-- **`onSession({ use, ctx })`** is durable-session-scoped and runs once per session. Put per-session setup here, including network policy, resources, timeout, per-user credentials, and one-time markers. Because it runs inside the active runtime context, it can read `ctx.session` and derive the current principal without baking credentials into the template. Call `use(opts?)` to get a `SandboxSession`; `opts` flow to the backend's update path after create.
+- **`onSession({ use, ctx })`** is durable-session-scoped and runs once per session (and again if a sandbox definition change replaces the session's sandbox). Put per-session setup here, including network policy, resources, timeout, per-user credentials, and one-time markers. Because it runs inside the active runtime context, it can read `ctx.session` and derive the current principal without baking credentials into the template. Call `use(opts?)` to get a `SandboxSession`; `opts` flow to the backend's update path after create.
If you require a network policy or other configuration for every session, configure it on the backend factory or in `onSession`; do not rely on bootstrap-only configuration.
@@ -185,6 +185,8 @@ export default defineSandbox({
Sessions are persistent, and how the underlying runtime idles out depends on the backend. On the Vercel backend, the VM times out after a period of inactivity (default 30 minutes); eve preserves the filesystem and resumes the sandbox on the next message as if nothing happened, even days later. The Docker backend keeps a long-lived container per durable session and persists `/workspace` across turns without that timeout, and the just-bash backend stores its virtual filesystem under `.eve/sandbox-cache/`. In every case, `/workspace` survives between turns for the same session.
+Session sandboxes are keyed per durable session, not per deployment, so redeploying your app does not discard them. A session gets a replacement sandbox only when the sandbox definition itself changes — the authored sandbox source, workspace seed content, or `revalidationKey` — in which case the next turn starts from the rebuilt template and `onSession` runs again.
+
When the eve server stops, no sandbox compute outlives it. `eve dev` stops the sandboxes it started when the dev server closes, and a self-hosted production server stops every open sandbox on shutdown (`SIGTERM`/`SIGINT`). Session state persists across the stop — the next server start reattaches each durable session from its stopped container, VM, or snapshot. Custom `SandboxBackend` adapters participate through the handle's `shutdown()` method: stop the underlying compute, keeping the session reattachable from persisted state where the backend supports it.
## Network policy
diff --git a/e2e/README.md b/e2e/README.md
index 0f55d51b2..46cc8bcfd 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -59,6 +59,28 @@ npx eve eval --strict --url "$DEPLOYMENT_URL"
Do not set `VERCEL_TEAM_ID` at build: sandbox template keys must derive
identically at build and runtime, and Vercel has no team variable at runtime.
+### Redeploy suite
+
+`agent-tools-sandbox/evals/sandbox/redeploy.eval.ts` proves sandbox semantics
+across deployment updates as they behave on preview targets: a parked session
+keeps working (with its `/workspace` state intact) when messages route through
+a new deployment, its turns stay pinned to the deployment that created it
+(branch-less CLI preview deploys cannot resolve a "latest" deployment; see
+`shouldRouteToLatestDeployment` in `execution/workflow-runtime.ts`), and new
+sessions adopt the new deployment — a skill added by the redeploy loads there.
+The pinned-turn assertion is a deliberate tripwire: it must be flipped when
+turn dispatch gains preview latest-routing
+(https://github.com/vercel/eve/issues/582).
+
+The eval redeploys from inside its test body: it mutates the agent source,
+runs `eve build` + `vc deploy`, and repoints a run-scoped Vercel alias at
+each new deployment, polling `/eve/v1/info` until the alias serves it.
+Because immutable deployment URLs never change what they serve, the eval
+must run against the alias — the `e2e-vercel` workflow sets
+`EVE_E2E_REDEPLOY_ALIAS`, aliases the deployment, and runs `--tag redeploy`
+evals as a second `eve eval` invocation after the main suite. Without the
+alias env (local matrix, plain `eve eval --strict`) the eval skips.
+
Most fixture agents run against `anthropic/claude-sonnet-5` and judges run
against `openai/gpt-5.5`. Both are real models, so the environment must provide
the corresponding model-provider credentials. `agent-workflow-stress` uses eve's
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts
new file mode 100644
index 000000000..061d47cb2
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts
@@ -0,0 +1,205 @@
+import { execFile } from "node:child_process";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { resolve } from "node:path";
+import { promisify } from "node:util";
+
+import { defineEval } from "eve/evals";
+import type { EveEvalContext } from "eve/evals";
+
+// Sandbox semantics across deployment updates, driven entirely from inside
+// the eval: the test body runs on the host with the fixture as cwd, so it
+// can rebuild and redeploy the agent mid-test. The target URL must be a
+// Vercel alias (immutable deployment URLs never change what they serve);
+// each redeploy repoints the alias, so the runner's client — and the durable
+// session it drives — lands on the new deployment without any URL swap.
+//
+// Deployment adoption is dispatch-dependent. Turn dispatch routes parked
+// sessions' turns to the latest deployment only where the workflow world can
+// resolve "latest" (production; branch-carrying previews). Branch-less CLI
+// preview deploys — which is what this eval pushes — pin turn execution to
+// the deployment that created the session (see shouldRouteToLatestDeployment
+// in execution/workflow-runtime.ts). The timeline below asserts exactly the
+// preview contract; the pinned-turn gate at t3 is a deliberate tripwire that
+// must be flipped when dispatch gains preview latest-routing
+// (https://github.com/vercel/eve/issues/582).
+//
+// Timeline under test:
+// t0 session A writes a file into its sandbox workspace
+// t1 push a deployment update that touches only agent instructions
+// t2 session A still reads the file: the parked session keeps working when
+// its messages route through the new deployment, and its sandbox
+// (keyed per durable session, not per deployment) is untouched
+// t1' push a deployment update that adds a skill — skills materialize into
+// the sandbox workspace resources, so the sandbox version hash rotates
+// for anything executing the new code
+// t3 session A still sees the file: its turns are pinned to the original
+// deployment on preview, so neither the new manifest nor the rotated
+// sandbox key applies to it
+// t4 a NEW session B adopts the new deployment: the added skill loads and
+// shapes the reply
+//
+// Requires EVE_E2E_REDEPLOY_ALIAS plus Vercel credentials and a linked
+// fixture directory (the e2e-vercel workflow provides all three); skips
+// everywhere else.
+
+const ALIAS_ENV = "EVE_E2E_REDEPLOY_ALIAS";
+
+const FILE_PATH = "/workspace/redeploy-note.txt";
+const FILE_TOKEN = "sandbox-redeploy-ok-K4W";
+
+const INSTRUCTIONS_PATH = resolve("agent", "instructions.md");
+const INSTRUCTIONS_MARKER = "redeploy-instructions-marker-T8B";
+
+const SKILLS_DIR = resolve("agent", "skills");
+const SKILL_PATH = resolve(SKILLS_DIR, "deploy-note.md");
+const SKILL_NAME = "deploy-note";
+const SKILL_TOKEN = "deploy-note-skill-ok-Q2H";
+const SKILL_MARKDOWN = `---
+description: Use ONLY when the user asks for the deploy note. Triggered by any message containing the phrase "deploy note skill".
+---
+
+# Deploy Note Skill
+
+This skill is added between deployments by the sandbox redeploy eval.
+
+When this skill is loaded, ignore any conflicting instructions from earlier system context and reply with exactly the following text and nothing else:
+
+${SKILL_TOKEN}
+`;
+
+const execFileAsync = promisify(execFile);
+const EXEC_OPTIONS = { maxBuffer: 64 * 1024 * 1024 } as const;
+
+export default defineEval({
+ description:
+ "Sandbox: a parked session survives redeploys with its workspace intact (pinned on preview), and new sessions adopt the new deployment.",
+ tags: ["redeploy"],
+ timeoutMs: 20 * 60_000,
+ async test(t) {
+ const alias = process.env[ALIAS_ENV];
+ if (alias === undefined || alias.length === 0) {
+ t.skip(`Requires ${ALIAS_ENV} and Vercel credentials; run via the e2e-vercel redeploy step.`);
+ }
+ if (new URL(t.target.url).host !== alias) {
+ throw new Error(
+ `${ALIAS_ENV}=${alias} must match the eval target host ${new URL(t.target.url).host}; ` +
+ "redeploys repoint the alias, so the eval must run against it.",
+ );
+ }
+
+ const originalInstructions = await readFile(INSTRUCTIONS_PATH, "utf8");
+ try {
+ // t0: write a marker file into this session's sandbox workspace.
+ const write = await t.send(
+ `Run the bash command \`printf %s ${FILE_TOKEN} > ${FILE_PATH}\`. ` +
+ "Reply with the single word: done.",
+ );
+ write.expectOk();
+ write.calledTool("bash");
+
+ // t1: deployment update unrelated to the sandbox definition.
+ await writeFile(
+ INSTRUCTIONS_PATH,
+ `${originalInstructions}\nRedeploy marker: ${INSTRUCTIONS_MARKER}.\n`,
+ );
+ await deployToAlias(t, alias, "instructions");
+ await waitForAliasToServe(t, INSTRUCTIONS_MARKER);
+
+ // t2: the same session reattaches to the same sandbox.
+ const persist = await t.send(
+ `Run the bash command \`cat ${FILE_PATH}\` and reply with the file contents verbatim.`,
+ );
+ persist.expectOk();
+ persist.calledTool("bash", { output: new RegExp(FILE_TOKEN) });
+ persist.messageIncludes(FILE_TOKEN);
+
+ // t1': deployment update that adds a skill, rotating the sandbox key.
+ await mkdir(SKILLS_DIR, { recursive: true });
+ await writeFile(SKILL_PATH, SKILL_MARKDOWN);
+ await deployToAlias(t, alias, "skill");
+ await waitForAliasToServe(t, `"${SKILL_NAME}"`);
+
+ // t3: TRIPWIRE — on preview, session A's turns stay pinned to the
+ // deployment that created it, so its sandbox key never rotates and the
+ // file is still present. When turn dispatch gains preview
+ // latest-routing (issue #582), this gate flips to /absent/ (and the
+ // skill becomes loadable in session A too).
+ const probe = await t.send(
+ `Run the bash command \`test -f ${FILE_PATH} && echo present || echo absent\` ` +
+ "and reply with the command output verbatim.",
+ );
+ probe.expectOk();
+ probe.calledTool("bash", { output: /present/ });
+ probe.messageIncludes("present");
+
+ // t4: a fresh session adopts the new deployment — the added skill is
+ // advertised and usable.
+ const adopted = t.newSession();
+ const skill = await adopted.send(
+ "Please use the deploy note skill and follow its instructions exactly.",
+ );
+ skill.expectOk();
+ skill.loadedSkill(SKILL_NAME);
+ skill.messageIncludes(SKILL_TOKEN);
+ } finally {
+ await writeFile(INSTRUCTIONS_PATH, originalInstructions);
+ await rm(SKILL_PATH, { force: true });
+ }
+ },
+});
+
+/** Builds the fixture and repoints the alias at the fresh deployment. */
+async function deployToAlias(t: EveEvalContext, alias: string, phase: string): Promise<void> {
+ // Mirror the workflow's build env. Sandbox templates key on
+ // VERCEL_PROJECT_ID (already in the environment); the deployment id is
+ // deliberately ignored by sandbox keys but must be present at build.
+ await execFileAsync("pnpm", ["exec", "eve", "build"], {
+ ...EXEC_OPTIONS,
+ env: {
+ ...process.env,
+ VERCEL: "1",
+ VERCEL_ENV: "preview",
+ VERCEL_TARGET_ENV: "preview",
+ VERCEL_DEPLOYMENT_ID: `dpl_eve_e2e_redeploy_${phase}_${Date.now()}`,
+ },
+ });
+
+ const tokenArgs =
+ process.env.VERCEL_TOKEN === undefined ? [] : ["--token", process.env.VERCEL_TOKEN];
+ // vc alias does not infer the team from the project link the way deploy
+ // does, so pass the scope explicitly.
+ const scopeArgs =
+ process.env.VERCEL_ORG_ID === undefined ? [] : ["--scope", process.env.VERCEL_ORG_ID];
+ const deploy = await execFileAsync(
+ "pnpm",
+ ["exec", "vc", "deploy", "--prebuilt", "--yes", "--target=preview", ...tokenArgs],
+ EXEC_OPTIONS,
+ );
+ const deploymentUrl = deploy.stdout.trim().split("\n").at(-1)?.trim();
+ if (deploymentUrl === undefined || !deploymentUrl.startsWith("https://")) {
+ throw new Error(`vc deploy did not print a deployment URL; got: ${deploy.stdout}`);
+ }
+ t.log(`deployed ${deploymentUrl} (${phase}); aliasing ${alias}`);
+
+ await execFileAsync(
+ "pnpm",
+ ["exec", "vc", "alias", "set", deploymentUrl, alias, ...tokenArgs, ...scopeArgs],
+ EXEC_OPTIONS,
+ );
+}
+
+/**
+ * Polls `/eve/v1/info` until the alias serves a deployment whose manifest
+ * contains `marker`, so post-redeploy turns cannot hit a stale deployment.
+ */
+async function waitForAliasToServe(t: EveEvalContext, marker: string): Promise<void> {
+ const deadline = Date.now() + 120_000;
+ while (Date.now() < deadline) {
+ const response = await t.target.fetch("/eve/v1/info");
+ if (response.ok && JSON.stringify(await response.json()).includes(marker)) {
+ return;
+ }
+ await t.sleep(1_000);
+ }
+ throw new Error(`Timed out waiting for the alias to serve a deployment containing ${marker}.`);
+}
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts b/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts
index f5224c2ef..dadbd679a 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts
@@ -1,4 +1,5 @@
import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";
+import { decodeVercelOidcTokenClaims } from "#shared/vercel-project.js";
import { withEveSandboxUserAgent } from "#execution/sandbox/bindings/vercel-user-agent.js";
import type { VercelCreateOptions } from "#execution/sandbox/bindings/vercel-sdk-types.js";
@@ -44,27 +45,12 @@ function readNonEmptyEnvironmentVariable(key: string): string | undefined {
}
function getVercelSandboxCredentialsFromOidcToken(token: string): VercelSandboxCredentials {
- const payloadSegment = token.split(".")[1];
- if (payloadSegment === undefined) {
- throw new Error("Invalid Vercel OIDC token: missing payload.");
- }
-
- const payload = JSON.parse(
- Buffer.from(base64UrlToBase64(payloadSegment), "base64").toString("utf8"),
- ) as { owner_id?: unknown; project_id?: unknown };
- const teamId = typeof payload.owner_id === "string" ? payload.owner_id : undefined;
- const projectId = typeof payload.project_id === "string" ? payload.project_id : undefined;
-
- if (teamId === undefined || projectId === undefined) {
+ const claims = decodeVercelOidcTokenClaims(token);
+ if (claims.ownerId === undefined || claims.projectId === undefined) {
throw new Error("Invalid Vercel OIDC token: missing owner_id or project_id.");
}
- return { projectId, teamId, token };
-}
-
-function base64UrlToBase64(value: string): string {
- const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
- return base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
+ return { projectId: claims.projectId, teamId: claims.ownerId, token };
}
export interface VercelSandboxCredentials {
diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.ts
index 73979a3e9..db07d14fc 100644
--- a/packages/eve/src/execution/sandbox/ensure.test.ts
+++ b/packages/eve/src/execution/sandbox/ensure.test.ts
@@ -27,6 +27,7 @@ import {
getInitializedDevelopmentSandboxBackendNames,
} from "#execution/sandbox/development-run.js";
import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
+import type { SandboxState } from "#sandbox/state.js";
const mocks = vi.hoisted(() => ({
prewarmAppSandboxes: vi.fn(async () => {}),
@@ -87,6 +88,7 @@ async function ensure(input: {
readonly compiledArtifactsSource?: RuntimeCompiledArtifactsSource;
readonly runOnSession?: (callback: () => Promise<void>) => Promise<void>;
readonly registry: RuntimeSandboxRegistry;
+ readonly state?: SandboxState;
readonly tags?: Record<string, string>;
}) {
return await ensureSandboxAccess({
@@ -96,7 +98,7 @@ async function ensure(input: {
registry: input.registry,
runOnSession: input.runOnSession,
sessionId: "session_1",
- state: null,
+ state: input.state ?? null,
tags: input.tags,
});
}
@@ -271,6 +273,52 @@ describe("ensureSandboxAccess", () => {
});
});
+ it("reattaches with persisted metadata and skips onSession when the session key matches", async () => {
+ const ctx = new ContextContainer();
+ ctx.set(SessionKey, createSession());
+ const runOnSession = async (callback: () => Promise<void>) =>
+ await contextStorage.run(ctx, callback);
+ const onSession = vi.fn();
+ const backend = createBackend();
+ const registry = createTestRegistry({ onSession }, backend);
+
+ const first = await ensure({ registry, runOnSession });
+ await first.get();
+ const state = await first.captureState();
+ expect(onSession).toHaveBeenCalledTimes(1);
+
+ const second = await ensure({ registry, runOnSession, state });
+ await second.get();
+
+ expect(onSession).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(backend.create).mock.calls[1]?.[0].existingMetadata).toEqual({});
+ });
+
+ it("re-runs onSession and drops stale metadata when the session key rotates", async () => {
+ const ctx = new ContextContainer();
+ ctx.set(SessionKey, createSession());
+ const onSession = vi.fn();
+ const backend = createBackend();
+ const registry = createTestRegistry({ onSession }, backend);
+
+ const access = await ensure({
+ registry,
+ runOnSession: async (callback) => await contextStorage.run(ctx, callback),
+ state: {
+ initialized: true,
+ session: {
+ backendName: "test",
+ metadata: { sandboxName: "stale" },
+ sessionKey: "eve-sbx-ses-test-stale-key",
+ },
+ },
+ });
+ await access.get();
+
+ expect(onSession).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(backend.create).mock.calls[0]?.[0].existingMetadata).toBeUndefined();
+ });
+
it("does not pass bootstrap or seed files to runtime create", async () => {
const bootstrap = vi.fn();
const backend = createBackend();
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index 30f84387f..6e63e3065 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -105,12 +105,23 @@ export async function ensureSandboxAccess(input: EnsureSandboxAccessInput): Prom
});
}
+ // The session eve may reattach to: the persisted record is only
+ // meaningful when it names the sandbox this step derived. A rotated
+ // session key (the sandbox definition changed) means the backend
+ // provisions a fresh sandbox, so per-session initialization must run
+ // again even though the durable state says it already did.
+ const reattachSession =
+ persistedSession !== null &&
+ persistedSession.backendName === backend.name &&
+ persistedSession.sessionKey === keys.sessionKey
+ ? persistedSession
+ : null;
+ if (reattachSession === null) {
+ initialized = false;
+ }
+
const createInput: SandboxBackendCreateInput = {
- existingMetadata:
- persistedSession?.backendName === backend.name &&
- persistedSession.sessionKey === keys.sessionKey
- ? persistedSession.metadata
- : undefined,
+ existingMetadata: reattachSession?.metadata,
runtimeContext: { appRoot },
sessionKey: keys.sessionKey,
tags: input.tags,
diff --git a/packages/eve/src/internal/testing/vercel-oidc-token.ts b/packages/eve/src/internal/testing/vercel-oidc-token.ts
new file mode 100644
index 000000000..f1c44da9c
--- /dev/null
+++ b/packages/eve/src/internal/testing/vercel-oidc-token.ts
@@ -0,0 +1,9 @@
+/**
+ * Builds a syntactically valid, unsigned Vercel OIDC token for tests.
+ * eve only ever reads payload claims and never verifies signatures, so
+ * a fixed header and a literal signature segment suffice.
+ */
+export function createFakeVercelOidcToken(claims: Record<string, unknown>): string {
+ const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
+ return `${encode({ alg: "none" })}.${encode(claims)}.signature`;
+}
diff --git a/packages/eve/src/runtime/sandbox/keys.test.ts b/packages/eve/src/runtime/sandbox/keys.test.ts
index 4f12ccc4d..1fe110db6 100644
--- a/packages/eve/src/runtime/sandbox/keys.test.ts
+++ b/packages/eve/src/runtime/sandbox/keys.test.ts
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
COMPILE_METADATA_KIND,
@@ -8,9 +8,13 @@ import {
} from "#compiler/artifacts.js";
import { createCompiledAgentManifest } from "#compiler/manifest.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
+import { createFakeVercelOidcToken } from "#internal/testing/vercel-oidc-token.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { withBundledCompiledArtifacts } from "#runtime/loaders/bundled-artifacts.js";
-import { createRuntimeSandboxTemplateKey } from "#runtime/sandbox/keys.js";
+import {
+ createRuntimeSandboxKeys,
+ createRuntimeSandboxTemplateKey,
+} from "#runtime/sandbox/keys.js";
const RUNTIME_SANDBOX_CONTRACT_VERSION = 7;
@@ -73,6 +77,110 @@ function withBundledMetadata<T>(
return withBundledCompiledArtifacts({ manifest, metadata, moduleMap: { nodes: {} } }, fn);
}
+async function deriveSessionKey(input?: {
+ readonly backendName?: string;
+ readonly contentHash?: string;
+}): Promise<string> {
+ const keys = await createRuntimeSandboxKeys({
+ backendName: input?.backendName ?? "local",
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
+ sessionId: "session_1",
+ sourceId: "eve:default-sandbox",
+ templatePlan: {
+ contentHash: input?.contentHash ?? CONTENT_HASH,
+ kind: "workspace-content",
+ },
+ });
+ return keys.sessionKey;
+}
+
+/**
+ * Derives one vercel-backed session key under exactly the given env.
+ * Unlisted project and deployment variables are stubbed empty so ambient
+ * CI values cannot leak into the derivation.
+ */
+async function deriveVercelSessionKey(env: Record<string, string>): Promise<string> {
+ const stubbed = {
+ VERCEL_DEPLOYMENT_ID: "",
+ VERCEL_OIDC_TOKEN: "",
+ VERCEL_PROJECT_ID: "",
+ ...env,
+ };
+ for (const [key, value] of Object.entries(stubbed)) {
+ vi.stubEnv(key, value);
+ }
+
+ return await withBundledMetadata(createMetadataFixture("1.0.0"), () =>
+ deriveSessionKey({ backendName: "vercel" }),
+ );
+}
+
+describe("createRuntimeSandboxKeys", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("pins the vercel session key across deployments when only the OIDC token names the project", async () => {
+ const token = createFakeVercelOidcToken({ project_id: "prj_123" });
+
+ const first = await deriveVercelSessionKey({
+ VERCEL_DEPLOYMENT_ID: "dpl_first",
+ VERCEL_OIDC_TOKEN: token,
+ });
+ const second = await deriveVercelSessionKey({
+ VERCEL_DEPLOYMENT_ID: "dpl_second",
+ VERCEL_OIDC_TOKEN: token,
+ });
+
+ expect(first).toBe(second);
+ });
+
+ it("derives the same session key from the project id env var and the OIDC token claim", async () => {
+ const fromEnv = await deriveVercelSessionKey({ VERCEL_PROJECT_ID: "prj_123" });
+ const fromToken = await deriveVercelSessionKey({
+ VERCEL_OIDC_TOKEN: createFakeVercelOidcToken({ project_id: "prj_123" }),
+ });
+
+ expect(fromEnv).toBe(fromToken);
+ });
+
+ it("never scopes the session key by deployment id, even without a resolvable project id", async () => {
+ const first = await deriveVercelSessionKey({ VERCEL_DEPLOYMENT_ID: "dpl_first" });
+ const second = await deriveVercelSessionKey({ VERCEL_DEPLOYMENT_ID: "dpl_second" });
+
+ expect(first).toBe(second);
+ });
+
+ it("keeps the session key stable across unrelated source and eve version changes", async () => {
+ const changedMetadata = createMetadataFixture("2.0.0");
+
+ const first = await withBundledMetadata(createMetadataFixture("1.0.0"), () =>
+ deriveSessionKey(),
+ );
+ const second = await withBundledMetadata(
+ {
+ ...changedMetadata,
+ discovery: { ...changedMetadata.discovery, sourceGraphHash: "f".repeat(64) },
+ },
+ () => deriveSessionKey(),
+ );
+
+ expect(first).toBe(second);
+ });
+
+ it("rotates the session key when the sandbox content changes", async () => {
+ const first = await withBundledMetadata(createMetadataFixture("1.0.0"), () =>
+ deriveSessionKey(),
+ );
+ const second = await withBundledMetadata(createMetadataFixture("1.0.0"), () =>
+ deriveSessionKey({ contentHash: "b".repeat(64) }),
+ );
+
+ expect(first).not.toBe(second);
+ });
+});
+
describe("createRuntimeSandboxTemplateKey", () => {
it("derives the version segment from compile metadata so build and runtime agree", async () => {
const templateKey = await withBundledMetadata(
diff --git a/packages/eve/src/runtime/sandbox/keys.ts b/packages/eve/src/runtime/sandbox/keys.ts
index d360ea77b..df77074a9 100644
--- a/packages/eve/src/runtime/sandbox/keys.ts
+++ b/packages/eve/src/runtime/sandbox/keys.ts
@@ -8,6 +8,7 @@ import {
type RuntimeCompiledArtifactsSource,
} from "#runtime/compiled-artifacts-source.js";
import { loadCompileMetadata } from "#runtime/loaders/compile-metadata.js";
+import { resolveVercelProjectIdFromEnvironment } from "#shared/vercel-project.js";
import type { RuntimeSandboxTemplatePlan } from "#runtime/sandbox/template-plan.js";
/*
@@ -32,14 +33,19 @@ interface CreateRuntimeSandboxKeysInput {
/**
* Creates the stable runtime template and session keys for one sandbox
* definition under the current artifact source and backend.
+ *
+ * Both keys derive from one {@link RuntimeSandboxKeyParts} value, so the
+ * coupling holds by construction: the session key rotates exactly when
+ * the template content rotates.
*/
export async function createRuntimeSandboxKeys(input: CreateRuntimeSandboxKeysInput): Promise<{
readonly sessionKey: string;
readonly templateKey: string | null;
}> {
+ const parts = await deriveRuntimeSandboxKeyParts(input);
return {
- sessionKey: await createRuntimeSandboxSessionKey(input),
- templateKey: await createRuntimeSandboxTemplateKey(input),
+ sessionKey: buildRuntimeSandboxSessionKey(input, parts),
+ templateKey: buildRuntimeSandboxTemplateKey(input, parts),
};
}
@@ -59,28 +65,83 @@ export async function createRuntimeSandboxTemplateKey(input: {
readonly sourceId: string;
readonly templatePlan: RuntimeSandboxTemplatePlan;
}): Promise<string | null> {
- if (input.templatePlan.kind === "none") {
+ return buildRuntimeSandboxTemplateKey(input, await deriveRuntimeSandboxKeyParts(input));
+}
+
+/**
+ * The facts both keys derive from, computed once per derivation:
+ * compile metadata, the partition scope, and the sandbox definition's
+ * version hash (`null` when the sandbox needs no template).
+ */
+interface RuntimeSandboxKeyParts {
+ readonly metadata: CompileMetadata | null;
+ readonly scope: string;
+ readonly versionHash: string | null;
+}
+
+async function deriveRuntimeSandboxKeyParts(input: {
+ readonly backendName: string;
+ readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
+ readonly nodeId: string;
+ readonly sourceId: string;
+ readonly templatePlan: RuntimeSandboxTemplatePlan;
+}): Promise<RuntimeSandboxKeyParts> {
+ const metadata = await loadCompileMetadataForKeys(input.compiledArtifactsSource);
+ const scope = await resolveRuntimeSandboxScope(input);
+ const versionHash =
+ input.templatePlan.kind === "none"
+ ? null
+ : resolveRuntimeSandboxVersionHash({
+ compiledArtifactsSource: input.compiledArtifactsSource,
+ metadata,
+ nodeId: input.nodeId,
+ sourceId: input.sourceId,
+ templatePlan: input.templatePlan,
+ });
+ return { metadata, scope, versionHash };
+}
+
+function buildRuntimeSandboxTemplateKey(
+ input: { readonly backendName: string },
+ parts: RuntimeSandboxKeyParts,
+): string | null {
+ if (parts.versionHash === null) {
return null;
}
- const metadata = await loadCompileMetadataForKeys(input.compiledArtifactsSource);
- const scope = await resolveRuntimeSandboxScope({
- backendName: input.backendName,
- compiledArtifactsSource: input.compiledArtifactsSource,
- scopeKind: input.templatePlan.kind === "source-graph" ? "deployment" : "stable",
- });
- const versionHash = resolveRuntimeSandboxVersionHash({
- compiledArtifactsSource: input.compiledArtifactsSource,
- metadata,
- nodeId: input.nodeId,
- sourceId: input.sourceId,
- templatePlan: input.templatePlan,
- });
const templateHash = createStableHash(
- `${resolvePackageVersionForTemplateKey(metadata)}:${RUNTIME_SANDBOX_CONTRACT_VERSION}:${versionHash}`,
+ `${resolvePackageVersionForTemplateKey(parts.metadata)}:${RUNTIME_SANDBOX_CONTRACT_VERSION}:${parts.versionHash}`,
).slice(0, 20);
- return sanitizeRuntimeSandboxKey(`eve-sbx-tpl-${input.backendName}-${scope}-${templateHash}`);
+ return sanitizeRuntimeSandboxKey(
+ `eve-sbx-tpl-${input.backendName}-${parts.scope}-${templateHash}`,
+ );
+}
+
+/**
+ * Builds the session sandbox key for one sandbox definition.
+ *
+ * Session keys are pinned per durable session: the scope is stable across
+ * deployments so a session reattaches to the same sandbox after a redeploy
+ * and keeps its `/workspace` state. The key also folds in the sandbox
+ * definition's version hash, so changing the sandbox itself (bootstrap
+ * source, `revalidationKey`, or workspace seed content) rotates the
+ * session sandbox onto the new template — unrelated source changes do not.
+ * The eve package version deliberately does not participate: upgrading
+ * eve must not discard session sandbox state.
+ */
+function buildRuntimeSandboxSessionKey(
+ input: { readonly backendName: string; readonly nodeId: string; readonly sessionId: string },
+ parts: RuntimeSandboxKeyParts,
+): string {
+ const version = createStableHash(
+ `${RUNTIME_SANDBOX_CONTRACT_VERSION}:${parts.versionHash ?? "none"}`,
+ ).slice(0, 12);
+ const nodeScope = sanitizeRuntimeSandboxKey(input.nodeId);
+
+ return sanitizeRuntimeSandboxKey(
+ `eve-sbx-ses-${input.backendName}-${parts.scope}-${version}-${input.sessionId}-${nodeScope}`,
+ );
}
/**
@@ -108,52 +169,28 @@ async function loadCompileMetadataForKeys(
}
}
-async function createRuntimeSandboxSessionKey(input: {
- readonly backendName: string;
- readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
- readonly nodeId: string;
- readonly sessionId: string;
-}): Promise<string> {
- const scope = await resolveRuntimeSandboxScope({
- backendName: input.backendName,
- compiledArtifactsSource: input.compiledArtifactsSource,
- scopeKind: "deployment",
- });
- const nodeScope = sanitizeRuntimeSandboxKey(input.nodeId);
-
- return sanitizeRuntimeSandboxKey(
- `eve-sbx-ses-${input.backendName}-${scope}-${input.sessionId}-${nodeScope}`,
- );
-}
-
/**
- * Resolves the partition key used in Vercel Sandbox template/session names.
+ * Resolves the partition scope shared by template and session keys.
*
- * Source-graph templates use deployment id for Vercel. Stable templates
- * prefer the Vercel project id, then fall back through deployment id,
- * realpath(appRoot), and the compiled-artifacts cache key.
+ * On Vercel the scope is the project id (env var or OIDC token claim),
+ * never a deployment-scoped identifier: a key that varies per deployment
+ * would discard prewarmed templates and, worse, silently discard session
+ * sandbox state on every redeploy. The project id is also the only
+ * identifier Vercel exposes at both build-time prewarm and deployed
+ * runtime; a build-only identifier (e.g. team id) would leave the
+ * prewarmed template "not provisioned" at runtime.
*
- * Stable scopes key on `VERCEL_PROJECT_ID` alone because it is the only
- * identifier Vercel exposes at both build-time prewarm and deployed runtime;
- * any build-only identifier (e.g. team id) would leave the prewarmed template
- * "not provisioned" at runtime.
+ * Everywhere else the scope falls back to realpath(appRoot), then the
+ * compiled-artifacts cache key.
*/
async function resolveRuntimeSandboxScope(input: {
readonly backendName: string;
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
- readonly scopeKind: "deployment" | "stable";
}): Promise<string> {
if (input.backendName === "vercel") {
- if (input.scopeKind === "stable") {
- const projectScope = resolveVercelProjectScope();
- if (projectScope !== undefined) {
- return createStableHash(projectScope).slice(0, 16);
- }
- }
-
- const deploymentId = process.env.VERCEL_DEPLOYMENT_ID?.trim();
- if (deploymentId !== undefined && deploymentId.length > 0) {
- return createStableHash(deploymentId).slice(0, 16);
+ const projectId = resolveVercelProjectIdFromEnvironment();
+ if (projectId !== undefined) {
+ return createStableHash(`vercel-project:${projectId}`).slice(0, 16);
}
}
@@ -175,25 +212,18 @@ function resolveRuntimeSandboxVersionHash(input: {
readonly sourceId: string;
readonly templatePlan: Exclude<RuntimeSandboxTemplatePlan, { readonly kind: "none" }>;
}): string {
+ const contentHash =
+ input.templatePlan.contentHash ??
+ resolveSourceGraphHash(input.metadata, input.compiledArtifactsSource);
+
if (input.templatePlan.kind === "bootstrap") {
- const contentHash =
- input.templatePlan.contentHash ??
- resolveSourceGraphHash(input.metadata, input.compiledArtifactsSource);
const revalidationKey = input.templatePlan.revalidationKey ?? "";
return createStableHash(
`bootstrap:${revalidationKey}:${input.templatePlan.sourceHash}:${contentHash}:${input.nodeId}:${input.sourceId}`,
);
}
- if (input.templatePlan.kind === "workspace-content") {
- const contentHash =
- input.templatePlan.contentHash ??
- resolveSourceGraphHash(input.metadata, input.compiledArtifactsSource);
- return createStableHash(`workspace-content:${contentHash}:${input.nodeId}:${input.sourceId}`);
- }
-
- const sourceGraphHash = resolveSourceGraphHash(input.metadata, input.compiledArtifactsSource);
- return createStableHash(`source-graph:${sourceGraphHash}:${input.nodeId}:${input.sourceId}`);
+ return createStableHash(`workspace-content:${contentHash}:${input.nodeId}:${input.sourceId}`);
}
function resolveSourceGraphHash(
@@ -206,15 +236,6 @@ function resolveSourceGraphHash(
);
}
-function resolveVercelProjectScope(): string | undefined {
- const projectId = process.env.VERCEL_PROJECT_ID?.trim();
- if (projectId === undefined || projectId.length === 0) {
- return undefined;
- }
-
- return `vercel-project:${projectId}`;
-}
-
function createStableHash(value: string): string {
return createHash("sha256").update(value).digest("hex");
}
diff --git a/packages/eve/src/runtime/sandbox/template-plan.ts b/packages/eve/src/runtime/sandbox/template-plan.ts
index 729597701..24989b03c 100644
--- a/packages/eve/src/runtime/sandbox/template-plan.ts
+++ b/packages/eve/src/runtime/sandbox/template-plan.ts
@@ -18,9 +18,6 @@ export type RuntimeSandboxTemplatePlan =
readonly kind: "bootstrap";
readonly revalidationKey?: string;
readonly sourceHash: string;
- }
- | {
- readonly kind: "source-graph";
};
/**
diff --git a/packages/eve/src/services/dev-client/request-headers.test.ts b/packages/eve/src/services/dev-client/request-headers.test.ts
index 7897d3bf0..20a86d8e0 100644
--- a/packages/eve/src/services/dev-client/request-headers.test.ts
+++ b/packages/eve/src/services/dev-client/request-headers.test.ts
@@ -1,4 +1,5 @@
import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";
+import { createFakeVercelOidcToken } from "#internal/testing/vercel-oidc-token.js";
import { readVercelProjectLink } from "#internal/vercel/project-link.js";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -18,9 +19,7 @@ vi.mock("#internal/vercel/project-link.js", () => ({
const target = { ownerId: "team_expected", projectId: "prj_expected" } as const;
-function token(claims: Record<string, string>): string {
- return `header.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.signature`;
-}
+const token = createFakeVercelOidcToken;
afterEach(() => {
vi.mocked(getVercelOidcToken).mockReset();
diff --git a/packages/eve/src/shared/vercel-project.test.ts b/packages/eve/src/shared/vercel-project.test.ts
new file mode 100644
index 000000000..9b65913d2
--- /dev/null
+++ b/packages/eve/src/shared/vercel-project.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createFakeVercelOidcToken } from "#internal/testing/vercel-oidc-token.js";
+import {
+ decodeVercelOidcTokenClaims,
+ resolveVercelProjectIdFromEnvironment,
+} from "#shared/vercel-project.js";
+
+const EMPTY_CLAIMS = { ownerId: undefined, projectId: undefined };
+
+describe("decodeVercelOidcTokenClaims", () => {
+ it("decodes owner and project claims", () => {
+ const claims = decodeVercelOidcTokenClaims(
+ createFakeVercelOidcToken({ owner_id: "team_1", project_id: "prj_123" }),
+ );
+
+ expect(claims).toEqual({ ownerId: "team_1", projectId: "prj_123" });
+ });
+
+ it("decodes missing or non-string claims as undefined fields", () => {
+ expect(decodeVercelOidcTokenClaims(createFakeVercelOidcToken({ project_id: 42 }))).toEqual(
+ EMPTY_CLAIMS,
+ );
+ });
+
+ it("decodes values that are not JWTs to empty claims", () => {
+ expect(decodeVercelOidcTokenClaims("not-a-jwt")).toEqual(EMPTY_CLAIMS);
+ expect(decodeVercelOidcTokenClaims("a.!!!.c")).toEqual(EMPTY_CLAIMS);
+ expect(decodeVercelOidcTokenClaims(`a.${Buffer.from("[]").toString("base64url")}.c`)).toEqual(
+ EMPTY_CLAIMS,
+ );
+ expect(decodeVercelOidcTokenClaims(`a.${Buffer.from("null").toString("base64url")}.c`)).toEqual(
+ EMPTY_CLAIMS,
+ );
+ });
+});
+
+describe("resolveVercelProjectIdFromEnvironment", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("prefers the VERCEL_PROJECT_ID env var", () => {
+ vi.stubEnv("VERCEL_PROJECT_ID", "prj_env");
+ vi.stubEnv("VERCEL_OIDC_TOKEN", createFakeVercelOidcToken({ project_id: "prj_token" }));
+
+ expect(resolveVercelProjectIdFromEnvironment()).toBe("prj_env");
+ });
+
+ it("falls back to the OIDC token project claim", () => {
+ vi.stubEnv("VERCEL_PROJECT_ID", "");
+ vi.stubEnv("VERCEL_OIDC_TOKEN", createFakeVercelOidcToken({ project_id: "prj_token" }));
+
+ expect(resolveVercelProjectIdFromEnvironment()).toBe("prj_token");
+ });
+
+ it("returns undefined when neither source names a project", () => {
+ vi.stubEnv("VERCEL_PROJECT_ID", "");
+ vi.stubEnv("VERCEL_OIDC_TOKEN", "");
+
+ expect(resolveVercelProjectIdFromEnvironment()).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/shared/vercel-project.ts b/packages/eve/src/shared/vercel-project.ts
new file mode 100644
index 000000000..fb8f9a3fd
--- /dev/null
+++ b/packages/eve/src/shared/vercel-project.ts
@@ -0,0 +1,62 @@
+/**
+ * Claims eve reads from a Vercel OIDC token payload.
+ *
+ * Decoded locally without signature verification: callers use the values
+ * as stable identifiers (sandbox key derivation, credential routing),
+ * never to make authentication decisions.
+ */
+export interface VercelOidcTokenClaims {
+ readonly ownerId: string | undefined;
+ readonly projectId: string | undefined;
+}
+
+const EMPTY_CLAIMS: VercelOidcTokenClaims = { ownerId: undefined, projectId: undefined };
+
+/**
+ * Decodes the payload claims of a Vercel OIDC token. Values that are not
+ * decodable JWTs, or that carry no recognized claims, decode to empty
+ * claims — callers only ever check individual fields.
+ */
+export function decodeVercelOidcTokenClaims(token: string): VercelOidcTokenClaims {
+ const payloadSegment = token.split(".")[1];
+ if (payloadSegment === undefined || payloadSegment.length === 0) {
+ return EMPTY_CLAIMS;
+ }
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(Buffer.from(payloadSegment, "base64url").toString("utf8"));
+ } catch {
+ return EMPTY_CLAIMS;
+ }
+ if (payload === null || typeof payload !== "object") {
+ return EMPTY_CLAIMS;
+ }
+
+ const claims = payload as { readonly owner_id?: unknown; readonly project_id?: unknown };
+ return {
+ ownerId: typeof claims.owner_id === "string" ? claims.owner_id : undefined,
+ projectId: typeof claims.project_id === "string" ? claims.project_id : undefined,
+ };
+}
+
+/**
+ * Resolves the Vercel project id visible to this process: the
+ * `VERCEL_PROJECT_ID` env var when exposed, otherwise the `project_id`
+ * claim of `VERCEL_OIDC_TOKEN`. Both sources exist at build time and at
+ * deployed runtime and name the same project, so identifiers derived
+ * from this value agree across the two phases.
+ */
+export function resolveVercelProjectIdFromEnvironment(): string | undefined {
+ const projectId = process.env.VERCEL_PROJECT_ID?.trim();
+ if (projectId !== undefined && projectId.length > 0) {
+ return projectId;
+ }
+
+ const token = process.env.VERCEL_OIDC_TOKEN?.trim();
+ if (token === undefined || token.length === 0) {
+ return undefined;
+ }
+
+ return decodeVercelOidcTokenClaims(token).projectId;
+}
diff --git a/packages/eve/test/scenarios/runtime-sandbox-keys.scenario.test.ts b/packages/eve/test/scenarios/runtime-sandbox-keys.scenario.test.ts
index 637d7bfa4..6da942199 100644
--- a/packages/eve/test/scenarios/runtime-sandbox-keys.scenario.test.ts
+++ b/packages/eve/test/scenarios/runtime-sandbox-keys.scenario.test.ts
@@ -50,34 +50,19 @@ async function createTemporaryAppRoot(options?: { sourceGraphHash?: string }): P
return appRoot;
}
-describe("createRuntimeSandboxTemplateKey", () => {
- it("derives Vercel template keys from VERCEL_DEPLOYMENT_ID when one is set", async () => {
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_123");
- vi.stubEnv("VERCEL_URL", "preview-456.vercel.app");
-
- const keyWithBoth = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: { kind: "source-graph" },
- });
-
- vi.stubEnv("VERCEL_URL", "");
-
- const keyWithDeploymentIdOnly = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: { kind: "source-graph" },
- });
-
- expect(keyWithBoth).toBe(keyWithDeploymentIdOnly);
- });
+const WORKSPACE_PLAN = { contentHash: "workspace-hash", kind: "workspace-content" } as const;
+
+function stubEmptyVercelProjectSources(): void {
+ vi.stubEnv("VERCEL_PROJECT_ID", "");
+ vi.stubEnv("VERCEL_OIDC_TOKEN", "");
+ // A deployment id must never participate in template scopes; set one to
+ // prove the fallback ignores it.
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_123");
+}
- it("falls back to the realpath of the disk app root for the Vercel adapter when VERCEL_DEPLOYMENT_ID is missing", async () => {
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "");
+describe("createRuntimeSandboxTemplateKey", () => {
+ it("falls back to the realpath of the disk app root for the Vercel adapter when no project id is resolvable", async () => {
+ stubEmptyVercelProjectSources();
const appRoot = await createTemporaryAppRoot();
const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(appRoot);
@@ -87,7 +72,7 @@ describe("createRuntimeSandboxTemplateKey", () => {
compiledArtifactsSource,
nodeId: "__root__",
sourceId: "sandbox/sandbox.ts",
- templatePlan: { kind: "source-graph" },
+ templatePlan: WORKSPACE_PLAN,
});
const secondKey = await createRuntimeSandboxTemplateKey({
@@ -95,15 +80,15 @@ describe("createRuntimeSandboxTemplateKey", () => {
compiledArtifactsSource,
nodeId: "__root__",
sourceId: "sandbox/sandbox.ts",
- templatePlan: { kind: "source-graph" },
+ templatePlan: WORKSPACE_PLAN,
});
expect(firstKey).toMatch(/^eve-sbx-tpl-vercel-/);
expect(secondKey).toBe(firstKey);
});
- it("isolates Vercel template keys per app root when VERCEL_DEPLOYMENT_ID is missing", async () => {
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "");
+ it("isolates Vercel template keys per app root when no project id is resolvable", async () => {
+ stubEmptyVercelProjectSources();
const firstAppRoot = await createTemporaryAppRoot();
const secondAppRoot = await createTemporaryAppRoot();
@@ -113,28 +98,28 @@ describe("createRuntimeSandboxTemplateKey", () => {
compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(firstAppRoot),
nodeId: "__root__",
sourceId: "sandbox/sandbox.ts",
- templatePlan: { kind: "source-graph" },
+ templatePlan: WORKSPACE_PLAN,
});
const secondKey = await createRuntimeSandboxTemplateKey({
backendName: "vercel",
compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(secondAppRoot),
nodeId: "__root__",
sourceId: "sandbox/sandbox.ts",
- templatePlan: { kind: "source-graph" },
+ templatePlan: WORKSPACE_PLAN,
});
expect(firstKey).not.toBe(secondKey);
});
- it("falls back to the bundled cache key for the Vercel adapter when no app root and no VERCEL_DEPLOYMENT_ID are available", async () => {
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "");
+ it("falls back to the bundled cache key for the Vercel adapter when no app root and no project id are available", async () => {
+ stubEmptyVercelProjectSources();
const key = await createRuntimeSandboxTemplateKey({
backendName: "vercel",
compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
nodeId: "__root__",
sourceId: "sandbox/sandbox.ts",
- templatePlan: { kind: "source-graph" },
+ templatePlan: WORKSPACE_PLAN,
});
expect(key).toMatch(/^eve-sbx-tpl-vercel-/);