Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): mint workflow callback URLs with the agent's public route prefix (#1099)

Rui8168518defa4
diff --git a/.changeset/callback-urls-per-agent-prefix.md b/.changeset/callback-urls-per-agent-prefix.md
new file mode 100644
index 000000000..2311d7bf2
--- /dev/null
+++ b/.changeset/callback-urls-per-agent-prefix.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Fix connector-auth and remote-subagent callback URLs returning 404 in multi-agent mode. Generated per-agent Vercel services now bake the agent's public route prefix (`/eve/agents/<name>`) into their workflow function environment via `EVE_PUBLIC_ROUTE_PREFIX`, framework-minted callback URLs prepend it, and the session-callback validator accepts callback URLs mounted behind a route prefix so OAuth redirects and remote-subagent session callbacks reach the deployed agent.
diff --git a/docs/guides/frontend/nextjs.mdx b/docs/guides/frontend/nextjs.mdx
index 9277207f8..128b98399 100644
--- a/docs/guides/frontend/nextjs.mdx
+++ b/docs/guides/frontend/nextjs.mdx
@@ -54,6 +54,8 @@ const billing = useEveAgent({ agent: "billing" });
Use either `eveRoot` or `agents`, not both. `eveRoot` remains the shorthand for a single unnamed agent mounted at `/eve/v1/*`.
+Generated agent services build with `EVE_PUBLIC_ROUTE_PREFIX` set to the agent's public mount (for example `/eve/agents/support`) so framework-minted callback URLs — OAuth connection callbacks and remote-subagent session callbacks — resolve to the public per-agent path. If you configure eve services manually in `vercel.json` instead, export that variable in each named agent's build command.
+
### `withEve` options
All fields are optional.
diff --git a/packages/eve/src/channel/session-callback.test.ts b/packages/eve/src/channel/session-callback.test.ts
new file mode 100644
index 000000000..e08f98d6f
--- /dev/null
+++ b/packages/eve/src/channel/session-callback.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from "vitest";
+
+import { parseSessionCallback } from "#channel/session-callback.js";
+
+function createCallback(url: string, token = "tok123"): Record<string, unknown> {
+ return {
+ callId: "call-1",
+ subagentName: "research",
+ token,
+ url,
+ };
+}
+
+describe("parseSessionCallback callback-URL token extraction", () => {
+ it("accepts a callback URL mounted at the origin root", () => {
+ expect(
+ parseSessionCallback(createCallback("https://agent.example.com/eve/v1/callback/tok123")),
+ ).toMatchObject({ ok: true });
+ });
+
+ it("accepts a callback URL mounted behind a public route prefix", () => {
+ expect(
+ parseSessionCallback(
+ createCallback("https://agent.example.com/eve/agents/support/eve/v1/callback/tok123"),
+ ),
+ ).toMatchObject({ ok: true });
+ });
+
+ it("reads the token from the last callback route segment", () => {
+ expect(
+ parseSessionCallback(
+ createCallback("https://agent.example.com/eve/v1/callback/x/eve/v1/callback/tok123"),
+ ),
+ ).toMatchObject({ ok: true });
+ });
+
+ it("decodes the encoded token segment before comparing", () => {
+ expect(
+ parseSessionCallback(
+ createCallback(
+ "https://agent.example.com/eve/agents/support/eve/v1/callback/eve%3Aparent-token",
+ "eve:parent-token",
+ ),
+ ),
+ ).toMatchObject({ ok: true });
+ });
+
+ it("rejects a URL without the callback route", () => {
+ expect(
+ parseSessionCallback(
+ createCallback("https://agent.example.com/eve/agents/support/eve/v1/session"),
+ ),
+ ).toMatchObject({
+ message: expect.stringContaining("Callback url token must match callback token"),
+ ok: false,
+ });
+ });
+
+ it("rejects a URL whose token segment does not match the token field", () => {
+ expect(
+ parseSessionCallback(
+ createCallback("https://agent.example.com/eve/agents/support/eve/v1/callback/other-token"),
+ ),
+ ).toMatchObject({ ok: false });
+ });
+
+ it("rejects an empty token segment", () => {
+ expect(
+ parseSessionCallback(createCallback("https://agent.example.com/eve/v1/callback/")),
+ ).toMatchObject({ ok: false });
+ });
+
+ it("rejects extra path segments after the token", () => {
+ expect(
+ parseSessionCallback(createCallback("https://agent.example.com/eve/v1/callback/tok123/more")),
+ ).toMatchObject({ ok: false });
+ });
+
+ it("rejects a token segment with invalid percent-encoding", () => {
+ expect(
+ parseSessionCallback(createCallback("https://agent.example.com/eve/v1/callback/%E0%A4%A")),
+ ).toMatchObject({ ok: false });
+ });
+});
diff --git a/packages/eve/src/channel/session-callback.ts b/packages/eve/src/channel/session-callback.ts
index 99fff8abf..27c4430ae 100644
--- a/packages/eve/src/channel/session-callback.ts
+++ b/packages/eve/src/channel/session-callback.ts
@@ -70,12 +70,17 @@ export function parseSessionCallback(value: unknown): SessionCallbackParseResult
}
function readCallbackUrlToken(url: URL): string | null {
+ // The callback route may be mounted behind a public route prefix (e.g.
+ // `/eve/agents/<name>/eve/v1/callback/<token>`), so locate the route
+ // suffix instead of anchoring at the path start. `tokenPrefix` begins
+ // with `/`, so a match is always segment-aligned.
const tokenPrefix = createEveCallbackRoutePath("");
- if (!url.pathname.startsWith(tokenPrefix)) {
+ const prefixIndex = url.pathname.lastIndexOf(tokenPrefix);
+ if (prefixIndex === -1) {
return null;
}
- const encodedToken = url.pathname.slice(tokenPrefix.length);
+ const encodedToken = url.pathname.slice(prefixIndex + tokenPrefix.length);
if (encodedToken.length === 0 || encodedToken.includes("/")) {
return null;
}
diff --git a/packages/eve/src/cli/commands/build.ts b/packages/eve/src/cli/commands/build.ts
index eae8d581b..d7684dcaa 100644
--- a/packages/eve/src/cli/commands/build.ts
+++ b/packages/eve/src/cli/commands/build.ts
@@ -4,6 +4,10 @@ import type { Command } from "#compiled/commander/index.js";
import { resolveInternalVercelServiceOutput } from "#cli/vercel-service-output.js";
import { createCliTheme, renderCliTaggedLine } from "#cli/ui/output.js";
import type { ApplicationBuildOptions } from "#internal/nitro/host/types.js";
+import {
+ EVE_PUBLIC_ROUTE_PREFIX_ENV,
+ normalizePublicRoutePrefix,
+} from "#shared/public-route-prefix.js";
export type BuildHost = (appRoot: string, options: ApplicationBuildOptions) => Promise<string>;
@@ -44,9 +48,11 @@ export function registerBuildCommand(input: {
options.profile === undefined ? undefined : resolve(input.appRoot, options.profile);
const buildOptions: {
profileOutputPath?: string;
+ readonly publicRoutePrefix: ApplicationBuildOptions["publicRoutePrefix"];
readonly skipVercelSandboxPrewarm: boolean;
readonly vercelServiceOutput: ApplicationBuildOptions["vercelServiceOutput"];
} = {
+ publicRoutePrefix: normalizePublicRoutePrefix(process.env[EVE_PUBLIC_ROUTE_PREFIX_ENV]),
skipVercelSandboxPrewarm: options.skipSandboxPrewarm === true,
vercelServiceOutput: resolveInternalVercelServiceOutput(input.appRoot),
};
diff --git a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
new file mode 100644
index 000000000..6a6c74e6b
--- /dev/null
+++ b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
@@ -0,0 +1,407 @@
+import { mkdtemp, readFile } from "node:fs/promises";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import { parseSessionCallback } from "#channel/session-callback.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionCallbackKey, SessionIdKey } from "#context/keys.js";
+import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
+import { startRemoteAgentSession } from "#execution/remote-agent-dispatch.js";
+import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
+import { authHookToken, CallbackBaseUrlKey, getHookUrl } from "#harness/authorization.js";
+import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";
+import {
+ createEveCallbackRoutePath,
+ createEveConnectionCallbackRoutePath,
+} from "#protocol/routes.js";
+import { ensureEveVercelOutputConfig } from "#public/next/vercel-output-config.js";
+import type { HarnessSession } from "#harness/types.js";
+
+/**
+ * Deployment-shaped callback loop for multi-agent mode (issue #839).
+ *
+ * Two named parent agents are mounted behind per-agent public route
+ * prefixes, exactly as `withEve({ agents })` generates them. The test wires
+ * the real pieces end to end over live HTTP:
+ *
+ * 1. the actual Build Output routing config from
+ * `ensureEveVercelOutputConfig` (route `src` regexes + `request.path`
+ * transforms) drives a router emulating Vercel's documented semantics;
+ * 2. the parent mints callback URLs through the real code paths — the
+ * remote-subagent session callback (`startRemoteAgentSession`) and the
+ * connection hook URL (`getHookUrl`);
+ * 3. the remote side validates the callback metadata with the real
+ * create-session parser (`parseSessionCallback`) and posts the terminal
+ * result with the real durable step (`fireSessionCallbackStep`);
+ * 4. each parent service only serves its own prefix-stripped `/eve/v1/*`
+ * callback routes — anything else 404s, matching production.
+ *
+ * The only simulated component is Vercel's route engine itself.
+ */
+
+const DEPLOYMENT_AGENTS = [
+ {
+ name: "support",
+ publicRoutePrefix: "/eve/agents/support",
+ serviceName: "eve-support",
+ },
+ {
+ name: "billing",
+ publicRoutePrefix: "/eve/agents/billing",
+ serviceName: "eve-billing",
+ },
+] as const;
+
+interface VercelOutputRoute {
+ readonly destination?: { readonly service?: string; readonly type?: string };
+ readonly src?: string;
+ readonly transforms?: readonly { args: string; op: string; type: string }[];
+}
+
+interface VercelOutputConfig {
+ readonly routes?: readonly VercelOutputRoute[];
+ readonly services?: Record<string, { readonly routes?: readonly VercelOutputRoute[] }>;
+}
+
+interface RoutedServiceRequest {
+ readonly service: string;
+ readonly servicePath: string;
+}
+
+/**
+ * Resolves an inbound public path the way the Vercel router does for the
+ * generated Build Output config: match a top-level route `src` to pick the
+ * destination service, then apply that service's `request.path` transform.
+ */
+function routeDeploymentRequest(
+ config: VercelOutputConfig,
+ pathname: string,
+): RoutedServiceRequest | null {
+ for (const route of config.routes ?? []) {
+ if (route.src === undefined || route.destination?.type !== "service") {
+ continue;
+ }
+ if (!new RegExp(route.src).test(pathname)) {
+ continue;
+ }
+
+ const serviceName = route.destination.service;
+ if (serviceName === undefined) {
+ return null;
+ }
+
+ for (const serviceRoute of config.services?.[serviceName]?.routes ?? []) {
+ if (serviceRoute.src === undefined) {
+ continue;
+ }
+ const match = new RegExp(serviceRoute.src).exec(pathname);
+ const transform = serviceRoute.transforms?.find(
+ (candidate) => candidate.type === "request.path" && candidate.op === "set",
+ );
+ if (match === null || transform === undefined) {
+ continue;
+ }
+
+ return {
+ service: serviceName,
+ servicePath: transform.args.replace(
+ /\$(\d+)/g,
+ (_, group: string) => match[Number(group)] ?? "",
+ ),
+ };
+ }
+
+ return { service: serviceName, servicePath: pathname };
+ }
+
+ return null;
+}
+
+interface RecordedServiceRequest {
+ readonly method: string;
+ readonly servicePath: string;
+}
+
+function createStubSession(sessionId: string): HarnessSession {
+ return {
+ agent: { modelReference: { id: "test" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: `${sessionId}:continuation`,
+ history: [],
+ sessionId,
+ };
+}
+
+async function listen(server: Server): Promise<string> {
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const { port } = server.address() as AddressInfo;
+ return `http://127.0.0.1:${String(port)}`;
+}
+
+describe("multi-agent callback routing", () => {
+ const serviceRequests = new Map<string, RecordedServiceRequest[]>();
+ const createSessionBodies: unknown[] = [];
+ const expectedTokens = new Map<string, string>();
+ const expectedSessionIds = new Map<string, string>();
+ let deploymentServer: Server;
+ let remoteAgentServer: Server;
+ let deploymentOrigin: string;
+ let remoteAgentOrigin: string;
+
+ beforeAll(async () => {
+ const nextRoot = await mkdtemp(join(tmpdir(), "eve-callback-routing-"));
+
+ for (const agent of DEPLOYMENT_AGENTS) {
+ serviceRequests.set(agent.serviceName, []);
+ expectedTokens.set(agent.serviceName, `${agent.name}-session:callback-token`);
+ expectedSessionIds.set(agent.serviceName, `${agent.name}-session`);
+ }
+
+ // Generate the real Build Output config the Next integration writes for
+ // two named agents on Vercel.
+ vi.stubEnv("VERCEL", "1");
+ try {
+ await ensureEveVercelOutputConfig({
+ agents: DEPLOYMENT_AGENTS.map((agent) => ({
+ appRoot: join(nextRoot, "agents", agent.name),
+ buildCommand: "eve build",
+ name: agent.name,
+ publicRoutePrefix: agent.publicRoutePrefix,
+ servicePrefix: `/_eve_internal/eve/${agent.name}`,
+ })),
+ nextRoot,
+ });
+ } finally {
+ vi.unstubAllEnvs();
+ }
+
+ const outputConfig = JSON.parse(
+ await readFile(join(nextRoot, ".vercel", "output", "config.json"), "utf8"),
+ ) as VercelOutputConfig;
+
+ // Deployment origin: routes public paths per the generated config, then
+ // serves each eve service's prefix-stripped framework callback routes.
+ // Unrouted paths 404, matching a deployment with no bare /eve/v1 mount.
+ deploymentServer = createServer((request, response) => {
+ const pathname = new URL(request.url ?? "/", "http://deployment.invalid").pathname;
+ const routed = routeDeploymentRequest(outputConfig, pathname);
+
+ if (routed === null) {
+ response.writeHead(404).end();
+ return;
+ }
+
+ serviceRequests.get(routed.service)?.push({
+ method: request.method ?? "",
+ servicePath: routed.servicePath,
+ });
+
+ const callbackToken = expectedTokens.get(routed.service) ?? "";
+ const sessionId = expectedSessionIds.get(routed.service) ?? "";
+ const servesPath =
+ (request.method === "POST" &&
+ routed.servicePath === createEveCallbackRoutePath(callbackToken)) ||
+ (request.method === "GET" &&
+ routed.servicePath ===
+ createEveConnectionCallbackRoutePath("linear", authHookToken(sessionId)));
+
+ if (!servesPath) {
+ response.writeHead(404).end();
+ return;
+ }
+
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(JSON.stringify({ ok: true }));
+ });
+ deploymentOrigin = await listen(deploymentServer);
+
+ // Remote subagent: records the create-session body and returns a session
+ // id, like the eve channel's create-session route.
+ remoteAgentServer = createServer((request, response) => {
+ const chunks: Buffer[] = [];
+ request.on("data", (chunk: Buffer) => chunks.push(chunk));
+ request.on("end", () => {
+ createSessionBodies.push(JSON.parse(Buffer.concat(chunks).toString("utf8")));
+ response.writeHead(200, {
+ "content-type": "application/json",
+ [EVE_SESSION_ID_HEADER]: "remote-session-1",
+ });
+ response.end(JSON.stringify({ ok: true }));
+ });
+ });
+ remoteAgentOrigin = await listen(remoteAgentServer);
+ });
+
+ afterAll(async () => {
+ await Promise.all([
+ new Promise((resolve) => deploymentServer.close(resolve)),
+ new Promise((resolve) => remoteAgentServer.close(resolve)),
+ ]);
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ function stubAgentRuntimeEnvironment(publicRoutePrefix: string | undefined): void {
+ // Mirrors the environment baked into the agent's deployed workflow
+ // functions: no local world override, non-production Vercel deployment,
+ // and (post-fix) the agent's public route prefix.
+ vi.stubEnv("VERCEL_ENV", "");
+ vi.stubEnv("WORKFLOW_LOCAL_BASE_URL", "");
+ if (publicRoutePrefix !== undefined) {
+ vi.stubEnv("EVE_PUBLIC_ROUTE_PREFIX", publicRoutePrefix);
+ }
+ }
+
+ async function mintRemoteAgentCallback(agentName: string): Promise<{
+ readonly callback: { token: string; url: string };
+ readonly remoteSessionId: string;
+ }> {
+ const sessionId = `${agentName}-session`;
+ const callbackToken = `${sessionId}:callback-token`;
+ const bodyCountBefore = createSessionBodies.length;
+
+ const remoteSessionId = await startRemoteAgentSession({
+ action: {
+ callId: `call-${agentName}`,
+ description: "delegate research",
+ input: { message: "run the report" },
+ kind: "remote-agent-call",
+ name: "research",
+ nodeId: "agent/agents/research.ts",
+ remoteAgentName: "research",
+ },
+ callbackBaseUrl: resolveWorkflowCallbackBaseUrl(deploymentOrigin),
+ callbackToken,
+ remote: {
+ description: "remote research agent",
+ kind: "remote",
+ logicalPath: "agent/agents/research.ts",
+ name: "research",
+ nodeId: "agent/agents/research.ts",
+ path: "/eve/v1/session",
+ sourceId: "agent/agents/research.ts",
+ sourceKind: "module",
+ url: remoteAgentOrigin,
+ },
+ session: createStubSession(sessionId),
+ });
+
+ const body = createSessionBodies[bodyCountBefore] as {
+ callback: { token: string; url: string };
+ };
+ expect(createSessionBodies.length).toBe(bodyCountBefore + 1);
+ return { callback: body.callback, remoteSessionId };
+ }
+
+ for (const agent of DEPLOYMENT_AGENTS) {
+ it(`delivers the remote-subagent session callback for ${agent.name} through its public mount`, async () => {
+ stubAgentRuntimeEnvironment(agent.publicRoutePrefix);
+
+ const { callback, remoteSessionId } = await mintRemoteAgentCallback(agent.name);
+ const callbackToken = `${agent.name}-session:callback-token`;
+
+ expect(remoteSessionId).toBe("remote-session-1");
+ expect(callback.url).toBe(
+ `${deploymentOrigin}${agent.publicRoutePrefix}${createEveCallbackRoutePath(callbackToken)}`,
+ );
+
+ // Remote-side create-session validation (public/channels/eve.ts):
+ // the prefixed URL must parse, or the remote rejects with HTTP 400.
+ expect(parseSessionCallback(callback)).toMatchObject({ ok: true });
+
+ // Remote-side terminal POST (the step that failed with HTTP 404 in
+ // production) must reach the parent service through the deployment
+ // router and succeed.
+ await expect(
+ fireSessionCallbackStep({
+ output: "report done",
+ serializedContext: {
+ [SessionIdKey.name]: "remote-session-1",
+ [SessionCallbackKey.name]: {
+ callId: `call-${agent.name}`,
+ subagentName: "research",
+ ...callback,
+ },
+ },
+ status: "completed",
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(serviceRequests.get(agent.serviceName)).toContainEqual({
+ method: "POST",
+ servicePath: createEveCallbackRoutePath(callbackToken),
+ });
+ });
+
+ it(`resolves the connection hook URL for ${agent.name} through its public mount`, async () => {
+ stubAgentRuntimeEnvironment(agent.publicRoutePrefix);
+
+ const sessionId = `${agent.name}-session`;
+ const ctx = new ContextContainer();
+ ctx.set(SessionIdKey, sessionId);
+ ctx.set(CallbackBaseUrlKey, resolveWorkflowCallbackBaseUrl(deploymentOrigin));
+
+ const hookUrl = contextStorage.run(ctx, () => getHookUrl("linear"));
+
+ expect(hookUrl).toBe(
+ `${deploymentOrigin}${agent.publicRoutePrefix}${createEveConnectionCallbackRoutePath(
+ "linear",
+ authHookToken(sessionId),
+ )}`,
+ );
+
+ // The IdP redirect follows this URL from the user's browser.
+ const response = await fetch(hookUrl ?? "");
+ expect(response.status).toBe(200);
+ expect(serviceRequests.get(agent.serviceName)).toContainEqual({
+ method: "GET",
+ servicePath: createEveConnectionCallbackRoutePath("linear", authHookToken(sessionId)),
+ });
+ });
+ }
+
+ it("keeps each parent's callbacks on its own service", () => {
+ // All prior traffic in this suite must have stayed on the minting
+ // agent's own service: support paths only on eve-support, billing paths
+ // only on eve-billing.
+ for (const agent of DEPLOYMENT_AGENTS) {
+ const requests = serviceRequests.get(agent.serviceName) ?? [];
+ expect(requests.length).toBeGreaterThan(0);
+ for (const request of requests) {
+ expect(request.servicePath).toContain(`${agent.name}-session`);
+ }
+ }
+ });
+
+ it("reproduces the 404 when the public route prefix is absent (pre-fix behavior)", async () => {
+ stubAgentRuntimeEnvironment(undefined);
+
+ const { callback } = await mintRemoteAgentCallback("support");
+
+ // Without the prefix the minted URL targets the bare /eve/v1 path that
+ // nothing serves in multi-agent mode — the exact production failure.
+ expect(callback.url).toBe(
+ `${deploymentOrigin}${createEveCallbackRoutePath("support-session:callback-token")}`,
+ );
+ await expect(
+ fireSessionCallbackStep({
+ output: "report done",
+ serializedContext: {
+ [SessionIdKey.name]: "remote-session-1",
+ [SessionCallbackKey.name]: {
+ callId: "call-support",
+ subagentName: "research",
+ ...callback,
+ },
+ },
+ status: "completed",
+ }),
+ ).rejects.toThrow("Session callback failed with HTTP 404.");
+ });
+});
diff --git a/packages/eve/src/execution/workflow-callback-url.test.ts b/packages/eve/src/execution/workflow-callback-url.test.ts
index 2f91a2c3d..e81f98587 100644
--- a/packages/eve/src/execution/workflow-callback-url.test.ts
+++ b/packages/eve/src/execution/workflow-callback-url.test.ts
@@ -77,4 +77,60 @@ describe("resolveWorkflowCallbackBaseUrl", () => {
"https://agent.example.com",
);
});
+
+ it("appends the configured public route prefix to the resolved base", () => {
+ vi.stubEnv("VERCEL_ENV", "");
+ vi.stubEnv("WORKFLOW_LOCAL_BASE_URL", "");
+ vi.stubEnv("EVE_PUBLIC_ROUTE_PREFIX", "/eve/agents/support");
+
+ expect(resolveWorkflowCallbackBaseUrl("https://deployment.example.com/")).toBe(
+ "https://deployment.example.com/eve/agents/support",
+ );
+ });
+
+ it("appends the public route prefix to the stable Vercel production URL", () => {
+ vi.stubEnv("VERCEL_ENV", "production");
+ vi.stubEnv("VERCEL_PROJECT_PRODUCTION_URL", "agent.example.com");
+ vi.stubEnv("EVE_PUBLIC_ROUTE_PREFIX", "eve/agents/support/");
+
+ expect(resolveWorkflowCallbackBaseUrl("https://deployment.example.com")).toBe(
+ "https://agent.example.com/eve/agents/support",
+ );
+ });
+
+ it("ignores a public route prefix resolving to the root route", () => {
+ vi.stubEnv("VERCEL_ENV", "");
+ vi.stubEnv("WORKFLOW_LOCAL_BASE_URL", "");
+ vi.stubEnv("EVE_PUBLIC_ROUTE_PREFIX", "/");
+
+ expect(resolveWorkflowCallbackBaseUrl("http://localhost:3000")).toBe("http://localhost:3000");
+ });
+});
+
+describe("createWorkflowCallbackUrl", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("preserves a public route prefix carried by the base URL", () => {
+ expect(
+ createWorkflowCallbackUrl(
+ "https://agent.example.com/eve/agents/support",
+ "/eve/v1/callback/eve%3Aparent-token",
+ ),
+ ).toBe("https://agent.example.com/eve/agents/support/eve/v1/callback/eve%3Aparent-token");
+ });
+
+ it("preserves the prefix when adding the Vercel bypass query param", () => {
+ vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "secret");
+
+ expect(
+ createWorkflowCallbackUrl(
+ "https://agent.example.com/eve/agents/support",
+ "/eve/v1/connections/linear/callback/tok123?code=abc",
+ ),
+ ).toBe(
+ "https://agent.example.com/eve/agents/support/eve/v1/connections/linear/callback/tok123?code=abc&x-vercel-protection-bypass=secret",
+ );
+ });
});
diff --git a/packages/eve/src/execution/workflow-callback-url.ts b/packages/eve/src/execution/workflow-callback-url.ts
index c0d4f417f..7f8abdbf4 100644
--- a/packages/eve/src/execution/workflow-callback-url.ts
+++ b/packages/eve/src/execution/workflow-callback-url.ts
@@ -1,3 +1,8 @@
+import {
+ EVE_PUBLIC_ROUTE_PREFIX_ENV,
+ normalizePublicRoutePrefix,
+} from "#shared/public-route-prefix.js";
+
const PRODUCTION_ENVIRONMENT = "production";
const VERCEL_PROTECTION_BYPASS_QUERY = "x-vercel-protection-bypass";
const WORKFLOW_LOCAL_BASE_URL_ENV = "WORKFLOW_LOCAL_BASE_URL";
@@ -22,24 +27,36 @@ export function resolveVercelProductionCallbackBaseUrl(): string | null {
}
/**
- * Resolves the origin used for framework-owned workflow callbacks.
+ * Resolves the base URL used for framework-owned workflow callbacks.
*
* Workflow metadata falls back to port 3000 when its optional local port
* discovery is unavailable. eve already configures the local world with the
* active dev-server origin, so prefer that value before the metadata fallback.
+ *
+ * When {@link EVE_PUBLIC_ROUTE_PREFIX_ENV} is set (baked into deployed
+ * Vercel workflow functions for named multi-agent mounts), the prefix is
+ * appended so callbacks built from this base resolve to the agent's public
+ * `<prefix>/eve/v1/*` mount instead of the bare `/eve/v1/*` path the origin
+ * does not serve.
*/
export function resolveWorkflowCallbackBaseUrl(metadataUrl: string): string {
const configuredLocalBaseUrl = process.env[WORKFLOW_LOCAL_BASE_URL_ENV]?.trim();
const localBaseUrl = configuredLocalBaseUrl ? configuredLocalBaseUrl : undefined;
const resolved = resolveVercelProductionCallbackBaseUrl() ?? localBaseUrl ?? metadataUrl;
- return resolved.replace(/\/$/, "");
+ const baseUrl = resolved.replace(/\/$/, "");
+ const publicRoutePrefix = normalizePublicRoutePrefix(process.env[EVE_PUBLIC_ROUTE_PREFIX_ENV]);
+ return publicRoutePrefix === undefined ? baseUrl : `${baseUrl}${publicRoutePrefix}`;
}
/**
- * Builds a framework-owned callback URL from a resolved callback origin.
+ * Builds a framework-owned callback URL from a resolved callback base URL.
+ *
+ * `callbackPath` is appended to the full base URL rather than resolved
+ * against it: the base may carry a public route prefix path, which
+ * `new URL(path, base)` would drop for absolute paths.
*/
export function createWorkflowCallbackUrl(baseUrl: string, callbackPath: string): string {
- const url = new URL(callbackPath, baseUrl);
+ const url = new URL(`${baseUrl.replace(/\/$/, "")}${callbackPath}`);
// https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/protection-bypass-automation
const bypassSecret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();
diff --git a/packages/eve/src/internal/nitro/host/build-application.ts b/packages/eve/src/internal/nitro/host/build-application.ts
index 76c8f5a2a..d5f77e2ac 100644
--- a/packages/eve/src/internal/nitro/host/build-application.ts
+++ b/packages/eve/src/internal/nitro/host/build-application.ts
@@ -314,6 +314,7 @@ async function emitVercelWorkflowFunctions(input: {
compiledArtifactsBootstrapPath: string;
flowNitroOutputDir: string;
outputDir: string;
+ publicRoutePrefix: string | undefined;
workflowBuildDir: string;
}): Promise<void> {
const builder = new WorkflowBundleBuilder({
@@ -321,6 +322,7 @@ async function emitVercelWorkflowFunctions(input: {
appRoot: input.appRoot,
compiledArtifactsBootstrapPath: input.compiledArtifactsBootstrapPath,
outDir: input.workflowBuildDir,
+ publicRoutePrefix: input.publicRoutePrefix,
rootDir: resolvePackageRoot(),
watch: false,
});
@@ -530,6 +532,7 @@ async function buildApplicationInWorkspace(
compiledArtifactsBootstrapPath: preparedHost.compiledArtifacts.bootstrapPath,
flowNitroOutputDir,
outputDir: workspace.publication.output.stagedDir,
+ publicRoutePrefix: options.publicRoutePrefix,
workflowBuildDir: workspace.workflow.buildDir,
}),
);
diff --git a/packages/eve/src/internal/nitro/host/types.ts b/packages/eve/src/internal/nitro/host/types.ts
index 53bca66b9..1df636db1 100644
--- a/packages/eve/src/internal/nitro/host/types.ts
+++ b/packages/eve/src/internal/nitro/host/types.ts
@@ -16,6 +16,15 @@ export type NitroBuildSurface = "all" | "app" | "flow";
export interface ApplicationBuildOptions {
/** Absolute path for an optional machine-readable profile of a successful build. */
readonly profileOutputPath?: string;
+ /**
+ * Public route prefix the agent's `/eve/v1/*` surface is mounted under on
+ * its callback origin. Baked into every emitted Vercel workflow function
+ * environment so deployed callback-URL minting resolves a routable public
+ * path. The CLI resolves it from `EVE_PUBLIC_ROUTE_PREFIX`, which
+ * multi-agent host integrations export in the generated service build
+ * command.
+ */
+ readonly publicRoutePrefix?: string;
readonly skipVercelSandboxPrewarm: boolean;
readonly vercelServiceOutput?: {
readonly hostOutputDirectory: string;
diff --git a/packages/eve/src/internal/workflow-bundle/builder-support.ts b/packages/eve/src/internal/workflow-bundle/builder-support.ts
index ec1cefd2b..f01767fa3 100644
--- a/packages/eve/src/internal/workflow-bundle/builder-support.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder-support.ts
@@ -21,6 +21,11 @@ export interface WorkflowBundleBuilderOptions {
appRoot: string;
compiledArtifactsBootstrapPath: string;
outDir: string;
+ /**
+ * The agent's resolved public route prefix, baked into every emitted Vercel
+ * workflow function's environment for callback-URL minting.
+ */
+ publicRoutePrefix?: string;
rootDir: string;
watch: boolean;
/** Test-harness-only: also scans `src/internal/testing/`. */
diff --git a/packages/eve/src/internal/workflow-bundle/builder.ts b/packages/eve/src/internal/workflow-bundle/builder.ts
index 691b9c177..fe5990a2e 100644
--- a/packages/eve/src/internal/workflow-bundle/builder.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder.ts
@@ -52,6 +52,7 @@ export class WorkflowBundleBuilder {
readonly #agentName: string;
readonly #compiledArtifactsBootstrapPath: string;
readonly #outDir: string;
+ readonly #publicRoutePrefix?: string;
readonly #queueNamespace: string;
protected readonly config: WorkflowBundleBuilderConfig;
readonly #discoveredEntries = new WeakMap<readonly string[], WorkflowBundleDiscoveredEntries>();
@@ -74,6 +75,7 @@ export class WorkflowBundleBuilder {
this.#agentName = options.agentName;
this.#compiledArtifactsBootstrapPath = options.compiledArtifactsBootstrapPath;
this.#outDir = options.outDir;
+ this.#publicRoutePrefix = options.publicRoutePrefix;
this.#queueNamespace = deriveEveWorkflowQueueNamespace(options.agentName);
}
@@ -458,7 +460,10 @@ export class WorkflowBundleBuilder {
const nextConfig: Record<string, unknown> = {
...baseConfig,
};
- nextConfig.environment = createWorkflowFunctionEnvironment(baseConfig.environment);
+ nextConfig.environment = createWorkflowFunctionEnvironment({
+ environment: baseConfig.environment,
+ publicRoutePrefix: this.#publicRoutePrefix,
+ });
if (patch.runtime !== null) {
nextConfig.runtime = patch.runtime;
diff --git a/packages/eve/src/internal/workflow-bundle/vercel-workflow-output.test.ts b/packages/eve/src/internal/workflow-bundle/vercel-workflow-output.test.ts
new file mode 100644
index 000000000..e19502cd8
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/vercel-workflow-output.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+
+import { createWorkflowFunctionEnvironment } from "#internal/workflow-bundle/vercel-workflow-output.js";
+
+describe("createWorkflowFunctionEnvironment", () => {
+ it("omits the public route prefix when the build input does not carry one", () => {
+ expect(createWorkflowFunctionEnvironment()).not.toHaveProperty("EVE_PUBLIC_ROUTE_PREFIX");
+ expect(createWorkflowFunctionEnvironment({ publicRoutePrefix: "" })).not.toHaveProperty(
+ "EVE_PUBLIC_ROUTE_PREFIX",
+ );
+ });
+
+ it("bakes the normalized public route prefix from the build input", () => {
+ expect(
+ createWorkflowFunctionEnvironment({
+ environment: { EXISTING: "1" },
+ publicRoutePrefix: "eve/agents/support/",
+ }),
+ ).toMatchObject({
+ EVE_PUBLIC_ROUTE_PREFIX: "/eve/agents/support",
+ EXISTING: "1",
+ });
+ });
+});
diff --git a/packages/eve/src/internal/workflow-bundle/vercel-workflow-output.ts b/packages/eve/src/internal/workflow-bundle/vercel-workflow-output.ts
index de2b9e9b6..f06d6d654 100644
--- a/packages/eve/src/internal/workflow-bundle/vercel-workflow-output.ts
+++ b/packages/eve/src/internal/workflow-bundle/vercel-workflow-output.ts
@@ -18,6 +18,10 @@ import {
isEveVercelFunctionPath,
normalizeEveVercelRoutes,
} from "#internal/workflow-bundle/eve-service-route-output.js";
+import {
+ EVE_PUBLIC_ROUTE_PREFIX_ENV,
+ normalizePublicRoutePrefix,
+} from "#shared/public-route-prefix.js";
// just-bash and microsandbox are optional peer dependencies (the
// opt-in local sandbox engines) loaded lazily from the application's
@@ -44,12 +48,24 @@ const WORKFLOW_PRECONDITION_GUARD_ENABLED = "1";
/**
* Builds the environment block every generated Vercel workflow function needs.
+ *
+ * When the build input carries the agent's resolved public route prefix, it
+ * is baked into the function environment under
+ * {@link EVE_PUBLIC_ROUTE_PREFIX_ENV} so callback-URL minting inside the
+ * deployed workflow functions knows the agent's public mount.
*/
-export function createWorkflowFunctionEnvironment(environment?: unknown): Record<string, unknown> {
+export function createWorkflowFunctionEnvironment(
+ input: { environment?: unknown; publicRoutePrefix?: string } = {},
+): Record<string, unknown> {
const nextEnvironment: Record<string, unknown> = {};
- if (isRecord(environment)) {
- Object.assign(nextEnvironment, environment);
+ if (isRecord(input.environment)) {
+ Object.assign(nextEnvironment, input.environment);
+ }
+
+ const publicRoutePrefix = normalizePublicRoutePrefix(input.publicRoutePrefix);
+ if (publicRoutePrefix !== undefined) {
+ nextEnvironment[EVE_PUBLIC_ROUTE_PREFIX_ENV] = publicRoutePrefix;
}
// Reject replay decisions made from an event log that missed a concurrent wake.
@@ -299,6 +315,7 @@ function normalizeVercelOutputPath(path: string): string {
export async function emitBundledWorkflowFunctionDirectory(input: {
bundlePath: string;
pluginPaths?: readonly string[];
+ publicRoutePrefix?: string;
targetPath: string;
}): Promise<void> {
await prepareVercelFunctionDirectory(input.targetPath);
@@ -342,7 +359,9 @@ export async function emitBundledWorkflowFunctionDirectory(input: {
join(input.targetPath, ".vc-config.json"),
`${JSON.stringify(
{
- environment: createWorkflowFunctionEnvironment(),
+ environment: createWorkflowFunctionEnvironment({
+ publicRoutePrefix: input.publicRoutePrefix,
+ }),
handler: "index.js",
launcherType: "Nodejs",
supportsResponseStreaming: true,
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index f8ec0019a..2e213116a 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -631,6 +631,26 @@ describe("eveChannel — create session (text)", () => {
});
});
+ it("accepts callback metadata whose URL is mounted behind a public route prefix", async () => {
+ const handler = createEveCreateHandler({ auth: none() });
+
+ const response = await handler.fetch(
+ createJsonMessageRequest({
+ callback: {
+ callId: "call-1",
+ subagentName: "research",
+ token: "tok123",
+ url: "https://caller.example.com/eve/agents/support/eve/v1/callback/tok123",
+ },
+ message: "hi",
+ mode: "task",
+ }),
+ );
+
+ expect(response.status).toBe(202);
+ expect(handler.send).toHaveBeenCalledTimes(1);
+ });
+
it("rejects callback metadata without a call id", async () => {
const handler = createEveCreateHandler({ auth: none() });
diff --git a/packages/eve/src/public/next/index.integration.test.ts b/packages/eve/src/public/next/index.integration.test.ts
index ce2a44f12..a4bc5d168 100644
--- a/packages/eve/src/public/next/index.integration.test.ts
+++ b/packages/eve/src/public/next/index.integration.test.ts
@@ -365,7 +365,7 @@ describe("withEve Vercel config", () => {
services: {
"eve-billing": {
buildCommand:
- "cd '../../../agents/billing' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='../../.eve/vercel-services/eve-billing/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && pnpm build:billing-agent",
+ "cd '../../../agents/billing' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='../../.eve/vercel-services/eve-billing/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && export EVE_PUBLIC_ROUTE_PREFIX='/eve/agents/billing' && pnpm build:billing-agent",
framework: "eve",
routes: [
{
@@ -384,7 +384,7 @@ describe("withEve Vercel config", () => {
},
"eve-support": {
buildCommand:
- "cd '../../../agents/support' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='../../.eve/vercel-services/eve-support/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && node '../../node_modules/eve/bin/eve.js' build",
+ "cd '../../../agents/support' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='../../.eve/vercel-services/eve-support/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && export EVE_PUBLIC_ROUTE_PREFIX='/eve/agents/support' && node '../../node_modules/eve/bin/eve.js' build",
framework: "eve",
routes: [
{
@@ -483,7 +483,7 @@ describe("withEve Vercel config", () => {
services: {
"eve-billing": {
buildCommand:
- "cd '../../../agents/billing' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='../../.eve/vercel-services/eve-billing/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && node '../../node_modules/eve/bin/eve.js' build",
+ "cd '../../../agents/billing' && export EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY='../../.eve/vercel-services/eve-billing/.vercel/output' && export EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY='../../.vercel/output' && export EVE_PUBLIC_ROUTE_PREFIX='/eve/agents/billing' && node '../../node_modules/eve/bin/eve.js' build",
framework: "eve",
routes: [
{
diff --git a/packages/eve/src/public/next/vercel-output-config.ts b/packages/eve/src/public/next/vercel-output-config.ts
index 37d592cf7..e568196cb 100644
--- a/packages/eve/src/public/next/vercel-output-config.ts
+++ b/packages/eve/src/public/next/vercel-output-config.ts
@@ -5,6 +5,10 @@ import {
EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,
EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV,
} from "#internal/application/paths.js";
+import {
+ EVE_PUBLIC_ROUTE_PREFIX_ENV,
+ normalizePublicRoutePrefix,
+} from "#shared/public-route-prefix.js";
import {
findClosestLinkedVercelDirectory,
findClosestVercelOutputDirectory,
@@ -167,9 +171,17 @@ function createGeneratedServiceBuild(input: {
input.agent.appRoot,
input.hostOutputDirectory,
);
+ // Named agents are publicly mounted under this prefix while the service
+ // itself receives prefix-stripped `/eve/v1/*` paths, so the build must
+ // carry the prefix into the workflow runtime for callback-URL minting.
+ const publicRoutePrefix = normalizePublicRoutePrefix(input.agent.publicRoutePrefix);
+ const publicRoutePrefixExport =
+ publicRoutePrefix === undefined
+ ? ""
+ : ` && export ${EVE_PUBLIC_ROUTE_PREFIX_ENV}=${quoteShellArgument(publicRoutePrefix)}`;
return {
- buildCommand: `cd ${quoteShellArgument(workingDirectory)} && export ${EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(configuredOutputDirectory)} && export ${EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(configuredHostOutputDirectory)} && ${input.agent.buildCommand}`,
+ buildCommand: `cd ${quoteShellArgument(workingDirectory)} && export ${EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(configuredOutputDirectory)} && export ${EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(configuredHostOutputDirectory)}${publicRoutePrefixExport} && ${input.agent.buildCommand}`,
root: resolveRelativeEntrypoint(input.nextRoot, rootDirectory),
rootDirectory,
};
diff --git a/packages/eve/src/shared/public-route-prefix.test.ts b/packages/eve/src/shared/public-route-prefix.test.ts
new file mode 100644
index 000000000..e35d6ace6
--- /dev/null
+++ b/packages/eve/src/shared/public-route-prefix.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+
+import { normalizePublicRoutePrefix } from "#shared/public-route-prefix.js";
+
+describe("normalizePublicRoutePrefix", () => {
+ it("returns undefined for values resolving to the root route", () => {
+ expect(normalizePublicRoutePrefix(undefined)).toBeUndefined();
+ expect(normalizePublicRoutePrefix("")).toBeUndefined();
+ expect(normalizePublicRoutePrefix(" ")).toBeUndefined();
+ expect(normalizePublicRoutePrefix("/")).toBeUndefined();
+ expect(normalizePublicRoutePrefix("//")).toBeUndefined();
+ });
+
+ it("adds the leading slash", () => {
+ expect(normalizePublicRoutePrefix("eve/agents/support")).toBe("/eve/agents/support");
+ });
+
+ it("strips trailing slashes", () => {
+ expect(normalizePublicRoutePrefix("/eve/agents/support/")).toBe("/eve/agents/support");
+ expect(normalizePublicRoutePrefix("/eve/agents/support//")).toBe("/eve/agents/support");
+ });
+
+ it("keeps an already-normalized prefix unchanged", () => {
+ expect(normalizePublicRoutePrefix("/eve/agents/support")).toBe("/eve/agents/support");
+ });
+});
diff --git a/packages/eve/src/shared/public-route-prefix.ts b/packages/eve/src/shared/public-route-prefix.ts
new file mode 100644
index 000000000..683226939
--- /dev/null
+++ b/packages/eve/src/shared/public-route-prefix.ts
@@ -0,0 +1,33 @@
+/**
+ * Environment variable naming the public route prefix an eve agent's
+ * `/eve/v1/*` transport surface is mounted under on its callback origin.
+ *
+ * Multi-agent host integrations mount each named agent under
+ * `/eve/agents/<name>/eve/v1/*` and strip that prefix before requests reach
+ * the eve service, so a running agent cannot recover its own public mount
+ * from an inbound request. The integration exports this variable in the
+ * generated service build command, the eve CLI resolves it once into the
+ * build input, the build bakes it into every emitted Vercel workflow function
+ * environment, and callback-URL minting prepends it so framework-owned
+ * callbacks resolve to a routable public path.
+ *
+ * Self-hosted deployments that proxy an agent behind a path prefix can set
+ * it directly on the runtime environment.
+ */
+export const EVE_PUBLIC_ROUTE_PREFIX_ENV = "EVE_PUBLIC_ROUTE_PREFIX";
+
+/**
+ * Normalizes a public route prefix to `/segment(/segment)*` form: adds the
+ * leading slash, strips trailing slashes, and returns `undefined` for
+ * values that resolve to the root route (empty, blank, or `/`).
+ */
+export function normalizePublicRoutePrefix(value: string | undefined): string | undefined {
+ const trimmed = value?.trim();
+ if (trimmed === undefined || trimmed.length === 0) {
+ return undefined;
+ }
+
+ const prefixed = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
+ const normalized = prefixed.replace(/\/+$/, "");
+ return normalized.length === 0 ? undefined : normalized;
+}