The Open Framework for Building Agents
feat(eve): compose workspace services in vercel.ts (#3038)
OwenKephart782911680c18
diff --git a/.changeset/compose-workspace-services.md b/.changeset/compose-workspace-services.mdnew file mode 100644index 000000000..2d37d70a6--- /dev/null+++ b/.changeset/compose-workspace-services.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add `withEve` from `eve/vercel` for composing native workspace agents with authored services in `vercel.ts`. Vercel resolves the generated agent services and transport routes before independently building each service.diff --git a/docs/guides/deployment/vercel.mdx b/docs/guides/deployment/vercel.mdxindex 6792b5ff5..685dc586d 100644--- a/docs/guides/deployment/vercel.mdx+++ b/docs/guides/deployment/vercel.mdx@@ -67,7 +67,58 @@ In an eve workspace, eve discovers direct `agents/<name>/` children that containCreate this layout with `eve init my-project --agents support,research`, or add one agent to an existing workspace with `eve init billing`.-With no authored `vercel.json#services`, `eve build` derives the complete Vercel Services graph on every build. If `vercel.json` declares `services`, that authored graph is authoritative instead; use `vercel build` to build and validate the complete project. This supports heterogeneous projects with frontends, private APIs, bindings, and other non-eve services without generated configuration files.+For an agent-only workspace, run `eve build`. eve owns the Vercel Build Output and generates one independently built service and a `/<name>/eve/v1/*` transport route for each workspace member.++### Compose agents with other Vercel services++Use Vercel's programmatic configuration when a workspace also deploys a frontend, private API, or another non-eve service. Replace `vercel.json` with a root `vercel.ts` and compose the authored graph with `withEve`:++```typescript title="vercel.ts"+import { withEve } from "eve/vercel";++export default await withEve({+ services: {+ web: {+ framework: "nextjs",+ root: "apps/web",+ },+ },+ routes: [+ {+ src: "^(.*)$",+ destination: { type: "service", service: "web" },+ },+ ],+});+```++Vercel evaluates `vercel.ts` before resolving the service graph. `withEve` discovers direct workspace members, adds their services and transport routes, and returns a plain Vercel configuration. Vercel can then build `web` and every eve agent independently. The frontend does not need `withEve` in its framework configuration or a build script that builds the agents.++Generated transport routes are inserted before a filesystem handler or, when no filesystem handler exists, before authored routes. `withEve` throws instead of overwriting an authored service key or exact transport route that belongs to a generated agent. Remove the authored route, and remove or rename the authored service; `withEve` adds both automatically. Names in the array form of `services` must also be unique. Other service names, routes, bindings, and Cron Jobs remain authored in `vercel.ts`.++Custom agent channel endpoints are not published automatically. Expose one explicitly by routing it to the generated service:++```typescript title="vercel.ts"+import { withEve } from "eve/vercel";++export default await withEve({+ services: {+ web: { framework: "nextjs", root: "apps/web" },+ },+ routes: [+ {+ src: "^/webhooks/github$",+ destination: { type: "service", service: "eve-triage" },+ },+ {+ src: "^(.*)$",+ destination: { type: "service", service: "web" },+ },+ ],+});+```++A Vercel project can use only one configuration source, so remove `vercel.json` when adopting `vercel.ts`. Keep `eve` in the root package dependencies so Vercel can import `eve/vercel` while evaluating the configuration. Pass `{ root: "/absolute/workspace/path" }` as the second argument only when `vercel.ts` is evaluated from somewhere other than the workspace root.An authored eve service routed at `/eve/v1` already uses the protocol path; callbacks remain at `/eve/v1/callback/*`. A named mount such as `/support` adds that mount before the protocol path, giving `/support/eve/v1/callback/*`.diff --git a/packages/eve/package.json b/packages/eve/package.jsonindex 65af95777..ae07d0af5 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -86,6 +86,12 @@"import": "./dist/src/public/next/index.js","default": "./dist/src/public/next/index.js"},+ "./vercel": {+ "eve-source": "./src/public/vercel/index.ts",+ "types": "./dist/src/public/vercel/index.d.ts",+ "import": "./dist/src/public/vercel/index.js",+ "default": "./dist/src/public/vercel/index.js"+ },"./nuxt": {"types": "./dist/src/public/nuxt/index.d.ts","import": "./dist/src/public/nuxt/index.js",diff --git a/packages/eve/src/internal/vercel/build-agent-workspace.integration.test.ts b/packages/eve/src/internal/vercel/build-agent-workspace.integration.test.tsindex ed2f77b2a..5b5a1d71c 100644--- a/packages/eve/src/internal/vercel/build-agent-workspace.integration.test.ts+++ b/packages/eve/src/internal/vercel/build-agent-workspace.integration.test.ts@@ -129,6 +129,6 @@ describe("buildAgentWorkspace", () => {const root = await createWorkspace();await writeFile(join(root, "vercel.json"), JSON.stringify({ services: {} }));const workspace = await resolveWorkspace(root);- await expect(buildAgentWorkspace(workspace)).rejects.toThrow(/Run `vercel build`/);+ await expect(buildAgentWorkspace(workspace)).rejects.toThrow(/vercel\.ts.*eve\/vercel/);});});diff --git a/packages/eve/src/internal/vercel/build-agent-workspace.ts b/packages/eve/src/internal/vercel/build-agent-workspace.tsindex 628f0e828..97296cedf 100644--- a/packages/eve/src/internal/vercel/build-agent-workspace.ts+++ b/packages/eve/src/internal/vercel/build-agent-workspace.ts@@ -42,7 +42,7 @@ export async function buildAgentWorkspace(workspace: AgentWorkspace): Promise<stconfig.experimentalServicesV2 !== undefined) {throw new Error(- "This project defines its Vercel service graph in vercel.json. Run `vercel build` to build the complete project, or run `eve build` from an individual agent directory.",+ "This project defines its Vercel service graph in vercel.json. Compose generated workspace agents from a programmatic vercel.ts with `withEve` from `eve/vercel`, manually define every service and run `vercel build`, or run `eve build` from an individual agent directory.",);}diff --git a/packages/eve/src/internal/vercel/vercel-services-config.test.ts b/packages/eve/src/internal/vercel/vercel-services-config.test.tsindex 51532cb97..94bc0160f 100644--- a/packages/eve/src/internal/vercel/vercel-services-config.test.ts+++ b/packages/eve/src/internal/vercel/vercel-services-config.test.ts@@ -16,6 +16,15 @@ describe("parseVercelServicesConfig", () => {});});+ it("rejects duplicate names in service arrays", () => {+ expect(() =>+ createServiceConfigRecord([+ { framework: "nextjs", name: "web" },+ { framework: "nuxtjs", name: "web" },+ ]),+ ).toThrow('Duplicate Vercel service name "web".');+ });+it.each([[null, /must contain a JSON object/],[{ services: null }, /services must be a JSON object or named service array/],diff --git a/packages/eve/src/internal/vercel/vercel-services-config.ts b/packages/eve/src/internal/vercel/vercel-services-config.tsindex 409e744cd..dd0951171 100644--- a/packages/eve/src/internal/vercel/vercel-services-config.ts+++ b/packages/eve/src/internal/vercel/vercel-services-config.ts@@ -201,7 +201,15 @@ export function createServiceConfigRecord(): Record<string, VercelServiceConfig> {if (services === undefined) return {};if (!isNamedServiceArray(services)) return services;- return Object.fromEntries(services.map(({ name, ...service }) => [name, service]));++ const record: Record<string, VercelServiceConfig> = {};+ for (const { name, ...service } of services) {+ if (Object.hasOwn(record, name)) {+ throw new Error(`Duplicate Vercel service name ${JSON.stringify(name)}.`);+ }+ record[name] = service;+ }+ return record;}export function hasServices(diff --git a/packages/eve/src/public/vercel/index.integration.test.ts b/packages/eve/src/public/vercel/index.integration.test.tsnew file mode 100644index 000000000..52ce4fe1d--- /dev/null+++ b/packages/eve/src/public/vercel/index.integration.test.ts@@ -0,0 +1,150 @@+import { access, mkdir, mkdtemp, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { describe, expect, it, vi } from "vitest";++vi.mock("#shared/resolve-eve-binary.js", () => ({+ resolveEveBinaryPath: (root: string) => join(root, "node_modules", "eve", "bin", "eve.js"),+}));++import { withEve } from "./index.js";++async function createWorkspace(): Promise<string> {+ const root = await mkdtemp(join(tmpdir(), "eve-vercel-config-"));+ await writeFile(+ join(root, "package.json"),+ JSON.stringify({ dependencies: { eve: "*" }, packageManager: "[email protected]", private: true }),+ );+ await Promise.all([+ mkdir(join(root, "agents", "support", "agent"), { recursive: true }),+ mkdir(join(root, "agents", "research", "agent"), { recursive: true }),+ ]);+ return root;+}++describe("withEve", () => {+ it("composes workspace agents with authored Vercel services and routes", async () => {+ const root = await createWorkspace();+ const config = await withEve(+ {+ crons: [{ path: "/api/dispatch", schedule: "* * * * *" }],+ routes: [+ { destination: { service: "web", type: "service" }, src: "^/api/(.*)$" },+ { handle: "filesystem" },+ ],+ services: { web: { framework: "nextjs", root: "apps/web" } },+ },+ { root },+ );++ expect(config.crons).toEqual([{ path: "/api/dispatch", schedule: "* * * * *" }]);+ expect(config.routes).toEqual([+ { destination: { service: "web", type: "service" }, src: "^/api/(.*)$" },+ {+ destination: { service: "eve-research", type: "service" },+ src: "^/research/eve/v1/(.*)$",+ },+ { destination: { service: "eve-research", type: "service" }, src: "^/research/?$" },+ {+ destination: { service: "eve-support", type: "service" },+ src: "^/support/eve/v1/(.*)$",+ },+ { destination: { service: "eve-support", type: "service" }, src: "^/support/?$" },+ { handle: "filesystem" },+ ]);+ expect(config.services.web).toEqual({ framework: "nextjs", root: "apps/web" });+ expect(config.services["eve-support"]).toEqual({+ 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' && export EVE_PUBLIC_ROUTE_PREFIX='/support' && export EVE_INTERNAL_AGENT_WORKSPACE_MEMBER=1 && node 'node_modules/eve/bin/eve.js' build",+ framework: "eve",+ root: ".eve/vercel-services/eve-support",+ routes: [+ {+ src: "^/support/?$",+ transforms: [{ args: "/", op: "set", type: "request.path" }],+ },+ {+ src: "^/support/eve/v1/(.*)$",+ transforms: [{ args: "/eve/v1/$1", op: "set", type: "request.path" }],+ },+ ],+ });+ await expect(+ access(join(root, ".eve", "vercel-services", "eve-support")),+ ).resolves.toBeUndefined();+ });++ it("does not modify the root Build Output", async () => {+ const root = await createWorkspace();+ const marker = join(root, ".vercel", "output", "services", "web", "config.json");+ await mkdir(join(marker, ".."), { recursive: true });+ await writeFile(marker, "web output");++ await withEve({}, { root });++ await expect(access(marker)).resolves.toBeUndefined();+ });++ it("rejects authored service keys owned by generated agents", async () => {+ const root = await createWorkspace();++ await expect(+ withEve({ services: { "eve-support": { framework: "nextjs" } } }, { root }),+ ).rejects.toThrow(+ 'Vercel service key "eve-support" conflicts with the service generated for eve workspace agent "support". Remove or rename the authored service; withEve owns this key.',+ );+ });++ it("rejects authored routes owned by generated agents", async () => {+ const root = await createWorkspace();++ await expect(+ withEve({ routes: [{ src: "^/support/eve/v1/(.*)$" }] }, { root }),+ ).rejects.toThrow(+ 'Vercel route "^/support/eve/v1/(.*)$" conflicts with the transport route generated for eve workspace agent "support". Remove the authored route; withEve adds it automatically.',+ );+ });++ it("rejects duplicate names in a service array", async () => {+ const root = await createWorkspace();++ await expect(+ withEve(+ {+ services: [+ { framework: "nextjs", name: "web", root: "apps/first" },+ { framework: "nuxtjs", name: "web", root: "apps/second" },+ ],+ },+ { root },+ ),+ ).rejects.toThrow('Duplicate Vercel service name "web".');+ });++ it("rejects obsolete service fields", async () => {+ const root = await createWorkspace();++ await expect(withEve({ experimentalServicesV2: {} }, { root })).rejects.toThrow(+ "withEve cannot compose experimentalServices or experimentalServicesV2. Remove the obsolete field and define authored services under services.",+ );+ });++ it("requires at least one workspace agent", async () => {+ const root = await mkdtemp(join(tmpdir(), "eve-vercel-config-empty-workspace-"));+ await writeFile(join(root, "package.json"), JSON.stringify({ dependencies: { eve: "*" } }));+ await mkdir(join(root, "agents"));++ await expect(withEve({}, { root })).rejects.toThrow(+ `withEve found no workspace agents under ${join(root, "agents")}. Add an agent or remove withEve from vercel.ts.`,+ );+ });++ it("requires an eve workspace root", async () => {+ const root = await mkdtemp(join(tmpdir(), "eve-vercel-config-standalone-"));+ await writeFile(join(root, "package.json"), JSON.stringify({ dependencies: { eve: "*" } }));+ await mkdir(join(root, "agent"), { recursive: true });++ await expect(withEve({}, { root })).rejects.toThrow(/workspace root/);+ });+});diff --git a/packages/eve/src/public/vercel/index.ts b/packages/eve/src/public/vercel/index.tsnew file mode 100644index 000000000..114c96178--- /dev/null+++ b/packages/eve/src/public/vercel/index.ts@@ -0,0 +1,158 @@+import { mkdir } from "node:fs/promises";+import { join, resolve } from "node:path";++import { resolveEveProjectContext } from "#internal/project-context.js";+import { assembleEveVercelServices } from "#internal/vercel/assemble-eve-services.js";+import { quoteVercelShellArgument, toVercelRelativePath } from "#internal/vercel/build-command.js";+import {+ createEveServiceName,+ createEveServiceRouteSrc,+} from "#internal/vercel/eve-service-contribution.js";+import {+ createServiceConfigRecord,+ type VercelServicesConfig,+} from "#internal/vercel/vercel-services-config.js";+import { resolveEveBinaryPath } from "#shared/resolve-eve-binary.js";++/** A route accepted by eve's Vercel configuration composer. */+export interface EveVercelRouteConfig {+ readonly destination?: string | { readonly service?: string; readonly type?: string };+ readonly handle?: string;+ readonly src?: string;+ readonly transforms?: readonly Record<string, unknown>[];+ readonly [key: string]: unknown;+}++/** A service accepted by eve's Vercel configuration composer. */+export interface EveVercelServiceConfig {+ readonly buildCommand?: string;+ readonly entrypoint?: string;+ readonly framework?: string;+ readonly mount?: string | { readonly path?: string; readonly subdomain?: string };+ readonly routes?: readonly EveVercelRouteConfig[];+ readonly root?: string;+ readonly type?: string;+ readonly [key: string]: unknown;+}++/** The portion of a programmatic Vercel configuration composed by eve. */+export interface EveVercelConfig {+ readonly experimentalServices?: unknown;+ readonly experimentalServicesV2?: unknown;+ readonly routes?: readonly EveVercelRouteConfig[];+ readonly services?:+ | Readonly<Record<string, EveVercelServiceConfig>>+ | readonly (EveVercelServiceConfig & { readonly name: string })[];+ readonly [key: string]: unknown;+}++/** Options for composing an eve workspace into a programmatic Vercel configuration. */+export interface WithEveOptions {+ /** Eve workspace root. Defaults to the directory evaluating `vercel.ts`. */+ readonly root?: string;+}++function toInternalConfig(config: EveVercelConfig): VercelServicesConfig {+ return config as VercelServicesConfig;+}++function assertComposableConfig(config: EveVercelConfig, agentNames: readonly string[]): void {+ if (config.experimentalServices !== undefined || config.experimentalServicesV2 !== undefined) {+ throw new Error(+ "withEve cannot compose experimentalServices or experimentalServicesV2. Remove the obsolete field and define authored services under services.",+ );+ }++ const internalConfig = toInternalConfig(config);+ const services = createServiceConfigRecord(internalConfig.services);+ for (const name of agentNames) {+ const serviceName = createEveServiceName(name);+ if (Object.hasOwn(services, serviceName)) {+ throw new Error(+ `Vercel service key ${JSON.stringify(serviceName)} conflicts with the service generated for eve workspace agent ${JSON.stringify(name)}. Remove or rename the authored service; withEve owns this key.`,+ );+ }++ const routeSrc = createEveServiceRouteSrc(`/${name}`);+ if (config.routes?.some((route) => route.src === routeSrc)) {+ throw new Error(+ `Vercel route ${JSON.stringify(routeSrc)} conflicts with the transport route generated for eve workspace agent ${JSON.stringify(name)}. Remove the authored route; withEve adds it automatically.`,+ );+ }+ }+}++/**+ * Add a hostless eve workspace's generated agent services and transport routes to `vercel.ts`.+ *+ * The returned object is a plain Vercel configuration. Vercel resolves it before independently+ * building the authored services and each generated eve agent service.+ */+export async function withEve<TConfig extends EveVercelConfig>(+ config: TConfig,+ options: WithEveOptions = {},+): Promise<+ Omit<TConfig, "routes" | "services"> & {+ readonly routes: readonly EveVercelRouteConfig[];+ readonly services: Readonly<Record<string, EveVercelServiceConfig>>;+ }+> {+ const root = resolve(options.root ?? process.cwd());+ const context = await resolveEveProjectContext(root);+ if (context.kind !== "workspace" || context.workspace.root !== root) {+ throw new Error(`withEve must run at an eve workspace root; received ${root}.`);+ }++ const { workspace } = context;+ if (workspace.members.length === 0) {+ throw new Error(+ `withEve found no workspace agents under ${join(root, "agents")}. Add an agent or remove withEve from vercel.ts.`,+ );+ }++ const agentNames = workspace.members.map((member) => member.name);+ const generatedServiceNames = new Set(agentNames.map(createEveServiceName));+ assertComposableConfig(config, agentNames);++ const outputDirectory = join(root, ".vercel", "output");+ const internalConfig = toInternalConfig(config);+ const assembled = assembleEveVercelServices({+ agents: workspace.members.map((member) => ({+ agent: {+ appRoot: member.appRoot,+ buildCommand: `node ${quoteVercelShellArgument(+ toVercelRelativePath(member.appRoot, resolveEveBinaryPath(member.appRoot)),+ )} build`,+ name: member.name,+ publicRoutePrefix: `/${member.name}`,+ workspaceMember: true,+ },+ target: {+ hostOutputDirectory: outputDirectory,+ projectRoot: root,+ },+ })),+ routes: internalConfig.routes,+ services: createServiceConfigRecord(internalConfig.services),+ });++ await Promise.all(+ assembled.rootDirectories.map((directory) => mkdir(directory, { recursive: true })),+ );++ const services = Object.fromEntries(+ Object.entries(assembled.services).map(([name, service]) => {+ if (!generatedServiceNames.has(name)) {+ return [name, service];+ }+ const { routePrefix: _routePrefix, ...vercelSourceService } = service;+ return [name, vercelSourceService];+ }),+ );++ return {+ ...config,+ routes: assembled.routes as readonly EveVercelRouteConfig[],+ services: services as Readonly<Record<string, EveVercelServiceConfig>>,+ };+}diff --git a/packages/eve/test/scenarios/public-api-portability.scenario.test.ts b/packages/eve/test/scenarios/public-api-portability.scenario.test.tsindex f4816ae2a..44a99afd3 100644--- a/packages/eve/test/scenarios/public-api-portability.scenario.test.ts+++ b/packages/eve/test/scenarios/public-api-portability.scenario.test.ts@@ -39,6 +39,29 @@ interface PortabilityCase {}const PORTABILITY_CASES: readonly PortabilityCase[] = [+ {+ descriptor: {+ files: {+ "agent/vercel.ts": `import { withEve, type EveVercelConfig } from "eve/vercel";++const config = {+ routes: [{ destination: { service: "web", type: "service" }, src: "^(.*)$" }],+ services: { web: { framework: "nextjs", root: "apps/web" } },+} satisfies EveVercelConfig;++export default withEve(config);+`,+ },+ name: "vercel-composer-public-api-portability",+ },+ include: ["src/public/vercel/index.ts"],+ name: "lets tsc typecheck withEve from the public Vercel subpath",+ packageExports: {+ "./vercel": {+ types: "./dist/src/public/vercel/index.d.ts",+ },+ },+ },{descriptor: {files: {